title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
C++ Program to Implement Sorting containers in STL
In this C++ program, we implement Sorting containers in STL. Functions used here: l.push_back() = It is used to push elements into a list from the front. l.sort() = Sorts the elements of the list. Where l is a list object. #include <iostream> #include <list> #include <string> #include <cstdlib> using namespace std; int main() { list<int> l; list<int>::iterator it; int c, i; while (1) { cout<<"1.Insert Element to the list"<<endl; cout<<"2.Display the List"<<endl; cout<<"3.Exit"<<endl; cout<<"Enter your Choice: "; cin>>c; switch(c) { case 1: cout<<"Enter value to be inserted"; cin>>i; l.push_back(i); break; case 2: l.sort(); cout<<"Elements of the List: "; for (it = l.begin(); it != l.end(); it++) cout<<*it<<" "; cout<<endl; break; case 3: exit(1); break; default: cout<<"Wrong Choice"<<endl; } } return 0; } 1.Insert Element to the list 2.Display the List 3.Exit Enter your Choice: 1 Enter value to be inserted7 1.Insert Element to the list 2.Display the List 3.Exit Enter your Choice: 1 Enter value to be inserted10 1.Insert Element to the list 2.Display the List 3.Exit Enter your Choice: 1 Enter value to be inserted6 1.Insert Element to the list 2.Display the List 3.Exit Enter your Choice: 1 Enter value to be inserted4 1.Insert Element to the list 2.Display the List 3.Exit Enter your Choice: 2 Elements of the List: 4 6 7 10 1.Insert Element to the list 2.Display the List 3.Exit Enter your Choice: 3 Exit code: 1
[ { "code": null, "e": 1123, "s": 1062, "text": "In this C++ program, we implement Sorting containers in STL." }, { "code": null, "e": 1294, "s": 1123, "text": "Functions used here:\n l.push_back() = It is used to push elements into a list from the front.\n l.sort() = Sorts the elements of the list.\n Where l is a list object." }, { "code": null, "e": 2134, "s": 1294, "text": "#include <iostream>\n#include <list>\n#include <string>\n#include <cstdlib>\nusing namespace std;\nint main() {\n list<int> l;\n list<int>::iterator it;\n int c, i;\n while (1) {\n cout<<\"1.Insert Element to the list\"<<endl;\n cout<<\"2.Display the List\"<<endl;\n cout<<\"3.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 l.push_back(i);\n break;\n case 2:\n l.sort();\n cout<<\"Elements of the List: \";\n for (it = l.begin(); it != l.end(); it++)\n cout<<*it<<\" \";\n cout<<endl;\n break;\n case 3:\n exit(1);\n break;\n default:\n cout<<\"Wrong Choice\"<<endl;\n }\n }\n return 0;\n}" }, { "code": null, "e": 2753, "s": 2134, "text": "1.Insert Element to the list\n2.Display the List\n3.Exit\n\nEnter your Choice: 1\nEnter value to be inserted7\n1.Insert Element to the list\n2.Display the List\n3.Exit\n\nEnter your Choice: 1\nEnter value to be inserted10\n1.Insert Element to the list\n2.Display the List\n3.Exit\n\nEnter your Choice: 1\nEnter value to be inserted6\n1.Insert Element to the list\n2.Display the List\n3.Exit\n\nEnter your Choice: 1\nEnter value to be inserted4\n1.Insert Element to the list\n2.Display the List\n3.Exit\n\nEnter your Choice: 2\nElements of the List: 4 6 7 10\n1.Insert Element to the list\n2.Display the List\n3.Exit\nEnter your Choice: 3\n\nExit code: 1" } ]
Set unique index in MongoDB
To set unique index in MongoDB, use unique:true. Let us create a collection with documents − > db.demo257.ensureIndex({Name:1},{unique:true}); { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.demo257.insertOne({Name:"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e47a5e51627c0c63e7dba91") } > db.demo257.insertOne({Name:"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e47a5e81627c0c63e7dba92") } > db.demo257.insertOne({Name:"Chris"}); 2020-02-15T13:33:54.064+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: test.demo257 index: Name_1 dup key: { : "Chris" } : WriteError({ "index" : 0, "code" : 11000, "errmsg" : "E11000 duplicate key error collection: test.demo257 index: Name_1 dup key: { : \"Chris\" }", "op" : { "_id" : ObjectId("5e47a5ea1627c0c63e7dba93"), "Name" : "Chris" } }) WriteError@src/mongo/shell/bulk_api.js:461:48 Bulk/mergeBatchResults@src/mongo/shell/bulk_api.js:841:49 Bulk/executeBatch@src/mongo/shell/bulk_api.js:906:13 Bulk/this.execute@src/mongo/shell/bulk_api.js:1150:21 DBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:252:9 @(shell):1:1 Display all documents from a collection with the help of find() method − > db.demo257.find(); This will produce the following output − { "_id" : ObjectId("5e47a5e51627c0c63e7dba91"), "Name" : "Chris" } { "_id" : ObjectId("5e47a5e81627c0c63e7dba92"), "Name" : "Bob" }
[ { "code": null, "e": 1155, "s": 1062, "text": "To set unique index in MongoDB, use unique:true. Let us create a collection with documents −" }, { "code": null, "e": 2296, "s": 1155, "text": "> db.demo257.ensureIndex({Name:1},{unique:true});\n{\n \"createdCollectionAutomatically\" : true,\n \"numIndexesBefore\" : 1,\n \"numIndexesAfter\" : 2,\n \"ok\" : 1\n}\n> db.demo257.insertOne({Name:\"Chris\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e47a5e51627c0c63e7dba91\")\n}\n> db.demo257.insertOne({Name:\"Bob\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e47a5e81627c0c63e7dba92\")\n}\n> db.demo257.insertOne({Name:\"Chris\"});\n2020-02-15T13:33:54.064+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: test.demo257 index: Name_1 dup key: { : \"Chris\" } :\nWriteError({\n \"index\" : 0,\n \"code\" : 11000,\n \"errmsg\" : \"E11000 duplicate key error collection: test.demo257 index: Name_1 dup key: { : \\\"Chris\\\" }\",\n \"op\" : {\n \"_id\" : ObjectId(\"5e47a5ea1627c0c63e7dba93\"),\n \"Name\" : \"Chris\"\n }\n})\nWriteError@src/mongo/shell/bulk_api.js:461:48\nBulk/mergeBatchResults@src/mongo/shell/bulk_api.js:841:49\nBulk/executeBatch@src/mongo/shell/bulk_api.js:906:13\nBulk/this.execute@src/mongo/shell/bulk_api.js:1150:21\nDBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:252:9\n@(shell):1:1" }, { "code": null, "e": 2369, "s": 2296, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 2390, "s": 2369, "text": "> db.demo257.find();" }, { "code": null, "e": 2431, "s": 2390, "text": "This will produce the following output −" }, { "code": null, "e": 2563, "s": 2431, "text": "{ \"_id\" : ObjectId(\"5e47a5e51627c0c63e7dba91\"), \"Name\" : \"Chris\" }\n{ \"_id\" : ObjectId(\"5e47a5e81627c0c63e7dba92\"), \"Name\" : \"Bob\" }" } ]
How to detect and deal with Multicollinearity | by Sushmitha Pulagam | Towards Data Science
Multicollinearity is one of the main assumptions that need to be ruled out to get a better estimation of any regression model ✌️ In this article, I’ll go through the impact of multicollinearity, how to identify, and when to fix this issue with a sample dataset. 👉 What is correlation? The correlation between two variables can be measured with a correlation coefficient which can range between -1 to 1. If the value is 0, the two variables are independent and there is no correlation. If the measure is extremely close to one of these values, it indicates a linear relationship and highly correlated with each other. This means a change in one variable is associated with a significant change in other variables.The correlation can be calculated with the Pearson correlation coefficient and Spearman rank-order coefficient. 👉 What is Multicollinearity? Multicollinearity occurs when there is a high correlation between the independent variables in the regression analysis which impacts the overall interpretation of the results. It reduces the power of coefficients and weakens the statistical measure to trust the p-values to identify the significant independent variables. Hence, we would not be able to examine the individual explanation of the independent variables on the dependent variable. 👉 When to fix Multicollinearity? The good news is that it is not always mandatory to fix the multicollinearity. It all depends on the primary goal of the regression model. The degree of multicollinearity greatly impacts the p-values and coefficients but not predictions and goodness-of-fit test. If your goal is to perform the predictions and not necessary to understand the significance of the independent variable, it is not a mandate to fix the multicollinearity issue. 👉 How to test Multicollinearity? Correlation matrix / Correlation plotVariation Inflation Factor (VIF) Correlation matrix / Correlation plot Variation Inflation Factor (VIF) A correlation plot can be used to identify the correlation or bivariate relationship between two independent variables whereas VIF is used to identify the correlation of one independent variable with a group of other variables. Hence, it is preferred to use VIF for better understanding. VIF = 1 → No correlationVIF = 1 to 5 → Moderate correlationVIF >10 → High correlation Let’s get started with code..... Here is the link for the dataset [House Sales] The features in the dataset are as below. Sale Price is the target variable and the remaining are independent features. Identifying Multicollinearity with numerical variables Now we will calculate the VIF scores for each independent variable. def vif_scores(df): VIF_Scores = pd.DataFrame() VIF_Scores["Independent Features"] = df.columns VIF_Scores["VIF Scores"] = [variance_inflation_factor(df.values,i) for i in range(df.shape[1])] return VIF_Scoresdf1 = df.iloc[:,:-1]vif_scores(df1) The VIF scores are higher than 10 for most of the variables. The individual coefficients and the p-values will be greatly impacted if we build a regression model with this dataset. We will proceed on how to fix this issue. Fixing Multicollinearity — Dropping variables We will consider dropping the features Interior(Sq Ft) and # of Rooms which are having high VIF values because the same information is being captured by other variables. Also, it helps to reduce the redundancy in the dataset. Let us compare the VIF values before and after dropping the VIF values. From the above, we can notice that the VIF scores have reduced for other variables also after dropping the high-value (Interior(Sq Ft) and # of Rooms) VIF features. Fixing Multicollinearity — Combining variables Next, we can observe that #of Bed and #of Bath can be combined to a single variable and it helps us to capture more information from both variables. df5 = df4.copy()df5['Total Rooms'] = df4.apply(lambda x: x['# of Bed'] + x['# of Bath'],axis=1)X = df5.drop(['# of Bed','# of Bath'],axis=1)vif_scores(X) From the above, we can notice that all three variables (Condo Fee, Tax, and Total Rooms) came up with satisfying VIF values and we can proceed further to build a regression model. Summary In this article, we learned how to identify and the ways to fix the multicollinearity issue with numerical values in regression analysis. This is an iterative process and we also need domain knowledge to decide on which variables to take an appropriate action. There are other techniques such as PCA and Regularization methods also to address this issue. Please visit my GitHub link for complete [code] Thank You for reading and Happy Learning! 🙂
[ { "code": null, "e": 300, "s": 171, "text": "Multicollinearity is one of the main assumptions that need to be ruled out to get a better estimation of any regression model ✌️" }, { "code": null, "e": 433, "s": 300, "text": "In this article, I’ll go through the impact of multicollinearity, how to identify, and when to fix this issue with a sample dataset." }, { "code": null, "e": 456, "s": 433, "text": "👉 What is correlation?" }, { "code": null, "e": 995, "s": 456, "text": "The correlation between two variables can be measured with a correlation coefficient which can range between -1 to 1. If the value is 0, the two variables are independent and there is no correlation. If the measure is extremely close to one of these values, it indicates a linear relationship and highly correlated with each other. This means a change in one variable is associated with a significant change in other variables.The correlation can be calculated with the Pearson correlation coefficient and Spearman rank-order coefficient." }, { "code": null, "e": 1024, "s": 995, "text": "👉 What is Multicollinearity?" }, { "code": null, "e": 1468, "s": 1024, "text": "Multicollinearity occurs when there is a high correlation between the independent variables in the regression analysis which impacts the overall interpretation of the results. It reduces the power of coefficients and weakens the statistical measure to trust the p-values to identify the significant independent variables. Hence, we would not be able to examine the individual explanation of the independent variables on the dependent variable." }, { "code": null, "e": 1501, "s": 1468, "text": "👉 When to fix Multicollinearity?" }, { "code": null, "e": 1640, "s": 1501, "text": "The good news is that it is not always mandatory to fix the multicollinearity. It all depends on the primary goal of the regression model." }, { "code": null, "e": 1941, "s": 1640, "text": "The degree of multicollinearity greatly impacts the p-values and coefficients but not predictions and goodness-of-fit test. If your goal is to perform the predictions and not necessary to understand the significance of the independent variable, it is not a mandate to fix the multicollinearity issue." }, { "code": null, "e": 1974, "s": 1941, "text": "👉 How to test Multicollinearity?" }, { "code": null, "e": 2044, "s": 1974, "text": "Correlation matrix / Correlation plotVariation Inflation Factor (VIF)" }, { "code": null, "e": 2082, "s": 2044, "text": "Correlation matrix / Correlation plot" }, { "code": null, "e": 2115, "s": 2082, "text": "Variation Inflation Factor (VIF)" }, { "code": null, "e": 2403, "s": 2115, "text": "A correlation plot can be used to identify the correlation or bivariate relationship between two independent variables whereas VIF is used to identify the correlation of one independent variable with a group of other variables. Hence, it is preferred to use VIF for better understanding." }, { "code": null, "e": 2489, "s": 2403, "text": "VIF = 1 → No correlationVIF = 1 to 5 → Moderate correlationVIF >10 → High correlation" }, { "code": null, "e": 2522, "s": 2489, "text": "Let’s get started with code....." }, { "code": null, "e": 2569, "s": 2522, "text": "Here is the link for the dataset [House Sales]" }, { "code": null, "e": 2689, "s": 2569, "text": "The features in the dataset are as below. Sale Price is the target variable and the remaining are independent features." }, { "code": null, "e": 2744, "s": 2689, "text": "Identifying Multicollinearity with numerical variables" }, { "code": null, "e": 2812, "s": 2744, "text": "Now we will calculate the VIF scores for each independent variable." }, { "code": null, "e": 3069, "s": 2812, "text": "def vif_scores(df): VIF_Scores = pd.DataFrame() VIF_Scores[\"Independent Features\"] = df.columns VIF_Scores[\"VIF Scores\"] = [variance_inflation_factor(df.values,i) for i in range(df.shape[1])] return VIF_Scoresdf1 = df.iloc[:,:-1]vif_scores(df1)" }, { "code": null, "e": 3292, "s": 3069, "text": "The VIF scores are higher than 10 for most of the variables. The individual coefficients and the p-values will be greatly impacted if we build a regression model with this dataset. We will proceed on how to fix this issue." }, { "code": null, "e": 3338, "s": 3292, "text": "Fixing Multicollinearity — Dropping variables" }, { "code": null, "e": 3564, "s": 3338, "text": "We will consider dropping the features Interior(Sq Ft) and # of Rooms which are having high VIF values because the same information is being captured by other variables. Also, it helps to reduce the redundancy in the dataset." }, { "code": null, "e": 3636, "s": 3564, "text": "Let us compare the VIF values before and after dropping the VIF values." }, { "code": null, "e": 3801, "s": 3636, "text": "From the above, we can notice that the VIF scores have reduced for other variables also after dropping the high-value (Interior(Sq Ft) and # of Rooms) VIF features." }, { "code": null, "e": 3848, "s": 3801, "text": "Fixing Multicollinearity — Combining variables" }, { "code": null, "e": 3997, "s": 3848, "text": "Next, we can observe that #of Bed and #of Bath can be combined to a single variable and it helps us to capture more information from both variables." }, { "code": null, "e": 4151, "s": 3997, "text": "df5 = df4.copy()df5['Total Rooms'] = df4.apply(lambda x: x['# of Bed'] + x['# of Bath'],axis=1)X = df5.drop(['# of Bed','# of Bath'],axis=1)vif_scores(X)" }, { "code": null, "e": 4331, "s": 4151, "text": "From the above, we can notice that all three variables (Condo Fee, Tax, and Total Rooms) came up with satisfying VIF values and we can proceed further to build a regression model." }, { "code": null, "e": 4339, "s": 4331, "text": "Summary" }, { "code": null, "e": 4694, "s": 4339, "text": "In this article, we learned how to identify and the ways to fix the multicollinearity issue with numerical values in regression analysis. This is an iterative process and we also need domain knowledge to decide on which variables to take an appropriate action. There are other techniques such as PCA and Regularization methods also to address this issue." }, { "code": null, "e": 4742, "s": 4694, "text": "Please visit my GitHub link for complete [code]" } ]
Apache Presto - substr(string,start,length)
presto:default> select substr('tutorialspoint',10,2) as substring; substring ----------- po 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2074, "s": 2006, "text": "presto:default> select substr('tutorialspoint',10,2) as substring; " }, { "code": null, "e": 2107, "s": 2074, "text": " substring \n----------- \n po\n" }, { "code": null, "e": 2142, "s": 2107, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 2161, "s": 2142, "text": " Arnab Chakraborty" }, { "code": null, "e": 2196, "s": 2161, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 2217, "s": 2196, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 2250, "s": 2217, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 2263, "s": 2250, "text": " Nilay Mehta" }, { "code": null, "e": 2298, "s": 2263, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 2316, "s": 2298, "text": " Bigdata Engineer" }, { "code": null, "e": 2349, "s": 2316, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 2367, "s": 2349, "text": " Bigdata Engineer" }, { "code": null, "e": 2400, "s": 2367, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 2418, "s": 2400, "text": " Bigdata Engineer" }, { "code": null, "e": 2425, "s": 2418, "text": " Print" }, { "code": null, "e": 2436, "s": 2425, "text": " Add Notes" } ]
Java Program for N Queen Problem | Backtracking-3 - GeeksforGeeks
11 Oct, 2021 The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example, the following is a solution for 4 Queen problem. The expected output is a binary matrix which has 1s for the blocks where queens are placed. For example, following is the output matrix for above 4 queen solution. { 0, 1, 0, 0} { 0, 0, 0, 1} { 1, 0, 0, 0} { 0, 0, 1, 0} Java /* Java program to solve N Queen Problem using backtracking */public class NQueenProblem { final int N = 4; /* A utility function to print solution */ void printSolution(int board[][]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.print(" " + board[i][j] + " "); System.out.println(); } } /* A utility function to check if a queen can be placed on board[row][col]. Note that this function is called when "col" queens are already placed in columns from 0 to col -1. So we need to check only left side for attacking queens */ boolean isSafe(int board[][], int row, int col) { int i, j; /* Check this row on left side */ for (i = 0; i < col; i++) if (board[row][i] == 1) return false; /* Check upper diagonal on left side */ for (i = row, j = col; i >= 0 && j >= 0; i--, j--) if (board[i][j] == 1) return false; /* Check lower diagonal on left side */ for (i = row, j = col; j >= 0 && i < N; i++, j--) if (board[i][j] == 1) return false; return true; } /* A recursive utility function to solve N Queen problem */ boolean solveNQUtil(int board[][], int col) { /* base case: If all queens are placed then return true */ if (col >= N) return true; /* Consider this column and try placing this queen in all rows one by one */ for (int i = 0; i < N; i++) { /* Check if the queen can be placed on board[i][col] */ if (isSafe(board, i, col)) { /* Place this queen in board[i][col] */ board[i][col] = 1; /* recur to place rest of the queens */ if (solveNQUtil(board, col + 1) == true) return true; /* If placing queen in board[i][col] doesn't lead to a solution then remove queen from board[i][col] */ board[i][col] = 0; // BACKTRACK } } /* If the queen can not be placed in any row in this column col, then return false */ return false; } /* This function solves the N Queen problem using Backtracking. It mainly uses solveNQUtil () to solve the problem. It returns false if queens cannot be placed, otherwise, return true and prints placement of queens in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ boolean solveNQ() { int board[][] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; if (solveNQUtil(board, 0) == false) { System.out.print("Solution does not exist"); return false; } printSolution(board); return true; } // driver program to test above function public static void main(String args[]) { NQueenProblem Queen = new NQueenProblem(); Queen.solveNQ(); }}// This code is contributed by Abhishek Shankhadhar 0 0 1 0 1 0 0 0 0 0 0 1 0 1 0 0 Please refer complete article on N Queen Problem | Backtracking-3 for more details! anikakapoor simmytarika5 Java Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Java Programming Examples How to Iterate HashMap in Java? Factory method design pattern in Java Traverse Through a HashMap in Java Iterate through List in Java Java Program to Remove Duplicate Elements From the Array Java program to count the occurrence of each character in a string using Hashmap Iterate Over the Characters of a String in Java Min Heap in Java How to Get Elements By Index from HashSet in Java?
[ { "code": null, "e": 24357, "s": 24329, "text": "\n11 Oct, 2021" }, { "code": null, "e": 24534, "s": 24357, "text": "The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example, the following is a solution for 4 Queen problem." }, { "code": null, "e": 24698, "s": 24534, "text": "The expected output is a binary matrix which has 1s for the blocks where queens are placed. For example, following is the output matrix for above 4 queen solution." }, { "code": null, "e": 24822, "s": 24698, "text": " { 0, 1, 0, 0}\n { 0, 0, 0, 1}\n { 1, 0, 0, 0}\n { 0, 0, 1, 0}" }, { "code": null, "e": 24827, "s": 24822, "text": "Java" }, { "code": "/* Java program to solve N Queen Problem using backtracking */public class NQueenProblem { final int N = 4; /* A utility function to print solution */ void printSolution(int board[][]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.print(\" \" + board[i][j] + \" \"); System.out.println(); } } /* A utility function to check if a queen can be placed on board[row][col]. Note that this function is called when \"col\" queens are already placed in columns from 0 to col -1. So we need to check only left side for attacking queens */ boolean isSafe(int board[][], int row, int col) { int i, j; /* Check this row on left side */ for (i = 0; i < col; i++) if (board[row][i] == 1) return false; /* Check upper diagonal on left side */ for (i = row, j = col; i >= 0 && j >= 0; i--, j--) if (board[i][j] == 1) return false; /* Check lower diagonal on left side */ for (i = row, j = col; j >= 0 && i < N; i++, j--) if (board[i][j] == 1) return false; return true; } /* A recursive utility function to solve N Queen problem */ boolean solveNQUtil(int board[][], int col) { /* base case: If all queens are placed then return true */ if (col >= N) return true; /* Consider this column and try placing this queen in all rows one by one */ for (int i = 0; i < N; i++) { /* Check if the queen can be placed on board[i][col] */ if (isSafe(board, i, col)) { /* Place this queen in board[i][col] */ board[i][col] = 1; /* recur to place rest of the queens */ if (solveNQUtil(board, col + 1) == true) return true; /* If placing queen in board[i][col] doesn't lead to a solution then remove queen from board[i][col] */ board[i][col] = 0; // BACKTRACK } } /* If the queen can not be placed in any row in this column col, then return false */ return false; } /* This function solves the N Queen problem using Backtracking. It mainly uses solveNQUtil () to solve the problem. It returns false if queens cannot be placed, otherwise, return true and prints placement of queens in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ boolean solveNQ() { int board[][] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; if (solveNQUtil(board, 0) == false) { System.out.print(\"Solution does not exist\"); return false; } printSolution(board); return true; } // driver program to test above function public static void main(String args[]) { NQueenProblem Queen = new NQueenProblem(); Queen.solveNQ(); }}// This code is contributed by Abhishek Shankhadhar", "e": 28158, "s": 24827, "text": null }, { "code": null, "e": 28205, "s": 28158, "text": "0 0 1 0 \n1 0 0 0 \n0 0 0 1 \n0 1 0 0" }, { "code": null, "e": 28292, "s": 28207, "text": "Please refer complete article on N Queen Problem | Backtracking-3 for more details! " }, { "code": null, "e": 28304, "s": 28292, "text": "anikakapoor" }, { "code": null, "e": 28317, "s": 28304, "text": "simmytarika5" }, { "code": null, "e": 28331, "s": 28317, "text": "Java Programs" }, { "code": null, "e": 28429, "s": 28331, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28438, "s": 28429, "text": "Comments" }, { "code": null, "e": 28451, "s": 28438, "text": "Old Comments" }, { "code": null, "e": 28477, "s": 28451, "text": "Java Programming Examples" }, { "code": null, "e": 28509, "s": 28477, "text": "How to Iterate HashMap in Java?" }, { "code": null, "e": 28547, "s": 28509, "text": "Factory method design pattern in Java" }, { "code": null, "e": 28582, "s": 28547, "text": "Traverse Through a HashMap in Java" }, { "code": null, "e": 28611, "s": 28582, "text": "Iterate through List in Java" }, { "code": null, "e": 28668, "s": 28611, "text": "Java Program to Remove Duplicate Elements From the Array" }, { "code": null, "e": 28749, "s": 28668, "text": "Java program to count the occurrence of each character in a string using Hashmap" }, { "code": null, "e": 28797, "s": 28749, "text": "Iterate Over the Characters of a String in Java" }, { "code": null, "e": 28814, "s": 28797, "text": "Min Heap in Java" } ]
Wildcards in column name for MySQL?
To work with wildcards in column name for MySQL, first, you need to select column_name and then apply LIKE operator to the wildcard. The syntax is as follows − SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ’yourTableName’ AND COLUMN_NAME LIKE 'yourWildCards%'; To understand the above syntax, let us create a table. The query to create a table is as follows − mysql> create table WildcardDemo -> ( -> ProductId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> ProductName varchar(10), -> Shippingdatetime datetime, -> ProductPrice int -> ); Query OK, 0 rows affected (1.31 sec) Now you can check the description of the table. The query is as follows − mysql> desc WildcardDemo; +------------------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------------+-------------+------+-----+---------+----------------+ | ProductId | int(11) | NO | PRI | NULL | auto_increment | | ProductName | varchar(10) | YES | | NULL | | | Shippingdatetime | datetime | YES | | NULL | | | ProductPrice | int(11) | YES | | NULL | | +------------------+-------------+------+-----+---------+----------------+ 4 rows in set (0.01 sec) We have four fields and out of which three of them begin from the word Product. Now apply the wildcards in column names. The query is as follows − mysql> select column_name from information_schema.columns -> where table_name = 'WildcardDemo' -> and column_name LIKE 'product%'; +--------------+ | COLUMN_NAME | +--------------+ | ProductId | | ProductName | | ProductPrice | +--------------+ 3 rows in set (0.10 sec)
[ { "code": null, "e": 1195, "s": 1062, "text": "To work with wildcards in column name for MySQL, first, you need to select column_name and then apply LIKE operator to the wildcard." }, { "code": null, "e": 1222, "s": 1195, "text": "The syntax is as follows −" }, { "code": null, "e": 1347, "s": 1222, "text": "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS\nWHERE TABLE_NAME = ’yourTableName’\nAND COLUMN_NAME LIKE 'yourWildCards%';" }, { "code": null, "e": 1446, "s": 1347, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1677, "s": 1446, "text": "mysql> create table WildcardDemo\n -> (\n -> ProductId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> ProductName varchar(10),\n -> Shippingdatetime datetime,\n -> ProductPrice int\n -> );\nQuery OK, 0 rows affected (1.31 sec)" }, { "code": null, "e": 1751, "s": 1677, "text": "Now you can check the description of the table. The query is as follows −" }, { "code": null, "e": 1777, "s": 1751, "text": "mysql> desc WildcardDemo;" }, { "code": null, "e": 2402, "s": 1777, "text": "+------------------+-------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+------------------+-------------+------+-----+---------+----------------+\n| ProductId | int(11) | NO | PRI | NULL | auto_increment |\n| ProductName | varchar(10) | YES | | NULL | |\n| Shippingdatetime | datetime | YES | | NULL | |\n| ProductPrice | int(11) | YES | | NULL | |\n+------------------+-------------+------+-----+---------+----------------+\n4 rows in set (0.01 sec)" }, { "code": null, "e": 2549, "s": 2402, "text": "We have four fields and out of which three of them begin from the word Product. Now apply the wildcards in column names. The query is as follows −" }, { "code": null, "e": 2686, "s": 2549, "text": "mysql> select column_name from information_schema.columns\n -> where table_name = 'WildcardDemo'\n -> and column_name LIKE 'product%';" }, { "code": null, "e": 2830, "s": 2686, "text": "+--------------+\n| COLUMN_NAME |\n+--------------+\n| ProductId |\n| ProductName |\n| ProductPrice |\n+--------------+\n3 rows in set (0.10 sec)" } ]
Recursive Programs to find Minimum and Maximum elements of array - GeeksforGeeks
23 Apr, 2021 Given an array of integers arr, the task is to find the minimum and maximum element of that array using recursion. Examples : Input: arr = {1, 4, 3, -5, -4, 8, 6}; Output: min = -5, max = 8 Input: arr = {1, 4, 45, 6, 10, -8}; Output: min = -8, max = 45 Recursive approach to find the Minimum element in the array Approach: Get the array for which the minimum is to be found Recursively find the minimum according to the following: Recursively traverse the array from the endBase case: If the remaining array is of length 1, return the only present element i.e. arr[0] Recursively traverse the array from the end Base case: If the remaining array is of length 1, return the only present element i.e. arr[0] if(n == 1) return arr[0]; Recursive call: If the base case is not met, then call the function by passing the array of one size less from the end, i.e. from arr[0] to arr[n-1]. Return statement: At each recursive call (except for the base case), return the minimum of the last element of the current array (i.e. arr[n-1]) and the element returned from the previous recursive call. return min(arr[n-1], recursive_function(arr, n-1)); Print the returned element from the recursive function as the minimum element Pseudocode for Recursive function: If there is single element, return it. Else return minimum of following. a) Last Element b) Value returned by recursive call fir n-1 elements. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // Recursive C++ program to find minimum #include <iostream>using namespace std; // function to print Minimum element using recursionint findMinRec(int A[], int n){ // if size = 0 means whole array has been traversed if (n == 1) return A[0]; return min(A[n-1], findMinRec(A, n-1));} // driver code to test above functionint main(){ int A[] = {1, 4, 45, 6, -50, 10, 2}; int n = sizeof(A)/sizeof(A[0]); cout << findMinRec(A, n); return 0;} // Recursive Java program to find minimumimport java.util.*; class GFG { // function to return minimum element using recursion public static int findMinRec(int A[], int n) { // if size = 0 means whole array // has been traversed if(n == 1) return A[0]; return Math.min(A[n-1], findMinRec(A, n-1)); } // Driver code public static void main(String args[]) { int A[] = {1, 4, 45, 6, -50, 10, 2}; int n = A.length; // Function calling System.out.println(findMinRec(A, n)); }} //This code is contributed by Niraj_Pandey # Recursive python 3 program to# find minimum # function to print Minimum element# using recursiondef findMinRec(A, n): # if size = 0 means whole array # has been traversed if (n == 1): return A[0] return min(A[n - 1], findMinRec(A, n - 1)) # Driver Codeif __name__ == '__main__': A = [1, 4, 45, 6, -50, 10, 2] n = len(A) print(findMinRec(A, n)) # This code is contributed by# Shashank_Sharma // Recursive C# program to find minimumusing System; class GFG{ // function to return minimum// element using recursionpublic static int findMinRec(int []A, int n){// if size = 0 means whole array// has been traversedif(n == 1) return A[0]; return Math.Min(A[n - 1], findMinRec(A, n - 1));} // Driver codestatic public void Main (){ int []A = {1, 4, 45, 6, -50, 10, 2}; int n = A.Length; // Function calling Console.WriteLine(findMinRec(A, n));}} // This code is contributed by Sachin <?php// Recursive PHP program to find minimum // function to print Minimum// element using recursionfunction findMinRec($A, $n){ // if size = 0 means whole // array has been traversed if ($n == 1) return $A[0]; return min($A[$n - 1], findMinRec($A, $n - 1));} // Driver Code $A = array (1, 4, 45, 6, -50, 10, 2); $n = sizeof($A); echo findMinRec($A, $n); // This code is contributed by akt?> <script> // Javascript program to find minimum // Function to print Minimum// element using recursionfunction findMinRec(A, n){ // If size = 0 means whole // array has been traversed if (n == 1) return A[0]; return Math.min(A[n - 1], findMinRec(A, n - 1));} // Driver Codelet A = [ 1, 4, 45, 6, -50, 10, 2 ];let n = A.length; document.write( findMinRec(A, n)); // This code is contributed by sravan kumar G </script> Output: -50 Recursive approach to find the Maximum element in the array Approach: Get the array for which the maximum is to be found Recursively find the maximum according to the following: Recursively traverse the array from the endBase case: If the remaining array is of length 1, return the only present element i.e. arr[0] Recursively traverse the array from the end Base case: If the remaining array is of length 1, return the only present element i.e. arr[0] if(n == 1) return arr[0]; Recursive call: If the base case is not met, then call the function by passing the array of one size less from the end, i.e. from arr[0] to arr[n-1]. Return statement: At each recursive call (except for the base case), return the maximum of the last element of the current array (i.e. arr[n-1]) and the element returned from the previous recursive call. return max(arr[n-1], recursive_function(arr, n-1)); Print the returned element from the recursive function as the maximum element Pseudocode for Recursive function: If there is single element, return it. Else return maximum of following. a) Last Element b) Value returned by recursive call fir n-1 elements. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // Recursive C++ program to find maximum#include <iostream>using namespace std; // function to return maximum element using recursionint findMaxRec(int A[], int n){ // if n = 0 means whole array has been traversed if (n == 1) return A[0]; return max(A[n-1], findMaxRec(A, n-1));} // driver code to test above functionint main(){ int A[] = {1, 4, 45, 6, -50, 10, 2}; int n = sizeof(A)/sizeof(A[0]); cout << findMaxRec(A, n); return 0;} // Recursive Java program to find maximumimport java.util.*; class GFG { // function to return maximum element using recursion public static int findMaxRec(int A[], int n) { // if size = 0 means whole array // has been traversed if(n == 1) return A[0]; return Math.max(A[n-1], findMaxRec(A, n-1)); } // Driver code public static void main(String args[]) { int A[] = {1, 4, 45, 6, -50, 10, 2}; int n = A.length; // Function calling System.out.println(findMaxRec(A, n)); }} //This code is contributed by Niraj_Pandey # Recursive Python 3 program to# find maximum # function to return maximum element# using recursiondef findMaxRec(A, n): # if n = 0 means whole array # has been traversed if (n == 1): return A[0] return max(A[n - 1], findMaxRec(A, n - 1)) # Driver Codeif __name__ == "__main__": A = [1, 4, 45, 6, -50, 10, 2] n = len(A) print(findMaxRec(A, n)) # This code is contributed by ita_c // Recursive C# program to find maximumusing System; class GFG{// function to return maximum// element using recursionpublic static int findMaxRec(int []A, int n){// if size = 0 means whole array// has been traversedif(n == 1) return A[0]; return Math.Max(A[n - 1], findMaxRec(A, n - 1));} // Driver codestatic public void Main (){ int []A = {1, 4, 45, 6, -50, 10, 2}; int n = A.Length; // Function calling Console.WriteLine(findMaxRec(A, n));}} // This code is contributed by Sach_Code <?php// Recursive PHP program to find maximum // function to return maximum// element using recursionfunction findMaxRec($A, $n){ // if n = 0 means whole array // has been traversed if ($n == 1) return $A[0]; return max($A[$n - 1], findMaxRec($A, $n - 1));} // Driver Code$A = array(1, 4, 45, 6, -50, 10, 2);$n = sizeof($A);echo findMaxRec($A, $n); // This code is contributed// by Akanksha Rai?> <script> // Recursive Java program to find maximum // Function to return maximum element// using recursionfunction findMaxRec(A, n){ // If size = 0 means whole array // has been traversed if (n == 1) return A[0]; return Math.max(A[n - 1], findMaxRec(A, n - 1));} // Driver codelet A = [ 1, 4, 45, 6, -50, 10, 2 ];let n = A.length; // Function callingdocument.write(findMaxRec(A, n)); // This code is contributed by sravan kumar G </script> Output: 45 Related article: Program to find largest element in an array This article is contributed by Pratik Chhajer. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Niraj_Pandey jit_t Sach_Code Akanksha_Rai Shashank_Sharma ukasp RajaHamza sravankumar8128 Arrays Recursion Searching Arrays Searching Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program to find sum of elements in a given array Building Heap from Array Window Sliding Technique 1's and 2's complement of a Binary Number Reversal algorithm for array rotation Write a program to print all permutations of a given string Recursion Backtracking | Introduction Program for Tower of Hanoi Sort a stack using recursion
[ { "code": null, "e": 24430, "s": 24402, "text": "\n23 Apr, 2021" }, { "code": null, "e": 24545, "s": 24430, "text": "Given an array of integers arr, the task is to find the minimum and maximum element of that array using recursion." }, { "code": null, "e": 24557, "s": 24545, "text": "Examples : " }, { "code": null, "e": 24685, "s": 24557, "text": "Input: arr = {1, 4, 3, -5, -4, 8, 6};\nOutput: min = -5, max = 8\n\nInput: arr = {1, 4, 45, 6, 10, -8};\nOutput: min = -8, max = 45" }, { "code": null, "e": 24745, "s": 24685, "text": "Recursive approach to find the Minimum element in the array" }, { "code": null, "e": 24757, "s": 24745, "text": "Approach: " }, { "code": null, "e": 24808, "s": 24757, "text": "Get the array for which the minimum is to be found" }, { "code": null, "e": 25003, "s": 24808, "text": "Recursively find the minimum according to the following: Recursively traverse the array from the endBase case: If the remaining array is of length 1, return the only present element i.e. arr[0] " }, { "code": null, "e": 25047, "s": 25003, "text": "Recursively traverse the array from the end" }, { "code": null, "e": 25142, "s": 25047, "text": "Base case: If the remaining array is of length 1, return the only present element i.e. arr[0] " }, { "code": null, "e": 25171, "s": 25142, "text": "if(n == 1)\n return arr[0];" }, { "code": null, "e": 25321, "s": 25171, "text": "Recursive call: If the base case is not met, then call the function by passing the array of one size less from the end, i.e. from arr[0] to arr[n-1]." }, { "code": null, "e": 25526, "s": 25321, "text": "Return statement: At each recursive call (except for the base case), return the minimum of the last element of the current array (i.e. arr[n-1]) and the element returned from the previous recursive call. " }, { "code": null, "e": 25578, "s": 25526, "text": "return min(arr[n-1], recursive_function(arr, n-1));" }, { "code": null, "e": 25656, "s": 25578, "text": "Print the returned element from the recursive function as the minimum element" }, { "code": null, "e": 25692, "s": 25656, "text": "Pseudocode for Recursive function: " }, { "code": null, "e": 25850, "s": 25692, "text": "If there is single element, return it.\nElse return minimum of following.\n a) Last Element\n b) Value returned by recursive call\n fir n-1 elements." }, { "code": null, "e": 25901, "s": 25850, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25905, "s": 25901, "text": "C++" }, { "code": null, "e": 25910, "s": 25905, "text": "Java" }, { "code": null, "e": 25918, "s": 25910, "text": "Python3" }, { "code": null, "e": 25921, "s": 25918, "text": "C#" }, { "code": null, "e": 25925, "s": 25921, "text": "PHP" }, { "code": null, "e": 25936, "s": 25925, "text": "Javascript" }, { "code": "// Recursive C++ program to find minimum #include <iostream>using namespace std; // function to print Minimum element using recursionint findMinRec(int A[], int n){ // if size = 0 means whole array has been traversed if (n == 1) return A[0]; return min(A[n-1], findMinRec(A, n-1));} // driver code to test above functionint main(){ int A[] = {1, 4, 45, 6, -50, 10, 2}; int n = sizeof(A)/sizeof(A[0]); cout << findMinRec(A, n); return 0;}", "e": 26403, "s": 25936, "text": null }, { "code": "// Recursive Java program to find minimumimport java.util.*; class GFG { // function to return minimum element using recursion public static int findMinRec(int A[], int n) { // if size = 0 means whole array // has been traversed if(n == 1) return A[0]; return Math.min(A[n-1], findMinRec(A, n-1)); } // Driver code public static void main(String args[]) { int A[] = {1, 4, 45, 6, -50, 10, 2}; int n = A.length; // Function calling System.out.println(findMinRec(A, n)); }} //This code is contributed by Niraj_Pandey", "e": 27023, "s": 26403, "text": null }, { "code": "# Recursive python 3 program to# find minimum # function to print Minimum element# using recursiondef findMinRec(A, n): # if size = 0 means whole array # has been traversed if (n == 1): return A[0] return min(A[n - 1], findMinRec(A, n - 1)) # Driver Codeif __name__ == '__main__': A = [1, 4, 45, 6, -50, 10, 2] n = len(A) print(findMinRec(A, n)) # This code is contributed by# Shashank_Sharma", "e": 27449, "s": 27023, "text": null }, { "code": "// Recursive C# program to find minimumusing System; class GFG{ // function to return minimum// element using recursionpublic static int findMinRec(int []A, int n){// if size = 0 means whole array// has been traversedif(n == 1) return A[0]; return Math.Min(A[n - 1], findMinRec(A, n - 1));} // Driver codestatic public void Main (){ int []A = {1, 4, 45, 6, -50, 10, 2}; int n = A.Length; // Function calling Console.WriteLine(findMinRec(A, n));}} // This code is contributed by Sachin", "e": 28013, "s": 27449, "text": null }, { "code": "<?php// Recursive PHP program to find minimum // function to print Minimum// element using recursionfunction findMinRec($A, $n){ // if size = 0 means whole // array has been traversed if ($n == 1) return $A[0]; return min($A[$n - 1], findMinRec($A, $n - 1));} // Driver Code $A = array (1, 4, 45, 6, -50, 10, 2); $n = sizeof($A); echo findMinRec($A, $n); // This code is contributed by akt?>", "e": 28442, "s": 28013, "text": null }, { "code": "<script> // Javascript program to find minimum // Function to print Minimum// element using recursionfunction findMinRec(A, n){ // If size = 0 means whole // array has been traversed if (n == 1) return A[0]; return Math.min(A[n - 1], findMinRec(A, n - 1));} // Driver Codelet A = [ 1, 4, 45, 6, -50, 10, 2 ];let n = A.length; document.write( findMinRec(A, n)); // This code is contributed by sravan kumar G </script>", "e": 28899, "s": 28442, "text": null }, { "code": null, "e": 28908, "s": 28899, "text": "Output: " }, { "code": null, "e": 28912, "s": 28908, "text": "-50" }, { "code": null, "e": 28972, "s": 28912, "text": "Recursive approach to find the Maximum element in the array" }, { "code": null, "e": 28984, "s": 28972, "text": "Approach: " }, { "code": null, "e": 29035, "s": 28984, "text": "Get the array for which the maximum is to be found" }, { "code": null, "e": 29231, "s": 29035, "text": "Recursively find the maximum according to the following: Recursively traverse the array from the endBase case: If the remaining array is of length 1, return the only present element i.e. arr[0] " }, { "code": null, "e": 29275, "s": 29231, "text": "Recursively traverse the array from the end" }, { "code": null, "e": 29371, "s": 29275, "text": "Base case: If the remaining array is of length 1, return the only present element i.e. arr[0] " }, { "code": null, "e": 29400, "s": 29371, "text": "if(n == 1)\n return arr[0];" }, { "code": null, "e": 29550, "s": 29400, "text": "Recursive call: If the base case is not met, then call the function by passing the array of one size less from the end, i.e. from arr[0] to arr[n-1]." }, { "code": null, "e": 29756, "s": 29550, "text": "Return statement: At each recursive call (except for the base case), return the maximum of the last element of the current array (i.e. arr[n-1]) and the element returned from the previous recursive call. " }, { "code": null, "e": 29808, "s": 29756, "text": "return max(arr[n-1], recursive_function(arr, n-1));" }, { "code": null, "e": 29886, "s": 29808, "text": "Print the returned element from the recursive function as the maximum element" }, { "code": null, "e": 29923, "s": 29886, "text": "Pseudocode for Recursive function: " }, { "code": null, "e": 30081, "s": 29923, "text": "If there is single element, return it.\nElse return maximum of following.\n a) Last Element\n b) Value returned by recursive call\n fir n-1 elements." }, { "code": null, "e": 30132, "s": 30081, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 30136, "s": 30132, "text": "C++" }, { "code": null, "e": 30141, "s": 30136, "text": "Java" }, { "code": null, "e": 30149, "s": 30141, "text": "Python3" }, { "code": null, "e": 30152, "s": 30149, "text": "C#" }, { "code": null, "e": 30156, "s": 30152, "text": "PHP" }, { "code": null, "e": 30167, "s": 30156, "text": "Javascript" }, { "code": "// Recursive C++ program to find maximum#include <iostream>using namespace std; // function to return maximum element using recursionint findMaxRec(int A[], int n){ // if n = 0 means whole array has been traversed if (n == 1) return A[0]; return max(A[n-1], findMaxRec(A, n-1));} // driver code to test above functionint main(){ int A[] = {1, 4, 45, 6, -50, 10, 2}; int n = sizeof(A)/sizeof(A[0]); cout << findMaxRec(A, n); return 0;}", "e": 30631, "s": 30167, "text": null }, { "code": "// Recursive Java program to find maximumimport java.util.*; class GFG { // function to return maximum element using recursion public static int findMaxRec(int A[], int n) { // if size = 0 means whole array // has been traversed if(n == 1) return A[0]; return Math.max(A[n-1], findMaxRec(A, n-1)); } // Driver code public static void main(String args[]) { int A[] = {1, 4, 45, 6, -50, 10, 2}; int n = A.length; // Function calling System.out.println(findMaxRec(A, n)); }} //This code is contributed by Niraj_Pandey", "e": 31251, "s": 30631, "text": null }, { "code": "# Recursive Python 3 program to# find maximum # function to return maximum element# using recursiondef findMaxRec(A, n): # if n = 0 means whole array # has been traversed if (n == 1): return A[0] return max(A[n - 1], findMaxRec(A, n - 1)) # Driver Codeif __name__ == \"__main__\": A = [1, 4, 45, 6, -50, 10, 2] n = len(A) print(findMaxRec(A, n)) # This code is contributed by ita_c", "e": 31665, "s": 31251, "text": null }, { "code": "// Recursive C# program to find maximumusing System; class GFG{// function to return maximum// element using recursionpublic static int findMaxRec(int []A, int n){// if size = 0 means whole array// has been traversedif(n == 1) return A[0]; return Math.Max(A[n - 1], findMaxRec(A, n - 1));} // Driver codestatic public void Main (){ int []A = {1, 4, 45, 6, -50, 10, 2}; int n = A.Length; // Function calling Console.WriteLine(findMaxRec(A, n));}} // This code is contributed by Sach_Code", "e": 32227, "s": 31665, "text": null }, { "code": "<?php// Recursive PHP program to find maximum // function to return maximum// element using recursionfunction findMaxRec($A, $n){ // if n = 0 means whole array // has been traversed if ($n == 1) return $A[0]; return max($A[$n - 1], findMaxRec($A, $n - 1));} // Driver Code$A = array(1, 4, 45, 6, -50, 10, 2);$n = sizeof($A);echo findMaxRec($A, $n); // This code is contributed// by Akanksha Rai?>", "e": 32650, "s": 32227, "text": null }, { "code": "<script> // Recursive Java program to find maximum // Function to return maximum element// using recursionfunction findMaxRec(A, n){ // If size = 0 means whole array // has been traversed if (n == 1) return A[0]; return Math.max(A[n - 1], findMaxRec(A, n - 1));} // Driver codelet A = [ 1, 4, 45, 6, -50, 10, 2 ];let n = A.length; // Function callingdocument.write(findMaxRec(A, n)); // This code is contributed by sravan kumar G </script>", "e": 33126, "s": 32650, "text": null }, { "code": null, "e": 33135, "s": 33126, "text": "Output: " }, { "code": null, "e": 33138, "s": 33135, "text": "45" }, { "code": null, "e": 33199, "s": 33138, "text": "Related article: Program to find largest element in an array" }, { "code": null, "e": 33626, "s": 33199, "text": "This article is contributed by Pratik Chhajer. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 33639, "s": 33626, "text": "Niraj_Pandey" }, { "code": null, "e": 33645, "s": 33639, "text": "jit_t" }, { "code": null, "e": 33655, "s": 33645, "text": "Sach_Code" }, { "code": null, "e": 33668, "s": 33655, "text": "Akanksha_Rai" }, { "code": null, "e": 33684, "s": 33668, "text": "Shashank_Sharma" }, { "code": null, "e": 33690, "s": 33684, "text": "ukasp" }, { "code": null, "e": 33700, "s": 33690, "text": "RajaHamza" }, { "code": null, "e": 33716, "s": 33700, "text": "sravankumar8128" }, { "code": null, "e": 33723, "s": 33716, "text": "Arrays" }, { "code": null, "e": 33733, "s": 33723, "text": "Recursion" }, { "code": null, "e": 33743, "s": 33733, "text": "Searching" }, { "code": null, "e": 33750, "s": 33743, "text": "Arrays" }, { "code": null, "e": 33760, "s": 33750, "text": "Searching" }, { "code": null, "e": 33770, "s": 33760, "text": "Recursion" }, { "code": null, "e": 33868, "s": 33770, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33877, "s": 33868, "text": "Comments" }, { "code": null, "e": 33890, "s": 33877, "text": "Old Comments" }, { "code": null, "e": 33939, "s": 33890, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 33964, "s": 33939, "text": "Building Heap from Array" }, { "code": null, "e": 33989, "s": 33964, "text": "Window Sliding Technique" }, { "code": null, "e": 34031, "s": 33989, "text": "1's and 2's complement of a Binary Number" }, { "code": null, "e": 34069, "s": 34031, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 34129, "s": 34069, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 34139, "s": 34129, "text": "Recursion" }, { "code": null, "e": 34167, "s": 34139, "text": "Backtracking | Introduction" }, { "code": null, "e": 34194, "s": 34167, "text": "Program for Tower of Hanoi" } ]
How to save a vector in R as CSV file?
To save a vector in R as CSV file, we can follow the below steps − First of all, create a vector. Then, use write.csv function to save the vector in CSV file. Let’s create a vector as shown below − Live Demo x<-rnorm(20) x On executing, the above script generates the below output(this output will vary on your system due to randomization) − [1] 0.1771119 0.1380003 -0.3802071 -1.1502674 -0.9965625 -0.3693598 [7] -0.5193763 1.4656757 -0.3345711 -0.4971942 -0.3540402 1.3554071 [13] 0.3902927 1.7747777 -2.3264197 -1.3224475 -1.0591576 0.1597807 [19] 3.3330014 -0.1953936 Using write.csv file to save the file − x<-rnorm(20) write.csv(x,file=”x.csv”,row.names=F) Let’s create a vector as shown below − Live Demo y<-sample(1:50000,20) y [1] 41211 37043 14530 17196 41975 28659 9982 42846 12751 37142 20830 32292 [13] 21529 1369 43475 10858 8845 48025 19639 39265 Using write.csv file to save the file − y<-sample(1:50000,20) write.csv(y,file="y.csv",row.names=F)
[ { "code": null, "e": 1129, "s": 1062, "text": "To save a vector in R as CSV file, we can follow the below steps −" }, { "code": null, "e": 1160, "s": 1129, "text": "First of all, create a vector." }, { "code": null, "e": 1221, "s": 1160, "text": "Then, use write.csv function to save the vector in CSV file." }, { "code": null, "e": 1260, "s": 1221, "text": "Let’s create a vector as shown below −" }, { "code": null, "e": 1271, "s": 1260, "text": " Live Demo" }, { "code": null, "e": 1286, "s": 1271, "text": "x<-rnorm(20)\nx" }, { "code": null, "e": 1405, "s": 1286, "text": "On executing, the above script generates the below output(this output will vary on your system due to randomization) −" }, { "code": null, "e": 1635, "s": 1405, "text": "[1] 0.1771119 0.1380003 -0.3802071 -1.1502674 -0.9965625 -0.3693598\n[7] -0.5193763 1.4656757 -0.3345711 -0.4971942 -0.3540402 1.3554071\n[13] 0.3902927 1.7747777 -2.3264197 -1.3224475 -1.0591576 0.1597807\n[19] 3.3330014 -0.1953936" }, { "code": null, "e": 1675, "s": 1635, "text": "Using write.csv file to save the file −" }, { "code": null, "e": 1726, "s": 1675, "text": "x<-rnorm(20)\nwrite.csv(x,file=”x.csv”,row.names=F)" }, { "code": null, "e": 1765, "s": 1726, "text": "Let’s create a vector as shown below −" }, { "code": null, "e": 1776, "s": 1765, "text": " Live Demo" }, { "code": null, "e": 1800, "s": 1776, "text": "y<-sample(1:50000,20)\ny" }, { "code": null, "e": 1926, "s": 1800, "text": "[1] 41211 37043 14530 17196 41975 28659 9982 42846 12751 37142 20830 32292\n[13] 21529 1369 43475 10858 8845 48025 19639 39265" }, { "code": null, "e": 1966, "s": 1926, "text": "Using write.csv file to save the file −" }, { "code": null, "e": 2026, "s": 1966, "text": "y<-sample(1:50000,20)\nwrite.csv(y,file=\"y.csv\",row.names=F)" } ]
OpenCV - Sobel Operator
Using the sobel operation, you can detect the edges of an image in both horizontal and vertical directions. You can apply sobel operation on an image using the method sobel(). Following is the syntax of this method − Sobel(src, dst, ddepth, dx, dy) This method accepts the following parameters − src − An object of the class Mat representing the source (input) image. src − An object of the class Mat representing the source (input) image. dst − An object of the class Mat representing the destination (output) image. dst − An object of the class Mat representing the destination (output) image. ddepth − An integer variable representing the depth of the image (-1) ddepth − An integer variable representing the depth of the image (-1) dx − An integer variable representing the x-derivative. (0 or 1) dx − An integer variable representing the x-derivative. (0 or 1) dy − An integer variable representing the y-derivative. (0 or 1) dy − An integer variable representing the y-derivative. (0 or 1) The following program demonstrates how to perform Sobel operation on a given image. import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; public class SobelTest { public static void main(String args[]) { // Loading the OpenCV core library System.loadLibrary(Core.NATIVE_LIBRARY_NAME); // Reading the Image from the file and storing it in to a Matrix object String file ="E:/OpenCV/chap16/sobel_input.jpg"; Mat src = Imgcodecs.imread(file); // Creating an empty matrix to store the result Mat dst = new Mat(); // Applying sobel on the Image Imgproc.Sobel(src, dst, -1, 1, 1); // Writing the image Imgcodecs.imwrite("E:/OpenCV/chap16/sobel_output.jpg", dst); System.out.println("Image processed"); } } Assume that following is the input image sobel_input.jpg specified in the above program. On executing the program, you will get the following output − Image Processed If you open the specified path, you can observe the output image as follows − On passing different values to the last to parameters (dx and dy) (among 0 and 1), you will get different outputs − // Applying sobel on the Image Imgproc.Sobel(src, dst, -1, 1, 1); The following table lists various values for the variables dx and dy of the method Sobel() and their respective outputs. 70 Lectures 9 hours Abhilash Nelson 41 Lectures 4 hours Abhilash Nelson 20 Lectures 2 hours Spotle Learn 12 Lectures 46 mins Srikanth Guskra 19 Lectures 2 hours Haithem Gasmi 67 Lectures 6.5 hours Gianluca Mottola Print Add Notes Bookmark this page
[ { "code": null, "e": 3221, "s": 3004, "text": "Using the sobel operation, you can detect the edges of an image in both horizontal and vertical directions. You can apply sobel operation on an image using the method sobel(). Following is the syntax of this method −" }, { "code": null, "e": 3254, "s": 3221, "text": "Sobel(src, dst, ddepth, dx, dy)\n" }, { "code": null, "e": 3301, "s": 3254, "text": "This method accepts the following parameters −" }, { "code": null, "e": 3373, "s": 3301, "text": "src − An object of the class Mat representing the source (input) image." }, { "code": null, "e": 3445, "s": 3373, "text": "src − An object of the class Mat representing the source (input) image." }, { "code": null, "e": 3523, "s": 3445, "text": "dst − An object of the class Mat representing the destination (output) image." }, { "code": null, "e": 3601, "s": 3523, "text": "dst − An object of the class Mat representing the destination (output) image." }, { "code": null, "e": 3671, "s": 3601, "text": "ddepth − An integer variable representing the depth of the image (-1)" }, { "code": null, "e": 3741, "s": 3671, "text": "ddepth − An integer variable representing the depth of the image (-1)" }, { "code": null, "e": 3806, "s": 3741, "text": "dx − An integer variable representing the x-derivative. (0 or 1)" }, { "code": null, "e": 3871, "s": 3806, "text": "dx − An integer variable representing the x-derivative. (0 or 1)" }, { "code": null, "e": 3936, "s": 3871, "text": "dy − An integer variable representing the y-derivative. (0 or 1)" }, { "code": null, "e": 4001, "s": 3936, "text": "dy − An integer variable representing the y-derivative. (0 or 1)" }, { "code": null, "e": 4085, "s": 4001, "text": "The following program demonstrates how to perform Sobel operation on a given image." }, { "code": null, "e": 4863, "s": 4085, "text": "import org.opencv.core.Core;\nimport org.opencv.core.Mat;\n\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\n\npublic class SobelTest {\n public static void main(String args[]) {\n // Loading the OpenCV core library\n System.loadLibrary(Core.NATIVE_LIBRARY_NAME);\n\n // Reading the Image from the file and storing it in to a Matrix object\n String file =\"E:/OpenCV/chap16/sobel_input.jpg\";\n Mat src = Imgcodecs.imread(file);\n\n // Creating an empty matrix to store the result\n Mat dst = new Mat();\n\n // Applying sobel on the Image\n Imgproc.Sobel(src, dst, -1, 1, 1);\n\n // Writing the image\n Imgcodecs.imwrite(\"E:/OpenCV/chap16/sobel_output.jpg\", dst);\n\n System.out.println(\"Image processed\");\n }\n}" }, { "code": null, "e": 4952, "s": 4863, "text": "Assume that following is the input image sobel_input.jpg specified in the above program." }, { "code": null, "e": 5014, "s": 4952, "text": "On executing the program, you will get the following output −" }, { "code": null, "e": 5031, "s": 5014, "text": "Image Processed\n" }, { "code": null, "e": 5109, "s": 5031, "text": "If you open the specified path, you can observe the output image as follows −" }, { "code": null, "e": 5225, "s": 5109, "text": "On passing different values to the last to parameters (dx and dy) (among 0 and 1), you will get different outputs −" }, { "code": null, "e": 5292, "s": 5225, "text": "// Applying sobel on the Image\nImgproc.Sobel(src, dst, -1, 1, 1);\n" }, { "code": null, "e": 5413, "s": 5292, "text": "The following table lists various values for the variables dx and dy of the method Sobel() and their respective outputs." }, { "code": null, "e": 5446, "s": 5413, "text": "\n 70 Lectures \n 9 hours \n" }, { "code": null, "e": 5463, "s": 5446, "text": " Abhilash Nelson" }, { "code": null, "e": 5496, "s": 5463, "text": "\n 41 Lectures \n 4 hours \n" }, { "code": null, "e": 5513, "s": 5496, "text": " Abhilash Nelson" }, { "code": null, "e": 5546, "s": 5513, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 5560, "s": 5546, "text": " Spotle Learn" }, { "code": null, "e": 5592, "s": 5560, "text": "\n 12 Lectures \n 46 mins\n" }, { "code": null, "e": 5609, "s": 5592, "text": " Srikanth Guskra" }, { "code": null, "e": 5642, "s": 5609, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 5657, "s": 5642, "text": " Haithem Gasmi" }, { "code": null, "e": 5692, "s": 5657, "text": "\n 67 Lectures \n 6.5 hours \n" }, { "code": null, "e": 5710, "s": 5692, "text": " Gianluca Mottola" }, { "code": null, "e": 5717, "s": 5710, "text": " Print" }, { "code": null, "e": 5728, "s": 5717, "text": " Add Notes" } ]
How to use shared preferences in Android using Kotlin?
This example demonstrates how to use shared preferences in Android using Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:text="Tutorials Point" android:textAlignment="center" android:textColor="@android:color/holo_green_dark" android:textSize="32sp" android:textStyle="bold" /> <EditText android:id="@+id/etName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView" android:layout_centerInParent="true" android:layout_marginTop="75dp" android:ems="10" android:hint="Enter Name" /> <EditText android:id="@+id/etPassword" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/etName" android:layout_centerHorizontal="true" android:ems="10" android:hint="Enter Password" /> <Button android:id="@+id/btnLogin" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/etPassword" android:layout_alignStart="@id/etPassword" android:layout_marginTop="10dp" android:text="Login" /> <CheckBox android:id="@+id/checkBox" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/btnLogin" android:layout_alignStart="@id/btnLogin" android:layout_marginTop="10dp" android:text="Remember my credentials" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.kt import android.content.SharedPreferences import android.os.Bundle import android.preference.PreferenceManager import android.widget.Button import android.widget.CheckBox import android.widget.EditText import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { private lateinit var sharedPreferences: SharedPreferences private lateinit var editor: SharedPreferences.Editor private lateinit var name: EditText private lateinit var password: EditText private lateinit var button: Button private lateinit var checkBox: CheckBox private lateinit var strName: String private lateinit var strPassword: String private lateinit var strCheckBox: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" name = findViewById(R.id.etName) password = findViewById(R.id.etPassword) button = findViewById(R.id.btnLogin) checkBox = findViewById(R.id.checkBox) sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this) editor = sharedPreferences.edit() checkSharedPreference() button.setOnClickListener { if (checkBox.isChecked) { editor.putString(getString(R.string.checkBox), "True") editor.apply() strName = name.text.toString() editor.putString(getString(R.string.name), strName) editor.commit() strPassword = password.text.toString() editor.putString(getString(R.string.password), strPassword) editor.commit() } else { editor.putString(getString(R.string.checkBox), "False") editor.commit() editor.putString(getString(R.string.name), "") editor.commit() editor.putString(getString(R.string.password), "") editor.commit() } } } private fun checkSharedPreference() { strCheckBox = sharedPreferences.getString(getString(R.string.checkBox), "False").toString() strName = sharedPreferences.getString(getString(R.string.name), "").toString() strPassword = sharedPreferences.getString(getString(R.string.password), "").toString() name.setText(strName) password.setText(strPassword) checkBox.isChecked = strCheckBox == "True" } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
[ { "code": null, "e": 1143, "s": 1062, "text": "This example demonstrates how to use shared preferences in Android using Kotlin." }, { "code": null, "e": 1272, "s": 1143, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1337, "s": 1272, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 3240, "s": 1337, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n <RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:text=\"Tutorials Point\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/holo_green_dark\"\n android:textSize=\"32sp\"\n android:textStyle=\"bold\" />\n <EditText\n android:id=\"@+id/etName\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@+id/textView\"\n android:layout_centerInParent=\"true\"\n android:layout_marginTop=\"75dp\"\n android:ems=\"10\"\n android:hint=\"Enter Name\" />\n <EditText\n android:id=\"@+id/etPassword\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/etName\"\n android:layout_centerHorizontal=\"true\"\n android:ems=\"10\"\n android:hint=\"Enter Password\" />\n <Button\n android:id=\"@+id/btnLogin\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/etPassword\"\n android:layout_alignStart=\"@id/etPassword\"\n android:layout_marginTop=\"10dp\"\n android:text=\"Login\" />\n <CheckBox\n android:id=\"@+id/checkBox\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/btnLogin\"\n android:layout_alignStart=\"@id/btnLogin\"\n android:layout_marginTop=\"10dp\"\n android:text=\"Remember my credentials\" />\n</RelativeLayout>" }, { "code": null, "e": 3295, "s": 3240, "text": "Step 3 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 5689, "s": 3295, "text": "import android.content.SharedPreferences\nimport android.os.Bundle\nimport android.preference.PreferenceManager\nimport android.widget.Button\nimport android.widget.CheckBox\nimport android.widget.EditText\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n private lateinit var sharedPreferences: SharedPreferences\n private lateinit var editor: SharedPreferences.Editor\n private lateinit var name: EditText\n private lateinit var password: EditText\n private lateinit var button: Button\n private lateinit var checkBox: CheckBox\n private lateinit var strName: String\n private lateinit var strPassword: String\n private lateinit var strCheckBox: String\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n name = findViewById(R.id.etName)\n password = findViewById(R.id.etPassword)\n button = findViewById(R.id.btnLogin)\n checkBox = findViewById(R.id.checkBox)\n sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)\n editor = sharedPreferences.edit()\n checkSharedPreference()\n button.setOnClickListener {\n if (checkBox.isChecked) {\n editor.putString(getString(R.string.checkBox), \"True\")\n editor.apply()\n strName = name.text.toString()\n editor.putString(getString(R.string.name), strName)\n editor.commit()\n strPassword = password.text.toString()\n editor.putString(getString(R.string.password), strPassword)\n editor.commit()\n } else {\n editor.putString(getString(R.string.checkBox), \"False\")\n editor.commit()\n editor.putString(getString(R.string.name), \"\")\n editor.commit()\n editor.putString(getString(R.string.password), \"\")\n editor.commit()\n }\n }\n }\n private fun checkSharedPreference() {\n strCheckBox = sharedPreferences.getString(getString(R.string.checkBox), \"False\").toString()\n strName = sharedPreferences.getString(getString(R.string.name), \"\").toString()\n strPassword = sharedPreferences.getString(getString(R.string.password), \"\").toString()\n name.setText(strName)\n password.setText(strPassword)\n checkBox.isChecked = strCheckBox == \"True\"\n }\n}" }, { "code": null, "e": 5744, "s": 5689, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 6415, "s": 5744, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 6763, "s": 6415, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen" } ]
Find possible numbers in array that can sum to a target value JavaScript
We are required to write a JavaScript function that takes in an array of numbers as the first argument and a single number as the second argument. The function should pick such elements from the array that when added gives the sum specified by the second argument of the array. The function should return an array of all such subarrays of numbers that when added gives the required sum. Note that the order is not important and if needed we have the liberty to use one number more than once in order to generate the sum. For example − If the input array and the sum are − const arr = [14, 6, 10]; const sum = 40; Then the output should be − const output = [ [ 14, 14, 6, 6 ], [ 14, 6, 10, 10 ], [ 6, 6, 6, 6, 6, 10 ], [ 10, 10, 10, 10 ] ]; const arr = [14, 6, 10]; const sum = 40; const findSum = (arr, sum) => { const res = []; const search = (index, part = []) => { const s = part.reduce((a, b) => a + b, 0); if (s === sum){ res.push(part) }; if (s >= sum || index >= arr.length){ return; }; search(index, part.concat(arr[index])); search(index + 1, part); }; search(0); return res; } console.log(findSum(arr, sum)); This will produce the following output − [ [ 14, 14, 6, 6 ], [ 14, 6, 10, 10 ], [ 6, 6, 6, 6, 6, 10 ], [ 10, 10, 10, 10 ] ]
[ { "code": null, "e": 1209, "s": 1062, "text": "We are required to write a JavaScript function that takes in an array of numbers as the first argument and a single number as the second argument." }, { "code": null, "e": 1449, "s": 1209, "text": "The function should pick such elements from the array that when added gives the sum specified by the second argument of the array. The function should return an array of all such subarrays of numbers that when added gives the required sum." }, { "code": null, "e": 1583, "s": 1449, "text": "Note that the order is not important and if needed we have the liberty to use one number more than once in order to generate the sum." }, { "code": null, "e": 1597, "s": 1583, "text": "For example −" }, { "code": null, "e": 1634, "s": 1597, "text": "If the input array and the sum are −" }, { "code": null, "e": 1675, "s": 1634, "text": "const arr = [14, 6, 10];\nconst sum = 40;" }, { "code": null, "e": 1703, "s": 1675, "text": "Then the output should be −" }, { "code": null, "e": 1814, "s": 1703, "text": "const output = [\n [ 14, 14, 6, 6 ],\n [ 14, 6, 10, 10 ],\n [ 6, 6, 6, 6, 6, 10 ],\n [ 10, 10, 10, 10 ]\n];" }, { "code": null, "e": 2259, "s": 1814, "text": "const arr = [14, 6, 10];\nconst sum = 40;\nconst findSum = (arr, sum) => {\n const res = [];\n const search = (index, part = []) => {\n const s = part.reduce((a, b) => a + b, 0);\n if (s === sum){\n res.push(part)\n };\n if (s >= sum || index >= arr.length){ return; };\n search(index, part.concat(arr[index]));\n search(index + 1, part);\n };\n search(0);\n return res;\n}\nconsole.log(findSum(arr, sum));" }, { "code": null, "e": 2300, "s": 2259, "text": "This will produce the following output −" }, { "code": null, "e": 2395, "s": 2300, "text": "[\n [ 14, 14, 6, 6 ],\n [ 14, 6, 10, 10 ],\n [ 6, 6, 6, 6, 6, 10 ],\n [ 10, 10, 10, 10 ]\n]" } ]
Reduce the fraction to its lowest form in C++
Given two integers Num1 and Num2 as input. The integers can be represented as fraction Num1/Num2. The goal is to reduce this fraction to its lowest form. We will calculate the greatest common divisor of both numbers. We will calculate the greatest common divisor of both numbers. Divide both numbers by that gcd Divide both numbers by that gcd Set both variables as quotient after division. Set both variables as quotient after division. Lowest fraction will be Num1/Num2. Lowest fraction will be Num1/Num2. Input − Num1=22 Num2=10 Output − Num1 = 11 Num2 = 5 Lowest Fraction : 11/5 Explanation− GCD of 22 and 10 is 2. 22/2=11 and 10/2=5 Lowest fraction is 11/5 Input− Num1=36 Num2=40 Output− Num1 = 9 Num2 = 10 Lowest Fraction : 9/10 Explanation − GCD of 36 and 40 is 4. 40/4=10 and 36/4=9 Lowest fraction is 9/10 In this approach we will first calculate the GCD of input numbers using a recursive approach. Divide both numbers by GCD and obtain quotients. These quotients will be part of the lowest fraction. Take the input variables Num1 and Num2. Take the input variables Num1 and Num2. Function findGCD(int a, int b) takes num1 and num2 and returns the gcd of both. Function findGCD(int a, int b) takes num1 and num2 and returns the gcd of both. If b is 0 return a else return findGCD(b,a%b). If b is 0 return a else return findGCD(b,a%b). Function lowestFraction(int num1, int num2) takes both numbers as input and prints the lowest fraction. Function lowestFraction(int num1, int num2) takes both numbers as input and prints the lowest fraction. Take variable denom for gcd. Take variable denom for gcd. Set num1=num1/denom and num2=num2/denom. Set num1=num1/denom and num2=num2/denom. Print num1 and num2. Print num1 and num2. Print the lowest fraction as num1/num2. Print the lowest fraction as num1/num2. #include <bits/stdc++.h> using namespace std; int findGCD(int a, int b) { if (b == 0) return a; return findGCD(b, a % b); } void lowestFraction(int num1, int num2){ int denom; denom = findGCD(num1,num2); num1/=denom; num2/=denom; cout<< "Num1 = " << num1<<endl; cout<< "Num2 = " << num2<<endl; cout<< "Lowest Fraction : "<<num1<<"/"<<num2; } int main(){ int Num1 = 14; int Num2 = 8; lowestFraction(Num1,Num2); return 0; } If we run the above code it will generate the following Output Num1 = 7 Num2 = 4 Lowest Fraction : 7/4
[ { "code": null, "e": 1216, "s": 1062, "text": "Given two integers Num1 and Num2 as input. The integers can be represented as fraction Num1/Num2. The goal is to reduce this fraction to its lowest form." }, { "code": null, "e": 1279, "s": 1216, "text": "We will calculate the greatest common divisor of both numbers." }, { "code": null, "e": 1342, "s": 1279, "text": "We will calculate the greatest common divisor of both numbers." }, { "code": null, "e": 1374, "s": 1342, "text": "Divide both numbers by that gcd" }, { "code": null, "e": 1406, "s": 1374, "text": "Divide both numbers by that gcd" }, { "code": null, "e": 1453, "s": 1406, "text": "Set both variables as quotient after division." }, { "code": null, "e": 1500, "s": 1453, "text": "Set both variables as quotient after division." }, { "code": null, "e": 1535, "s": 1500, "text": "Lowest fraction will be Num1/Num2." }, { "code": null, "e": 1570, "s": 1535, "text": "Lowest fraction will be Num1/Num2." }, { "code": null, "e": 1594, "s": 1570, "text": "Input − Num1=22 Num2=10" }, { "code": null, "e": 1622, "s": 1594, "text": "Output − Num1 = 11 Num2 = 5" }, { "code": null, "e": 1645, "s": 1622, "text": "Lowest Fraction : 11/5" }, { "code": null, "e": 1681, "s": 1645, "text": "Explanation− GCD of 22 and 10 is 2." }, { "code": null, "e": 1700, "s": 1681, "text": "22/2=11 and 10/2=5" }, { "code": null, "e": 1724, "s": 1700, "text": "Lowest fraction is 11/5" }, { "code": null, "e": 1747, "s": 1724, "text": "Input− Num1=36 Num2=40" }, { "code": null, "e": 1774, "s": 1747, "text": "Output− Num1 = 9 Num2 = 10" }, { "code": null, "e": 1797, "s": 1774, "text": "Lowest Fraction : 9/10" }, { "code": null, "e": 1834, "s": 1797, "text": "Explanation − GCD of 36 and 40 is 4." }, { "code": null, "e": 1853, "s": 1834, "text": "40/4=10 and 36/4=9" }, { "code": null, "e": 1877, "s": 1853, "text": "Lowest fraction is 9/10" }, { "code": null, "e": 2073, "s": 1877, "text": "In this approach we will first calculate the GCD of input numbers using a recursive approach. Divide both numbers by GCD and obtain quotients. These quotients will be part of the lowest fraction." }, { "code": null, "e": 2113, "s": 2073, "text": "Take the input variables Num1 and Num2." }, { "code": null, "e": 2153, "s": 2113, "text": "Take the input variables Num1 and Num2." }, { "code": null, "e": 2233, "s": 2153, "text": "Function findGCD(int a, int b) takes num1 and num2 and returns the gcd of both." }, { "code": null, "e": 2313, "s": 2233, "text": "Function findGCD(int a, int b) takes num1 and num2 and returns the gcd of both." }, { "code": null, "e": 2360, "s": 2313, "text": "If b is 0 return a else return findGCD(b,a%b)." }, { "code": null, "e": 2407, "s": 2360, "text": "If b is 0 return a else return findGCD(b,a%b)." }, { "code": null, "e": 2511, "s": 2407, "text": "Function lowestFraction(int num1, int num2) takes both numbers as input and prints the lowest fraction." }, { "code": null, "e": 2615, "s": 2511, "text": "Function lowestFraction(int num1, int num2) takes both numbers as input and prints the lowest fraction." }, { "code": null, "e": 2644, "s": 2615, "text": "Take variable denom for gcd." }, { "code": null, "e": 2673, "s": 2644, "text": "Take variable denom for gcd." }, { "code": null, "e": 2714, "s": 2673, "text": "Set num1=num1/denom and num2=num2/denom." }, { "code": null, "e": 2755, "s": 2714, "text": "Set num1=num1/denom and num2=num2/denom." }, { "code": null, "e": 2776, "s": 2755, "text": "Print num1 and num2." }, { "code": null, "e": 2797, "s": 2776, "text": "Print num1 and num2." }, { "code": null, "e": 2837, "s": 2797, "text": "Print the lowest fraction as num1/num2." }, { "code": null, "e": 2877, "s": 2837, "text": "Print the lowest fraction as num1/num2." }, { "code": null, "e": 3374, "s": 2877, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint findGCD(int a, int b) {\n if (b == 0)\n return a;\n return findGCD(b, a % b);\n }\n void lowestFraction(int num1, int num2){\n int denom;\n denom = findGCD(num1,num2);\n num1/=denom;\n num2/=denom;\n cout<< \"Num1 = \" << num1<<endl;\n cout<< \"Num2 = \" << num2<<endl;\n cout<< \"Lowest Fraction : \"<<num1<<\"/\"<<num2;\n}\nint main(){\n int Num1 = 14;\n int Num2 = 8;\n lowestFraction(Num1,Num2);\n return 0;\n}" }, { "code": null, "e": 3437, "s": 3374, "text": "If we run the above code it will generate the following Output" }, { "code": null, "e": 3477, "s": 3437, "text": "Num1 = 7\nNum2 = 4\nLowest Fraction : 7/4" } ]
Evaluation of Prefix Expressions in C++
In this article, we will discuss the evaluation of prefix Expression. In this notation, operator is prefixed to operands, i.e. operator is written ahead of operands. For example, +ab. This is equivalent to its infix notation a + b. Prefix notation is also known as Polish Notation. For more read. * + 6 9 - 3 1 Prefix expressions are evaluated faster than infix expressions. Also, there are no brackets in prefix expressions which make it evaluate quicker. The evaluation of prefix expression requires a stack data structure. We will push the operators in the stack and then solve the expression. We will visit each element of the expression one by one. If the current element is an operand, we will push it to the stack. And if it is an operator, we will pop two operands, perform the operation, operand operator operand and then push the result back to the stack. Step 1: Start from the last element of the expression. Step 2: check the current element. Step 2.1: if it is an operand, push it to the stack.Step 2.2: If it is an operator, pop two operands from the stack. Perform the operation and push the elements back to the stack. Step 3: Do this till all the elements of the expression are traversed and return the top of stack which will be the result of the operation. Prefix Expression : * + 6 9 - 3 1 Iteration : 1 Element scanned => 1 Operation => push to stackStack => 1 Iteration : 2 Element scanned => 3 Operation => push to stackStack => 3 , 1 Iteration : 3 Element scanned => - Operation => pop two from stack, perform operation and push back the result. 3 - 1 = 2Stack => 2 Iteration : 4 Element scanned => 9 Operation => push to stackStack => 9 , 2 Iteration : 5 Element scanned => 6 Operation => push to stackStack => 6, 9 , 2 Iteration : 6 Element scanned => + Operation => pop two from stack, perform operation and push back the result. 6 + 9 = 15 Stack => 15 , 2 Iteration : 7 Element scanned => * Operation => pop two from stack, perform operation and push back the result. 15 * 2 = 30Stack => 30 End => return top of stack, result = 30. Live Demo #include <bits/stdc++.h> using namespace std; double evaluatePrefix(string prefixExp) { stack<double> operendStack; int size = prefixExp.size() - 1; for (int i = size; i >= 0; i--) { if (isdigit(prefixExp[i])) operendStack.push(prefixExp[i] - '0'); else { double o1 = operendStack.top(); operendStack.pop(); double o2 = operendStack.top(); operendStack.pop(); if( prefixExp[i] == '+') operendStack.push(o1 + o2); else if( prefixExp[i] == '-') operendStack.push(o1 - o2); else if( prefixExp[i] == '*') operendStack.push(o1 * o2); else if( prefixExp[i] == '/') operendStack.push(o1 / o2); else{ cout<<"Invalid Expression"; return -1; } } } return operendStack.top(); } int main() { string prefixExp = "*+69-31"; cout<<"The result of evaluation of expression "<<prefixExp<<" is "<<evaluatePrefix(prefixExp); return 0; } The result of evaluation of expression *+69-31 is 30
[ { "code": null, "e": 1133, "s": 1062, "text": "In this article, we will discuss the evaluation of prefix Expression. " }, { "code": null, "e": 1345, "s": 1133, "text": "In this notation, operator is prefixed to operands, i.e. operator is written ahead of operands. For example, +ab. This is equivalent to its infix notation a + b. Prefix notation is also known as Polish Notation." }, { "code": null, "e": 1360, "s": 1345, "text": "For more read." }, { "code": null, "e": 1374, "s": 1360, "text": "* + 6 9 - 3 1" }, { "code": null, "e": 1520, "s": 1374, "text": "Prefix expressions are evaluated faster than infix expressions. Also, there are no brackets in prefix expressions which make it evaluate quicker." }, { "code": null, "e": 1660, "s": 1520, "text": "The evaluation of prefix expression requires a stack data structure. We will push the operators in the stack and then solve the expression." }, { "code": null, "e": 1929, "s": 1660, "text": "We will visit each element of the expression one by one. If the current element is an operand, we will push it to the stack. And if it is an operator, we will pop two operands, perform the operation, operand operator operand and then push the result back to the stack." }, { "code": null, "e": 1984, "s": 1929, "text": "Step 1: Start from the last element of the expression." }, { "code": null, "e": 2019, "s": 1984, "text": "Step 2: check the current element." }, { "code": null, "e": 2199, "s": 2019, "text": "Step 2.1: if it is an operand, push it to the stack.Step 2.2: If it is an operator, pop two operands from the stack. Perform the operation and push the elements back to the stack." }, { "code": null, "e": 2340, "s": 2199, "text": "Step 3: Do this till all the elements of the expression are traversed and return the top of stack which will be the result of the operation." }, { "code": null, "e": 2361, "s": 2340, "text": "Prefix Expression : " }, { "code": null, "e": 2375, "s": 2361, "text": "* + 6 9 - 3 1" }, { "code": null, "e": 2389, "s": 2375, "text": "Iteration : 1" }, { "code": null, "e": 2411, "s": 2389, "text": "Element scanned => 1" }, { "code": null, "e": 2448, "s": 2411, "text": "Operation => push to stackStack => 1" }, { "code": null, "e": 2462, "s": 2448, "text": "Iteration : 2" }, { "code": null, "e": 2484, "s": 2462, "text": "Element scanned => 3" }, { "code": null, "e": 2525, "s": 2484, "text": "Operation => push to stackStack => 3 , 1" }, { "code": null, "e": 2539, "s": 2525, "text": "Iteration : 3" }, { "code": null, "e": 2561, "s": 2539, "text": "Element scanned => -" }, { "code": null, "e": 2638, "s": 2561, "text": "Operation => pop two from stack, perform operation and push back the result." }, { "code": null, "e": 2658, "s": 2638, "text": "3 - 1 = 2Stack => 2" }, { "code": null, "e": 2672, "s": 2658, "text": "Iteration : 4" }, { "code": null, "e": 2694, "s": 2672, "text": "Element scanned => 9" }, { "code": null, "e": 2735, "s": 2694, "text": "Operation => push to stackStack => 9 , 2" }, { "code": null, "e": 2749, "s": 2735, "text": "Iteration : 5" }, { "code": null, "e": 2771, "s": 2749, "text": "Element scanned => 6" }, { "code": null, "e": 2815, "s": 2771, "text": "Operation => push to stackStack => 6, 9 , 2" }, { "code": null, "e": 2829, "s": 2815, "text": "Iteration : 6" }, { "code": null, "e": 2851, "s": 2829, "text": "Element scanned => +" }, { "code": null, "e": 2928, "s": 2851, "text": "Operation => pop two from stack, perform operation and push back the result." }, { "code": null, "e": 2939, "s": 2928, "text": "6 + 9 = 15" }, { "code": null, "e": 2956, "s": 2939, "text": "Stack => 15 , 2" }, { "code": null, "e": 2970, "s": 2956, "text": "Iteration : 7" }, { "code": null, "e": 2992, "s": 2970, "text": "Element scanned => *" }, { "code": null, "e": 3069, "s": 2992, "text": "Operation => pop two from stack, perform operation and push back the result." }, { "code": null, "e": 3092, "s": 3069, "text": "15 * 2 = 30Stack => 30" }, { "code": null, "e": 3133, "s": 3092, "text": "End => return top of stack, result = 30." }, { "code": null, "e": 3143, "s": 3133, "text": "Live Demo" }, { "code": null, "e": 4184, "s": 3143, "text": "#include <bits/stdc++.h>\nusing namespace std;\n\ndouble evaluatePrefix(string prefixExp) {\n \n stack<double> operendStack;\n int size = prefixExp.size() - 1;\n \n for (int i = size; i >= 0; i--) {\n\n if (isdigit(prefixExp[i]))\n operendStack.push(prefixExp[i] - '0');\n else {\n double o1 = operendStack.top();\n operendStack.pop();\n double o2 = operendStack.top();\n operendStack.pop();\n if( prefixExp[i] == '+')\n operendStack.push(o1 + o2);\n else if( prefixExp[i] == '-')\n operendStack.push(o1 - o2);\n else if( prefixExp[i] == '*')\n operendStack.push(o1 * o2);\n else if( prefixExp[i] == '/')\n operendStack.push(o1 / o2);\n else{\n cout<<\"Invalid Expression\";\n return -1;\n }\n }\n }\n return operendStack.top();\n}\n\nint main()\n{\n string prefixExp = \"*+69-31\";\n cout<<\"The result of evaluation of expression \"<<prefixExp<<\" is \"<<evaluatePrefix(prefixExp);\n return 0;\n}" }, { "code": null, "e": 4237, "s": 4184, "text": "The result of evaluation of expression *+69-31 is 30" } ]
Calculating distance between two geo-locations in Python | by Ashutosh Bhardwaj | Towards Data Science
A few months back I was working on a freelance project of visualizing geo-location data(i.e. latitude and longitude) in which I have to visualize central facilities and customers location on a map. As per one of the client’s requirements, I have to find all the customers locations that are within the range of 3 km from different facilities. To do this I have to calculate the distance between all the locations. It was the first time I was working with raw coordinates, so I tried a naive attempt to calculate distance using Euclidean distance, but sooner realized that this approach was wrong. Euclidean Distance works for the flat surface like a Cartesian plain however, Earth is not flat. So we have to use a special type of formula known as Haversine Distance. Haversine Distance can be defined as the angular distance between two locations on the Earth’s surface. Haversine distance can be calculated as: Looks Daunting, yes it would be daunting if you have to apply it using raw python code, but thanks to the python’s vibrant developers community that we have a dedicated library to calculate Haversine distance called haversine(one of the perks of using python). That’s it with the introduction lets get started with its implementation: Step 1: Installing “haversine” To install haversine type following command in jupyter notebook. !pip install haversine If you are installing through anaconda prompt remove the “!” mark from the above command. Step 2: Importing library After installing the library import it import haversine as hs Step 3: Calculating distance between two locations loc1=(28.426846,77.088834)loc2=(28.394231,77.050308)hs.haversine(loc1,loc2) Output: 5.229712941541709 By default the haversine function returns distance in km. If you want to change the unit of distance to miles or meters you can use unit parameter of haversine function as shown below: from haversine import Unit#To calculate distance in meters hs.haversine(loc1,loc2,unit=Unit.METERS) Output: 5229.7129415417085 #To calculate distance in miles hs.haversine(loc1,loc2,unit=Unit.MILES) Output: 3.2495929643035977 Similarly you can calculate distance in inches also. Calculating distance between two locations is a basic requirement if you are working with raw location data. It not only helps you to visualize better but it also provides an edge to your Machine learning algorithm. It might give an edge to your model and improves its overall efficiency by adding a new dimension “distance”. This is the output of the project that i mentioned earlier in this article: If you want to see the whole code you can visit my github page: https://github.com/ashutoshb418/Foodies-Visualization
[ { "code": null, "e": 769, "s": 172, "text": "A few months back I was working on a freelance project of visualizing geo-location data(i.e. latitude and longitude) in which I have to visualize central facilities and customers location on a map. As per one of the client’s requirements, I have to find all the customers locations that are within the range of 3 km from different facilities. To do this I have to calculate the distance between all the locations. It was the first time I was working with raw coordinates, so I tried a naive attempt to calculate distance using Euclidean distance, but sooner realized that this approach was wrong." }, { "code": null, "e": 939, "s": 769, "text": "Euclidean Distance works for the flat surface like a Cartesian plain however, Earth is not flat. So we have to use a special type of formula known as Haversine Distance." }, { "code": null, "e": 1043, "s": 939, "text": "Haversine Distance can be defined as the angular distance between two locations on the Earth’s surface." }, { "code": null, "e": 1084, "s": 1043, "text": "Haversine distance can be calculated as:" }, { "code": null, "e": 1345, "s": 1084, "text": "Looks Daunting, yes it would be daunting if you have to apply it using raw python code, but thanks to the python’s vibrant developers community that we have a dedicated library to calculate Haversine distance called haversine(one of the perks of using python)." }, { "code": null, "e": 1419, "s": 1345, "text": "That’s it with the introduction lets get started with its implementation:" }, { "code": null, "e": 1450, "s": 1419, "text": "Step 1: Installing “haversine”" }, { "code": null, "e": 1515, "s": 1450, "text": "To install haversine type following command in jupyter notebook." }, { "code": null, "e": 1538, "s": 1515, "text": "!pip install haversine" }, { "code": null, "e": 1628, "s": 1538, "text": "If you are installing through anaconda prompt remove the “!” mark from the above command." }, { "code": null, "e": 1654, "s": 1628, "text": "Step 2: Importing library" }, { "code": null, "e": 1693, "s": 1654, "text": "After installing the library import it" }, { "code": null, "e": 1716, "s": 1693, "text": "import haversine as hs" }, { "code": null, "e": 1767, "s": 1716, "text": "Step 3: Calculating distance between two locations" }, { "code": null, "e": 1843, "s": 1767, "text": "loc1=(28.426846,77.088834)loc2=(28.394231,77.050308)hs.haversine(loc1,loc2)" }, { "code": null, "e": 1869, "s": 1843, "text": "Output: 5.229712941541709" }, { "code": null, "e": 2054, "s": 1869, "text": "By default the haversine function returns distance in km. If you want to change the unit of distance to miles or meters you can use unit parameter of haversine function as shown below:" }, { "code": null, "e": 2154, "s": 2054, "text": "from haversine import Unit#To calculate distance in meters hs.haversine(loc1,loc2,unit=Unit.METERS)" }, { "code": null, "e": 2181, "s": 2154, "text": "Output: 5229.7129415417085" }, { "code": null, "e": 2253, "s": 2181, "text": "#To calculate distance in miles hs.haversine(loc1,loc2,unit=Unit.MILES)" }, { "code": null, "e": 2280, "s": 2253, "text": "Output: 3.2495929643035977" }, { "code": null, "e": 2333, "s": 2280, "text": "Similarly you can calculate distance in inches also." }, { "code": null, "e": 2659, "s": 2333, "text": "Calculating distance between two locations is a basic requirement if you are working with raw location data. It not only helps you to visualize better but it also provides an edge to your Machine learning algorithm. It might give an edge to your model and improves its overall efficiency by adding a new dimension “distance”." }, { "code": null, "e": 2735, "s": 2659, "text": "This is the output of the project that i mentioned earlier in this article:" } ]
Encoding and Decoding Custom Objects in Python-JSON - GeeksforGeeks
10 Jul, 2020 JSON as we know stands for JavaScript Object Notation. It is a lightweight data-interchange format and has become the most popular medium of exchanging data over the web. The reason behind its popularity is that it is both human-readable and easy for machines to parse and generate. Also, it’s the most widely used format for the REST APIs. Note: For more information, refer to Read, Write and Parse JSON using Python Python provides a built-in json library to deal with JSON objects. All you need is to import the JSON module using the following line in your Python program and start using its functionality. import json Now the JSON module provides a lot of functionality and we’re going to discuss only 2 methods out of them. They are dumps and loads. The process of converting a python object to a json one is called JSON serialization or encoding and the reverse process i.e. converting json object to Python one is called deserialization or decoding For encoding, we use json.dumps() and for decoding, we’ll use json.loads(). So it is obvious that the dumps method will convert a python object to a serialized JSON string and the loads method will parse the Python object from a serialized JSON string. Note: It is worth mentioning here that the JSON object which is created during serialization is just a Python string, that’s why you’ll find the terms “JSON object” and “JSON string” used interchangeably in this article Also it is important to note that a JSON object corresponds to a Dictionary in Python. So when you use loads method, a Python dictionary is returned by default (unless you change this behaviour as discussed in the custom decoding section of this article) Example: import json # A basic python dictionarypy_object = {"c": 0, "b": 0, "a": 0} # Encodingjson_string = json.dumps(py_object)print(json_string)print(type(json_string)) # Decoding JSONpy_obj = json.loads(json_string) print()print(py_obj)print(type(py_obj)) Output: {"c": 0, "b": 0, "a": 0} <class 'str'> {'c': 0, 'b': 0, 'a': 0} <class 'dict'> Although what we saw above is a very simple example. But have you wondered what happens in the case of custom objects? In that case he above code will not work and we will get an error something like – TypeError: Object of type SampleClass is not JSON serializable. So what to do? Don’t worry we will get to get in the below section. In such cases, we need to put more efforts to make them serialize. Let’s see how we can do that. Suppose we have a user-defined class Student and we want to make it JSON serializable. The simplest way of doing that is to define a method in our class that will provide the JSON version of our class’ instance. Example: import json class Student: def __init__(self, name, roll_no, address): self.name = name self.roll_no = roll_no self.address = address def to_json(self): ''' convert the instance of this class to json ''' return json.dumps(self, indent = 4, default=lambda o: o.__dict__) class Address: def __init__(self, city, street, pin): self.city = city self.street = street self.pin = pin address = Address("Bulandshahr", "Adarsh Nagar", "203001")student = Student("Raju", 53, address) # Encodingstudent_json = student.to_json()print(student_json)print(type(student_json)) # Decodingstudent = json.loads(student_json)print(student)print(type(student)) Output: {“name”: “Raju”,“roll_no”: 53,“address”: {“city”: “Bulandshahr”,“street”: “Adarsh Nagar”,“pin”: “203001”}}<class ‘str’> {‘name’: ‘Raju’, ‘roll_no’: 53, ‘address’: {‘city’: ‘Bulandshahr’, ‘street’: ‘Adarsh Nagar’, ‘pin’: ‘203001’}}<class ‘dict’> Another way of achieving this is to create a new class that will extend the JSONEncoder and then using that class as an argument to the dumps method. Example: import jsonfrom json import JSONEncoder class Student: def __init__(self, name, roll_no, address): self.name = name self.roll_no = roll_no self.address = address class Address: def __init__(self, city, street, pin): self.city = city self.street = street self.pin = pin class EncodeStudent(JSONEncoder): def default(self, o): return o.__dict__ address = Address("Bulandshahr", "Adarsh Nagar", "203001")student = Student("Raju", 53, address) # Encoding custom object to json# using cls(class) argument of# dumps methodstudent_JSON = json.dumps(student, indent = 4, cls = EncodeStudent)print(student_JSON)print(type(student_JSON)) # Decodingstudent = json.loads(student_JSON)print()print(student)print(type(student)) Output: {“name”: “Raju”,“roll_no”: 53,“address”: {“city”: “Bulandshahr”,“street”: “Adarsh Nagar”,“pin”: “203001”}}<class ‘str’> {‘name’: ‘Raju’, ‘roll_no’: 53, ‘address’: {‘city’: ‘Bulandshahr’, ‘street’: ‘Adarsh Nagar’, ‘pin’: ‘203001’}}<class ‘dict’> For Custom Decoding, if we want to convert the JSON into some other Python object (i.e. not the default dictionary) there is a very simple way of doing that which is using the object_hook parameter of the loads method. All we need to do is to define a method that will define how do we want to process the data and then send that method as the object_hook argument to the loads method, see in given code. Also, the return type of load will no longer be the Python dictionary. Whatever is the return type of the method we’ll pass in as object_hook, it will also become the return type of loads method. This means that in following example, complex number will be the return type. import json def as_complex(dct): if '__complex__' in dct: return complex(dct['real'], dct['imag']) return dct res = json.loads('{"__complex__": true, "real": 1, "imag": 2}', object_hook = as_complex)print(res)print(type(res)) Output: (1+2j) <class 'complex'> Python-json Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Defaultdict in Python Python | os.path.join() method Python | Get unique values from a list Selecting rows in pandas DataFrame based on conditions Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24318, "s": 24290, "text": "\n10 Jul, 2020" }, { "code": null, "e": 24659, "s": 24318, "text": "JSON as we know stands for JavaScript Object Notation. It is a lightweight data-interchange format and has become the most popular medium of exchanging data over the web. The reason behind its popularity is that it is both human-readable and easy for machines to parse and generate. Also, it’s the most widely used format for the REST APIs." }, { "code": null, "e": 24736, "s": 24659, "text": "Note: For more information, refer to Read, Write and Parse JSON using Python" }, { "code": null, "e": 24928, "s": 24736, "text": "Python provides a built-in json library to deal with JSON objects. All you need is to import the JSON module using the following line in your Python program and start using its functionality." }, { "code": null, "e": 24940, "s": 24928, "text": "import json" }, { "code": null, "e": 25274, "s": 24940, "text": "Now the JSON module provides a lot of functionality and we’re going to discuss only 2 methods out of them. They are dumps and loads. The process of converting a python object to a json one is called JSON serialization or encoding and the reverse process i.e. converting json object to Python one is called deserialization or decoding" }, { "code": null, "e": 25527, "s": 25274, "text": "For encoding, we use json.dumps() and for decoding, we’ll use json.loads(). So it is obvious that the dumps method will convert a python object to a serialized JSON string and the loads method will parse the Python object from a serialized JSON string." }, { "code": null, "e": 25533, "s": 25527, "text": "Note:" }, { "code": null, "e": 25747, "s": 25533, "text": "It is worth mentioning here that the JSON object which is created during serialization is just a Python string, that’s why you’ll find the terms “JSON object” and “JSON string” used interchangeably in this article" }, { "code": null, "e": 26002, "s": 25747, "text": "Also it is important to note that a JSON object corresponds to a Dictionary in Python. So when you use loads method, a Python dictionary is returned by default (unless you change this behaviour as discussed in the custom decoding section of this article)" }, { "code": null, "e": 26011, "s": 26002, "text": "Example:" }, { "code": "import json # A basic python dictionarypy_object = {\"c\": 0, \"b\": 0, \"a\": 0} # Encodingjson_string = json.dumps(py_object)print(json_string)print(type(json_string)) # Decoding JSONpy_obj = json.loads(json_string) print()print(py_obj)print(type(py_obj))", "e": 26267, "s": 26011, "text": null }, { "code": null, "e": 26275, "s": 26267, "text": "Output:" }, { "code": null, "e": 26355, "s": 26275, "text": "{\"c\": 0, \"b\": 0, \"a\": 0}\n<class 'str'>\n\n{'c': 0, 'b': 0, 'a': 0}\n<class 'dict'>" }, { "code": null, "e": 26689, "s": 26355, "text": "Although what we saw above is a very simple example. But have you wondered what happens in the case of custom objects? In that case he above code will not work and we will get an error something like – TypeError: Object of type SampleClass is not JSON serializable. So what to do? Don’t worry we will get to get in the below section." }, { "code": null, "e": 26998, "s": 26689, "text": "In such cases, we need to put more efforts to make them serialize. Let’s see how we can do that. Suppose we have a user-defined class Student and we want to make it JSON serializable. The simplest way of doing that is to define a method in our class that will provide the JSON version of our class’ instance." }, { "code": null, "e": 27007, "s": 26998, "text": "Example:" }, { "code": "import json class Student: def __init__(self, name, roll_no, address): self.name = name self.roll_no = roll_no self.address = address def to_json(self): ''' convert the instance of this class to json ''' return json.dumps(self, indent = 4, default=lambda o: o.__dict__) class Address: def __init__(self, city, street, pin): self.city = city self.street = street self.pin = pin address = Address(\"Bulandshahr\", \"Adarsh Nagar\", \"203001\")student = Student(\"Raju\", 53, address) # Encodingstudent_json = student.to_json()print(student_json)print(type(student_json)) # Decodingstudent = json.loads(student_json)print(student)print(type(student))", "e": 27744, "s": 27007, "text": null }, { "code": null, "e": 27752, "s": 27744, "text": "Output:" }, { "code": null, "e": 27872, "s": 27752, "text": "{“name”: “Raju”,“roll_no”: 53,“address”: {“city”: “Bulandshahr”,“street”: “Adarsh Nagar”,“pin”: “203001”}}<class ‘str’>" }, { "code": null, "e": 27997, "s": 27872, "text": "{‘name’: ‘Raju’, ‘roll_no’: 53, ‘address’: {‘city’: ‘Bulandshahr’, ‘street’: ‘Adarsh Nagar’, ‘pin’: ‘203001’}}<class ‘dict’>" }, { "code": null, "e": 28147, "s": 27997, "text": "Another way of achieving this is to create a new class that will extend the JSONEncoder and then using that class as an argument to the dumps method." }, { "code": null, "e": 28156, "s": 28147, "text": "Example:" }, { "code": "import jsonfrom json import JSONEncoder class Student: def __init__(self, name, roll_no, address): self.name = name self.roll_no = roll_no self.address = address class Address: def __init__(self, city, street, pin): self.city = city self.street = street self.pin = pin class EncodeStudent(JSONEncoder): def default(self, o): return o.__dict__ address = Address(\"Bulandshahr\", \"Adarsh Nagar\", \"203001\")student = Student(\"Raju\", 53, address) # Encoding custom object to json# using cls(class) argument of# dumps methodstudent_JSON = json.dumps(student, indent = 4, cls = EncodeStudent)print(student_JSON)print(type(student_JSON)) # Decodingstudent = json.loads(student_JSON)print()print(student)print(type(student))", "e": 28981, "s": 28156, "text": null }, { "code": null, "e": 28989, "s": 28981, "text": "Output:" }, { "code": null, "e": 29109, "s": 28989, "text": "{“name”: “Raju”,“roll_no”: 53,“address”: {“city”: “Bulandshahr”,“street”: “Adarsh Nagar”,“pin”: “203001”}}<class ‘str’>" }, { "code": null, "e": 29234, "s": 29109, "text": "{‘name’: ‘Raju’, ‘roll_no’: 53, ‘address’: {‘city’: ‘Bulandshahr’, ‘street’: ‘Adarsh Nagar’, ‘pin’: ‘203001’}}<class ‘dict’>" }, { "code": null, "e": 29913, "s": 29234, "text": "For Custom Decoding, if we want to convert the JSON into some other Python object (i.e. not the default dictionary) there is a very simple way of doing that which is using the object_hook parameter of the loads method. All we need to do is to define a method that will define how do we want to process the data and then send that method as the object_hook argument to the loads method, see in given code. Also, the return type of load will no longer be the Python dictionary. Whatever is the return type of the method we’ll pass in as object_hook, it will also become the return type of loads method. This means that in following example, complex number will be the return type." }, { "code": "import json def as_complex(dct): if '__complex__' in dct: return complex(dct['real'], dct['imag']) return dct res = json.loads('{\"__complex__\": true, \"real\": 1, \"imag\": 2}', object_hook = as_complex)print(res)print(type(res))", "e": 30178, "s": 29913, "text": null }, { "code": null, "e": 30186, "s": 30178, "text": "Output:" }, { "code": null, "e": 30211, "s": 30186, "text": "(1+2j)\n<class 'complex'>" }, { "code": null, "e": 30223, "s": 30211, "text": "Python-json" }, { "code": null, "e": 30230, "s": 30223, "text": "Python" }, { "code": null, "e": 30328, "s": 30230, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30360, "s": 30328, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30416, "s": 30360, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30458, "s": 30416, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30500, "s": 30458, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30522, "s": 30500, "text": "Defaultdict in Python" }, { "code": null, "e": 30553, "s": 30522, "text": "Python | os.path.join() method" }, { "code": null, "e": 30592, "s": 30553, "text": "Python | Get unique values from a list" }, { "code": null, "e": 30647, "s": 30592, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 30676, "s": 30647, "text": "Create a directory in Python" } ]
Python Blockchain - Transaction Class
In this chapter, let us create a Transaction class so that a client will be able to send money to somebody. Note that a client can be both a sender or a recipient of the money. When you want to receive money, some other sender will create a transaction and specify your public address in it. We define the initialization of a transaction class as follows − def __init__(self, sender, recipient, value): self.sender = sender self.recipient = recipient self.value = value self.time = datetime.datetime.now() The init method takes three parameters − the sender’s public key, the recipient’s public key, and the amount to be sent. These are stored in the instance variables for use by other methods. Additionally, we create one more variable for storing the time of transaction. Next, we write a utility method called to_dict that combines all the four above-mentioned instance variables in a dictionary object. This is just to put the entire transaction information accessible through a single variable. As you know from the earlier tutorial that the first block in the blockchain is a Genesis block. The Genesis block contains the first transaction initiated by the creator of the blockchain. The identity of this person may be kept a secret like in the case of Bitcoins. So when this first transaction is created, the creator may just send his identity as Genesis. Thus, while creating the dictionary, we check if the sender is Genesis and if so we simply assign some string value to the identity variable; else, we assign the sender’s identity to the identity variable. if self.sender == "Genesis": identity = "Genesis" else: identity = self.sender.identity We construct the dictionary using following line of code return collections.OrderedDict({ 'sender': identity, 'recipient': self.recipient, 'value': self.value, 'time' : self.time}) The entire code for the to_dict method is shown below − def to_dict(self): if self.sender == "Genesis": identity = "Genesis" else: identity = self.sender.identity return collections.OrderedDict({ 'sender': identity, 'recipient': self.recipient, 'value': self.value, 'time' : self.time}) Finally, we will sign this dictionary object using the private key of the sender. As before, we use the built-in PKI with SHA algorithm. The generated signature is decoded to get the ASCII representation for printing and storing it in our blockchain. The sign_transaction method code is shown here − def sign_transaction(self): private_key = self.sender._private_key signer = PKCS1_v1_5.new(private_key) h = SHA.new(str(self.to_dict()).encode('utf8')) return binascii.hexlify(signer.sign(h)).decode('ascii') We will now test this Transaction class. For this purpose, we will create two users, called Dinesh and Ramesh. Dinesh will send 5 TPCoins to Ramesh. For this first we create the clients called Dinesh and Ramesh. Dinesh = Client() Ramesh = Client() Remember that when you instantiate a Client class, the public and private keys unique to the client would be created. As Dinesh is sending payment to Ramesh, he will need the public key of Ramesh which is obtained by using the identity property of the client. Thus, we will create the transaction instance using following code − t = Transaction( Dinesh, Ramesh.identity, 5.0 ) Note that the first parameter is the sender, the second parameter is the public key of the recipient and the third parameter is the amount to be transferred. The sign_transaction method retrieves the sender’s private key from the first parameter for singing the transaction. After the transaction object is created, you will sign it by calling its sign_transaction method. This method returns the generated signature in the printable format. We generate and print the signature using following two lines of code − signature = t.sign_transaction() print (signature) When you run the above code, you will see the output similar to this − 7c7e3c97629b218e9ec6e86b01f9abd8e361fd69e7d373c38420790b655b9abe3b575e343c7 13703ca1aee781acd7157a0624db3d57d7c2f1172730ee3f45af943338157f899965856f6b0 0e34db240b62673ad5a08c8e490f880b568efbc36035cae2e748f1d802d5e8e66298be826f5 c6363dc511222fb2416036ac04eb972 Now as our basic infrastructure of creating a client and a transaction is ready, we will now have multiple clients doing multiple transactions as in a real life situation. 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": 2352, "s": 1995, "text": "In this chapter, let us create a Transaction class so that a client will be able to send money to somebody. Note that a client can be both a sender or a recipient of the money. When you want to receive money, some other sender will create a transaction and specify your public address in it. We define the initialization of a transaction class as follows −" }, { "code": null, "e": 2513, "s": 2352, "text": "def __init__(self, sender, recipient, value):\n self.sender = sender\n self.recipient = recipient\n self.value = value\n self.time = datetime.datetime.now()" }, { "code": null, "e": 2782, "s": 2513, "text": "The init method takes three parameters − the sender’s public key, the recipient’s public key, and the amount to be sent. These are stored in the instance variables for use by other methods. Additionally, we create one more variable for storing the time of transaction." }, { "code": null, "e": 3008, "s": 2782, "text": "Next, we write a utility method called to_dict that combines all the four above-mentioned instance variables in a dictionary object. This is just to put the entire transaction information accessible through a single variable." }, { "code": null, "e": 3577, "s": 3008, "text": "As you know from the earlier tutorial that the first block in the blockchain is a Genesis block. The Genesis block contains the first transaction initiated by the creator of the blockchain. The identity of this person may be kept a secret like in the case of Bitcoins. So when this first transaction is created, the creator may just send his identity as Genesis. Thus, while creating the dictionary, we check if the sender is Genesis and if so we simply assign some string value to the identity variable; else, we assign the sender’s identity to the identity variable." }, { "code": null, "e": 3671, "s": 3577, "text": "if self.sender == \"Genesis\":\n identity = \"Genesis\"\nelse:\n identity = self.sender.identity" }, { "code": null, "e": 3728, "s": 3671, "text": "We construct the dictionary using following line of code" }, { "code": null, "e": 3864, "s": 3728, "text": "return collections.OrderedDict({\n 'sender': identity,\n 'recipient': self.recipient,\n 'value': self.value,\n 'time' : self.time})" }, { "code": null, "e": 3920, "s": 3864, "text": "The entire code for the to_dict method is shown below −" }, { "code": null, "e": 4197, "s": 3920, "text": "def to_dict(self):\n if self.sender == \"Genesis\":\n identity = \"Genesis\"\n else:\n identity = self.sender.identity\n\n return collections.OrderedDict({\n 'sender': identity,\n 'recipient': self.recipient,\n 'value': self.value,\n 'time' : self.time})" }, { "code": null, "e": 4497, "s": 4197, "text": "Finally, we will sign this dictionary object using the private key of the sender. As before, we use the built-in PKI with SHA algorithm. The generated signature is decoded to get the ASCII representation for printing and storing it in our blockchain. The sign_transaction method code is shown here −" }, { "code": null, "e": 4718, "s": 4497, "text": "def sign_transaction(self):\n private_key = self.sender._private_key\n signer = PKCS1_v1_5.new(private_key)\n h = SHA.new(str(self.to_dict()).encode('utf8'))\n return binascii.hexlify(signer.sign(h)).decode('ascii')\n" }, { "code": null, "e": 4759, "s": 4718, "text": "We will now test this Transaction class." }, { "code": null, "e": 4930, "s": 4759, "text": "For this purpose, we will create two users, called Dinesh and Ramesh. Dinesh will send 5 TPCoins to Ramesh. For this first we create the clients called Dinesh and Ramesh." }, { "code": null, "e": 4967, "s": 4930, "text": "Dinesh = Client()\nRamesh = Client()\n" }, { "code": null, "e": 5227, "s": 4967, "text": "Remember that when you instantiate a Client class, the public and private keys unique to the client would be created. As Dinesh is sending payment to Ramesh, he will need the public key of Ramesh which is obtained by using the identity property of the client." }, { "code": null, "e": 5296, "s": 5227, "text": "Thus, we will create the transaction instance using following code −" }, { "code": null, "e": 5354, "s": 5296, "text": "t = Transaction(\n Dinesh,\n Ramesh.identity,\n 5.0\n)\n" }, { "code": null, "e": 5629, "s": 5354, "text": "Note that the first parameter is the sender, the second parameter is the public key of the recipient and the third parameter is the amount to be transferred. The sign_transaction method retrieves the sender’s private key from the first parameter for singing the transaction." }, { "code": null, "e": 5868, "s": 5629, "text": "After the transaction object is created, you will sign it by calling its sign_transaction method. This method returns the generated signature in the printable format. We generate and print the signature using following two lines of code −" }, { "code": null, "e": 5921, "s": 5868, "text": "signature = t.sign_transaction()\nprint (signature) \n" }, { "code": null, "e": 5992, "s": 5921, "text": "When you run the above code, you will see the output similar to this −" }, { "code": null, "e": 6253, "s": 5992, "text": "7c7e3c97629b218e9ec6e86b01f9abd8e361fd69e7d373c38420790b655b9abe3b575e343c7\n13703ca1aee781acd7157a0624db3d57d7c2f1172730ee3f45af943338157f899965856f6b0\n0e34db240b62673ad5a08c8e490f880b568efbc36035cae2e748f1d802d5e8e66298be826f5\nc6363dc511222fb2416036ac04eb972\n" }, { "code": null, "e": 6425, "s": 6253, "text": "Now as our basic infrastructure of creating a client and a transaction is ready, we will now have multiple clients doing multiple transactions as in a real life situation." }, { "code": null, "e": 6462, "s": 6425, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 6478, "s": 6462, "text": " Malhar Lathkar" }, { "code": null, "e": 6511, "s": 6478, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 6530, "s": 6511, "text": " Arnab Chakraborty" }, { "code": null, "e": 6565, "s": 6530, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 6587, "s": 6565, "text": " In28Minutes Official" }, { "code": null, "e": 6621, "s": 6587, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 6649, "s": 6621, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6684, "s": 6649, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 6698, "s": 6684, "text": " Lets Kode It" }, { "code": null, "e": 6731, "s": 6698, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 6748, "s": 6731, "text": " Abhilash Nelson" }, { "code": null, "e": 6755, "s": 6748, "text": " Print" }, { "code": null, "e": 6766, "s": 6755, "text": " Add Notes" } ]
What data type to use for hashed password field in MySQL?
The hashed password data type depends upon which hashing algorithm we are using. The hashing algorithm does not depends upon the input size because it produces a result of the same length. It gives the result in a series of hexadecimal digits, and we can reduce the hexadecimal digits by half with the help of UNHEX() function. There are various algorithms and data types to store values. MD5 − It can use char(32) or BINARY(16). MD5 − It can use char(32) or BINARY(16). SHA-1 − It can use data type char(40) or BINARY(20). SHA-1 − It can use data type char(40) or BINARY(20). The following is an example − mysql> select MD5('This is a hashed password'); Here is the output. +----------------------------------+ | MD5('This is a hashed password') | +----------------------------------+ | e9d4c42db40abbb4724a0047f7e91e67 | +----------------------------------+ 1 row in set (0.03 sec) To know the length of the hashed password. mysql> SELECT CHARACTER_LENGTH(MD5('This is a hashed password')); +----------------------------------------------------+ | CHARACTER_LENGTH(MD5('This is a hashed password')) | +----------------------------------------------------+ | 32 | +----------------------------------------------------+ 1 row in set (0.04 sec) mysql> select SHA1('This is a hashed password'); The following is the output. +------------------------------------------+ | SHA1('This is a hashed password') | +------------------------------------------+ | 4e2e1a39dba84a0b5a91043bb0e4dbef23970837 | +------------------------------------------+ 1 row in set (0.00 sec) We can know the length with the help of character_length() function. mysql> SELECT CHARACTER_LENGTH(SHA1('This is a hashed password')); The following is the output. +-----------------------------------------------------+ | CHARACTER_LENGTH(SHA1('This is a hashed password')) | +-----------------------------------------------------+ | 40 | +-----------------------------------------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1390, "s": 1062, "text": "The hashed password data type depends upon which hashing algorithm we are using. The hashing algorithm does not depends upon the input size because it produces a result of the same length. It gives the result in a series of hexadecimal digits, and we can reduce the hexadecimal digits by half with the help of UNHEX() function." }, { "code": null, "e": 1451, "s": 1390, "text": "There are various algorithms and data types to store values." }, { "code": null, "e": 1492, "s": 1451, "text": "MD5 − It can use char(32) or BINARY(16)." }, { "code": null, "e": 1533, "s": 1492, "text": "MD5 − It can use char(32) or BINARY(16)." }, { "code": null, "e": 1586, "s": 1533, "text": "SHA-1 − It can use data type char(40) or BINARY(20)." }, { "code": null, "e": 1639, "s": 1586, "text": "SHA-1 − It can use data type char(40) or BINARY(20)." }, { "code": null, "e": 1669, "s": 1639, "text": "The following is an example −" }, { "code": null, "e": 1717, "s": 1669, "text": "mysql> select MD5('This is a hashed password');" }, { "code": null, "e": 1737, "s": 1717, "text": "Here is the output." }, { "code": null, "e": 1947, "s": 1737, "text": "+----------------------------------+\n| MD5('This is a hashed password') |\n+----------------------------------+\n| e9d4c42db40abbb4724a0047f7e91e67 |\n+----------------------------------+\n1 row in set (0.03 sec)\n" }, { "code": null, "e": 1990, "s": 1947, "text": "To know the length of the hashed password." }, { "code": null, "e": 2356, "s": 1990, "text": "mysql> SELECT CHARACTER_LENGTH(MD5('This is a hashed password'));\n+----------------------------------------------------+\n| CHARACTER_LENGTH(MD5('This is a hashed password')) |\n+----------------------------------------------------+\n| 32 |\n+----------------------------------------------------+\n1 row in set (0.04 sec)" }, { "code": null, "e": 2405, "s": 2356, "text": "mysql> select SHA1('This is a hashed password');" }, { "code": null, "e": 2434, "s": 2405, "text": "The following is the output." }, { "code": null, "e": 2684, "s": 2434, "text": "+------------------------------------------+\n| SHA1('This is a hashed password') |\n+------------------------------------------+\n| 4e2e1a39dba84a0b5a91043bb0e4dbef23970837 |\n+------------------------------------------+\n1 row in set (0.00 sec)\n" }, { "code": null, "e": 2753, "s": 2684, "text": "We can know the length with the help of character_length() function." }, { "code": null, "e": 2821, "s": 2753, "text": "mysql> SELECT CHARACTER_LENGTH(SHA1('This is a hashed password'));" }, { "code": null, "e": 2850, "s": 2821, "text": "The following is the output." }, { "code": null, "e": 3155, "s": 2850, "text": "+-----------------------------------------------------+\n| CHARACTER_LENGTH(SHA1('This is a hashed password')) |\n+-----------------------------------------------------+\n| 40 |\n+-----------------------------------------------------+\n1 row in set (0.00 sec)\n" } ]
XAML - GridPanel
A Grid panel provides a flexible area which consists of rows and columns. In a Grid, child elements can be arranged in a tabular form. Elements can be added to any specific row and column by using the Grid.Row and Grid.Column properties. By default, a Grid panel is created with one row and one column. Multiple rows and columns can be created by using the RowDefinitions and ColumnDefinitions properties. The height of rows and the width of columns can be defined in the following three ways − Fixed value − To assign a fixed size of logical units (1/96 inch) Fixed value − To assign a fixed size of logical units (1/96 inch) Auto − It will take only as much space as is required for the controls in that specific row/column. Auto − It will take only as much space as is required for the controls in that specific row/column. Star (*) − It will take the remaining space when Auto and fixed sized are filled. Star (*) − It will take the remaining space when Auto and fixed sized are filled. The hierarchical inheritance of Grid class is as follows − Background Gets or sets a Brush that fills the panel content area. (Inherited from Panel) Children Gets a UIElementCollection of child elements of this Panel. (Inherited from Panel.) ColumnDefinitions Gets a list of ColumnDefinition objects defined on this instance of Grid. Height Gets or sets the suggested height of the element. (Inherited from FrameworkElement.) ItemHeight Gets or sets a value that specifies the height of all items that are contained within a WrapPanel. ItemWidth Gets or sets a value that specifies the width of all items that are contained within a WrapPanel. Margin Gets or sets the outer margin of an element. (Inherited from FrameworkElement.) Name Gets or sets the identifying name of the element. The name provides a reference so that code-behind, such as event handler code, can refer to a markup element after it is constructed during processing by a XAML processor. (Inherited from FrameworkElement.) Orientation Gets or sets a value that specifies the dimension in which child content is arranged. Parent Gets the logical parent element of this element. (Inherited from FrameworkElement.) Resources Gets or sets the locally-defined resource dictionary. (Inherited from FrameworkElement.) RowDefinitions Gets a list of RowDefinition objects defined on this instance of Grid. Style Gets or sets the style used by this element when it is rendered. (Inherited from FrameworkElement.) Width Gets or sets the width of the element. (Inherited from FrameworkElement.) GetColumn Gets the value of the Grid.Column XAML attached property from the specified FrameworkElement. GetColumnSpan Gets the value of the Grid.ColumnSpan XAML attached property from the specified FrameworkElement. GetRow Gets the value of the Grid.Row XAML attached property from the specified FrameworkElement. SetColumn Sets the value of the Grid.Column XAML attached property on the specified FrameworkElement. SetRow Sets the value of the Grid.Row XAML attached property on the specified FrameworkElement. SetRowSpan Sets the value of the Grid.RowSpan XAML attached property on the specified FrameworkElement. The following example shows how to add child elements into a Grid to specify it in a tabular form. Here is the XAML implementation in which Text Blocks are added in the first column and Text Boxes are added in the second column of a Grid. <Window x:Class = "XAMLGrid.Window1" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "Window1" Height = "300" Width = "604"> <Grid x:Name = "FormLayoutGrid" Background = "LightGray"> <Grid.ColumnDefinitions> <ColumnDefinition Width = "Auto" /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height = "*" /> <RowDefinition Height = "*" /> <RowDefinition Height = "*" /> </Grid.RowDefinitions> <TextBlock Grid.Row = "0" Grid.Column = "0" Text = "Name" Margin = "10" HorizontalAlignment = "Left" VerticalAlignment = "Center" Width = "100"/> <TextBox Grid.Row = "0" Grid.Column = "1" Margin = "10"/> <TextBlock Grid.Row = "1" Grid.Column = "0" Text = "ID" Margin = "10" HorizontalAlignment = "Left" VerticalAlignment = "Center" Width = "100"/> <TextBox Grid.Row = "1" Grid.Column = "1" Margin = "10"/> <TextBlock Grid.Row = "2" Grid.Column = "0" Text = "Age" Margin = "10" HorizontalAlignment = "Left" VerticalAlignment = "Center" Width = "100"/> <TextBox Grid.Row = "2" Grid.Column = "1" Margin = "10"/> </Grid> </Window> When you compile and execute the above code, it will produce the following output− We recommend you to execute the above example code and experiment with some other properties as well. Nesting of layout means using a layout panel inside another layout, e.g., defining stack panels inside a grid. This concept is widely used to take advantage of multiple layouts in an application. In the following example, we will be using stack panels inside a grid. Let’s have a look at the following XAML code − <Window x:Class = "XAMLNestingLayouts.Window1" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "Window1" Height = "300" Width = "604"> <Grid Background = "LightGray"> <Grid.RowDefinitions> <RowDefinition Height = "*"/> <RowDefinition Height = "*"/> <RowDefinition Height = "*"/> <RowDefinition Height = "*"/> <RowDefinition Height = "*"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width = "*"/> </Grid.ColumnDefinitions> <Label Content = "Employee Info" FontSize = "15" FontWeight = "Bold" Grid.Column = "0" Grid.Row = "0"/> <StackPanel Grid.Column = "0" Grid.Row = "1" Orientation = "Horizontal"> <Label Content = "Name" VerticalAlignment = "Center" Width = "70"/> <TextBox Name = "txtName" Text = "Muhammad Ali" VerticalAlignment = "Center" Width = "200"></TextBox> </StackPanel> <StackPanel Grid.Column = "0" Grid.Row = "2" Orientation = "Horizontal"> <Label Content = "ID" VerticalAlignment = "Center" Width = "70"/> <TextBox Name = "txtCity" Text = "421" VerticalAlignment = "Center" Width = "50"></TextBox> </StackPanel> <StackPanel Grid.Column = "0" Grid.Row = "3" Orientation = "Horizontal"> <Label Content = "Age" VerticalAlignment = "Center" Width = "70"/> <TextBox Name = "txtState" Text = "32" VerticalAlignment = "Center" Width = "50"></TextBox> </StackPanel> <StackPanel Grid.Column = "0" Grid.Row = "4" Orientation = "Horizontal"> <Label Content = "Title" VerticalAlignment = "Center" Width = "70"/> <TextBox Name = "txtCountry" Text = "Programmer" VerticalAlignment = "Center" Width = "20></TextBox> </StackPanel> </Grid> </Window> When you compile and execute the above code, it will produce the following output − We recommend you to execute the above example code and experiment with some other nesting layouts. Print Add Notes Bookmark this page
[ { "code": null, "e": 2161, "s": 1923, "text": "A Grid panel provides a flexible area which consists of rows and columns. In a Grid, child elements can be arranged in a tabular form. Elements can be added to any specific row and column by using the Grid.Row and Grid.Column properties." }, { "code": null, "e": 2418, "s": 2161, "text": "By default, a Grid panel is created with one row and one column. Multiple rows and columns can be created by using the RowDefinitions and ColumnDefinitions properties. The height of rows and the width of columns can be defined in the following three ways −" }, { "code": null, "e": 2484, "s": 2418, "text": "Fixed value − To assign a fixed size of logical units (1/96 inch)" }, { "code": null, "e": 2550, "s": 2484, "text": "Fixed value − To assign a fixed size of logical units (1/96 inch)" }, { "code": null, "e": 2650, "s": 2550, "text": "Auto − It will take only as much space as is required for the controls in that specific row/column." }, { "code": null, "e": 2750, "s": 2650, "text": "Auto − It will take only as much space as is required for the controls in that specific row/column." }, { "code": null, "e": 2832, "s": 2750, "text": "Star (*) − It will take the remaining space when Auto and fixed sized are filled." }, { "code": null, "e": 2914, "s": 2832, "text": "Star (*) − It will take the remaining space when Auto and fixed sized are filled." }, { "code": null, "e": 2973, "s": 2914, "text": "The hierarchical inheritance of Grid class is as follows −" }, { "code": null, "e": 2984, "s": 2973, "text": "Background" }, { "code": null, "e": 3063, "s": 2984, "text": "Gets or sets a Brush that fills the panel content area. (Inherited from Panel)" }, { "code": null, "e": 3072, "s": 3063, "text": "Children" }, { "code": null, "e": 3156, "s": 3072, "text": "Gets a UIElementCollection of child elements of this Panel. (Inherited from Panel.)" }, { "code": null, "e": 3174, "s": 3156, "text": "ColumnDefinitions" }, { "code": null, "e": 3248, "s": 3174, "text": "Gets a list of ColumnDefinition objects defined on this instance of Grid." }, { "code": null, "e": 3255, "s": 3248, "text": "Height" }, { "code": null, "e": 3340, "s": 3255, "text": "Gets or sets the suggested height of the element. (Inherited from FrameworkElement.)" }, { "code": null, "e": 3351, "s": 3340, "text": "ItemHeight" }, { "code": null, "e": 3450, "s": 3351, "text": "Gets or sets a value that specifies the height of all items that are contained within a WrapPanel." }, { "code": null, "e": 3460, "s": 3450, "text": "ItemWidth" }, { "code": null, "e": 3558, "s": 3460, "text": "Gets or sets a value that specifies the width of all items that are contained within a WrapPanel." }, { "code": null, "e": 3565, "s": 3558, "text": "Margin" }, { "code": null, "e": 3645, "s": 3565, "text": "Gets or sets the outer margin of an element. (Inherited from FrameworkElement.)" }, { "code": null, "e": 3650, "s": 3645, "text": "Name" }, { "code": null, "e": 3907, "s": 3650, "text": "Gets or sets the identifying name of the element. The name provides a reference so that code-behind, such as event handler code, can refer to a markup element after it is constructed during processing by a XAML processor. (Inherited from FrameworkElement.)" }, { "code": null, "e": 3919, "s": 3907, "text": "Orientation" }, { "code": null, "e": 4005, "s": 3919, "text": "Gets or sets a value that specifies the dimension in which child content is arranged." }, { "code": null, "e": 4012, "s": 4005, "text": "Parent" }, { "code": null, "e": 4096, "s": 4012, "text": "Gets the logical parent element of this element. (Inherited from FrameworkElement.)" }, { "code": null, "e": 4106, "s": 4096, "text": "Resources" }, { "code": null, "e": 4195, "s": 4106, "text": "Gets or sets the locally-defined resource dictionary. (Inherited from FrameworkElement.)" }, { "code": null, "e": 4210, "s": 4195, "text": "RowDefinitions" }, { "code": null, "e": 4281, "s": 4210, "text": "Gets a list of RowDefinition objects defined on this instance of Grid." }, { "code": null, "e": 4287, "s": 4281, "text": "Style" }, { "code": null, "e": 4387, "s": 4287, "text": "Gets or sets the style used by this element when it is rendered. (Inherited from FrameworkElement.)" }, { "code": null, "e": 4393, "s": 4387, "text": "Width" }, { "code": null, "e": 4467, "s": 4393, "text": "Gets or sets the width of the element. (Inherited from FrameworkElement.)" }, { "code": null, "e": 4477, "s": 4467, "text": "GetColumn" }, { "code": null, "e": 4571, "s": 4477, "text": "Gets the value of the Grid.Column XAML attached property from the specified FrameworkElement." }, { "code": null, "e": 4585, "s": 4571, "text": "GetColumnSpan" }, { "code": null, "e": 4683, "s": 4585, "text": "Gets the value of the Grid.ColumnSpan XAML attached property from the specified FrameworkElement." }, { "code": null, "e": 4690, "s": 4683, "text": "GetRow" }, { "code": null, "e": 4781, "s": 4690, "text": "Gets the value of the Grid.Row XAML attached property from the specified FrameworkElement." }, { "code": null, "e": 4791, "s": 4781, "text": "SetColumn" }, { "code": null, "e": 4883, "s": 4791, "text": "Sets the value of the Grid.Column XAML attached property on the specified FrameworkElement." }, { "code": null, "e": 4890, "s": 4883, "text": "SetRow" }, { "code": null, "e": 4979, "s": 4890, "text": "Sets the value of the Grid.Row XAML attached property on the specified FrameworkElement." }, { "code": null, "e": 4990, "s": 4979, "text": "SetRowSpan" }, { "code": null, "e": 5083, "s": 4990, "text": "Sets the value of the Grid.RowSpan XAML attached property on the specified FrameworkElement." }, { "code": null, "e": 5322, "s": 5083, "text": "The following example shows how to add child elements into a Grid to specify it in a tabular form. Here is the XAML implementation in which Text Blocks are added in the first column and Text Boxes are added in the second column of a Grid." }, { "code": null, "e": 6675, "s": 5322, "text": "<Window x:Class = \"XAMLGrid.Window1\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"Window1\" Height = \"300\" Width = \"604\"> \n\t\n <Grid x:Name = \"FormLayoutGrid\" Background = \"LightGray\"> \n <Grid.ColumnDefinitions> \n <ColumnDefinition Width = \"Auto\" /> \n <ColumnDefinition /> \n </Grid.ColumnDefinitions> \n\t\t\n <Grid.RowDefinitions> \n <RowDefinition Height = \"*\" /> \n <RowDefinition Height = \"*\" /> \n <RowDefinition Height = \"*\" /> \n </Grid.RowDefinitions> \n\t\t\n <TextBlock Grid.Row = \"0\" Grid.Column = \"0\" Text = \"Name\" \n Margin = \"10\" HorizontalAlignment = \"Left\" VerticalAlignment = \"Center\" \n Width = \"100\"/> \n \n <TextBox Grid.Row = \"0\" Grid.Column = \"1\" Margin = \"10\"/> \n <TextBlock Grid.Row = \"1\" Grid.Column = \"0\" Text = \"ID\" Margin = \"10\" \n HorizontalAlignment = \"Left\" VerticalAlignment = \"Center\" Width = \"100\"/> \n \n <TextBox Grid.Row = \"1\" Grid.Column = \"1\" Margin = \"10\"/> \n <TextBlock Grid.Row = \"2\" Grid.Column = \"0\" Text = \"Age\" Margin = \"10\" \n HorizontalAlignment = \"Left\" VerticalAlignment = \"Center\" Width = \"100\"/> \n \n <TextBox Grid.Row = \"2\" Grid.Column = \"1\" Margin = \"10\"/>\n </Grid> \n\t\n</Window>\t" }, { "code": null, "e": 6758, "s": 6675, "text": "When you compile and execute the above code, it will produce the following output−" }, { "code": null, "e": 6860, "s": 6758, "text": "We recommend you to execute the above example code and experiment with some other properties as well." }, { "code": null, "e": 7056, "s": 6860, "text": "Nesting of layout means using a layout panel inside another layout, e.g., defining stack panels inside a grid. This concept is widely used to take advantage of multiple layouts in an application." }, { "code": null, "e": 7174, "s": 7056, "text": "In the following example, we will be using stack panels inside a grid. Let’s have a look at the following XAML code −" }, { "code": null, "e": 9164, "s": 7174, "text": "<Window x:Class = \"XAMLNestingLayouts.Window1\"\n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"Window1\" Height = \"300\" Width = \"604\"> \n\t\n <Grid Background = \"LightGray\"> \n <Grid.RowDefinitions> \n <RowDefinition Height = \"*\"/> \n <RowDefinition Height = \"*\"/> \n <RowDefinition Height = \"*\"/> \n <RowDefinition Height = \"*\"/> \n <RowDefinition Height = \"*\"/> \n </Grid.RowDefinitions>\n\t\t\n <Grid.ColumnDefinitions> \n <ColumnDefinition Width = \"*\"/> \n </Grid.ColumnDefinitions> \n\t\t\n <Label Content = \"Employee Info\" FontSize = \"15\" FontWeight = \"Bold\" \n Grid.Column = \"0\" Grid.Row = \"0\"/> \n\t\t\n <StackPanel Grid.Column = \"0\" Grid.Row = \"1\" Orientation = \"Horizontal\"> \n <Label Content = \"Name\" VerticalAlignment = \"Center\" Width = \"70\"/>\n <TextBox Name = \"txtName\" Text = \"Muhammad Ali\" \n VerticalAlignment = \"Center\" Width = \"200\"></TextBox> \n </StackPanel> \n\t\t\n <StackPanel Grid.Column = \"0\" Grid.Row = \"2\" Orientation = \"Horizontal\"> \n <Label Content = \"ID\" VerticalAlignment = \"Center\" Width = \"70\"/> \n <TextBox Name = \"txtCity\" Text = \"421\" VerticalAlignment = \"Center\" \n Width = \"50\"></TextBox> \n </StackPanel>\n\t\t\n <StackPanel Grid.Column = \"0\" Grid.Row = \"3\" Orientation = \"Horizontal\"> \n <Label Content = \"Age\" VerticalAlignment = \"Center\" Width = \"70\"/> \n <TextBox Name = \"txtState\" Text = \"32\" VerticalAlignment = \"Center\" \n Width = \"50\"></TextBox> \n </StackPanel> \n\t\t\n <StackPanel Grid.Column = \"0\" Grid.Row = \"4\" Orientation = \"Horizontal\"> \n <Label Content = \"Title\" VerticalAlignment = \"Center\" Width = \"70\"/>\n <TextBox Name = \"txtCountry\" Text = \"Programmer\" \n VerticalAlignment = \"Center\" Width = \"20></TextBox> \n </StackPanel>\n </Grid> \n\t\n</Window>" }, { "code": null, "e": 9248, "s": 9164, "text": "When you compile and execute the above code, it will produce the following output −" }, { "code": null, "e": 9347, "s": 9248, "text": "We recommend you to execute the above example code and experiment with some other nesting layouts." }, { "code": null, "e": 9354, "s": 9347, "text": " Print" }, { "code": null, "e": 9365, "s": 9354, "text": " Add Notes" } ]
Java Program to Convert Enum to String - GeeksforGeeks
17 Jun, 2021 Given an enum containing a group of constants, the task is to convert the enum to a String. Methods: We can solve this problem using two methods: Using name() MethodUsing toString() Method Using name() Method Using toString() Method Let us discuss both of them in detail and implementing them to get a better understanding of the same. Method 1: Using name() Method It returns the name of the enum constant same as declared in its enum declaration. We would be using name() method to return the name of the enum constant. In the main class, we just have to print it. The value given inside is first the name of the enum class that we will create further, then calling the constant that is named, finally using the name() method. Now create another java enum file named Fruits.java in the same folder where you created the main file, and declare the enum as follows: Example public enum Fruits { Orange, Apple, Banana, Mango; } Java // Java Program to Convert Enum to String// using // Importing input output classesimport java.io.*; // Enumenum Fruits { Orange, Apple, Banana, Mango;} // Main classclass GFG { // Main driver method public static void main(String[] args) { // Printing all the values System.out.println(Fruits.Orange.name()); System.out.println(Fruits.Apple.name()); System.out.println(Fruits.Banana.name()); System.out.println(Fruits.Mango.name()); }} Orange Apple Banana Mango Method 2: Using toString() Method It is used to get a string object which represents the value of the number object. We will be following the same procedure as earlier used but the only difference here is that we will be using toString() method. So just replace name() method with toString() method. Note: Do not forgot to create a Fruits.java enum file in the same folder. Illustration: public enum Fruits { Orange, Apple, Banana, Mango; } Example 2 Java // Java Program to Convert Enum to String// Using toString() Method // Importing input output classes import java.io.*; // Enumenum Fruits { // Custom entries Orange, Apple, Banana, Mango;} // Main class class Main { // Main driver method public static void main (String[] args) { // Printing all the values System.out.println(Fruits.Orange.toString()); System.out.println(Fruits.Apple.toString()); System.out.println(Fruits.Banana.toString()); System.out.println(Fruits.Mango.toString()); }} Orange Apple Banana Mango Java-Enumeration Java-String-Programs Picked 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 How to Iterate HashMap in Java?
[ { "code": null, "e": 23557, "s": 23529, "text": "\n17 Jun, 2021" }, { "code": null, "e": 23649, "s": 23557, "text": "Given an enum containing a group of constants, the task is to convert the enum to a String." }, { "code": null, "e": 23658, "s": 23649, "text": "Methods:" }, { "code": null, "e": 23703, "s": 23658, "text": "We can solve this problem using two methods:" }, { "code": null, "e": 23746, "s": 23703, "text": "Using name() MethodUsing toString() Method" }, { "code": null, "e": 23766, "s": 23746, "text": "Using name() Method" }, { "code": null, "e": 23790, "s": 23766, "text": "Using toString() Method" }, { "code": null, "e": 23893, "s": 23790, "text": "Let us discuss both of them in detail and implementing them to get a better understanding of the same." }, { "code": null, "e": 23923, "s": 23893, "text": "Method 1: Using name() Method" }, { "code": null, "e": 24008, "s": 23923, "text": " It returns the name of the enum constant same as declared in its enum declaration. " }, { "code": null, "e": 24081, "s": 24008, "text": "We would be using name() method to return the name of the enum constant." }, { "code": null, "e": 24126, "s": 24081, "text": "In the main class, we just have to print it." }, { "code": null, "e": 24288, "s": 24126, "text": "The value given inside is first the name of the enum class that we will create further, then calling the constant that is named, finally using the name() method." }, { "code": null, "e": 24425, "s": 24288, "text": "Now create another java enum file named Fruits.java in the same folder where you created the main file, and declare the enum as follows:" }, { "code": null, "e": 24433, "s": 24425, "text": "Example" }, { "code": null, "e": 24490, "s": 24433, "text": "public enum Fruits {\n Orange, Apple, Banana, Mango;\n}" }, { "code": null, "e": 24495, "s": 24490, "text": "Java" }, { "code": "// Java Program to Convert Enum to String// using // Importing input output classesimport java.io.*; // Enumenum Fruits { Orange, Apple, Banana, Mango;} // Main classclass GFG { // Main driver method public static void main(String[] args) { // Printing all the values System.out.println(Fruits.Orange.name()); System.out.println(Fruits.Apple.name()); System.out.println(Fruits.Banana.name()); System.out.println(Fruits.Mango.name()); }}", "e": 24996, "s": 24495, "text": null }, { "code": null, "e": 25023, "s": 24996, "text": "Orange\nApple\nBanana\nMango\n" }, { "code": null, "e": 25058, "s": 25023, "text": " Method 2: Using toString() Method" }, { "code": null, "e": 25142, "s": 25058, "text": " It is used to get a string object which represents the value of the number object." }, { "code": null, "e": 25325, "s": 25142, "text": "We will be following the same procedure as earlier used but the only difference here is that we will be using toString() method. So just replace name() method with toString() method." }, { "code": null, "e": 25399, "s": 25325, "text": "Note: Do not forgot to create a Fruits.java enum file in the same folder." }, { "code": null, "e": 25414, "s": 25399, "text": "Illustration: " }, { "code": null, "e": 25471, "s": 25414, "text": "public enum Fruits {\n Orange, Apple, Banana, Mango;\n}" }, { "code": null, "e": 25481, "s": 25471, "text": "Example 2" }, { "code": null, "e": 25486, "s": 25481, "text": "Java" }, { "code": "// Java Program to Convert Enum to String// Using toString() Method // Importing input output classes import java.io.*; // Enumenum Fruits { // Custom entries Orange, Apple, Banana, Mango;} // Main class class Main { // Main driver method public static void main (String[] args) { // Printing all the values System.out.println(Fruits.Orange.toString()); System.out.println(Fruits.Apple.toString()); System.out.println(Fruits.Banana.toString()); System.out.println(Fruits.Mango.toString()); }}", "e": 26055, "s": 25486, "text": null }, { "code": null, "e": 26082, "s": 26055, "text": "Orange\nApple\nBanana\nMango\n" }, { "code": null, "e": 26099, "s": 26082, "text": "Java-Enumeration" }, { "code": null, "e": 26120, "s": 26099, "text": "Java-String-Programs" }, { "code": null, "e": 26127, "s": 26120, "text": "Picked" }, { "code": null, "e": 26132, "s": 26127, "text": "Java" }, { "code": null, "e": 26146, "s": 26132, "text": "Java Programs" }, { "code": null, "e": 26151, "s": 26146, "text": "Java" }, { "code": null, "e": 26249, "s": 26151, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26258, "s": 26249, "text": "Comments" }, { "code": null, "e": 26271, "s": 26258, "text": "Old Comments" }, { "code": null, "e": 26301, "s": 26271, "text": "Functional Interfaces in Java" }, { "code": null, "e": 26316, "s": 26301, "text": "Stream In Java" }, { "code": null, "e": 26337, "s": 26316, "text": "Constructors in Java" }, { "code": null, "e": 26383, "s": 26337, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26402, "s": 26383, "text": "Exceptions in Java" }, { "code": null, "e": 26446, "s": 26402, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 26472, "s": 26446, "text": "Java Programming Examples" }, { "code": null, "e": 26506, "s": 26472, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 26553, "s": 26506, "text": "Implementing a Linked List in Java using Class" } ]
java.util.regex.Pattern.matcher() Method
The java.util.regex.Pattern.matcher(CharSequence input) method creates a matcher that will match the given input against this pattern. Following is the declaration for java.util.regex.Pattern.matcher(CharSequence input) method. public Matcher matcher(CharSequence input) input − The character sequence to be matched. input − The character sequence to be matched. A new matcher for this pattern. The following example shows the usage of java.util.regex.Pattern.matcher(CharSequence input) method. package com.tutorialspoint; import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; public class PatternDemo { private static final String REGEX = "(.*)(\\d+)(.*)"; private static final String INPUT = "This is a sample Text, 1234, with numbers in between."; public static void main(String[] args) { // create a pattern Pattern pattern = Pattern.compile(REGEX); // get a matcher object Matcher matcher = pattern.matcher(INPUT); if(matcher.find()) { //get the MatchResult Object MatchResult result = matcher.toMatchResult(); //Prints the offset after the last character matched. System.out.println("First Capturing Group - Match String end(): "+result.end()); } } } Let us compile and run the above program, this will produce the following result − First Capturing Group - Match String end(): 53 Print Add Notes Bookmark this page
[ { "code": null, "e": 2259, "s": 2124, "text": "The java.util.regex.Pattern.matcher(CharSequence input) method creates a matcher that will match the given input against this pattern." }, { "code": null, "e": 2352, "s": 2259, "text": "Following is the declaration for java.util.regex.Pattern.matcher(CharSequence input) method." }, { "code": null, "e": 2396, "s": 2352, "text": "public Matcher matcher(CharSequence input)\n" }, { "code": null, "e": 2442, "s": 2396, "text": "input − The character sequence to be matched." }, { "code": null, "e": 2488, "s": 2442, "text": "input − The character sequence to be matched." }, { "code": null, "e": 2520, "s": 2488, "text": "A new matcher for this pattern." }, { "code": null, "e": 2621, "s": 2520, "text": "The following example shows the usage of java.util.regex.Pattern.matcher(CharSequence input) method." }, { "code": null, "e": 3436, "s": 2621, "text": "package com.tutorialspoint;\n\nimport java.util.regex.MatchResult;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class PatternDemo {\n private static final String REGEX = \"(.*)(\\\\d+)(.*)\";\n private static final String INPUT = \"This is a sample Text, 1234, with numbers in between.\";\n\n public static void main(String[] args) {\n // create a pattern\n Pattern pattern = Pattern.compile(REGEX);\n \n // get a matcher object\n Matcher matcher = pattern.matcher(INPUT); \n\n if(matcher.find()) {\n //get the MatchResult Object \n MatchResult result = matcher.toMatchResult();\n\n //Prints the offset after the last character matched.\n System.out.println(\"First Capturing Group - Match String end(): \"+result.end()); \n }\n }\n}" }, { "code": null, "e": 3519, "s": 3436, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3567, "s": 3519, "text": "First Capturing Group - Match String end(): 53\n" }, { "code": null, "e": 3574, "s": 3567, "text": " Print" }, { "code": null, "e": 3585, "s": 3574, "text": " Add Notes" } ]
Convert string (varchar) to timestamp format in MySQL?
To convert string to timestamp format, use STR_TO_DATE() along with DATE_FORMAT(). Let us first create a table − mysql> create table DemoTable1602 -> ( -> ReportingDate varchar(40) -> ); Query OK, 0 rows affected (0.51 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1602 values('Wed Oct 02 16:10:45 IST 2019'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable1602 values('Fri May 31 13:00:10 IST 2019'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1602 values('Mon Dec 31 14:20:00 IST 2018'); Query OK, 1 row affected (0.23 sec) Display all records from the table using select statement − mysql> select * from DemoTable1602; This will produce the following output − +------------------------------+ | ReportingDate | +------------------------------+ | Wed Oct 02 16:10:45 IST 2019 | | Fri May 31 13:00:10 IST 2019 | | Mon Dec 31 14:20:00 IST 2018 | +------------------------------+ 3 rows in set (0.00 sec) Following is the query to convert string to timestamp format in MySQL − mysql> select date_format(str_to_date(ReportingDate,'%a %b %d %T IST %Y'),'%d-%m-%Y %H:%i:%s') from DemoTable1602; This will produce the following output − +----------------------------------------------------------------------------------+ | date_format(str_to_date(ReportingDate,'%a %b %d %T IST %Y'),'%d-%m-%Y %H:%i:%s') | +----------------------------------------------------------------------------------+ | 02-10-2019 16:10:45 | | 31-05-2019 13:00:10 | | 31-12-2018 14:20:00 | +----------------------------------------------------------------------------------+ 3 rows in set (0.03 sec)
[ { "code": null, "e": 1175, "s": 1062, "text": "To convert string to timestamp format, use STR_TO_DATE() along with DATE_FORMAT(). Let us first create a table −" }, { "code": null, "e": 1295, "s": 1175, "text": "mysql> create table DemoTable1602\n -> (\n -> ReportingDate varchar(40)\n -> );\nQuery OK, 0 rows affected (0.51 sec)" }, { "code": null, "e": 1351, "s": 1295, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1678, "s": 1351, "text": "mysql> insert into DemoTable1602 values('Wed Oct 02 16:10:45 IST 2019');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into DemoTable1602 values('Fri May 31 13:00:10 IST 2019');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable1602 values('Mon Dec 31 14:20:00 IST 2018');\nQuery OK, 1 row affected (0.23 sec)" }, { "code": null, "e": 1738, "s": 1678, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1774, "s": 1738, "text": "mysql> select * from DemoTable1602;" }, { "code": null, "e": 1815, "s": 1774, "text": "This will produce the following output −" }, { "code": null, "e": 2071, "s": 1815, "text": "+------------------------------+\n| ReportingDate |\n+------------------------------+\n| Wed Oct 02 16:10:45 IST 2019 |\n| Fri May 31 13:00:10 IST 2019 |\n| Mon Dec 31 14:20:00 IST 2018 |\n+------------------------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2143, "s": 2071, "text": "Following is the query to convert string to timestamp format in MySQL −" }, { "code": null, "e": 2258, "s": 2143, "text": "mysql> select date_format(str_to_date(ReportingDate,'%a %b %d %T IST %Y'),'%d-%m-%Y %H:%i:%s') from DemoTable1602;" }, { "code": null, "e": 2299, "s": 2258, "text": "This will produce the following output −" }, { "code": null, "e": 2919, "s": 2299, "text": "+----------------------------------------------------------------------------------+\n| date_format(str_to_date(ReportingDate,'%a %b %d %T IST %Y'),'%d-%m-%Y %H:%i:%s') |\n+----------------------------------------------------------------------------------+\n| 02-10-2019 16:10:45 |\n| 31-05-2019 13:00:10 |\n| 31-12-2018 14:20:00 |\n+----------------------------------------------------------------------------------+\n3 rows in set (0.03 sec)" } ]
Add 1 to a number represented as linked list - GeeksforGeeks
04 Feb, 2022 Number is represented in linked list such that each digit corresponds to a node in linked list. Add 1 to it. For example 1999 is represented as (1-> 9-> 9 -> 9) and adding 1 to it should change it to (2->0->0->0) Below are the steps : Reverse given linked list. For example, 1-> 9-> 9 -> 9 is converted to 9-> 9 -> 9 ->1.Start traversing linked list from leftmost node and add 1 to it. If there is a carry, move to the next node. Keep moving to the next node while there is a carry.Reverse modified linked list and return head. Reverse given linked list. For example, 1-> 9-> 9 -> 9 is converted to 9-> 9 -> 9 ->1. Start traversing linked list from leftmost node and add 1 to it. If there is a carry, move to the next node. Keep moving to the next node while there is a carry. Reverse modified linked list and return head. Below is the implementation of above steps. C++ C Java Python3 C# Javascript // C++ program to add 1 to a linked list#include <bits/stdc++.h>using namespace std; /* Linked list node */class Node{ public: int data; Node* next;}; /* Function to create a new node with given data */Node *newNode(int data){ Node *new_node = new Node; new_node->data = data; new_node->next = NULL; return new_node;} /* Function to reverse the linked list */Node *reverse(Node *head){ Node * prev = NULL; Node * current = head; Node * next; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } return prev;} /* Adds one to a linked lists and return the headnode of resultant list */Node *addOneUtil(Node *head){ // res is head node of the resultant list Node* res = head; Node *temp; int carry = 1, sum; while (head != NULL) //while both lists exist { // Calculate value of next digit in resultant list. // The next digit is sum of following things // (i) Carry // (ii) Next digit of head list (if there is a // next digit) sum = carry + head->data; // update carry for next calculation carry = (sum >= 10)? 1 : 0; // update sum if it is greater than 10 sum = sum % 10; // Create a new node with sum as data head->data = sum; // Move head and second pointers to next nodes temp = head; head = head->next; } // if some carry is still there, add a new node to // result list. if (carry > 0) temp->next = newNode(carry); // return head of the resultant list return res;} // This function mainly uses addOneUtil().Node* addOne(Node *head){ // Reverse linked list head = reverse(head); // Add one from left to right of reversed // list head = addOneUtil(head); // Reverse the modified list return reverse(head);} // A utility function to print a linked listvoid printList(Node *node){ while (node != NULL) { cout << node->data; node = node->next; } cout<<endl;} /* Driver program to test above function */int main(void){ Node *head = newNode(1); head->next = newNode(9); head->next->next = newNode(9); head->next->next->next = newNode(9); cout << "List is "; printList(head); head = addOne(head); cout << "\nResultant list is "; printList(head); return 0;} // This is code is contributed by rathbhupendra // C program to add 1 to a linked list#include<bits/stdc++.h> /* Linked list node */struct Node{ int data; Node* next;}; /* Function to create a new node with given data */Node *newNode(int data){ Node *new_node = new Node; new_node->data = data; new_node->next = NULL; return new_node;} /* Function to reverse the linked list */Node *reverse(Node *head){ Node * prev = NULL; Node * current = head; Node * next; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } return prev;} /* Adds one to a linked lists and return the head node of resultant list */Node *addOneUtil(Node *head){ // res is head node of the resultant list Node* res = head; Node *temp, *prev = NULL; int carry = 1, sum; while (head != NULL) //while both lists exist { // Calculate value of next digit in resultant list. // The next digit is sum of following things // (i) Carry // (ii) Next digit of head list (if there is a // next digit) sum = carry + head->data; // update carry for next calculation carry = (sum >= 10)? 1 : 0; // update sum if it is greater than 10 sum = sum % 10; // Create a new node with sum as data head->data = sum; // Move head and second pointers to next nodes temp = head; head = head->next; } // if some carry is still there, add a new node to // result list. if (carry > 0) temp->next = newNode(carry); // return head of the resultant list return res;} // This function mainly uses addOneUtil().Node* addOne(Node *head){ // Reverse linked list head = reverse(head); // Add one from left to right of reversed // list head = addOneUtil(head); // Reverse the modified list return reverse(head);} // A utility function to print a linked listvoid printList(Node *node){ while (node != NULL) { printf("%d", node->data); node = node->next; } printf("\n");} /* Driver program to test above function */int main(void){ Node *head = newNode(1); head->next = newNode(9); head->next->next = newNode(9); head->next->next->next = newNode(9); printf("List is "); printList(head); head = addOne(head); printf("\nResultant list is "); printList(head); return 0;} // Java program to add 1 to a linked listclass GfG { /* Linked list node */ static class Node { int data; Node next; } /* Function to create a new node with given data */ static Node newNode(int data) { Node new_node = new Node(); new_node.data = data; new_node.next = null; return new_node; } /* Function to reverse the linked list */ static Node reverse(Node head) { Node prev = null; Node current = head; Node next = null; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } return prev; } /* Adds one to a linked lists and return the head node of resultant list */ static Node addOneUtil(Node head) { // res is head node of the resultant list Node res = head; Node temp = null, prev = null; int carry = 1, sum; while (head != null) // while both lists exist { // Calculate value of next digit in resultant // list. The next digit is sum of following // things (i) Carry (ii) Next digit of head list // (if there is a next digit) sum = carry + head.data; // update carry for next calculation carry = (sum >= 10) ? 1 : 0; // update sum if it is greater than 10 sum = sum % 10; // Create a new node with sum as data head.data = sum; // Move head and second pointers to next nodes temp = head; head = head.next; } // if some carry is still there, add a new node to // result list. if (carry > 0) temp.next = newNode(carry); // return head of the resultant list return res; } // This function mainly uses addOneUtil(). static Node addOne(Node head) { // Reverse linked list head = reverse(head); // Add one from left to right of reversed // list head = addOneUtil(head); // Reverse the modified list return reverse(head); } // A utility function to print a linked list static void printList(Node node) { while (node != null) { System.out.print(node.data); node = node.next; } System.out.println(); } /* Driver code */ public static void main(String[] args) { Node head = newNode(1); head.next = newNode(9); head.next.next = newNode(9); head.next.next.next = newNode(9); System.out.print("List is "); printList(head); head = addOne(head); System.out.println(); System.out.print("Resultant list is "); printList(head); }} // This code is contributed by prerna saini # Python3 program to add 1 to a linked listimport sysimport math # Linked list node class Node: def __init__(self, data): self.data = data self.next = None # Function to create a new node with given data */ def newNode(data): return Node(data) # Function to reverse the linked list */ def reverseList(head): if not head: return curNode = head prevNode = head nextNode = head.next curNode.next = None while(nextNode): curNode = nextNode nextNode = nextNode.next curNode.next = prevNode prevNode = curNode return curNode # Adds one to a linked lists and return the head# node of resultant list def addOne(head): # Reverse linked list and add one to head head = reverseList(head) k = head carry = 0 prev = None head.data += 1 # update carry for next calculation while(head != None) and (head.data > 9 or carry > 0): prev = head head.data += carry carry = head.data // 10 head.data = head.data % 10 head = head.next if carry > 0: prev.next = Node(carry) # Reverse the modified list return reverseList(k) # A utility function to print a linked list def printList(head): if not head: return while(head): print("{}".format(head.data), end="") head = head.next # Driver codeif __name__ == '__main__': head = newNode(1) head.next = newNode(9) head.next.next = newNode(9) head.next.next.next = newNode(9) print("List is: ", end="") printList(head) head = addOne(head) print("\nResultant list is: ", end="") printList(head) # This code is contributed by Rohit // C# program to add 1 to a linked listusing System; class GfG { /* Linked list node */ public class Node { public int data; public Node next; } /* Function to create a new node with given data */ static Node newNode(int data) { Node new_node = new Node(); new_node.data = data; new_node.next = null; return new_node; } /* Function to reverse the linked list */ static Node reverse(Node head) { Node prev = null; Node current = head; Node next = null; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } return prev; } /* Adds one to a linked lists and return the head node of resultant list */ static Node addOneUtil(Node head) { // res is head node of the resultant list Node res = head; Node temp = null, prev = null; int carry = 1, sum; while (head != null) // while both lists exist { // Calculate value of next digit in resultant // list. The next digit is sum of following // things (i) Carry (ii) Next digit of head list // (if there is a next digit) sum = carry + head.data; // update carry for next calculation carry = (sum >= 10) ? 1 : 0; // update sum if it is greater than 10 sum = sum % 10; // Create a new node with sum as data head.data = sum; // Move head and second pointers to next nodes temp = head; head = head.next; } // if some carry is still there, add a new node to // result list. if (carry > 0) temp.next = newNode(carry); // return head of the resultant list return res; } // This function mainly uses addOneUtil(). static Node addOne(Node head) { // Reverse linked list head = reverse(head); // Add one from left to right of reversed // list head = addOneUtil(head); // Reverse the modified list return reverse(head); } // A utility function to print a linked list static void printList(Node node) { while (node != null) { Console.Write(node.data); node = node.next; } Console.WriteLine(); } /* Driver code */ public static void Main(String[] args) { Node head = newNode(1); head.next = newNode(9); head.next.next = newNode(9); head.next.next.next = newNode(9); Console.Write("List is "); printList(head); head = addOne(head); Console.WriteLine(); Console.Write("Resultant list is "); printList(head); }} // This code contributed by Rajput-Ji <script> // Javascript program to add 1 to a linked list /* Linked list node */class Node{ constructor() { this.data = 0; this.next = null; }}; /* Function to create a new node with given data */function newNode(data){ var new_node = new Node(); new_node.data = data; new_node.next = null; return new_node;} /* Function to reverse the linked list */function reverse(head){ var prev = null; var current = head; var next; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } return prev;} /* Adds one to a linked lists and return the headnode of resultant list */function addOneUtil(head){ // res is head node of the resultant list var res = head; var temp, prev = null; var carry = 1, sum; while (head != null) //while both lists exist { // Calculate value of next digit in resultant list. // The next digit is sum of following things // (i) Carry // (ii) Next digit of head list (if there is a // next digit) sum = carry + head.data; // update carry for next calculation carry = (sum >= 10)? 1 : 0; // update sum if it is greater than 10 sum = sum % 10; // Create a new node with sum as data head.data = sum; // Move head and second pointers to next nodes temp = head; head = head.next; } // if some carry is still there, add a new node to // result list. if (carry > 0) temp.next = newNode(carry); // return head of the resultant list return res;} // This function mainly uses addOneUtil().function addOne(head){ // Reverse linked list head = reverse(head); // Add one from left to right of reversed // list head = addOneUtil(head); // Reverse the modified list return reverse(head);} // A utility function to print a linked listfunction printList(node){ while (node != null) { document.write( node.data); node = node.next; } document.write("<br>");} /* Driver program to test above function */var head = newNode(1);head.next = newNode(9);head.next.next = newNode(9);head.next.next.next = newNode(9);document.write( "List is ");printList(head);head = addOne(head);document.write( "<br>Resultant list is ");printList(head); // This code is contributed by rrrtnx.</script> List is 1999 Resultant list is 2000 Recursive Implementation: We can recursively reach the last node and forward carry to previous nodes. Recursive solution doesn’t require reversing of linked list. We can also use a stack in place of recursion to temporarily hold nodes. Below is the implementation of recursive solution. C++ Java Python C# Javascript // Recursive C++ program to add 1 to a linked list#include <bits/stdc++.h> /* Linked list node */struct Node { int data; Node* next;}; /* Function to create a new node with given data */Node* newNode(int data){ Node* new_node = new Node; new_node->data = data; new_node->next = NULL; return new_node;} // Recursively add 1 from end to beginning and returns// carry after all nodes are processed.int addWithCarry(Node* head){ // If linked list is empty, then // return carry if (head == NULL) return 1; // Add carry returned be next node call int res = head->data + addWithCarry(head->next); // Update data and return new carry head->data = (res) % 10; return (res) / 10;} // This function mainly uses addWithCarry().Node* addOne(Node* head){ // Add 1 to linked list from end to beginning int carry = addWithCarry(head); // If there is carry after processing all nodes, // then we need to add a new node to linked list if (carry) { Node* newNode = new Node; newNode->data = carry; newNode->next = head; return newNode; // New node becomes head now } return head;} // A utility function to print a linked listvoid printList(Node* node){ while (node != NULL) { printf("%d", node->data); node = node->next; } printf("\n");} /* Driver code */int main(void){ Node* head = newNode(1); head->next = newNode(9); head->next->next = newNode(9); head->next->next->next = newNode(9); printf("List is "); printList(head); head = addOne(head); printf("\nResultant list is "); printList(head); return 0;} // Recursive Java program to add 1 to a linked listclass GfG { /* Linked list node */ static class Node { int data; Node next; } /* Function to create a new node with given data */ static Node newNode(int data) { Node new_node = new Node(); new_node.data = data; new_node.next = null; return new_node; } // Recursively add 1 from end to beginning and returns // carry after all nodes are processed. static int addWithCarry(Node head) { // If linked list is empty, then // return carry if (head == null) return 1; // Add carry returned be next node call int res = head.data + addWithCarry(head.next); // Update data and return new carry head.data = (res) % 10; return (res) / 10; } // This function mainly uses addWithCarry(). static Node addOne(Node head) { // Add 1 to linked list from end to beginning int carry = addWithCarry(head); // If there is carry after processing all nodes, // then we need to add a new node to linked list if (carry > 0) { Node newNode = newNode(carry); newNode.next = head; return newNode; // New node becomes head now } return head; } // A utility function to print a linked list static void printList(Node node) { while (node != null) { System.out.print(node.data); node = node.next; } System.out.println(); } /* Driver code */ public static void main(String[] args) { Node head = newNode(1); head.next = newNode(9); head.next.next = newNode(9); head.next.next.next = newNode(9); System.out.print("List is "); printList(head); head = addOne(head); System.out.println(); System.out.print("Resultant list is "); printList(head); }} // This code is contributed by shubham96301 # Recursive Python program to add 1 to a linked list # Node classclass Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None # Function to create a new node with given datadef newNode(data): new_node = Node(0) new_node.data = data new_node.next = None return new_node # Recursively add 1 from end to beginning and returns# carry after all nodes are processed.def addWithCarry(head): # If linked list is empty, then # return carry if (head == None): return 1 # Add carry returned be next node call res = head.data + addWithCarry(head.next) # Update data and return new carry head.data = int((res) % 10) return int((res) / 10) # This function mainly uses addWithCarry().def addOne(head): # Add 1 to linked list from end to beginning carry = addWithCarry(head) # If there is carry after processing all nodes, # then we need to add a new node to linked list if (carry != 0): newNode = Node(0) newNode.data = carry newNode.next = head return newNode # New node becomes head now return head # A utility function to print a linked listdef printList(node): while (node != None): print( node.data,end = "") node = node.next print("\n") # Driver program to test above function head = newNode(1)head.next = newNode(9)head.next.next = newNode(9)head.next.next.next = newNode(9) print("List is ")printList(head) head = addOne(head) print("\nResultant list is ")printList(head) # This code is contributed by Arnab Kundu // Recursive C# program to add 1 to a linked listusing System; class GfG{ /* Linked list node */ public class Node { public int data; public Node next; } /* Function to create a new node with given data */ public static Node newNode(int data) { Node new_node = new Node(); new_node.data = data; new_node.next = null; return new_node; } // Recursively add 1 from end to beginning and returns // carry after all nodes are processed. public static int addWithCarry(Node head) { // If linked list is empty, then // return carry if (head == null) return 1; // Add carry returned be next node call int res = head.data + addWithCarry(head.next); // Update data and return new carry head.data = (res) % 10; return (res) / 10; } // This function mainly uses addWithCarry(). public static Node addOne(Node head) { // Add 1 to linked list from end to beginning int carry = addWithCarry(head); Node newNodes = null; // If there is carry after processing all nodes, // then we need to add a new node to linked list if (carry > 0) { newNodes = newNode(carry); newNodes.next = head; return newNodes; // New node becomes head now } return head; } // A utility function to print a linked list public static void printList(Node node) { while (node != null) { Console.Write(node.data); node = node.next; } Console.WriteLine(); } /* Driver code */ public static void Main(String[] args) { Node head = newNode(1); head.next = newNode(9); head.next.next = newNode(9); head.next.next.next = newNode(9); Console.Write("List is "); printList(head); head = addOne(head); Console.WriteLine(); Console.Write("Resultant list is "); printList(head); }} /* This code contributed by PrinciRaj1992 */ <script> // Recursive JavaScript program // to add 1 to a linked list /* Linked list node */ class Node { constructor() { this.data = 0; this.next = null; } } /* Function to create a new node with given data */ function newNode(data) { var new_node = new Node(); new_node.data = data; new_node.next = null; return new_node; } // Recursively add 1 from end to beginning and returns // carry after all nodes are processed. function addWithCarry(head) { // If linked list is empty, then // return carry if (head == null) return 1; // Add carry returned be next node call var res = head.data + addWithCarry(head.next); // Update data and return new carry head.data = res % 10; return parseInt(res / 10); } // This function mainly uses addWithCarry(). function addOne(head) { // Add 1 to linked list from end to beginning var carry = addWithCarry(head); var newNodes = null; // If there is carry after processing all nodes, // then we need to add a new node to linked list if (carry > 0) { newNodes = newNode(carry); newNodes.next = head; return newNodes; // New node becomes head now } return head; } // A utility function to print a linked list function printList(node) { while (node != null) { document.write(node.data); node = node.next; } document.write("<br>"); } /* Driver code */ var head = newNode(1); head.next = newNode(9); head.next.next = newNode(9); head.next.next.next = newNode(9); document.write("List is "); printList(head); head = addOne(head); document.write("<br>"); document.write("Resultant list is "); printList(head); </script> List is 1999 Resultant list is 2000 Simple approach and easy implementation: The idea is to store the last non 9 digit pointer so that if the last pointer is zero we can replace all the nodes after stored node(which contains the location of last digit before 9) to 0 and add the value of the stored node by 1 C++ Java // Recursive C++ program to add 1 to a linked list#include <bits/stdc++.h> /* Linked list node */struct Node { int data; Node* next;}; /* Function to create a new node with given data */Node* newNode(int data){ Node* new_node = new Node; new_node->data = data; new_node->next = NULL; return new_node;} Node* addOne(Node* head){ // Your Code here // return head of list after adding one Node* ln = head; if (head->next == NULL) { head->data += 1; return head; } Node* t = head; int prev; while (t->next) { if (t->data != 9) { ln = t; } t = t->next; } if (t->data == 9 && ln != NULL) { if (ln->data == 9 && ln == head) { Node* temp = newNode(1); temp->next = head; head = temp; t = ln; } else { t = ln; t->data += 1; t = t->next; } while (t) { t->data = 0; t = t->next; } } else { t->data += 1; } return head;} // A utility function to print a linked listvoid printList(Node* node){ while (node != NULL) { printf("%d->", node->data); node = node->next; } printf("NULL"); printf("\n");} /* Driver code */int main(void){ Node* head = newNode(1); head->next = newNode(9); head->next->next = newNode(9); head->next->next->next = newNode(9); printf("List is "); printList(head); head = addOne(head); printf("\nResultant list is "); printList(head); return 0;}// This code is contribute bu maddler // Recursive Java program to add 1 to a linked listclass GFG{ // Linked list nodestatic class Node{ int data; Node next;} // Function to create a new node with given datastatic Node newNode(int data){ Node new_node = new Node(); new_node.data = data; new_node.next = null; return new_node;} static Node addOne(Node head){ // Return head of list after adding one Node ln = head; if (head.next == null) { head.data += 1; return head; } Node t = head; int prev; while (t.next != null) { if (t.data != 9) { ln = t; } t = t.next; } if (t.data == 9 && ln != null) { t = ln; t.data += 1; t = t.next; while (t != null) { t.data = 0; t = t.next; } } else { t.data += 1; } return head;} // A utility function to print a linked liststatic void printList(Node node){ while (node != null) { System.out.print(node.data); node = node.next; } System.out.println();} // Driver codepublic static void main(String[] args){ Node head = newNode(1); head.next = newNode(9); head.next.next = newNode(9); head.next.next.next = newNode(9); System.out.print("List is "); printList(head); head = addOne(head); System.out.println(); System.out.print("Resultant list is "); printList(head);}} // This code is contributed by rajsanghavi9. List is 1999 Resultant list is 2000 YouTubeGeeksforGeeks500K subscribersAdd 1 to a number represented as linked list | 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 / 14:09•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=utc8bwTDjLk" 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 Aditya Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above prerna saini Rajput-Ji rathbhupendra nobody_cares princiraj1992 Vikash Kumar 37 andrew1234 rv720468 maddler rrrtnx rdtank rajsanghavi9 gulshankumarar231 simmytarika5 sambitskd3 Amazon Linked List Amazon Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments LinkedList in Java Doubly Linked List | Set 1 (Introduction and Insertion) Linked List vs Array Queue - Linked List Implementation Implementing a Linked List in Java using Class Implement a stack using singly linked list Merge two sorted linked lists Circular Linked List | Set 1 (Introduction and Applications) Merge Sort for Linked Lists Remove duplicates from a sorted linked list
[ { "code": null, "e": 24520, "s": 24492, "text": "\n04 Feb, 2022" }, { "code": null, "e": 24734, "s": 24520, "text": "Number is represented in linked list such that each digit corresponds to a node in linked list. Add 1 to it. For example 1999 is represented as (1-> 9-> 9 -> 9) and adding 1 to it should change it to (2->0->0->0) " }, { "code": null, "e": 24757, "s": 24734, "text": "Below are the steps : " }, { "code": null, "e": 25050, "s": 24757, "text": "Reverse given linked list. For example, 1-> 9-> 9 -> 9 is converted to 9-> 9 -> 9 ->1.Start traversing linked list from leftmost node and add 1 to it. If there is a carry, move to the next node. Keep moving to the next node while there is a carry.Reverse modified linked list and return head." }, { "code": null, "e": 25137, "s": 25050, "text": "Reverse given linked list. For example, 1-> 9-> 9 -> 9 is converted to 9-> 9 -> 9 ->1." }, { "code": null, "e": 25299, "s": 25137, "text": "Start traversing linked list from leftmost node and add 1 to it. If there is a carry, move to the next node. Keep moving to the next node while there is a carry." }, { "code": null, "e": 25345, "s": 25299, "text": "Reverse modified linked list and return head." }, { "code": null, "e": 25390, "s": 25345, "text": "Below is the implementation of above steps. " }, { "code": null, "e": 25394, "s": 25390, "text": "C++" }, { "code": null, "e": 25396, "s": 25394, "text": "C" }, { "code": null, "e": 25401, "s": 25396, "text": "Java" }, { "code": null, "e": 25409, "s": 25401, "text": "Python3" }, { "code": null, "e": 25412, "s": 25409, "text": "C#" }, { "code": null, "e": 25423, "s": 25412, "text": "Javascript" }, { "code": "// C++ program to add 1 to a linked list#include <bits/stdc++.h>using namespace std; /* Linked list node */class Node{ public: int data; Node* next;}; /* Function to create a new node with given data */Node *newNode(int data){ Node *new_node = new Node; new_node->data = data; new_node->next = NULL; return new_node;} /* Function to reverse the linked list */Node *reverse(Node *head){ Node * prev = NULL; Node * current = head; Node * next; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } return prev;} /* Adds one to a linked lists and return the headnode of resultant list */Node *addOneUtil(Node *head){ // res is head node of the resultant list Node* res = head; Node *temp; int carry = 1, sum; while (head != NULL) //while both lists exist { // Calculate value of next digit in resultant list. // The next digit is sum of following things // (i) Carry // (ii) Next digit of head list (if there is a // next digit) sum = carry + head->data; // update carry for next calculation carry = (sum >= 10)? 1 : 0; // update sum if it is greater than 10 sum = sum % 10; // Create a new node with sum as data head->data = sum; // Move head and second pointers to next nodes temp = head; head = head->next; } // if some carry is still there, add a new node to // result list. if (carry > 0) temp->next = newNode(carry); // return head of the resultant list return res;} // This function mainly uses addOneUtil().Node* addOne(Node *head){ // Reverse linked list head = reverse(head); // Add one from left to right of reversed // list head = addOneUtil(head); // Reverse the modified list return reverse(head);} // A utility function to print a linked listvoid printList(Node *node){ while (node != NULL) { cout << node->data; node = node->next; } cout<<endl;} /* Driver program to test above function */int main(void){ Node *head = newNode(1); head->next = newNode(9); head->next->next = newNode(9); head->next->next->next = newNode(9); cout << \"List is \"; printList(head); head = addOne(head); cout << \"\\nResultant list is \"; printList(head); return 0;} // This is code is contributed by rathbhupendra", "e": 27884, "s": 25423, "text": null }, { "code": "// C program to add 1 to a linked list#include<bits/stdc++.h> /* Linked list node */struct Node{ int data; Node* next;}; /* Function to create a new node with given data */Node *newNode(int data){ Node *new_node = new Node; new_node->data = data; new_node->next = NULL; return new_node;} /* Function to reverse the linked list */Node *reverse(Node *head){ Node * prev = NULL; Node * current = head; Node * next; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } return prev;} /* Adds one to a linked lists and return the head node of resultant list */Node *addOneUtil(Node *head){ // res is head node of the resultant list Node* res = head; Node *temp, *prev = NULL; int carry = 1, sum; while (head != NULL) //while both lists exist { // Calculate value of next digit in resultant list. // The next digit is sum of following things // (i) Carry // (ii) Next digit of head list (if there is a // next digit) sum = carry + head->data; // update carry for next calculation carry = (sum >= 10)? 1 : 0; // update sum if it is greater than 10 sum = sum % 10; // Create a new node with sum as data head->data = sum; // Move head and second pointers to next nodes temp = head; head = head->next; } // if some carry is still there, add a new node to // result list. if (carry > 0) temp->next = newNode(carry); // return head of the resultant list return res;} // This function mainly uses addOneUtil().Node* addOne(Node *head){ // Reverse linked list head = reverse(head); // Add one from left to right of reversed // list head = addOneUtil(head); // Reverse the modified list return reverse(head);} // A utility function to print a linked listvoid printList(Node *node){ while (node != NULL) { printf(\"%d\", node->data); node = node->next; } printf(\"\\n\");} /* Driver program to test above function */int main(void){ Node *head = newNode(1); head->next = newNode(9); head->next->next = newNode(9); head->next->next->next = newNode(9); printf(\"List is \"); printList(head); head = addOne(head); printf(\"\\nResultant list is \"); printList(head); return 0;}", "e": 30296, "s": 27884, "text": null }, { "code": "// Java program to add 1 to a linked listclass GfG { /* Linked list node */ static class Node { int data; Node next; } /* Function to create a new node with given data */ static Node newNode(int data) { Node new_node = new Node(); new_node.data = data; new_node.next = null; return new_node; } /* Function to reverse the linked list */ static Node reverse(Node head) { Node prev = null; Node current = head; Node next = null; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } return prev; } /* Adds one to a linked lists and return the head node of resultant list */ static Node addOneUtil(Node head) { // res is head node of the resultant list Node res = head; Node temp = null, prev = null; int carry = 1, sum; while (head != null) // while both lists exist { // Calculate value of next digit in resultant // list. The next digit is sum of following // things (i) Carry (ii) Next digit of head list // (if there is a next digit) sum = carry + head.data; // update carry for next calculation carry = (sum >= 10) ? 1 : 0; // update sum if it is greater than 10 sum = sum % 10; // Create a new node with sum as data head.data = sum; // Move head and second pointers to next nodes temp = head; head = head.next; } // if some carry is still there, add a new node to // result list. if (carry > 0) temp.next = newNode(carry); // return head of the resultant list return res; } // This function mainly uses addOneUtil(). static Node addOne(Node head) { // Reverse linked list head = reverse(head); // Add one from left to right of reversed // list head = addOneUtil(head); // Reverse the modified list return reverse(head); } // A utility function to print a linked list static void printList(Node node) { while (node != null) { System.out.print(node.data); node = node.next; } System.out.println(); } /* Driver code */ public static void main(String[] args) { Node head = newNode(1); head.next = newNode(9); head.next.next = newNode(9); head.next.next.next = newNode(9); System.out.print(\"List is \"); printList(head); head = addOne(head); System.out.println(); System.out.print(\"Resultant list is \"); printList(head); }} // This code is contributed by prerna saini", "e": 33151, "s": 30296, "text": null }, { "code": "# Python3 program to add 1 to a linked listimport sysimport math # Linked list node class Node: def __init__(self, data): self.data = data self.next = None # Function to create a new node with given data */ def newNode(data): return Node(data) # Function to reverse the linked list */ def reverseList(head): if not head: return curNode = head prevNode = head nextNode = head.next curNode.next = None while(nextNode): curNode = nextNode nextNode = nextNode.next curNode.next = prevNode prevNode = curNode return curNode # Adds one to a linked lists and return the head# node of resultant list def addOne(head): # Reverse linked list and add one to head head = reverseList(head) k = head carry = 0 prev = None head.data += 1 # update carry for next calculation while(head != None) and (head.data > 9 or carry > 0): prev = head head.data += carry carry = head.data // 10 head.data = head.data % 10 head = head.next if carry > 0: prev.next = Node(carry) # Reverse the modified list return reverseList(k) # A utility function to print a linked list def printList(head): if not head: return while(head): print(\"{}\".format(head.data), end=\"\") head = head.next # Driver codeif __name__ == '__main__': head = newNode(1) head.next = newNode(9) head.next.next = newNode(9) head.next.next.next = newNode(9) print(\"List is: \", end=\"\") printList(head) head = addOne(head) print(\"\\nResultant list is: \", end=\"\") printList(head) # This code is contributed by Rohit", "e": 34820, "s": 33151, "text": null }, { "code": "// C# program to add 1 to a linked listusing System; class GfG { /* Linked list node */ public class Node { public int data; public Node next; } /* Function to create a new node with given data */ static Node newNode(int data) { Node new_node = new Node(); new_node.data = data; new_node.next = null; return new_node; } /* Function to reverse the linked list */ static Node reverse(Node head) { Node prev = null; Node current = head; Node next = null; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } return prev; } /* Adds one to a linked lists and return the head node of resultant list */ static Node addOneUtil(Node head) { // res is head node of the resultant list Node res = head; Node temp = null, prev = null; int carry = 1, sum; while (head != null) // while both lists exist { // Calculate value of next digit in resultant // list. The next digit is sum of following // things (i) Carry (ii) Next digit of head list // (if there is a next digit) sum = carry + head.data; // update carry for next calculation carry = (sum >= 10) ? 1 : 0; // update sum if it is greater than 10 sum = sum % 10; // Create a new node with sum as data head.data = sum; // Move head and second pointers to next nodes temp = head; head = head.next; } // if some carry is still there, add a new node to // result list. if (carry > 0) temp.next = newNode(carry); // return head of the resultant list return res; } // This function mainly uses addOneUtil(). static Node addOne(Node head) { // Reverse linked list head = reverse(head); // Add one from left to right of reversed // list head = addOneUtil(head); // Reverse the modified list return reverse(head); } // A utility function to print a linked list static void printList(Node node) { while (node != null) { Console.Write(node.data); node = node.next; } Console.WriteLine(); } /* Driver code */ public static void Main(String[] args) { Node head = newNode(1); head.next = newNode(9); head.next.next = newNode(9); head.next.next.next = newNode(9); Console.Write(\"List is \"); printList(head); head = addOne(head); Console.WriteLine(); Console.Write(\"Resultant list is \"); printList(head); }} // This code contributed by Rajput-Ji", "e": 37684, "s": 34820, "text": null }, { "code": "<script> // Javascript program to add 1 to a linked list /* Linked list node */class Node{ constructor() { this.data = 0; this.next = null; }}; /* Function to create a new node with given data */function newNode(data){ var new_node = new Node(); new_node.data = data; new_node.next = null; return new_node;} /* Function to reverse the linked list */function reverse(head){ var prev = null; var current = head; var next; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } return prev;} /* Adds one to a linked lists and return the headnode of resultant list */function addOneUtil(head){ // res is head node of the resultant list var res = head; var temp, prev = null; var carry = 1, sum; while (head != null) //while both lists exist { // Calculate value of next digit in resultant list. // The next digit is sum of following things // (i) Carry // (ii) Next digit of head list (if there is a // next digit) sum = carry + head.data; // update carry for next calculation carry = (sum >= 10)? 1 : 0; // update sum if it is greater than 10 sum = sum % 10; // Create a new node with sum as data head.data = sum; // Move head and second pointers to next nodes temp = head; head = head.next; } // if some carry is still there, add a new node to // result list. if (carry > 0) temp.next = newNode(carry); // return head of the resultant list return res;} // This function mainly uses addOneUtil().function addOne(head){ // Reverse linked list head = reverse(head); // Add one from left to right of reversed // list head = addOneUtil(head); // Reverse the modified list return reverse(head);} // A utility function to print a linked listfunction printList(node){ while (node != null) { document.write( node.data); node = node.next; } document.write(\"<br>\");} /* Driver program to test above function */var head = newNode(1);head.next = newNode(9);head.next.next = newNode(9);head.next.next.next = newNode(9);document.write( \"List is \");printList(head);head = addOne(head);document.write( \"<br>Resultant list is \");printList(head); // This code is contributed by rrrtnx.</script>", "e": 40094, "s": 37684, "text": null }, { "code": null, "e": 40131, "s": 40094, "text": "List is 1999\n\nResultant list is 2000" }, { "code": null, "e": 40367, "s": 40131, "text": "Recursive Implementation: We can recursively reach the last node and forward carry to previous nodes. Recursive solution doesn’t require reversing of linked list. We can also use a stack in place of recursion to temporarily hold nodes." }, { "code": null, "e": 40418, "s": 40367, "text": "Below is the implementation of recursive solution." }, { "code": null, "e": 40422, "s": 40418, "text": "C++" }, { "code": null, "e": 40427, "s": 40422, "text": "Java" }, { "code": null, "e": 40434, "s": 40427, "text": "Python" }, { "code": null, "e": 40437, "s": 40434, "text": "C#" }, { "code": null, "e": 40448, "s": 40437, "text": "Javascript" }, { "code": "// Recursive C++ program to add 1 to a linked list#include <bits/stdc++.h> /* Linked list node */struct Node { int data; Node* next;}; /* Function to create a new node with given data */Node* newNode(int data){ Node* new_node = new Node; new_node->data = data; new_node->next = NULL; return new_node;} // Recursively add 1 from end to beginning and returns// carry after all nodes are processed.int addWithCarry(Node* head){ // If linked list is empty, then // return carry if (head == NULL) return 1; // Add carry returned be next node call int res = head->data + addWithCarry(head->next); // Update data and return new carry head->data = (res) % 10; return (res) / 10;} // This function mainly uses addWithCarry().Node* addOne(Node* head){ // Add 1 to linked list from end to beginning int carry = addWithCarry(head); // If there is carry after processing all nodes, // then we need to add a new node to linked list if (carry) { Node* newNode = new Node; newNode->data = carry; newNode->next = head; return newNode; // New node becomes head now } return head;} // A utility function to print a linked listvoid printList(Node* node){ while (node != NULL) { printf(\"%d\", node->data); node = node->next; } printf(\"\\n\");} /* Driver code */int main(void){ Node* head = newNode(1); head->next = newNode(9); head->next->next = newNode(9); head->next->next->next = newNode(9); printf(\"List is \"); printList(head); head = addOne(head); printf(\"\\nResultant list is \"); printList(head); return 0;}", "e": 42096, "s": 40448, "text": null }, { "code": "// Recursive Java program to add 1 to a linked listclass GfG { /* Linked list node */ static class Node { int data; Node next; } /* Function to create a new node with given data */ static Node newNode(int data) { Node new_node = new Node(); new_node.data = data; new_node.next = null; return new_node; } // Recursively add 1 from end to beginning and returns // carry after all nodes are processed. static int addWithCarry(Node head) { // If linked list is empty, then // return carry if (head == null) return 1; // Add carry returned be next node call int res = head.data + addWithCarry(head.next); // Update data and return new carry head.data = (res) % 10; return (res) / 10; } // This function mainly uses addWithCarry(). static Node addOne(Node head) { // Add 1 to linked list from end to beginning int carry = addWithCarry(head); // If there is carry after processing all nodes, // then we need to add a new node to linked list if (carry > 0) { Node newNode = newNode(carry); newNode.next = head; return newNode; // New node becomes head now } return head; } // A utility function to print a linked list static void printList(Node node) { while (node != null) { System.out.print(node.data); node = node.next; } System.out.println(); } /* Driver code */ public static void main(String[] args) { Node head = newNode(1); head.next = newNode(9); head.next.next = newNode(9); head.next.next.next = newNode(9); System.out.print(\"List is \"); printList(head); head = addOne(head); System.out.println(); System.out.print(\"Resultant list is \"); printList(head); }} // This code is contributed by shubham96301", "e": 44108, "s": 42096, "text": null }, { "code": "# Recursive Python program to add 1 to a linked list # Node classclass Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None # Function to create a new node with given datadef newNode(data): new_node = Node(0) new_node.data = data new_node.next = None return new_node # Recursively add 1 from end to beginning and returns# carry after all nodes are processed.def addWithCarry(head): # If linked list is empty, then # return carry if (head == None): return 1 # Add carry returned be next node call res = head.data + addWithCarry(head.next) # Update data and return new carry head.data = int((res) % 10) return int((res) / 10) # This function mainly uses addWithCarry().def addOne(head): # Add 1 to linked list from end to beginning carry = addWithCarry(head) # If there is carry after processing all nodes, # then we need to add a new node to linked list if (carry != 0): newNode = Node(0) newNode.data = carry newNode.next = head return newNode # New node becomes head now return head # A utility function to print a linked listdef printList(node): while (node != None): print( node.data,end = \"\") node = node.next print(\"\\n\") # Driver program to test above function head = newNode(1)head.next = newNode(9)head.next.next = newNode(9)head.next.next.next = newNode(9) print(\"List is \")printList(head) head = addOne(head) print(\"\\nResultant list is \")printList(head) # This code is contributed by Arnab Kundu", "e": 45728, "s": 44108, "text": null }, { "code": "// Recursive C# program to add 1 to a linked listusing System; class GfG{ /* Linked list node */ public class Node { public int data; public Node next; } /* Function to create a new node with given data */ public static Node newNode(int data) { Node new_node = new Node(); new_node.data = data; new_node.next = null; return new_node; } // Recursively add 1 from end to beginning and returns // carry after all nodes are processed. public static int addWithCarry(Node head) { // If linked list is empty, then // return carry if (head == null) return 1; // Add carry returned be next node call int res = head.data + addWithCarry(head.next); // Update data and return new carry head.data = (res) % 10; return (res) / 10; } // This function mainly uses addWithCarry(). public static Node addOne(Node head) { // Add 1 to linked list from end to beginning int carry = addWithCarry(head); Node newNodes = null; // If there is carry after processing all nodes, // then we need to add a new node to linked list if (carry > 0) { newNodes = newNode(carry); newNodes.next = head; return newNodes; // New node becomes head now } return head; } // A utility function to print a linked list public static void printList(Node node) { while (node != null) { Console.Write(node.data); node = node.next; } Console.WriteLine(); } /* Driver code */ public static void Main(String[] args) { Node head = newNode(1); head.next = newNode(9); head.next.next = newNode(9); head.next.next.next = newNode(9); Console.Write(\"List is \"); printList(head); head = addOne(head); Console.WriteLine(); Console.Write(\"Resultant list is \"); printList(head); }} /* This code contributed by PrinciRaj1992 */", "e": 47818, "s": 45728, "text": null }, { "code": "<script> // Recursive JavaScript program // to add 1 to a linked list /* Linked list node */ class Node { constructor() { this.data = 0; this.next = null; } } /* Function to create a new node with given data */ function newNode(data) { var new_node = new Node(); new_node.data = data; new_node.next = null; return new_node; } // Recursively add 1 from end to beginning and returns // carry after all nodes are processed. function addWithCarry(head) { // If linked list is empty, then // return carry if (head == null) return 1; // Add carry returned be next node call var res = head.data + addWithCarry(head.next); // Update data and return new carry head.data = res % 10; return parseInt(res / 10); } // This function mainly uses addWithCarry(). function addOne(head) { // Add 1 to linked list from end to beginning var carry = addWithCarry(head); var newNodes = null; // If there is carry after processing all nodes, // then we need to add a new node to linked list if (carry > 0) { newNodes = newNode(carry); newNodes.next = head; return newNodes; // New node becomes head now } return head; } // A utility function to print a linked list function printList(node) { while (node != null) { document.write(node.data); node = node.next; } document.write(\"<br>\"); } /* Driver code */ var head = newNode(1); head.next = newNode(9); head.next.next = newNode(9); head.next.next.next = newNode(9); document.write(\"List is \"); printList(head); head = addOne(head); document.write(\"<br>\"); document.write(\"Resultant list is \"); printList(head); </script>", "e": 49767, "s": 47818, "text": null }, { "code": null, "e": 49807, "s": 49770, "text": "List is 1999\n\nResultant list is 2000" }, { "code": null, "e": 50082, "s": 49809, "text": "Simple approach and easy implementation: The idea is to store the last non 9 digit pointer so that if the last pointer is zero we can replace all the nodes after stored node(which contains the location of last digit before 9) to 0 and add the value of the stored node by 1" }, { "code": null, "e": 50088, "s": 50084, "text": "C++" }, { "code": null, "e": 50093, "s": 50088, "text": "Java" }, { "code": "// Recursive C++ program to add 1 to a linked list#include <bits/stdc++.h> /* Linked list node */struct Node { int data; Node* next;}; /* Function to create a new node with given data */Node* newNode(int data){ Node* new_node = new Node; new_node->data = data; new_node->next = NULL; return new_node;} Node* addOne(Node* head){ // Your Code here // return head of list after adding one Node* ln = head; if (head->next == NULL) { head->data += 1; return head; } Node* t = head; int prev; while (t->next) { if (t->data != 9) { ln = t; } t = t->next; } if (t->data == 9 && ln != NULL) { if (ln->data == 9 && ln == head) { Node* temp = newNode(1); temp->next = head; head = temp; t = ln; } else { t = ln; t->data += 1; t = t->next; } while (t) { t->data = 0; t = t->next; } } else { t->data += 1; } return head;} // A utility function to print a linked listvoid printList(Node* node){ while (node != NULL) { printf(\"%d->\", node->data); node = node->next; } printf(\"NULL\"); printf(\"\\n\");} /* Driver code */int main(void){ Node* head = newNode(1); head->next = newNode(9); head->next->next = newNode(9); head->next->next->next = newNode(9); printf(\"List is \"); printList(head); head = addOne(head); printf(\"\\nResultant list is \"); printList(head); return 0;}// This code is contribute bu maddler", "e": 51697, "s": 50093, "text": null }, { "code": "// Recursive Java program to add 1 to a linked listclass GFG{ // Linked list nodestatic class Node{ int data; Node next;} // Function to create a new node with given datastatic Node newNode(int data){ Node new_node = new Node(); new_node.data = data; new_node.next = null; return new_node;} static Node addOne(Node head){ // Return head of list after adding one Node ln = head; if (head.next == null) { head.data += 1; return head; } Node t = head; int prev; while (t.next != null) { if (t.data != 9) { ln = t; } t = t.next; } if (t.data == 9 && ln != null) { t = ln; t.data += 1; t = t.next; while (t != null) { t.data = 0; t = t.next; } } else { t.data += 1; } return head;} // A utility function to print a linked liststatic void printList(Node node){ while (node != null) { System.out.print(node.data); node = node.next; } System.out.println();} // Driver codepublic static void main(String[] args){ Node head = newNode(1); head.next = newNode(9); head.next.next = newNode(9); head.next.next.next = newNode(9); System.out.print(\"List is \"); printList(head); head = addOne(head); System.out.println(); System.out.print(\"Resultant list is \"); printList(head);}} // This code is contributed by rajsanghavi9.", "e": 53169, "s": 51697, "text": null }, { "code": null, "e": 53209, "s": 53172, "text": "List is 1999\n\nResultant list is 2000" }, { "code": null, "e": 54055, "s": 53211, "text": "YouTubeGeeksforGeeks500K subscribersAdd 1 to a number represented as linked list | 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 / 14:09•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=utc8bwTDjLk\" 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": 54226, "s": 54057, "text": "This article is contributed by Aditya Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 54245, "s": 54232, "text": "prerna saini" }, { "code": null, "e": 54255, "s": 54245, "text": "Rajput-Ji" }, { "code": null, "e": 54269, "s": 54255, "text": "rathbhupendra" }, { "code": null, "e": 54282, "s": 54269, "text": "nobody_cares" }, { "code": null, "e": 54296, "s": 54282, "text": "princiraj1992" }, { "code": null, "e": 54312, "s": 54296, "text": "Vikash Kumar 37" }, { "code": null, "e": 54323, "s": 54312, "text": "andrew1234" }, { "code": null, "e": 54332, "s": 54323, "text": "rv720468" }, { "code": null, "e": 54340, "s": 54332, "text": "maddler" }, { "code": null, "e": 54347, "s": 54340, "text": "rrrtnx" }, { "code": null, "e": 54354, "s": 54347, "text": "rdtank" }, { "code": null, "e": 54367, "s": 54354, "text": "rajsanghavi9" }, { "code": null, "e": 54385, "s": 54367, "text": "gulshankumarar231" }, { "code": null, "e": 54398, "s": 54385, "text": "simmytarika5" }, { "code": null, "e": 54409, "s": 54398, "text": "sambitskd3" }, { "code": null, "e": 54416, "s": 54409, "text": "Amazon" }, { "code": null, "e": 54428, "s": 54416, "text": "Linked List" }, { "code": null, "e": 54435, "s": 54428, "text": "Amazon" }, { "code": null, "e": 54447, "s": 54435, "text": "Linked List" }, { "code": null, "e": 54545, "s": 54447, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 54554, "s": 54545, "text": "Comments" }, { "code": null, "e": 54567, "s": 54554, "text": "Old Comments" }, { "code": null, "e": 54586, "s": 54567, "text": "LinkedList in Java" }, { "code": null, "e": 54642, "s": 54586, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" }, { "code": null, "e": 54663, "s": 54642, "text": "Linked List vs Array" }, { "code": null, "e": 54698, "s": 54663, "text": "Queue - Linked List Implementation" }, { "code": null, "e": 54745, "s": 54698, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 54788, "s": 54745, "text": "Implement a stack using singly linked list" }, { "code": null, "e": 54818, "s": 54788, "text": "Merge two sorted linked lists" }, { "code": null, "e": 54879, "s": 54818, "text": "Circular Linked List | Set 1 (Introduction and Applications)" }, { "code": null, "e": 54907, "s": 54879, "text": "Merge Sort for Linked Lists" } ]
Reduce the string by removing K consecutive identical characters - GeeksforGeeks
29 Nov, 2021 Given a string str and an integer K, the task is to reduce the string by applying the following operation any number of times until it is no longer possible: Choose a group of K consecutive identical characters and remove them from the string. Finally, print the reduced string. Examples: Input: K = 2, str = “geeksforgeeks” Output: gksforgks Explanation: After removal of both occurrences of the substring “ee”, the string reduces to “gksforgks”. Input: K = 3, str = “qddxxxd” Output: q Explanation: Removal of “xxx” modifies the string to “qddd”. Again, removal of “ddd”modifies the string to “q”. Approach: This problem can be solved using the Stack data structure. Follow the steps below to solve the problem: Initialize a stack of pair<char, int>, to store characters and their respective consecutive frequencies. Iterate over the characters of the string. If the current character is different from the character present currently at the top of the stack, then set its frequency to 1. Otherwise, if the current character is the same as the character at the top of the stack, then increase its frequency by 1. If the frequency of the character at the top of the stack is K, pop that out of the stack. Finally, print the characters which are remaining in the stack as the resultant string. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // CPP program for the above approach#include <bits/stdc++.h>#include <iostream>using namespace std; // Basic Approach is to create a Stack that store the// Character and its continuous repetition number This is// done using pair<char,int> Further we check at each// iteration, whether the character matches the top of stack// if it does then check for number of repetitions// else add to top of stack with count 1 class Solution {public: string remove_k_char(int k, string s) { // Base Case // If k=1 then all characters // can be removed at each // instance if (k == 1) return ""; // initialize string string output = ""; // create a stack using pair<> for storing each // character and corresponding // repetition stack<pair<char, int> > stk; // iterate through the string for (int i = 0; i < s.length(); i++) { // if stack is empty then simply add the // character with count 1 else check if // character is same as top of stack if (stk.empty() == true) { stk.push(make_pair(s[i], 1)); } else { // if character at top of stack is same as // current character increase the number of // repetitions in the top of stack by 1 if (s[i] == (stk.top()).first) { stk.push( { s[i], stk.top().second + 1 }); if (stk.top().second == k) { int x = k; while (x) { stk.pop(); x--; } } } else { // if character at top of stack is not // same as current character push the // character along with count 1 into the // top of stack stk.push(make_pair(s[i], 1)); } } } // Iterate through the stack // Use string(int,char) in order to replicate the // character multiple times and convert into string // then add in front of output string while (!stk.empty()) { output += stk.top().first; stk.pop(); } reverse(output.begin(), output.end()); return output; }}; // Driver Codeint main(){ string s = "geeksforgeeks"; int k = 2; Solution obj; cout << obj.remove_k_char(k, s) << "\n"; return 0;} // This code has been contributed by Navansh Goel // Java implementation of the approachimport java.util.*; class GFG { // Function to find the reduced string public static String reduced_String(int k, String s) { // Base Case if (k == 1) { String ans = ""; return ans; } // Creating a stack of type Pair Stack<Pair> st = new Stack<Pair>(); // Length of the string S int l = s.length(); int ctr = 0; // iterate through the string for (int i = 0; i < l; i++) { // if stack is empty then simply add the // character with count 1 else check if // character is same as top of stack if (st.size() == 0) { st.push(new Pair(s.charAt(i), 1)); continue; } // if character at top of stack is same as // current character increase the number of // repetitions in the top of stack by 1 if (st.peek().c == s.charAt(i)) { Pair p = st.peek(); st.pop(); p.ctr += 1; if (p.ctr == k) { continue; } else { st.push(p); } } else { // if character at top of stack is not // same as current character push the // character along with count 1 into the // top of stack st.push(new Pair(s.charAt(i), 1)); } } // iterate through the stack // Use string(int,char) in order to replicate the // character multiple times and convert into string // then add in front of output string String ans = ""; while (st.size() > 0) { char c = st.peek().c; int cnt = st.peek().ctr; while (cnt-- > 0) ans = c + ans; st.pop(); } return ans; } // Driver code public static void main(String[] args) { int k = 2; String st = "geeksforgeeks"; String ans = reduced_String(k, st); System.out.println(ans); } static class Pair { char c; int ctr; Pair(char c, int ctr) { this.c = c; this.ctr = ctr; } }} # Python3 implementation of the approach # Pair class to store character and freqclass Pair: def __init__(self,c ,ctr): self.c= c self.ctr = ctr class Solution: # Function to find the reduced string def reduced_String(self , k , s): #Base Case if (k == 1): return "" # Creating a stack of type Pair st = [] # iterate through given string for i in range(len(s)): # if stack is empty then simply add the # character with count 1 else check if # character is same as top of stack if (len(st) == 0): st.append((Pair(s[i] , 1))) continue # if character at top of stack is same as # current character increase the number of # repetitions in the top of stack by 1 if (st[-1].c == s[i]): pair = st.pop() pair.ctr +=1 if (pair.ctr == k): continue else: st.append(pair) else: # if character at top of stack is not # same as current character push the # character along with count 1 into the # top of stack st.append((Pair(s[i] , 1))) # Iterate through the stack # Use string(int,char) in order to replicate the # character multiple times and convert into string # then add in front of output string ans = "" while(len(st) > 0): c = st[-1].c cnt = st[-1].ctr while(cnt >0): ans = c + ans cnt -= 1 st.pop() return (ans) # Driver codeif __name__ == "__main__": k = 2 s = "geeksforgeeks" obj = Solution() print(obj.reduced_String(k,s)) # This code is contributed by chantya17. // C# implementation of the above approachusing System;using System.Collections.Generic;public class GFG { // Function to find the reduced string public static String reduced_String(int k, String s) { // Base Case if (k == 1) { return ""; } // Creating a stack of type Pair Stack<Pair> st = new Stack<Pair>(); // Length of the string S int l = s.Length; // iterate through the string for (int i = 0; i < l; i++) { // if stack is empty then simply add the // character with count 1 else check if // character is same as top of stack if (st.Count == 0) { st.Push(new Pair(s[i], 1)); continue; } // if character at top of stack is same as // current character increase the number of // repetitions in the top of stack by 1 if (st.Peek().c == s[i]) { Pair p = st.Peek(); st.Pop(); p.ctr += 1; if (p.ctr == k) { continue; } else { st.Push(p); } } else { // if character at top of stack is not // same as current character push the // character along with count 1 into the // top of stack st.Push(new Pair(s[i], 1)); } } // iterate through the stack // Use string(int,char) in order to replicate the // character multiple times and convert into string // then add in front of output string String ans = ""; while (st.Count > 0) { char c = st.Peek().c; int cnt = st.Peek().ctr; while (cnt-- > 0) ans = c + ans; st.Pop(); } return ans; } // Driver code public static void Main(String[] args) { int k = 2; String st = "geeksforgeeks"; String ans = reduced_String(k, st); Console.Write(ans); } public class Pair { public char c; public int ctr; public Pair(char c, int ctr) { this.c = c; this.ctr = ctr; } }}// This code has been contributed by 29AjayKumar <script>// Javascript implementation of the approach class Pair{ constructor(c,ctr) { this.c = c; this.ctr = ctr; }} // Function to find the reduced stringfunction reduced_String(k,s){ // Base Case if (k == 1) { let ans = ""; return ans; } // Creating a stack of type Pair let st = []; // Length of the string S let l = s.length; let ctr = 0; // iterate through the string for (let i = 0; i < l; i++) { // if stack is empty then simply add the // character with count 1 else check if // character is same as top of stack if (st.length == 0) { st.push(new Pair(s[i], 1)); continue; } // if character at top of stack is same as // current character increase the number of // repetitions in the top of stack by 1 if (st[st.length-1].c == s[i]) { let p = st[st.length-1]; st.pop(); p.ctr += 1; if (p.ctr == k) { continue; } else { st.push(p); } } else { // if character at top of stack is not // same as current character push the // character along with count 1 into the // top of stack st.push(new Pair(s[i], 1)); } } // iterate through the stack // Use string(int,char) in order to replicate the // character multiple times and convert into string // then add in front of output string let ans = ""; while (st.length > 0) { let c = st[st.length-1].c; let cnt = st[st.length-1].ctr; while (cnt-- > 0) ans = c + ans; st.pop(); } return ans;} // Driver codelet k = 2;let st = "geeksforgeeks";let ans = reduced_String(k, st);document.write(ans+"<br>"); // This code is contributed by rag2127</script> gksforgks Time Complexity: O(N) Auxiliary Space: O(N) imdhruvgupta 29AjayKumar Akanksha_Rai navanshgoel UtkarshPandey6 simmytarika5 rag2127 tejendrapratap amartyaniel20 chantya17 surinderdawra388 Competitive Programming Hash Stack Strings Hash Strings Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Prefix Sum Array - Implementation and Applications in Competitive Programming Ordered Set and GNU C++ PBDS Multistage Graph (Shortest Path) 7 Best Coding Challenge Websites in 2020 What is Competitive Programming and How to Prepare for It? 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) Hashing | Set 3 (Open Addressing) Hashing | Set 2 (Separate Chaining)
[ { "code": null, "e": 26753, "s": 26725, "text": "\n29 Nov, 2021" }, { "code": null, "e": 26911, "s": 26753, "text": "Given a string str and an integer K, the task is to reduce the string by applying the following operation any number of times until it is no longer possible:" }, { "code": null, "e": 26997, "s": 26911, "text": "Choose a group of K consecutive identical characters and remove them from the string." }, { "code": null, "e": 27032, "s": 26997, "text": "Finally, print the reduced string." }, { "code": null, "e": 27044, "s": 27032, "text": "Examples: " }, { "code": null, "e": 27203, "s": 27044, "text": "Input: K = 2, str = “geeksforgeeks” Output: gksforgks Explanation: After removal of both occurrences of the substring “ee”, the string reduces to “gksforgks”." }, { "code": null, "e": 27356, "s": 27203, "text": "Input: K = 3, str = “qddxxxd” Output: q Explanation: Removal of “xxx” modifies the string to “qddd”. Again, removal of “ddd”modifies the string to “q”. " }, { "code": null, "e": 27470, "s": 27356, "text": "Approach: This problem can be solved using the Stack data structure. Follow the steps below to solve the problem:" }, { "code": null, "e": 27575, "s": 27470, "text": "Initialize a stack of pair<char, int>, to store characters and their respective consecutive frequencies." }, { "code": null, "e": 27618, "s": 27575, "text": "Iterate over the characters of the string." }, { "code": null, "e": 27747, "s": 27618, "text": "If the current character is different from the character present currently at the top of the stack, then set its frequency to 1." }, { "code": null, "e": 27871, "s": 27747, "text": "Otherwise, if the current character is the same as the character at the top of the stack, then increase its frequency by 1." }, { "code": null, "e": 27962, "s": 27871, "text": "If the frequency of the character at the top of the stack is K, pop that out of the stack." }, { "code": null, "e": 28050, "s": 27962, "text": "Finally, print the characters which are remaining in the stack as the resultant string." }, { "code": null, "e": 28102, "s": 28050, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 28106, "s": 28102, "text": "C++" }, { "code": null, "e": 28111, "s": 28106, "text": "Java" }, { "code": null, "e": 28119, "s": 28111, "text": "Python3" }, { "code": null, "e": 28122, "s": 28119, "text": "C#" }, { "code": null, "e": 28133, "s": 28122, "text": "Javascript" }, { "code": "// CPP program for the above approach#include <bits/stdc++.h>#include <iostream>using namespace std; // Basic Approach is to create a Stack that store the// Character and its continuous repetition number This is// done using pair<char,int> Further we check at each// iteration, whether the character matches the top of stack// if it does then check for number of repetitions// else add to top of stack with count 1 class Solution {public: string remove_k_char(int k, string s) { // Base Case // If k=1 then all characters // can be removed at each // instance if (k == 1) return \"\"; // initialize string string output = \"\"; // create a stack using pair<> for storing each // character and corresponding // repetition stack<pair<char, int> > stk; // iterate through the string for (int i = 0; i < s.length(); i++) { // if stack is empty then simply add the // character with count 1 else check if // character is same as top of stack if (stk.empty() == true) { stk.push(make_pair(s[i], 1)); } else { // if character at top of stack is same as // current character increase the number of // repetitions in the top of stack by 1 if (s[i] == (stk.top()).first) { stk.push( { s[i], stk.top().second + 1 }); if (stk.top().second == k) { int x = k; while (x) { stk.pop(); x--; } } } else { // if character at top of stack is not // same as current character push the // character along with count 1 into the // top of stack stk.push(make_pair(s[i], 1)); } } } // Iterate through the stack // Use string(int,char) in order to replicate the // character multiple times and convert into string // then add in front of output string while (!stk.empty()) { output += stk.top().first; stk.pop(); } reverse(output.begin(), output.end()); return output; }}; // Driver Codeint main(){ string s = \"geeksforgeeks\"; int k = 2; Solution obj; cout << obj.remove_k_char(k, s) << \"\\n\"; return 0;} // This code has been contributed by Navansh Goel", "e": 30773, "s": 28133, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG { // Function to find the reduced string public static String reduced_String(int k, String s) { // Base Case if (k == 1) { String ans = \"\"; return ans; } // Creating a stack of type Pair Stack<Pair> st = new Stack<Pair>(); // Length of the string S int l = s.length(); int ctr = 0; // iterate through the string for (int i = 0; i < l; i++) { // if stack is empty then simply add the // character with count 1 else check if // character is same as top of stack if (st.size() == 0) { st.push(new Pair(s.charAt(i), 1)); continue; } // if character at top of stack is same as // current character increase the number of // repetitions in the top of stack by 1 if (st.peek().c == s.charAt(i)) { Pair p = st.peek(); st.pop(); p.ctr += 1; if (p.ctr == k) { continue; } else { st.push(p); } } else { // if character at top of stack is not // same as current character push the // character along with count 1 into the // top of stack st.push(new Pair(s.charAt(i), 1)); } } // iterate through the stack // Use string(int,char) in order to replicate the // character multiple times and convert into string // then add in front of output string String ans = \"\"; while (st.size() > 0) { char c = st.peek().c; int cnt = st.peek().ctr; while (cnt-- > 0) ans = c + ans; st.pop(); } return ans; } // Driver code public static void main(String[] args) { int k = 2; String st = \"geeksforgeeks\"; String ans = reduced_String(k, st); System.out.println(ans); } static class Pair { char c; int ctr; Pair(char c, int ctr) { this.c = c; this.ctr = ctr; } }}", "e": 33094, "s": 30773, "text": null }, { "code": "# Python3 implementation of the approach # Pair class to store character and freqclass Pair: def __init__(self,c ,ctr): self.c= c self.ctr = ctr class Solution: # Function to find the reduced string def reduced_String(self , k , s): #Base Case if (k == 1): return \"\" # Creating a stack of type Pair st = [] # iterate through given string for i in range(len(s)): # if stack is empty then simply add the # character with count 1 else check if # character is same as top of stack if (len(st) == 0): st.append((Pair(s[i] , 1))) continue # if character at top of stack is same as # current character increase the number of # repetitions in the top of stack by 1 if (st[-1].c == s[i]): pair = st.pop() pair.ctr +=1 if (pair.ctr == k): continue else: st.append(pair) else: # if character at top of stack is not # same as current character push the # character along with count 1 into the # top of stack st.append((Pair(s[i] , 1))) # Iterate through the stack # Use string(int,char) in order to replicate the # character multiple times and convert into string # then add in front of output string ans = \"\" while(len(st) > 0): c = st[-1].c cnt = st[-1].ctr while(cnt >0): ans = c + ans cnt -= 1 st.pop() return (ans) # Driver codeif __name__ == \"__main__\": k = 2 s = \"geeksforgeeks\" obj = Solution() print(obj.reduced_String(k,s)) # This code is contributed by chantya17.", "e": 35187, "s": 33094, "text": null }, { "code": "// C# implementation of the above approachusing System;using System.Collections.Generic;public class GFG { // Function to find the reduced string public static String reduced_String(int k, String s) { // Base Case if (k == 1) { return \"\"; } // Creating a stack of type Pair Stack<Pair> st = new Stack<Pair>(); // Length of the string S int l = s.Length; // iterate through the string for (int i = 0; i < l; i++) { // if stack is empty then simply add the // character with count 1 else check if // character is same as top of stack if (st.Count == 0) { st.Push(new Pair(s[i], 1)); continue; } // if character at top of stack is same as // current character increase the number of // repetitions in the top of stack by 1 if (st.Peek().c == s[i]) { Pair p = st.Peek(); st.Pop(); p.ctr += 1; if (p.ctr == k) { continue; } else { st.Push(p); } } else { // if character at top of stack is not // same as current character push the // character along with count 1 into the // top of stack st.Push(new Pair(s[i], 1)); } } // iterate through the stack // Use string(int,char) in order to replicate the // character multiple times and convert into string // then add in front of output string String ans = \"\"; while (st.Count > 0) { char c = st.Peek().c; int cnt = st.Peek().ctr; while (cnt-- > 0) ans = c + ans; st.Pop(); } return ans; } // Driver code public static void Main(String[] args) { int k = 2; String st = \"geeksforgeeks\"; String ans = reduced_String(k, st); Console.Write(ans); } public class Pair { public char c; public int ctr; public Pair(char c, int ctr) { this.c = c; this.ctr = ctr; } }}// This code has been contributed by 29AjayKumar", "e": 37553, "s": 35187, "text": null }, { "code": "<script>// Javascript implementation of the approach class Pair{ constructor(c,ctr) { this.c = c; this.ctr = ctr; }} // Function to find the reduced stringfunction reduced_String(k,s){ // Base Case if (k == 1) { let ans = \"\"; return ans; } // Creating a stack of type Pair let st = []; // Length of the string S let l = s.length; let ctr = 0; // iterate through the string for (let i = 0; i < l; i++) { // if stack is empty then simply add the // character with count 1 else check if // character is same as top of stack if (st.length == 0) { st.push(new Pair(s[i], 1)); continue; } // if character at top of stack is same as // current character increase the number of // repetitions in the top of stack by 1 if (st[st.length-1].c == s[i]) { let p = st[st.length-1]; st.pop(); p.ctr += 1; if (p.ctr == k) { continue; } else { st.push(p); } } else { // if character at top of stack is not // same as current character push the // character along with count 1 into the // top of stack st.push(new Pair(s[i], 1)); } } // iterate through the stack // Use string(int,char) in order to replicate the // character multiple times and convert into string // then add in front of output string let ans = \"\"; while (st.length > 0) { let c = st[st.length-1].c; let cnt = st[st.length-1].ctr; while (cnt-- > 0) ans = c + ans; st.pop(); } return ans;} // Driver codelet k = 2;let st = \"geeksforgeeks\";let ans = reduced_String(k, st);document.write(ans+\"<br>\"); // This code is contributed by rag2127</script>", "e": 39680, "s": 37553, "text": null }, { "code": null, "e": 39690, "s": 39680, "text": "gksforgks" }, { "code": null, "e": 39734, "s": 39690, "text": "Time Complexity: O(N) Auxiliary Space: O(N)" }, { "code": null, "e": 39747, "s": 39734, "text": "imdhruvgupta" }, { "code": null, "e": 39759, "s": 39747, "text": "29AjayKumar" }, { "code": null, "e": 39772, "s": 39759, "text": "Akanksha_Rai" }, { "code": null, "e": 39784, "s": 39772, "text": "navanshgoel" }, { "code": null, "e": 39799, "s": 39784, "text": "UtkarshPandey6" }, { "code": null, "e": 39812, "s": 39799, "text": "simmytarika5" }, { "code": null, "e": 39820, "s": 39812, "text": "rag2127" }, { "code": null, "e": 39835, "s": 39820, "text": "tejendrapratap" }, { "code": null, "e": 39849, "s": 39835, "text": "amartyaniel20" }, { "code": null, "e": 39859, "s": 39849, "text": "chantya17" }, { "code": null, "e": 39876, "s": 39859, "text": "surinderdawra388" }, { "code": null, "e": 39900, "s": 39876, "text": "Competitive Programming" }, { "code": null, "e": 39905, "s": 39900, "text": "Hash" }, { "code": null, "e": 39911, "s": 39905, "text": "Stack" }, { "code": null, "e": 39919, "s": 39911, "text": "Strings" }, { "code": null, "e": 39924, "s": 39919, "text": "Hash" }, { "code": null, "e": 39932, "s": 39924, "text": "Strings" }, { "code": null, "e": 39938, "s": 39932, "text": "Stack" }, { "code": null, "e": 40036, "s": 39938, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40114, "s": 40036, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" }, { "code": null, "e": 40143, "s": 40114, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 40176, "s": 40143, "text": "Multistage Graph (Shortest Path)" }, { "code": null, "e": 40217, "s": 40176, "text": "7 Best Coding Challenge Websites in 2020" }, { "code": null, "e": 40276, "s": 40217, "text": "What is Competitive Programming and How to Prepare for It?" }, { "code": null, "e": 40361, "s": 40276, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 40397, "s": 40361, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 40428, "s": 40397, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 40462, "s": 40428, "text": "Hashing | Set 3 (Open Addressing)" } ]
Boolean Operators - Django Template Tags - GeeksforGeeks
02 Dec, 2021 A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some limited features of a programming such as variables, for loops, comments, extends, if else etc. This article revolves about how to use boolean operators in Templates. The {% if %} tag evaluates a variable, and if that variable is “true” (i.e. exists, is not empty, and is not a false boolean value) the contents of the block are output. One can use various boolean operators with Django If Template tag. Syntax: {% if variable boolean_operator value %} // statements {% endif %} Example:if tags may use and, or or not to test a number of variables or to negate a given variable: html {% if athlete_list and coach_list %} Both athletes and coaches are available.{% endif %} {% if not athlete_list %} There are no athletes.{% endif %} {% if athlete_list or coach_list %} There are some athletes or some coaches.{% endif %} {% if not athlete_list or coach_list %} There are no athletes or there are some coaches.{% endif %} {% if athlete_list and not coach_list %} There are some athletes and absolutely no coaches.{% endif %} As one can see, the if tag may take one or several {% elif %} clauses, as well as an {% else %} clause that will be displayed if all previous conditions fail. These clauses are optional. Illustration of How to use Boolean operators in Django templates using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? Now create a view through which we will pass the context dictionary, In geeks/views.py, Python3 # import Http Response from djangofrom django.shortcuts import render # create a functiondef geeks_view(request): # create a dictionary context = { "data" : 99, } # return response return render(request, "geeks.html", context) Create a url path to map to this view. In geeks/urls.py, Python3 from django.urls import path # importing views from views.pyfrom .views import geeks_view urlpatterns = [ path('', geeks_view),] Create a template in templates/geeks.html, html {% if data == 99 %}Value in data is : - {{ data }}{% else %}Data is empty{% endif%} Let’s check what is displayed on “/” are displayed in the template. == operator Equality. Example: {% if somevar == "x" %} This appears if variable somevar equals the string "x" {% endif %} != operator Inequality. Example: {% if somevar != "x" %} This appears if variable somevar does not equal the string "x", or if somevar is not found in the context {% endif %} < operator Less than. Example: {% if somevar < 100 %} This appears if variable somevar is less than 100. {% endif %} > operator Greater than. Example: {% if somevar > 0 %} This appears if variable somevar is greater than 0. {% endif %} <= operator Less than or equal to. Example: {% if somevar <= 100 %} This appears if variable somevar is less than 100 or equal to 100. {% endif %} >= operator Greater than or equal to. Example: {% if somevar >= 1 %} This appears if variable somevar is greater than 1 or equal to 1. {% endif %} in operator Contained within. This operator is supported by many Python containers to test whether the given value is in the container. The following are some examples of how x in y will be interpreted: {% if "bc" in "abcdef" %} This appears since "bc" is a substring of "abcdef" {% endif %} {% if "hello" in greetings %} If greetings is a list or set, one element of which is the string "hello", this will appear. {% endif %} {% if user in users %} If users is a QuerySet, this will appear if user is an instance that belongs to the QuerySet. {% endif %} not in operator Not contained within. This is the negation of the in operator.is operator Object identity. Tests if two values are the same object. Example: {% if somevar is True %} This appears if and only if somevar is True. {% endif %} {% if somevar is None %} This appears if somevar is None, or if somevar is not found in the context. {% endif %} is not operator Negated object identity. Tests if two values are not the same object. This is the negation of the is operator. Example: {% if somevar is not True %} This appears if somevar is not True, or if somevar is not found in the context. {% endif %} {% if somevar is not None %} This appears if and only if somevar is not None. {% endif %} surindertarika1234 Django-templates Python Django 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": 25575, "s": 25547, "text": "\n02 Dec, 2021" }, { "code": null, "e": 26280, "s": 25575, "text": "A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some limited features of a programming such as variables, for loops, comments, extends, if else etc. This article revolves about how to use boolean operators in Templates. The {% if %} tag evaluates a variable, and if that variable is “true” (i.e. exists, is not empty, and is not a false boolean value) the contents of the block are output. One can use various boolean operators with Django If Template tag. " }, { "code": null, "e": 26289, "s": 26280, "text": "Syntax: " }, { "code": null, "e": 26356, "s": 26289, "text": "{% if variable boolean_operator value %}\n// statements\n{% endif %}" }, { "code": null, "e": 26456, "s": 26356, "text": "Example:if tags may use and, or or not to test a number of variables or to negate a given variable:" }, { "code": null, "e": 26461, "s": 26456, "text": "html" }, { "code": "{% if athlete_list and coach_list %} Both athletes and coaches are available.{% endif %} {% if not athlete_list %} There are no athletes.{% endif %} {% if athlete_list or coach_list %} There are some athletes or some coaches.{% endif %} {% if not athlete_list or coach_list %} There are no athletes or there are some coaches.{% endif %} {% if athlete_list and not coach_list %} There are some athletes and absolutely no coaches.{% endif %}", "e": 26916, "s": 26461, "text": null }, { "code": null, "e": 27104, "s": 26916, "text": "As one can see, the if tag may take one or several {% elif %} clauses, as well as an {% else %} clause that will be displayed if all previous conditions fail. These clauses are optional. " }, { "code": null, "e": 27254, "s": 27104, "text": "Illustration of How to use Boolean operators in Django templates using an Example. Consider a project named geeksforgeeks having an app named geeks. " }, { "code": null, "e": 27343, "s": 27254, "text": "Refer to the following articles to check how to create a project and an app in Django. " }, { "code": null, "e": 27394, "s": 27343, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 27427, "s": 27394, "text": "How to Create an App in Django ?" }, { "code": null, "e": 27516, "s": 27427, "text": "Now create a view through which we will pass the context dictionary, In geeks/views.py, " }, { "code": null, "e": 27524, "s": 27516, "text": "Python3" }, { "code": "# import Http Response from djangofrom django.shortcuts import render # create a functiondef geeks_view(request): # create a dictionary context = { \"data\" : 99, } # return response return render(request, \"geeks.html\", context)", "e": 27774, "s": 27524, "text": null }, { "code": null, "e": 27831, "s": 27774, "text": "Create a url path to map to this view. In geeks/urls.py," }, { "code": null, "e": 27839, "s": 27831, "text": "Python3" }, { "code": "from django.urls import path # importing views from views.pyfrom .views import geeks_view urlpatterns = [ path('', geeks_view),]", "e": 27971, "s": 27839, "text": null }, { "code": null, "e": 28014, "s": 27971, "text": "Create a template in templates/geeks.html," }, { "code": null, "e": 28019, "s": 28014, "text": "html" }, { "code": "{% if data == 99 %}Value in data is : - {{ data }}{% else %}Data is empty{% endif%}", "e": 28103, "s": 28019, "text": null }, { "code": null, "e": 28172, "s": 28103, "text": "Let’s check what is displayed on “/” are displayed in the template. " }, { "code": null, "e": 28205, "s": 28172, "text": "== operator Equality. Example: " }, { "code": null, "e": 28298, "s": 28205, "text": "{% if somevar == \"x\" %}\n This appears if variable somevar equals the string \"x\"\n{% endif %}" }, { "code": null, "e": 28332, "s": 28298, "text": "!= operator Inequality. Example: " }, { "code": null, "e": 28478, "s": 28332, "text": "{% if somevar != \"x\" %}\n This appears if variable somevar does not equal the string \"x\",\n or if somevar is not found in the context\n{% endif %}" }, { "code": null, "e": 28510, "s": 28478, "text": "< operator Less than. Example: " }, { "code": null, "e": 28598, "s": 28510, "text": "{% if somevar < 100 %}\n This appears if variable somevar is less than 100.\n{% endif %}" }, { "code": null, "e": 28633, "s": 28598, "text": "> operator Greater than. Example: " }, { "code": null, "e": 28720, "s": 28633, "text": "{% if somevar > 0 %}\n This appears if variable somevar is greater than 0.\n{% endif %}" }, { "code": null, "e": 28765, "s": 28720, "text": "<= operator Less than or equal to. Example: " }, { "code": null, "e": 28870, "s": 28765, "text": "{% if somevar <= 100 %}\n This appears if variable somevar is less than 100 or equal to 100.\n{% endif %}" }, { "code": null, "e": 28918, "s": 28870, "text": ">= operator Greater than or equal to. Example: " }, { "code": null, "e": 29020, "s": 28918, "text": "{% if somevar >= 1 %}\n This appears if variable somevar is greater than 1 or equal to 1.\n{% endif %}" }, { "code": null, "e": 29224, "s": 29020, "text": "in operator Contained within. This operator is supported by many Python containers to test whether the given value is in the container. The following are some examples of how x in y will be interpreted: " }, { "code": null, "e": 29315, "s": 29224, "text": "{% if \"bc\" in \"abcdef\" %}\n This appears since \"bc\" is a substring of \"abcdef\"\n{% endif %}" }, { "code": null, "e": 29454, "s": 29315, "text": "{% if \"hello\" in greetings %}\n If greetings is a list or set, one element of which is the string\n \"hello\", this will appear.\n{% endif %}" }, { "code": null, "e": 29587, "s": 29454, "text": "{% if user in users %}\n If users is a QuerySet, this will appear if user is an\n instance that belongs to the QuerySet.\n{% endif %}" }, { "code": null, "e": 29744, "s": 29587, "text": "not in operator Not contained within. This is the negation of the in operator.is operator Object identity. Tests if two values are the same object. Example:" }, { "code": null, "e": 29944, "s": 29744, "text": "{% if somevar is True %}\n This appears if and only if somevar is True.\n{% endif %}\n\n{% if somevar is None %}\n This appears if somevar is None, or if somevar is not found in the context.\n{% endif %}" }, { "code": null, "e": 30080, "s": 29944, "text": "is not operator Negated object identity. Tests if two values are not the same object. This is the negation of the is operator. Example:" }, { "code": null, "e": 30298, "s": 30080, "text": "{% if somevar is not True %}\n This appears if somevar is not True, or if somevar is not found in the\n context.\n{% endif %}\n\n{% if somevar is not None %}\n This appears if and only if somevar is not None.\n{% endif %}" }, { "code": null, "e": 30317, "s": 30298, "text": "surindertarika1234" }, { "code": null, "e": 30334, "s": 30317, "text": "Django-templates" }, { "code": null, "e": 30348, "s": 30334, "text": "Python Django" }, { "code": null, "e": 30355, "s": 30348, "text": "Python" }, { "code": null, "e": 30453, "s": 30355, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30471, "s": 30453, "text": "Python Dictionary" }, { "code": null, "e": 30506, "s": 30471, "text": "Read a file line by line in Python" }, { "code": null, "e": 30538, "s": 30506, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30560, "s": 30538, "text": "Enumerate() in Python" }, { "code": null, "e": 30602, "s": 30560, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30632, "s": 30602, "text": "Iterate over a list in Python" }, { "code": null, "e": 30658, "s": 30632, "text": "Python String | replace()" }, { "code": null, "e": 30687, "s": 30658, "text": "*args and **kwargs in Python" }, { "code": null, "e": 30731, "s": 30687, "text": "Reading and Writing to text files in Python" } ]
C# | Check if the Hashtable contains a specific Value - GeeksforGeeks
01 Feb, 2019 The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Hashtable.ContainsValue(Object) Method is used to check whether the Hashtable contains a specific value or not. Syntax: public virtual bool ContainsValue(object value); Parameter: value: The value of type System.Object to locate in the Hashtable. The value can be null. Return Type: This method returns true if the Hashtable contains an element with the specified value otherwise it returns false. The return type of this method is System.Boolean. Below given are some examples to understand the implementation in a better way: Example 1: // C# code to check if the HashTable// contains a specific Valueusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Hashtable Hashtable myTable = new Hashtable(); // Adding elements in Hashtable myTable.Add("g", "geeks"); myTable.Add("c", "c++"); myTable.Add("d", "data structures"); myTable.Add("q", "quiz"); // check if the HashTable contains // the required Value or not. if (myTable.ContainsValue("c++")) Console.WriteLine("myTable contains the Value"); else Console.WriteLine("myTable doesn't contain the Value"); }} myTable contains the Value Example 2: // C# code to check if the HashTable// contains a specific Valueusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Hashtable Hashtable myTable = new Hashtable(); // Adding elements in Hashtable myTable.Add("India", "Country"); myTable.Add("Chandigarh", "City"); myTable.Add("Mars", "Planet"); myTable.Add("China", "Country"); // check if the HashTable contains // the required Value or not. if (myTable.ContainsKey("Ocean")) Console.WriteLine("myTable contains the Value"); else Console.WriteLine("myTable doesn't contain the Value"); }} myTable doesn't contain the Value Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.hashtable.containsvalue?view=netframework-4.7.2 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# C# | How to insert an element in an Array? Convert String to Character Array in C# Lambda Expressions in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n01 Feb, 2019" }, { "code": null, "e": 25835, "s": 25547, "text": "The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Hashtable.ContainsValue(Object) Method is used to check whether the Hashtable contains a specific value or not." }, { "code": null, "e": 25843, "s": 25835, "text": "Syntax:" }, { "code": null, "e": 25893, "s": 25843, "text": "public virtual bool ContainsValue(object value);\n" }, { "code": null, "e": 25904, "s": 25893, "text": "Parameter:" }, { "code": null, "e": 25994, "s": 25904, "text": "value: The value of type System.Object to locate in the Hashtable. The value can be null." }, { "code": null, "e": 26172, "s": 25994, "text": "Return Type: This method returns true if the Hashtable contains an element with the specified value otherwise it returns false. The return type of this method is System.Boolean." }, { "code": null, "e": 26252, "s": 26172, "text": "Below given are some examples to understand the implementation in a better way:" }, { "code": null, "e": 26263, "s": 26252, "text": "Example 1:" }, { "code": "// C# code to check if the HashTable// contains a specific Valueusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Hashtable Hashtable myTable = new Hashtable(); // Adding elements in Hashtable myTable.Add(\"g\", \"geeks\"); myTable.Add(\"c\", \"c++\"); myTable.Add(\"d\", \"data structures\"); myTable.Add(\"q\", \"quiz\"); // check if the HashTable contains // the required Value or not. if (myTable.ContainsValue(\"c++\")) Console.WriteLine(\"myTable contains the Value\"); else Console.WriteLine(\"myTable doesn't contain the Value\"); }}", "e": 26961, "s": 26263, "text": null }, { "code": null, "e": 26989, "s": 26961, "text": "myTable contains the Value\n" }, { "code": null, "e": 27000, "s": 26989, "text": "Example 2:" }, { "code": "// C# code to check if the HashTable// contains a specific Valueusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Hashtable Hashtable myTable = new Hashtable(); // Adding elements in Hashtable myTable.Add(\"India\", \"Country\"); myTable.Add(\"Chandigarh\", \"City\"); myTable.Add(\"Mars\", \"Planet\"); myTable.Add(\"China\", \"Country\"); // check if the HashTable contains // the required Value or not. if (myTable.ContainsKey(\"Ocean\")) Console.WriteLine(\"myTable contains the Value\"); else Console.WriteLine(\"myTable doesn't contain the Value\"); }}", "e": 27715, "s": 27000, "text": null }, { "code": null, "e": 27750, "s": 27715, "text": "myTable doesn't contain the Value\n" }, { "code": null, "e": 27761, "s": 27750, "text": "Reference:" }, { "code": null, "e": 27872, "s": 27761, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.hashtable.containsvalue?view=netframework-4.7.2" }, { "code": null, "e": 27901, "s": 27872, "text": "CSharp-Collections-Hashtable" }, { "code": null, "e": 27930, "s": 27901, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 27944, "s": 27930, "text": "CSharp-method" }, { "code": null, "e": 27947, "s": 27944, "text": "C#" }, { "code": null, "e": 28045, "s": 27947, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28068, "s": 28045, "text": "Extension Method in C#" }, { "code": null, "e": 28096, "s": 28068, "text": "HashSet in C# with Examples" }, { "code": null, "e": 28113, "s": 28096, "text": "C# | Inheritance" }, { "code": null, "e": 28135, "s": 28113, "text": "Partial Classes in C#" }, { "code": null, "e": 28164, "s": 28135, "text": "C# | Generics - Introduction" }, { "code": null, "e": 28204, "s": 28164, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 28227, "s": 28204, "text": "Switch Statement in C#" }, { "code": null, "e": 28270, "s": 28227, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 28310, "s": 28270, "text": "Convert String to Character Array in C#" } ]
Generate an Array by multiplying each element of given Array by K - GeeksforGeeks
19 Jan, 2022 Given an array arr[] of size N and an integer K. The task is to multiply each element of the array by K. Examples : Input: arr[] = { 3, 4 }, K = 2Output: 6 8Explanation: The elements become 3*2 = 6 and 4*2 = 8. Input: arr[] = { 0, 1, 2 }, K = 7Output: { 0, 7, 14 } Approach: The given problem can be solved using the following steps : Iterate through all the elements in the list Multiply each element by K Returned the modified list Below is the implementation of the above approach. C++ Java Python C# Javascript // C++ code for the above approach#include <bits/stdc++.h>using namespace std; // Function to multiply all// the elements of array by Kvoid multiplyAllByK(vector<int> arr, int K){ int N = arr.size(); // Loop to multiply all // the array elements for (int i = 0; i < N; i++) { int x = arr[i]; arr[i] = K * x; } // Print the modified array for (int i = 0; i < N; i++) cout << (arr[i]) << " ";} // Driver codeint main(){ vector<int> arr; arr.push_back(3); arr.push_back(4); int K = 2; multiplyAllByK(arr, K); return 0;} // This code is contributed by lokeshpotta20. // Java code to implement above approachimport java.io.*;import java.util.*; class GFG { // Function to multiply all // the elements of array by K public static void multiplyAllByK( ArrayList<Integer> arr, int K) { int N = arr.size(); // Loop to multiply all // the array elements for (int i = 0; i < N; i++) { int x = arr.get(i); arr.set(i, K * x); } // Print the modified array for (int i = 0; i < N; i++) System.out.print(arr.get(i) + " "); } // Driver code public static void main(String[] args) { ArrayList<Integer> arr = new ArrayList<Integer>(); arr.add(3); arr.add(4); int K = 2; multiplyAllByK(arr, K); }} # Python code to implement above approach # Function to multiply all# the elements of array by Kdef multiplyAllByK(arr, K): n = len(arr) for i in range(n): x = arr[i] arr[i] = K * x for i in range(n): print(arr[i], end = ' ') # Driver codearr = [3, 4]K = 2multiplyAllByK(arr, K) # This code is contributed by Samim Hossain Mondal. // C# code to implement above approach using System;using System.Collections.Generic; public class GFG { // Function to multiply all // the elements of array by K public static void multiplyAllByK( List<int> arr, int K) { int N = arr.Count; // Loop to multiply all // the array elements for (int i = 0; i < N; i++) { int x = arr[i]; arr[i] =( K * x); } // Print the modified array for (int i = 0; i < N; i++) Console.Write(arr[i] + " "); } // Driver code public static void Main(String[] args) { List<int> arr = new List<int>(); arr.Add(3); arr.Add(4); int K = 2; multiplyAllByK(arr, K); }} // This code is contributed by 29AjayKumar <script> // JavaScript code for the above approach // Function to multiply all // the elements of array by K const multiplyAllByK = (arr, K) => { let N = arr.length; // Loop to multiply all // the array elements for (let i = 0; i < N; i++) { let x = arr[i]; arr[i] = K * x; } // Print the modified array for (let i = 0; i < N; i++) document.write(`${arr[i]} `); } // Driver code let arr = []; arr.push(3); arr.push(4); let K = 2; multiplyAllByK(arr, K); // This code is contributed by rakeshsahni </script> 6 8 Time Complexity: O(N)Auxiliary Space: O(1) Approach Using Lambda Expression: This can also be implemented using lambda expression. n -> n * K where n can be a particular element, or complete array. Below is the implementation of the above approach: C++ C Java Python3 C# Javascript // C++ code to implement above approach#include <iostream>using namespace std; // Function to multiply all// the elements of array by Kvoid multiplyAllByK(int arr[], int K){ for(int i = 0; i < 2; i++) arr[i] *= K; for (int i = 0; i < 2; i++) cout << arr[i] << " ";} // Driver codeint main(){ int arr[2]; arr[0] = 3; arr[1] = 4; int K = 2; multiplyAllByK(arr, K); return 0;} // This code is contributed by Shubham Singh // C code to implement above approach#include <stdio.h> // Function to multiply all// the elements of array by Kvoid multiplyAllByK(int arr[], int K){ for(int i = 0; i < 2; i++) arr[i] *= K; for (int i = 0; i<2; i++) printf("%d ",arr[i]);} // Driver codeint main(){ int arr[2]; arr[0] = 3; arr[1] = 4; int K = 2; multiplyAllByK(arr, K); return 0;} //This code is contributed by Shubham Singh // Java code to implement above approachimport java.io.*;import java.util.*; class GFG { // Function to multiply all // the elements of array by K public static void multiplyAllByK( ArrayList<Integer> arr, int K) { arr.replaceAll(n -> n * K); for (Integer x : arr) System.out.print(x + " "); } // Driver code public static void main(String[] args) { ArrayList<Integer> arr = new ArrayList<Integer>(); arr.add(3); arr.add(4); int K = 2; multiplyAllByK(arr, K); }} # Python3 code to implement above approach # Function to multiply all# the elements of array by Kdef multiplyAllByK(arr, K): lambda_func = lambda n: n * K for i in range(len(arr)): print(lambda_func(arr[i]), end = ' ') # Driver codearr = [3, 4]K = 2 multiplyAllByK(arr, K) # This code is contributed by Samim Hossain Mondal. // C# code to implement above approachusing System;using System.Collections.Generic;using System.Linq; public class GFG { // Function to multiply all // the elements of array by K public static void multiplyAllByK( List<int> arr, int K) { var temp = arr.Select(n => n * K); foreach (int x in temp) Console.Write(x + " "); } // Driver code public static void Main(String[] args) { List<int> arr = new List<int>(); arr.Add(3); arr.Add(4); int K = 2; multiplyAllByK(arr, K); }} // This code is contributed by shikhasingrajput <script>// Javascript code to implement above approach // Function to multiply all// the elements of array by Kfunction multiplyAllByK(arr, K) { arr = arr.map(k => { return k * K }); for (x of arr) document.write(x + " ");} // Driver codelet arr = [];arr.push(3);arr.push(4);let K = 2;multiplyAllByK(arr, K); // This code is contributed by saurabh_jaiswal.</script> 6 8 Time Complexity: O(N)Auxiliary Space: O(1) lokeshpotta20 29AjayKumar samim2000 rakeshsahni shikhasingrajput _saurabh_jaiswal shubhamsingh84100 SHUBHAMSINGH10 java-lambda Arrays Mathematical School Programming Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Reversal algorithm for array rotation Window Sliding Technique Next Greater Element Find duplicates in O(n) time and O(1) extra space | Set 1 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": 26176, "s": 26148, "text": "\n19 Jan, 2022" }, { "code": null, "e": 26281, "s": 26176, "text": "Given an array arr[] of size N and an integer K. The task is to multiply each element of the array by K." }, { "code": null, "e": 26292, "s": 26281, "text": "Examples :" }, { "code": null, "e": 26387, "s": 26292, "text": "Input: arr[] = { 3, 4 }, K = 2Output: 6 8Explanation: The elements become 3*2 = 6 and 4*2 = 8." }, { "code": null, "e": 26441, "s": 26387, "text": "Input: arr[] = { 0, 1, 2 }, K = 7Output: { 0, 7, 14 }" }, { "code": null, "e": 26511, "s": 26441, "text": "Approach: The given problem can be solved using the following steps :" }, { "code": null, "e": 26556, "s": 26511, "text": "Iterate through all the elements in the list" }, { "code": null, "e": 26583, "s": 26556, "text": "Multiply each element by K" }, { "code": null, "e": 26610, "s": 26583, "text": "Returned the modified list" }, { "code": null, "e": 26661, "s": 26610, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 26665, "s": 26661, "text": "C++" }, { "code": null, "e": 26670, "s": 26665, "text": "Java" }, { "code": null, "e": 26677, "s": 26670, "text": "Python" }, { "code": null, "e": 26680, "s": 26677, "text": "C#" }, { "code": null, "e": 26691, "s": 26680, "text": "Javascript" }, { "code": "// C++ code for the above approach#include <bits/stdc++.h>using namespace std; // Function to multiply all// the elements of array by Kvoid multiplyAllByK(vector<int> arr, int K){ int N = arr.size(); // Loop to multiply all // the array elements for (int i = 0; i < N; i++) { int x = arr[i]; arr[i] = K * x; } // Print the modified array for (int i = 0; i < N; i++) cout << (arr[i]) << \" \";} // Driver codeint main(){ vector<int> arr; arr.push_back(3); arr.push_back(4); int K = 2; multiplyAllByK(arr, K); return 0;} // This code is contributed by lokeshpotta20.", "e": 27317, "s": 26691, "text": null }, { "code": "// Java code to implement above approachimport java.io.*;import java.util.*; class GFG { // Function to multiply all // the elements of array by K public static void multiplyAllByK( ArrayList<Integer> arr, int K) { int N = arr.size(); // Loop to multiply all // the array elements for (int i = 0; i < N; i++) { int x = arr.get(i); arr.set(i, K * x); } // Print the modified array for (int i = 0; i < N; i++) System.out.print(arr.get(i) + \" \"); } // Driver code public static void main(String[] args) { ArrayList<Integer> arr = new ArrayList<Integer>(); arr.add(3); arr.add(4); int K = 2; multiplyAllByK(arr, K); }}", "e": 28087, "s": 27317, "text": null }, { "code": "# Python code to implement above approach # Function to multiply all# the elements of array by Kdef multiplyAllByK(arr, K): n = len(arr) for i in range(n): x = arr[i] arr[i] = K * x for i in range(n): print(arr[i], end = ' ') # Driver codearr = [3, 4]K = 2multiplyAllByK(arr, K) # This code is contributed by Samim Hossain Mondal.", "e": 28467, "s": 28087, "text": null }, { "code": "// C# code to implement above approach using System;using System.Collections.Generic; public class GFG { // Function to multiply all // the elements of array by K public static void multiplyAllByK( List<int> arr, int K) { int N = arr.Count; // Loop to multiply all // the array elements for (int i = 0; i < N; i++) { int x = arr[i]; arr[i] =( K * x); } // Print the modified array for (int i = 0; i < N; i++) Console.Write(arr[i] + \" \"); } // Driver code public static void Main(String[] args) { List<int> arr = new List<int>(); arr.Add(3); arr.Add(4); int K = 2; multiplyAllByK(arr, K); }} // This code is contributed by 29AjayKumar", "e": 29256, "s": 28467, "text": null }, { "code": "<script> // JavaScript code for the above approach // Function to multiply all // the elements of array by K const multiplyAllByK = (arr, K) => { let N = arr.length; // Loop to multiply all // the array elements for (let i = 0; i < N; i++) { let x = arr[i]; arr[i] = K * x; } // Print the modified array for (let i = 0; i < N; i++) document.write(`${arr[i]} `); } // Driver code let arr = []; arr.push(3); arr.push(4); let K = 2; multiplyAllByK(arr, K); // This code is contributed by rakeshsahni </script>", "e": 29882, "s": 29256, "text": null }, { "code": null, "e": 29887, "s": 29882, "text": "6 8 " }, { "code": null, "e": 29930, "s": 29887, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 30019, "s": 29930, "text": "Approach Using Lambda Expression: This can also be implemented using lambda expression. " }, { "code": null, "e": 30086, "s": 30019, "text": "n -> n * K where n can be a particular element, or complete array." }, { "code": null, "e": 30137, "s": 30086, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 30141, "s": 30137, "text": "C++" }, { "code": null, "e": 30143, "s": 30141, "text": "C" }, { "code": null, "e": 30148, "s": 30143, "text": "Java" }, { "code": null, "e": 30156, "s": 30148, "text": "Python3" }, { "code": null, "e": 30159, "s": 30156, "text": "C#" }, { "code": null, "e": 30170, "s": 30159, "text": "Javascript" }, { "code": "// C++ code to implement above approach#include <iostream>using namespace std; // Function to multiply all// the elements of array by Kvoid multiplyAllByK(int arr[], int K){ for(int i = 0; i < 2; i++) arr[i] *= K; for (int i = 0; i < 2; i++) cout << arr[i] << \" \";} // Driver codeint main(){ int arr[2]; arr[0] = 3; arr[1] = 4; int K = 2; multiplyAllByK(arr, K); return 0;} // This code is contributed by Shubham Singh", "e": 30604, "s": 30170, "text": null }, { "code": "// C code to implement above approach#include <stdio.h> // Function to multiply all// the elements of array by Kvoid multiplyAllByK(int arr[], int K){ for(int i = 0; i < 2; i++) arr[i] *= K; for (int i = 0; i<2; i++) printf(\"%d \",arr[i]);} // Driver codeint main(){ int arr[2]; arr[0] = 3; arr[1] = 4; int K = 2; multiplyAllByK(arr, K); return 0;} //This code is contributed by Shubham Singh", "e": 31032, "s": 30604, "text": null }, { "code": "// Java code to implement above approachimport java.io.*;import java.util.*; class GFG { // Function to multiply all // the elements of array by K public static void multiplyAllByK( ArrayList<Integer> arr, int K) { arr.replaceAll(n -> n * K); for (Integer x : arr) System.out.print(x + \" \"); } // Driver code public static void main(String[] args) { ArrayList<Integer> arr = new ArrayList<Integer>(); arr.add(3); arr.add(4); int K = 2; multiplyAllByK(arr, K); }}", "e": 31602, "s": 31032, "text": null }, { "code": "# Python3 code to implement above approach # Function to multiply all# the elements of array by Kdef multiplyAllByK(arr, K): lambda_func = lambda n: n * K for i in range(len(arr)): print(lambda_func(arr[i]), end = ' ') # Driver codearr = [3, 4]K = 2 multiplyAllByK(arr, K) # This code is contributed by Samim Hossain Mondal.", "e": 31949, "s": 31602, "text": null }, { "code": "// C# code to implement above approachusing System;using System.Collections.Generic;using System.Linq; public class GFG { // Function to multiply all // the elements of array by K public static void multiplyAllByK( List<int> arr, int K) { var temp = arr.Select(n => n * K); foreach (int x in temp) Console.Write(x + \" \"); } // Driver code public static void Main(String[] args) { List<int> arr = new List<int>(); arr.Add(3); arr.Add(4); int K = 2; multiplyAllByK(arr, K); }} // This code is contributed by shikhasingrajput", "e": 32579, "s": 31949, "text": null }, { "code": "<script>// Javascript code to implement above approach // Function to multiply all// the elements of array by Kfunction multiplyAllByK(arr, K) { arr = arr.map(k => { return k * K }); for (x of arr) document.write(x + \" \");} // Driver codelet arr = [];arr.push(3);arr.push(4);let K = 2;multiplyAllByK(arr, K); // This code is contributed by saurabh_jaiswal.</script>", "e": 32968, "s": 32579, "text": null }, { "code": null, "e": 32973, "s": 32968, "text": "6 8 " }, { "code": null, "e": 33018, "s": 32973, "text": " Time Complexity: O(N)Auxiliary Space: O(1) " }, { "code": null, "e": 33032, "s": 33018, "text": "lokeshpotta20" }, { "code": null, "e": 33044, "s": 33032, "text": "29AjayKumar" }, { "code": null, "e": 33054, "s": 33044, "text": "samim2000" }, { "code": null, "e": 33066, "s": 33054, "text": "rakeshsahni" }, { "code": null, "e": 33083, "s": 33066, "text": "shikhasingrajput" }, { "code": null, "e": 33100, "s": 33083, "text": "_saurabh_jaiswal" }, { "code": null, "e": 33118, "s": 33100, "text": "shubhamsingh84100" }, { "code": null, "e": 33133, "s": 33118, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 33145, "s": 33133, "text": "java-lambda" }, { "code": null, "e": 33152, "s": 33145, "text": "Arrays" }, { "code": null, "e": 33165, "s": 33152, "text": "Mathematical" }, { "code": null, "e": 33184, "s": 33165, "text": "School Programming" }, { "code": null, "e": 33191, "s": 33184, "text": "Arrays" }, { "code": null, "e": 33204, "s": 33191, "text": "Mathematical" }, { "code": null, "e": 33302, "s": 33204, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33333, "s": 33302, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 33371, "s": 33333, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 33396, "s": 33371, "text": "Window Sliding Technique" }, { "code": null, "e": 33417, "s": 33396, "text": "Next Greater Element" }, { "code": null, "e": 33475, "s": 33417, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 33505, "s": 33475, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 33565, "s": 33505, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 33580, "s": 33565, "text": "C++ Data Types" }, { "code": null, "e": 33623, "s": 33580, "text": "Set in C++ Standard Template Library (STL)" } ]
Using Deep Learning for End to End Multiclass Text Classification | by Rahul Agarwal | Towards Data Science
Have you ever thought about how toxic comments get flagged automatically on platforms like Quora or Reddit? Or how mail gets marked as spam? Or what decides which online ads are shown to you? All of the above are examples of how text classification is used in different areas. Text classification is a common task in natural language processing (NLP) which transforms a sequence of a text of indefinite length into a single category. One theme that emerges from the above examples is that all have a binary target class. For example, either the comment is toxic or not toxic, or the review is fake or not fake. In short, there are only two target classes, hence the term binary. But this is not always the case, and some problems might have more than two target classes. These problems are conveniently termed multiclass classifications, and it is these problems we’ll focus on in this post. Some examples of multiclass classification include: The sentiment of a review: positive, negative or neutral (three classes) News Categorization by genre: Entertainment, education, politics, etc. On a side note, if you are interested in a custom deep learning workstation or server to use in your work, Exxact Corporation has a great line of AI-based solutions starting at $3,700, with a couple of NVIDIA RTX 30 Series GPUs, 3-year warranty, and a deep learning software stack. In this post, we will go through a multiclass text classification problem using various Deep Learning Methods. For this post, I am using the UCI ML Drug Review dataset from Kaggle. It contains over 200,000 patient drug reviews, along with related conditions. The dataset has many columns, but we will be using just two of them for our NLP Task. So, our dataset mostly looks like this: Task: We want to classify the top disease conditions based on the drug review. Before we go any further into text classification, we need a way to represent words numerically in a vocabulary. Why? Because most of our ML models require numbers, not text. One way to achieve this goal is by using the one-hot encoding of word vectors, but this is not the right choice. Given a vast vocabulary, this representation would take a lot of space, and it cannot accurately express the similarity between different words, such as if we want to find the cosine similarity between numerical words x and y: Given the structure of one-hot encoded vectors, the similarity is always going to be 0 between different words. Word2Vec overcomes the above difficulties by providing us with a fixed-length (usually much smaller than the vocabulary size) vector representation of words. It also captures the similarity and analogous relationships between different words. Word2vec vectors of words are learned in such a way that they allow us to learn different analogies. This enables us to do algebraic manipulations on words that were not possible previously. For example: What is king — man + woman? The result is Queen. Word2Vec vectors also help us to find the similarity between words. If we look for similar words to “good”, we will find awesome, great, etc. It is this property of word2vec that makes it invaluable for text classification. With this, our deep learning network understands that “good” and “great” are words with similar meanings. In simple terms, word2vec creates fixed-length vectors for words, giving us a d dimensional vector for every word (and common bigrams) in a dictionary. These word vectors are usually pre-trained, and provided by others after training on large corpora of texts like Wikipedia, Twitter, etc. The most commonly used pre-trained word vectors are Glove and Fast text with 300-dimensional word vectors. In this post, we will use the Glove word vectors. In most cases, text data is not entirely clean. Data coming from different sources have different characteristics, and this makes text preprocessing one of the most critical steps in the classification pipeline. For example, Text data from Twitter is different from the text data found on Quora or other news/blogging platforms, and each needs to be treated differently. However, the techniques we’ll cover in this post are generic enough for almost any kind of data you might encounter in the jungles of NLP. Our preprocessing pipeline depends heavily on the word2vec embeddings we are going to use for our classification task. In principle, our preprocessing should match the preprocessing used before training the word embedding. Since most of the embeddings don’t provide vector values for punctuation and other special characters, the first thing we want to do is get rid of the special characters in our text data. # Some preprocesssing that will be common to all the text classification methods you will see.import redef clean_text(x): pattern = r'[^a-zA-z0-9\s]' text = re.sub(pattern, '', x) return x Why do we want to replace numbers with #s? Because most embeddings, including Glove, have preprocessed their text in this way. Small Python Trick: We use an if statement in the code below to check beforehand if a number exists in a text because an if is always faster than a re.sub command, and most of our text doesn’t contain numbers. def clean_numbers(x): if bool(re.search(r'\d', x)): x = re.sub('[0-9]{5,}', '#####', x) x = re.sub('[0-9]{4}', '####', x) x = re.sub('[0-9]{3}', '###', x) x = re.sub('[0-9]{2}', '##', x) return x Contractions are words that we write with an apostrophe. Examples of contractions are words like “ain’t” or “aren’t”. Since we want to standardize our text, it makes sense to expand these contractions. Below we have done this using contraction mapping and regex functions. contraction_dict = {"ain't": "is not", "aren't": "are not","can't": "cannot", "'cause": "because", "could've": "could have"}def _get_contractions(contraction_dict): contraction_re = re.compile('(%s)' % '|'.join(contraction_dict.keys())) return contraction_dict, contraction_recontractions, contractions_re = _get_contractions(contraction_dict)def replace_contractions(text): def replace(match): return contractions[match.group(0)] return contractions_re.sub(replace, text)# Usagereplace_contractions("this's a text with contraction") Apart from the above techniques, you may want to do spell correction, too. But since our post is already quite long, we’ll leave that for now. One thing that has made deep learning a go-to choice for NLP is the fact that we don’t have to hand-engineer features from our text data; deep learning algorithms take as input a sequence of text to learn its structure just like humans do. Since machines cannot understand words, they expect their data in numerical form. So we need to represent our text data as a series of numbers. To understand how this is done, we need to understand a little about the Keras Tokenizer function. Other tokenizers are also viable, but the Keras Tokenizer is a good choice for me. Put simply, a tokenizer is a utility function that splits a sentence into words. keras.preprocessing.text.Tokenizer tokenizes (splits) a text into tokens (words) while keeping only the words that occur the most in the text corpus. #Signature:Tokenizer(num_words=None, filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n',lower=True, split=' ', char_level=False, oov_token=None, document_count=0, **kwargs) The num_words parameter keeps only a pre-specified number of words in the text. This is helpful because we don’t want our model to get a lot of noise by considering words that occur infrequently. In real-world data, most of the words we leave using the num_words parameter are normally misspelled words. The tokenizer also filters some non-wanted tokens by default and converts the text into lowercase. Once fitted to the data, the tokenizer also keeps an index of words (a dictionary we can use to assign unique numbers to words), which can be accessed by tokenizer.word_index. The words in the indexed dictionary are ranked in order of frequency. So the whole code to use the tokenizer is as follows: from keras.preprocessing.text import Tokenizer## Tokenize the sentencestokenizer = Tokenizer(num_words=max_features)tokenizer.fit_on_texts(list(train_X)+list(test_X))train_X = tokenizer.texts_to_sequences(train_X)test_X = tokenizer.texts_to_sequences(test_X) where train_X and test_X are lists of documents in the corpus. Normally our model expects that each text sequence (each training example) will be of the same length (the same number of words/tokens). We can control this using the maxlen parameter. For example: train_X = pad_sequences(train_X, maxlen=maxlen)test_X = pad_sequences(test_X, maxlen=maxlen) Now our training data contains a list of numbers. Each list has the same length. And we also have the word_index which is a dictionary of the words that occur most in the text corpus. The Pytorch model expects the target variable as a number and not a string. We can use Label encoder from sklearn to convert our target variable. from sklearn.preprocessing import LabelEncoderle = LabelEncoder()train_y = le.fit_transform(train_y.values)test_y = le.transform(test_y.values) First, we need to load the required Glove embeddings. def load_glove(word_index): EMBEDDING_FILE = '../input/glove840b300dtxt/glove.840B.300d.txt' def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')[:300] embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE)) all_embs = np.stack(embeddings_index.values()) emb_mean,emb_std = -0.005838499,0.48782197 embed_size = all_embs.shape[1]nb_words = min(max_features, len(word_index)+1) embedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words, embed_size)) for word, i in word_index.items(): if i >= max_features: continue embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector else: embedding_vector = embeddings_index.get(word.capitalize()) if embedding_vector is not None: embedding_matrix[i] = embedding_vector return embedding_matrixembedding_matrix = load_glove(tokenizer.word_index) Be sure to put the path of the folder where you download these GLoVE vectors. What does the embeddings_index contain? It’s a dictionary in which the key is the word, and the value is the word vector, a np.array of length 300. The length of this dictionary is somewhere around a billion. Since we only want the embeddings of words that are in our word_index, we will create a matrix that just contains required embeddings using the word index from our tokenizer. The idea of using a CNN to classify text was first presented in the paper Convolutional Neural Networks for Sentence Classification by Yoon Kim. Representation: The central concept of this idea is to see our documents as images. But how? Let’s say we have a sentence, and we have maxlen = 70 and embedding size = 300. We can create a matrix of numbers with the shape 70×300 to represent this sentence. Images also have a matrix where individual elements are pixel values. But instead of image pixels, the input to the task is sentences or documents represented as a matrix. Each row of the matrix corresponds to a one-word vector. Convolution Idea: For images, we move our conv. filter both horizontally as well as vertically, but for text we fix kernel size to filter_size x embed_size, i.e. (3,300) we are just going to move vertically down the convolution looking at three words at once, since our filter size in this case is 3. This idea seems right since our convolution filter is not splitting word embedding; it gets to look at the full embedding of each word. Also, one can think of filter sizes as unigrams, bigrams, trigrams, etc. Since we are looking at a context window of 1, 2, 3, and 5 words respectively. Here is the text classification CNN network coded in Pytorch. class CNN_Text(nn.Module): def __init__(self): super(CNN_Text, self).__init__() filter_sizes = [1,2,3,5] num_filters = 36 n_classes = len(le.classes_) self.embedding = nn.Embedding(max_features, embed_size) self.embedding.weight = nn.Parameter(torch.tensor(embedding_matrix, dtype=torch.float32)) self.embedding.weight.requires_grad = False self.convs1 = nn.ModuleList([nn.Conv2d(1, num_filters, (K, embed_size)) for K in filter_sizes]) self.dropout = nn.Dropout(0.1) self.fc1 = nn.Linear(len(filter_sizes)*num_filters, n_classes)def forward(self, x): x = self.embedding(x) x = x.unsqueeze(1) x = [F.relu(conv(x)).squeeze(3) for conv in self.convs1] x = [F.max_pool1d(i, i.size(2)).squeeze(2) for i in x] x = torch.cat(x, 1) x = self.dropout(x) logit = self.fc1(x) return logit TextCNN works well for text classification because it takes care of words in close range. For example, it can see “new york” together. However, it still can’t take care of all the context provided in a particular text sequence. It still does not learn the sequential structure of the data, where each word is dependent on the previous word, or a word in the previous sentence. RNNs can help us with that. They can remember previous information using hidden states and connect it to the current task. Long Short Term Memory networks (LSTM) are a subclass of RNN, specialized in remembering information for extended periods. Moreover, a bidirectional LSTM keeps the contextual information in both directions, which is pretty useful in text classification tasks (However, it won’t work for a time series prediction task as we don’t have visibility into the future in this case). For a simple explanation of a bidirectional RNN, think of an RNN cell as a black box taking as input a hidden state (a vector) and a word vector and giving out an output vector and the next hidden state. This box has some weights which need to be tuned using backpropagation of the losses. Also, the same cell is applied to all the words so that the weights are shared across the words in the sentence. This phenomenon is called weight-sharing. Hidden state, Word vector ->(RNN Cell) -> Output Vector , Next Hidden state For a sequence of length 4 like “you will never believe”, The RNN cell gives 4 output vectors, which can be concatenated and then used as part of a dense feedforward architecture. In the bidirectional RNN, the only change is that we read the text in the usual fashion as well in reverse. So we stack two RNNs in parallel, and we get 8 output vectors to append. Once we get the output vectors, we send them through a series of dense layers and finally, a softmax layer to build a text classifier. In most cases, you need to understand how to stack some layers in a neural network to get the best results. We can try out multiple bidirectional GRU/LSTM layers in the network if it performs better. Due to the limitations of RNNs, such as not remembering long term dependencies, in practice, we almost always use LSTM/GRU to model long term dependencies. In this case, you can think of the RNN cell being replaced by an LSTM cell or a GRU cell in the above figure. Here is some code in Pytorch for this network: class BiLSTM(nn.Module): def __init__(self): super(BiLSTM, self).__init__() self.hidden_size = 64 drp = 0.1 n_classes = len(le.classes_) self.embedding = nn.Embedding(max_features, embed_size) self.embedding.weight = nn.Parameter(torch.tensor(embedding_matrix, dtype=torch.float32)) self.embedding.weight.requires_grad = False self.lstm = nn.LSTM(embed_size, self.hidden_size, bidirectional=True, batch_first=True) self.linear = nn.Linear(self.hidden_size*4 , 64) self.relu = nn.ReLU() self.dropout = nn.Dropout(drp) self.out = nn.Linear(64, n_classes) def forward(self, x): #rint(x.size()) h_embedding = self.embedding(x) #_embedding = torch.squeeze(torch.unsqueeze(h_embedding, 0)) h_lstm, _ = self.lstm(h_embedding) avg_pool = torch.mean(h_lstm, 1) max_pool, _ = torch.max(h_lstm, 1) conc = torch.cat(( avg_pool, max_pool), 1) conc = self.relu(self.linear(conc)) conc = self.dropout(conc) out = self.out(conc) return out Below is the code we use to train our BiLSTM Model. The code is well commented, so please go through the code to understand it. You might also want to look at my post on Pytorch. n_epochs = 6model = BiLSTM()loss_fn = nn.CrossEntropyLoss(reduction='sum')optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=0.001)model.cuda()# Load train and test in CUDA Memoryx_train = torch.tensor(train_X, dtype=torch.long).cuda()y_train = torch.tensor(train_y, dtype=torch.long).cuda()x_cv = torch.tensor(test_X, dtype=torch.long).cuda()y_cv = torch.tensor(test_y, dtype=torch.long).cuda()# Create Torch datasetstrain = torch.utils.data.TensorDataset(x_train, y_train)valid = torch.utils.data.TensorDataset(x_cv, y_cv)# Create Data Loaderstrain_loader = torch.utils.data.DataLoader(train, batch_size=batch_size, shuffle=True)valid_loader = torch.utils.data.DataLoader(valid, batch_size=batch_size, shuffle=False)train_loss = []valid_loss = []for epoch in range(n_epochs): start_time = time.time() # Set model to train configuration model.train() avg_loss = 0. for i, (x_batch, y_batch) in enumerate(train_loader): # Predict/Forward Pass y_pred = model(x_batch) # Compute loss loss = loss_fn(y_pred, y_batch) optimizer.zero_grad() loss.backward() optimizer.step() avg_loss += loss.item() / len(train_loader) # Set model to validation configuration -Doesn't get trained here model.eval() avg_val_loss = 0. val_preds = np.zeros((len(x_cv),len(le.classes_))) for i, (x_batch, y_batch) in enumerate(valid_loader): y_pred = model(x_batch).detach() avg_val_loss += loss_fn(y_pred, y_batch).item() / len(valid_loader) # keep/store predictions val_preds[i * batch_size:(i+1) * batch_size] =F.softmax(y_pred).cpu().numpy() # Check Accuracy val_accuracy = sum(val_preds.argmax(axis=1)==test_y)/len(test_y) train_loss.append(avg_loss) valid_loss.append(avg_val_loss) elapsed_time = time.time() - start_time print('Epoch {}/{} \t loss={:.4f} \t val_loss={:.4f} \t val_acc={:.4f} \t time={:.2f}s'.format( epoch + 1, n_epochs, avg_loss, avg_val_loss, val_accuracy, elapsed_time)) The training output looks like below: import scikitplot as skplty_true = [le.classes_[x] for x in test_y]y_pred = [le.classes_[x] for x in val_preds.argmax(axis=1)]skplt.metrics.plot_confusion_matrix( y_true, y_pred, figsize=(12,12),x_tick_rotation=90) Below is the confusion matrix for the results of the BiLSTM model. We can see that our model does reasonably well, with an 87% accuracy on the validation dataset. What’s interesting is that even at points where the model performs poorly, it is quite understandable. For example, the model gets confused between weight loss and obesity, or between depression and anxiety, or between depression and bipolar disorder. I am not an expert, but these diseases do feel quite similar. In this post, we covered deep learning architectures like LSTM and CNN for text classification and explained the different steps used in deep learning for NLP. There is still a lot that can be done to improve this model’s performance. Changing the learning rates, using learning rate schedules, using extra features, enriching embeddings, removing misspellings, etc. I hope this boilerplate code provides a go-to baseline for any text classification problem you might face. You can find the full working code here on Github, or this Kaggle Kernel. Also, if you want to learn more about NLP, here is an excellent course. If you want to learn more about NLP, I would like to call out an excellent course on Natural Language Processing from the Advanced Machine Learning Specialization. Do check it out. I am going to be writing more of such posts in the future too. Let me know what you think about the series. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz. Also, a small disclaimer — There might be some affiliate links in this post to relevant resources, as sharing knowledge is never a bad idea. This story was first published here.
[ { "code": null, "e": 364, "s": 172, "text": "Have you ever thought about how toxic comments get flagged automatically on platforms like Quora or Reddit? Or how mail gets marked as spam? Or what decides which online ads are shown to you?" }, { "code": null, "e": 606, "s": 364, "text": "All of the above are examples of how text classification is used in different areas. Text classification is a common task in natural language processing (NLP) which transforms a sequence of a text of indefinite length into a single category." }, { "code": null, "e": 851, "s": 606, "text": "One theme that emerges from the above examples is that all have a binary target class. For example, either the comment is toxic or not toxic, or the review is fake or not fake. In short, there are only two target classes, hence the term binary." }, { "code": null, "e": 1116, "s": 851, "text": "But this is not always the case, and some problems might have more than two target classes. These problems are conveniently termed multiclass classifications, and it is these problems we’ll focus on in this post. Some examples of multiclass classification include:" }, { "code": null, "e": 1189, "s": 1116, "text": "The sentiment of a review: positive, negative or neutral (three classes)" }, { "code": null, "e": 1260, "s": 1189, "text": "News Categorization by genre: Entertainment, education, politics, etc." }, { "code": null, "e": 1542, "s": 1260, "text": "On a side note, if you are interested in a custom deep learning workstation or server to use in your work, Exxact Corporation has a great line of AI-based solutions starting at $3,700, with a couple of NVIDIA RTX 30 Series GPUs, 3-year warranty, and a deep learning software stack." }, { "code": null, "e": 1653, "s": 1542, "text": "In this post, we will go through a multiclass text classification problem using various Deep Learning Methods." }, { "code": null, "e": 1887, "s": 1653, "text": "For this post, I am using the UCI ML Drug Review dataset from Kaggle. It contains over 200,000 patient drug reviews, along with related conditions. The dataset has many columns, but we will be using just two of them for our NLP Task." }, { "code": null, "e": 1927, "s": 1887, "text": "So, our dataset mostly looks like this:" }, { "code": null, "e": 2006, "s": 1927, "text": "Task: We want to classify the top disease conditions based on the drug review." }, { "code": null, "e": 2181, "s": 2006, "text": "Before we go any further into text classification, we need a way to represent words numerically in a vocabulary. Why? Because most of our ML models require numbers, not text." }, { "code": null, "e": 2521, "s": 2181, "text": "One way to achieve this goal is by using the one-hot encoding of word vectors, but this is not the right choice. Given a vast vocabulary, this representation would take a lot of space, and it cannot accurately express the similarity between different words, such as if we want to find the cosine similarity between numerical words x and y:" }, { "code": null, "e": 2633, "s": 2521, "text": "Given the structure of one-hot encoded vectors, the similarity is always going to be 0 between different words." }, { "code": null, "e": 2876, "s": 2633, "text": "Word2Vec overcomes the above difficulties by providing us with a fixed-length (usually much smaller than the vocabulary size) vector representation of words. It also captures the similarity and analogous relationships between different words." }, { "code": null, "e": 3067, "s": 2876, "text": "Word2vec vectors of words are learned in such a way that they allow us to learn different analogies. This enables us to do algebraic manipulations on words that were not possible previously." }, { "code": null, "e": 3129, "s": 3067, "text": "For example: What is king — man + woman? The result is Queen." }, { "code": null, "e": 3459, "s": 3129, "text": "Word2Vec vectors also help us to find the similarity between words. If we look for similar words to “good”, we will find awesome, great, etc. It is this property of word2vec that makes it invaluable for text classification. With this, our deep learning network understands that “good” and “great” are words with similar meanings." }, { "code": null, "e": 3611, "s": 3459, "text": "In simple terms, word2vec creates fixed-length vectors for words, giving us a d dimensional vector for every word (and common bigrams) in a dictionary." }, { "code": null, "e": 3906, "s": 3611, "text": "These word vectors are usually pre-trained, and provided by others after training on large corpora of texts like Wikipedia, Twitter, etc. The most commonly used pre-trained word vectors are Glove and Fast text with 300-dimensional word vectors. In this post, we will use the Glove word vectors." }, { "code": null, "e": 4416, "s": 3906, "text": "In most cases, text data is not entirely clean. Data coming from different sources have different characteristics, and this makes text preprocessing one of the most critical steps in the classification pipeline. For example, Text data from Twitter is different from the text data found on Quora or other news/blogging platforms, and each needs to be treated differently. However, the techniques we’ll cover in this post are generic enough for almost any kind of data you might encounter in the jungles of NLP." }, { "code": null, "e": 4827, "s": 4416, "text": "Our preprocessing pipeline depends heavily on the word2vec embeddings we are going to use for our classification task. In principle, our preprocessing should match the preprocessing used before training the word embedding. Since most of the embeddings don’t provide vector values for punctuation and other special characters, the first thing we want to do is get rid of the special characters in our text data." }, { "code": null, "e": 5025, "s": 4827, "text": "# Some preprocesssing that will be common to all the text classification methods you will see.import redef clean_text(x): pattern = r'[^a-zA-z0-9\\s]' text = re.sub(pattern, '', x) return x" }, { "code": null, "e": 5152, "s": 5025, "text": "Why do we want to replace numbers with #s? Because most embeddings, including Glove, have preprocessed their text in this way." }, { "code": null, "e": 5362, "s": 5152, "text": "Small Python Trick: We use an if statement in the code below to check beforehand if a number exists in a text because an if is always faster than a re.sub command, and most of our text doesn’t contain numbers." }, { "code": null, "e": 5592, "s": 5362, "text": "def clean_numbers(x): if bool(re.search(r'\\d', x)): x = re.sub('[0-9]{5,}', '#####', x) x = re.sub('[0-9]{4}', '####', x) x = re.sub('[0-9]{3}', '###', x) x = re.sub('[0-9]{2}', '##', x) return x" }, { "code": null, "e": 5865, "s": 5592, "text": "Contractions are words that we write with an apostrophe. Examples of contractions are words like “ain’t” or “aren’t”. Since we want to standardize our text, it makes sense to expand these contractions. Below we have done this using contraction mapping and regex functions." }, { "code": null, "e": 6418, "s": 5865, "text": "contraction_dict = {\"ain't\": \"is not\", \"aren't\": \"are not\",\"can't\": \"cannot\", \"'cause\": \"because\", \"could've\": \"could have\"}def _get_contractions(contraction_dict): contraction_re = re.compile('(%s)' % '|'.join(contraction_dict.keys())) return contraction_dict, contraction_recontractions, contractions_re = _get_contractions(contraction_dict)def replace_contractions(text): def replace(match): return contractions[match.group(0)] return contractions_re.sub(replace, text)# Usagereplace_contractions(\"this's a text with contraction\")" }, { "code": null, "e": 6561, "s": 6418, "text": "Apart from the above techniques, you may want to do spell correction, too. But since our post is already quite long, we’ll leave that for now." }, { "code": null, "e": 6945, "s": 6561, "text": "One thing that has made deep learning a go-to choice for NLP is the fact that we don’t have to hand-engineer features from our text data; deep learning algorithms take as input a sequence of text to learn its structure just like humans do. Since machines cannot understand words, they expect their data in numerical form. So we need to represent our text data as a series of numbers." }, { "code": null, "e": 7127, "s": 6945, "text": "To understand how this is done, we need to understand a little about the Keras Tokenizer function. Other tokenizers are also viable, but the Keras Tokenizer is a good choice for me." }, { "code": null, "e": 7358, "s": 7127, "text": "Put simply, a tokenizer is a utility function that splits a sentence into words. keras.preprocessing.text.Tokenizer tokenizes (splits) a text into tokens (words) while keeping only the words that occur the most in the text corpus." }, { "code": null, "e": 7527, "s": 7358, "text": "#Signature:Tokenizer(num_words=None, filters='!\"#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~\\t\\n',lower=True, split=' ', char_level=False, oov_token=None, document_count=0, **kwargs)" }, { "code": null, "e": 7930, "s": 7527, "text": "The num_words parameter keeps only a pre-specified number of words in the text. This is helpful because we don’t want our model to get a lot of noise by considering words that occur infrequently. In real-world data, most of the words we leave using the num_words parameter are normally misspelled words. The tokenizer also filters some non-wanted tokens by default and converts the text into lowercase." }, { "code": null, "e": 8176, "s": 7930, "text": "Once fitted to the data, the tokenizer also keeps an index of words (a dictionary we can use to assign unique numbers to words), which can be accessed by tokenizer.word_index. The words in the indexed dictionary are ranked in order of frequency." }, { "code": null, "e": 8230, "s": 8176, "text": "So the whole code to use the tokenizer is as follows:" }, { "code": null, "e": 8489, "s": 8230, "text": "from keras.preprocessing.text import Tokenizer## Tokenize the sentencestokenizer = Tokenizer(num_words=max_features)tokenizer.fit_on_texts(list(train_X)+list(test_X))train_X = tokenizer.texts_to_sequences(train_X)test_X = tokenizer.texts_to_sequences(test_X)" }, { "code": null, "e": 8552, "s": 8489, "text": "where train_X and test_X are lists of documents in the corpus." }, { "code": null, "e": 8737, "s": 8552, "text": "Normally our model expects that each text sequence (each training example) will be of the same length (the same number of words/tokens). We can control this using the maxlen parameter." }, { "code": null, "e": 8750, "s": 8737, "text": "For example:" }, { "code": null, "e": 8843, "s": 8750, "text": "train_X = pad_sequences(train_X, maxlen=maxlen)test_X = pad_sequences(test_X, maxlen=maxlen)" }, { "code": null, "e": 9027, "s": 8843, "text": "Now our training data contains a list of numbers. Each list has the same length. And we also have the word_index which is a dictionary of the words that occur most in the text corpus." }, { "code": null, "e": 9173, "s": 9027, "text": "The Pytorch model expects the target variable as a number and not a string. We can use Label encoder from sklearn to convert our target variable." }, { "code": null, "e": 9317, "s": 9173, "text": "from sklearn.preprocessing import LabelEncoderle = LabelEncoder()train_y = le.fit_transform(train_y.values)test_y = le.transform(test_y.values)" }, { "code": null, "e": 9371, "s": 9317, "text": "First, we need to load the required Glove embeddings." }, { "code": null, "e": 10374, "s": 9371, "text": "def load_glove(word_index): EMBEDDING_FILE = '../input/glove840b300dtxt/glove.840B.300d.txt' def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')[:300] embeddings_index = dict(get_coefs(*o.split(\" \")) for o in open(EMBEDDING_FILE)) all_embs = np.stack(embeddings_index.values()) emb_mean,emb_std = -0.005838499,0.48782197 embed_size = all_embs.shape[1]nb_words = min(max_features, len(word_index)+1) embedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words, embed_size)) for word, i in word_index.items(): if i >= max_features: continue embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector else: embedding_vector = embeddings_index.get(word.capitalize()) if embedding_vector is not None: embedding_matrix[i] = embedding_vector return embedding_matrixembedding_matrix = load_glove(tokenizer.word_index)" }, { "code": null, "e": 10661, "s": 10374, "text": "Be sure to put the path of the folder where you download these GLoVE vectors. What does the embeddings_index contain? It’s a dictionary in which the key is the word, and the value is the word vector, a np.array of length 300. The length of this dictionary is somewhere around a billion." }, { "code": null, "e": 10836, "s": 10661, "text": "Since we only want the embeddings of words that are in our word_index, we will create a matrix that just contains required embeddings using the word index from our tokenizer." }, { "code": null, "e": 10981, "s": 10836, "text": "The idea of using a CNN to classify text was first presented in the paper Convolutional Neural Networks for Sentence Classification by Yoon Kim." }, { "code": null, "e": 11467, "s": 10981, "text": "Representation: The central concept of this idea is to see our documents as images. But how? Let’s say we have a sentence, and we have maxlen = 70 and embedding size = 300. We can create a matrix of numbers with the shape 70×300 to represent this sentence. Images also have a matrix where individual elements are pixel values. But instead of image pixels, the input to the task is sentences or documents represented as a matrix. Each row of the matrix corresponds to a one-word vector." }, { "code": null, "e": 12056, "s": 11467, "text": "Convolution Idea: For images, we move our conv. filter both horizontally as well as vertically, but for text we fix kernel size to filter_size x embed_size, i.e. (3,300) we are just going to move vertically down the convolution looking at three words at once, since our filter size in this case is 3. This idea seems right since our convolution filter is not splitting word embedding; it gets to look at the full embedding of each word. Also, one can think of filter sizes as unigrams, bigrams, trigrams, etc. Since we are looking at a context window of 1, 2, 3, and 5 words respectively." }, { "code": null, "e": 12118, "s": 12056, "text": "Here is the text classification CNN network coded in Pytorch." }, { "code": null, "e": 13039, "s": 12118, "text": "class CNN_Text(nn.Module): def __init__(self): super(CNN_Text, self).__init__() filter_sizes = [1,2,3,5] num_filters = 36 n_classes = len(le.classes_) self.embedding = nn.Embedding(max_features, embed_size) self.embedding.weight = nn.Parameter(torch.tensor(embedding_matrix, dtype=torch.float32)) self.embedding.weight.requires_grad = False self.convs1 = nn.ModuleList([nn.Conv2d(1, num_filters, (K, embed_size)) for K in filter_sizes]) self.dropout = nn.Dropout(0.1) self.fc1 = nn.Linear(len(filter_sizes)*num_filters, n_classes)def forward(self, x): x = self.embedding(x) x = x.unsqueeze(1) x = [F.relu(conv(x)).squeeze(3) for conv in self.convs1] x = [F.max_pool1d(i, i.size(2)).squeeze(2) for i in x] x = torch.cat(x, 1) x = self.dropout(x) logit = self.fc1(x) return logit" }, { "code": null, "e": 13416, "s": 13039, "text": "TextCNN works well for text classification because it takes care of words in close range. For example, it can see “new york” together. However, it still can’t take care of all the context provided in a particular text sequence. It still does not learn the sequential structure of the data, where each word is dependent on the previous word, or a word in the previous sentence." }, { "code": null, "e": 13539, "s": 13416, "text": "RNNs can help us with that. They can remember previous information using hidden states and connect it to the current task." }, { "code": null, "e": 13915, "s": 13539, "text": "Long Short Term Memory networks (LSTM) are a subclass of RNN, specialized in remembering information for extended periods. Moreover, a bidirectional LSTM keeps the contextual information in both directions, which is pretty useful in text classification tasks (However, it won’t work for a time series prediction task as we don’t have visibility into the future in this case)." }, { "code": null, "e": 14360, "s": 13915, "text": "For a simple explanation of a bidirectional RNN, think of an RNN cell as a black box taking as input a hidden state (a vector) and a word vector and giving out an output vector and the next hidden state. This box has some weights which need to be tuned using backpropagation of the losses. Also, the same cell is applied to all the words so that the weights are shared across the words in the sentence. This phenomenon is called weight-sharing." }, { "code": null, "e": 14436, "s": 14360, "text": "Hidden state, Word vector ->(RNN Cell) -> Output Vector , Next Hidden state" }, { "code": null, "e": 14616, "s": 14436, "text": "For a sequence of length 4 like “you will never believe”, The RNN cell gives 4 output vectors, which can be concatenated and then used as part of a dense feedforward architecture." }, { "code": null, "e": 14797, "s": 14616, "text": "In the bidirectional RNN, the only change is that we read the text in the usual fashion as well in reverse. So we stack two RNNs in parallel, and we get 8 output vectors to append." }, { "code": null, "e": 14932, "s": 14797, "text": "Once we get the output vectors, we send them through a series of dense layers and finally, a softmax layer to build a text classifier." }, { "code": null, "e": 15132, "s": 14932, "text": "In most cases, you need to understand how to stack some layers in a neural network to get the best results. We can try out multiple bidirectional GRU/LSTM layers in the network if it performs better." }, { "code": null, "e": 15398, "s": 15132, "text": "Due to the limitations of RNNs, such as not remembering long term dependencies, in practice, we almost always use LSTM/GRU to model long term dependencies. In this case, you can think of the RNN cell being replaced by an LSTM cell or a GRU cell in the above figure." }, { "code": null, "e": 15445, "s": 15398, "text": "Here is some code in Pytorch for this network:" }, { "code": null, "e": 16536, "s": 15445, "text": "class BiLSTM(nn.Module): def __init__(self): super(BiLSTM, self).__init__() self.hidden_size = 64 drp = 0.1 n_classes = len(le.classes_) self.embedding = nn.Embedding(max_features, embed_size) self.embedding.weight = nn.Parameter(torch.tensor(embedding_matrix, dtype=torch.float32)) self.embedding.weight.requires_grad = False self.lstm = nn.LSTM(embed_size, self.hidden_size, bidirectional=True, batch_first=True) self.linear = nn.Linear(self.hidden_size*4 , 64) self.relu = nn.ReLU() self.dropout = nn.Dropout(drp) self.out = nn.Linear(64, n_classes) def forward(self, x): #rint(x.size()) h_embedding = self.embedding(x) #_embedding = torch.squeeze(torch.unsqueeze(h_embedding, 0)) h_lstm, _ = self.lstm(h_embedding) avg_pool = torch.mean(h_lstm, 1) max_pool, _ = torch.max(h_lstm, 1) conc = torch.cat(( avg_pool, max_pool), 1) conc = self.relu(self.linear(conc)) conc = self.dropout(conc) out = self.out(conc) return out" }, { "code": null, "e": 16715, "s": 16536, "text": "Below is the code we use to train our BiLSTM Model. The code is well commented, so please go through the code to understand it. You might also want to look at my post on Pytorch." }, { "code": null, "e": 18794, "s": 16715, "text": "n_epochs = 6model = BiLSTM()loss_fn = nn.CrossEntropyLoss(reduction='sum')optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=0.001)model.cuda()# Load train and test in CUDA Memoryx_train = torch.tensor(train_X, dtype=torch.long).cuda()y_train = torch.tensor(train_y, dtype=torch.long).cuda()x_cv = torch.tensor(test_X, dtype=torch.long).cuda()y_cv = torch.tensor(test_y, dtype=torch.long).cuda()# Create Torch datasetstrain = torch.utils.data.TensorDataset(x_train, y_train)valid = torch.utils.data.TensorDataset(x_cv, y_cv)# Create Data Loaderstrain_loader = torch.utils.data.DataLoader(train, batch_size=batch_size, shuffle=True)valid_loader = torch.utils.data.DataLoader(valid, batch_size=batch_size, shuffle=False)train_loss = []valid_loss = []for epoch in range(n_epochs): start_time = time.time() # Set model to train configuration model.train() avg_loss = 0. for i, (x_batch, y_batch) in enumerate(train_loader): # Predict/Forward Pass y_pred = model(x_batch) # Compute loss loss = loss_fn(y_pred, y_batch) optimizer.zero_grad() loss.backward() optimizer.step() avg_loss += loss.item() / len(train_loader) # Set model to validation configuration -Doesn't get trained here model.eval() avg_val_loss = 0. val_preds = np.zeros((len(x_cv),len(le.classes_))) for i, (x_batch, y_batch) in enumerate(valid_loader): y_pred = model(x_batch).detach() avg_val_loss += loss_fn(y_pred, y_batch).item() / len(valid_loader) # keep/store predictions val_preds[i * batch_size:(i+1) * batch_size] =F.softmax(y_pred).cpu().numpy() # Check Accuracy val_accuracy = sum(val_preds.argmax(axis=1)==test_y)/len(test_y) train_loss.append(avg_loss) valid_loss.append(avg_val_loss) elapsed_time = time.time() - start_time print('Epoch {}/{} \\t loss={:.4f} \\t val_loss={:.4f} \\t val_acc={:.4f} \\t time={:.2f}s'.format( epoch + 1, n_epochs, avg_loss, avg_val_loss, val_accuracy, elapsed_time))" }, { "code": null, "e": 18832, "s": 18794, "text": "The training output looks like below:" }, { "code": null, "e": 19057, "s": 18832, "text": "import scikitplot as skplty_true = [le.classes_[x] for x in test_y]y_pred = [le.classes_[x] for x in val_preds.argmax(axis=1)]skplt.metrics.plot_confusion_matrix( y_true, y_pred, figsize=(12,12),x_tick_rotation=90)" }, { "code": null, "e": 19220, "s": 19057, "text": "Below is the confusion matrix for the results of the BiLSTM model. We can see that our model does reasonably well, with an 87% accuracy on the validation dataset." }, { "code": null, "e": 19534, "s": 19220, "text": "What’s interesting is that even at points where the model performs poorly, it is quite understandable. For example, the model gets confused between weight loss and obesity, or between depression and anxiety, or between depression and bipolar disorder. I am not an expert, but these diseases do feel quite similar." }, { "code": null, "e": 19694, "s": 19534, "text": "In this post, we covered deep learning architectures like LSTM and CNN for text classification and explained the different steps used in deep learning for NLP." }, { "code": null, "e": 20008, "s": 19694, "text": "There is still a lot that can be done to improve this model’s performance. Changing the learning rates, using learning rate schedules, using extra features, enriching embeddings, removing misspellings, etc. I hope this boilerplate code provides a go-to baseline for any text classification problem you might face." }, { "code": null, "e": 20082, "s": 20008, "text": "You can find the full working code here on Github, or this Kaggle Kernel." }, { "code": null, "e": 20154, "s": 20082, "text": "Also, if you want to learn more about NLP, here is an excellent course." }, { "code": null, "e": 20335, "s": 20154, "text": "If you want to learn more about NLP, I would like to call out an excellent course on Natural Language Processing from the Advanced Machine Learning Specialization. Do check it out." }, { "code": null, "e": 20613, "s": 20335, "text": "I am going to be writing more of such posts in the future too. Let me know what you think about the series. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz." }, { "code": null, "e": 20754, "s": 20613, "text": "Also, a small disclaimer — There might be some affiliate links in this post to relevant resources, as sharing knowledge is never a bad idea." } ]
Depth of an N-Ary tree in C++ Program
In this tutorial, we are going to learn how to find the depth of the n-ary tree. An n-ary tree is a tree in which each node of the tree has no more than n child nodes. We have to find the depth of the n-ary tree. We will be using the vector to store the children of each node in the tree. Let's see the steps to solve the problem. Initialize the tree with dummy data. Initialize the tree with dummy data. Write a recursive function to find the depth of the n-ary tree.Initialize a variable to store the max depth of the tree.Iterate over the children of each node.The max depth is the max of the current max depth and the depth of the node children.If we assume the max depth variable is maxDepth and maxDepth = max(maxDepth, findDepthOfTree(*children) is the recursive statement to find the depth of the tree.The final maximum depth of the tree is maxDepth + 1. Write a recursive function to find the depth of the n-ary tree. Initialize a variable to store the max depth of the tree. Initialize a variable to store the max depth of the tree. Iterate over the children of each node.The max depth is the max of the current max depth and the depth of the node children.If we assume the max depth variable is maxDepth and maxDepth = max(maxDepth, findDepthOfTree(*children) is the recursive statement to find the depth of the tree. Iterate over the children of each node. The max depth is the max of the current max depth and the depth of the node children. The max depth is the max of the current max depth and the depth of the node children. If we assume the max depth variable is maxDepth and maxDepth = max(maxDepth, findDepthOfTree(*children) is the recursive statement to find the depth of the tree. If we assume the max depth variable is maxDepth and maxDepth = max(maxDepth, findDepthOfTree(*children) is the recursive statement to find the depth of the tree. The final maximum depth of the tree is maxDepth + 1. The final maximum depth of the tree is maxDepth + 1. Print the max depth of the tree. Print the max depth of the tree. Let's see the code. Live Demo #include <bits/stdc++.h> using namespace std; struct Node { int data; vector<Node *> child; }; Node *newNode(int data) { Node *temp = new Node; temp->data = data; return temp; } int findDepthOfTree(struct Node *node) { if (node == NULL) { return 0; } int maxDepth = 0; for (vector<Node*>::iterator it = node->child.begin(); it != node->child.end(); it++) { maxDepth = max(maxDepth, findDepthOfTree(*it)); } return maxDepth + 1; } int main() { Node *root = newNode(1); root->child.push_back(newNode(2)); root->child.push_back(newNode(3)); root->child.push_back(newNode(4)); root->child[2]->child.push_back(newNode(1)); root->child[2]->child.push_back(newNode(2)); root->child[2]->child.push_back(newNode(3)); root->child[2]->child.push_back(newNode(4)); cout << findDepthOfTree(root) << endl; return 0; } If you run the above code, then you will get the following result. 3 If you have any queries in the tutorial, mention them in the comment section.
[ { "code": null, "e": 1143, "s": 1062, "text": "In this tutorial, we are going to learn how to find the depth of the n-ary tree." }, { "code": null, "e": 1230, "s": 1143, "text": "An n-ary tree is a tree in which each node of the tree has no more than n child nodes." }, { "code": null, "e": 1351, "s": 1230, "text": "We have to find the depth of the n-ary tree. We will be using the vector to store the children of each node in the tree." }, { "code": null, "e": 1393, "s": 1351, "text": "Let's see the steps to solve the problem." }, { "code": null, "e": 1430, "s": 1393, "text": "Initialize the tree with dummy data." }, { "code": null, "e": 1467, "s": 1430, "text": "Initialize the tree with dummy data." }, { "code": null, "e": 1925, "s": 1467, "text": "Write a recursive function to find the depth of the n-ary tree.Initialize a variable to store the max depth of the tree.Iterate over the children of each node.The max depth is the max of the current max depth and the depth of the node children.If we assume the max depth variable is maxDepth and maxDepth = max(maxDepth, findDepthOfTree(*children) is the recursive statement to find the depth of the tree.The final maximum depth of the tree is maxDepth + 1." }, { "code": null, "e": 1989, "s": 1925, "text": "Write a recursive function to find the depth of the n-ary tree." }, { "code": null, "e": 2047, "s": 1989, "text": "Initialize a variable to store the max depth of the tree." }, { "code": null, "e": 2105, "s": 2047, "text": "Initialize a variable to store the max depth of the tree." }, { "code": null, "e": 2391, "s": 2105, "text": "Iterate over the children of each node.The max depth is the max of the current max depth and the depth of the node children.If we assume the max depth variable is maxDepth and maxDepth = max(maxDepth, findDepthOfTree(*children) is the recursive statement to find the depth of the tree." }, { "code": null, "e": 2431, "s": 2391, "text": "Iterate over the children of each node." }, { "code": null, "e": 2517, "s": 2431, "text": "The max depth is the max of the current max depth and the depth of the node children." }, { "code": null, "e": 2603, "s": 2517, "text": "The max depth is the max of the current max depth and the depth of the node children." }, { "code": null, "e": 2765, "s": 2603, "text": "If we assume the max depth variable is maxDepth and maxDepth = max(maxDepth, findDepthOfTree(*children) is the recursive statement to find the depth of the tree." }, { "code": null, "e": 2927, "s": 2765, "text": "If we assume the max depth variable is maxDepth and maxDepth = max(maxDepth, findDepthOfTree(*children) is the recursive statement to find the depth of the tree." }, { "code": null, "e": 2980, "s": 2927, "text": "The final maximum depth of the tree is maxDepth + 1." }, { "code": null, "e": 3033, "s": 2980, "text": "The final maximum depth of the tree is maxDepth + 1." }, { "code": null, "e": 3066, "s": 3033, "text": "Print the max depth of the tree." }, { "code": null, "e": 3099, "s": 3066, "text": "Print the max depth of the tree." }, { "code": null, "e": 3119, "s": 3099, "text": "Let's see the code." }, { "code": null, "e": 3130, "s": 3119, "text": " Live Demo" }, { "code": null, "e": 4009, "s": 3130, "text": "#include <bits/stdc++.h>\nusing namespace std;\nstruct Node {\n int data;\n vector<Node *> child;\n};\nNode *newNode(int data) {\n Node *temp = new Node;\n temp->data = data;\n return temp;\n}\nint findDepthOfTree(struct Node *node) {\n if (node == NULL) {\n return 0;\n }\n int maxDepth = 0;\n for (vector<Node*>::iterator it = node->child.begin(); it != node->child.end(); it++) {\n maxDepth = max(maxDepth, findDepthOfTree(*it));\n }\n return maxDepth + 1;\n}\nint main() {\n Node *root = newNode(1);\n root->child.push_back(newNode(2));\n root->child.push_back(newNode(3));\n root->child.push_back(newNode(4));\n root->child[2]->child.push_back(newNode(1));\n root->child[2]->child.push_back(newNode(2));\n root->child[2]->child.push_back(newNode(3));\n root->child[2]->child.push_back(newNode(4));\n cout << findDepthOfTree(root) << endl;\n return 0;\n}" }, { "code": null, "e": 4076, "s": 4009, "text": "If you run the above code, then you will get the following result." }, { "code": null, "e": 4078, "s": 4076, "text": "3" }, { "code": null, "e": 4156, "s": 4078, "text": "If you have any queries in the tutorial, mention them in the comment section." } ]
Dart Programming - Debugging
Every now and then, developers commit mistakes while coding. A mistake in a program is referred to as a bug. The process of finding and fixing bugs is called debugging and is a normal part of the development process. This section covers tools and techniques that can help you with debugging tasks. The WebStorm editor enables breakpoints and step-by-step debugging. The program will break at the point where the breakpoint is attached. This functionality is like what you might expect from Java or C# application development. You can watch variables, browse the stack, step over and step into method and function calls, all from the WebStorm Editor. Consider the following code snippet. (TestString.dart) void main() { int a = 10, b = 20, c = 5; c = c * c * c; print("$a + $b = ${a+b}"); print("$a%$b = ${a%b}"); // Add a break point here print("$a*$b = ${a*b}"); print("$a/$b = ${a/b}"); print(c); } To add a breakpoint, click on the left margin to. In the figure given below, line number 7 has a break point. Run the program in debug mode. In the project explorer right click on the dart program in our case TestString.dart. Once the program runs in debug mode, you will get the Debugger window as shown in the following screenshot. The variables tab shows the values of variables in the current context. You can add watchers for specific variables and listen to that values changes using watches window. Step Into (F7) arrow icon on debug menu helps to Executes code one statement at a time. If main methods call a subroutine, then this will go into the subroutine code also. Step over (F8): It is similar to Step Into. The difference in use occurs when the current statement contains a call to a subroutine. If the main method calls a subroutine, step over will not drill into the subroutine. it will skip the subroutine. Step Out (Shift+F8): Executes the remaining lines of a function in which the current execution point lies. The next statement displayed is the statement following the subroutine call. After running in debug mode, the program gives the following output − 10 + 20 = 30 10 % 20 = 10 10 * 20 = 200 10 / 20 = 0.5 125 44 Lectures 4.5 hours Sriyank Siddhartha 34 Lectures 4 hours Sriyank Siddhartha 69 Lectures 4 hours Frahaan Hussain 117 Lectures 10 hours Frahaan Hussain 22 Lectures 1.5 hours Pranjal Srivastava 34 Lectures 3 hours Pranjal Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2823, "s": 2525, "text": "Every now and then, developers commit mistakes while coding. A mistake in a program is referred to as a bug. The process of finding and fixing bugs is called debugging and is a normal part of the development process. This section covers tools and techniques that can help you with debugging tasks." }, { "code": null, "e": 3175, "s": 2823, "text": "The WebStorm editor enables breakpoints and step-by-step debugging. The program will break at the point where the breakpoint is attached. This functionality is like what you might expect from Java or C# application development. You can watch variables, browse the stack, step over and step into method and function calls, all from the WebStorm Editor." }, { "code": null, "e": 3230, "s": 3175, "text": "Consider the following code snippet. (TestString.dart)" }, { "code": null, "e": 3460, "s": 3230, "text": "void main() { \n int a = 10, b = 20, c = 5; \n c = c * c * c; \n \n print(\"$a + $b = ${a+b}\"); \n print(\"$a%$b = ${a%b}\"); // Add a break point here \n print(\"$a*$b = ${a*b}\"); \n print(\"$a/$b = ${a/b}\"); \n print(c); \n}" }, { "code": null, "e": 3570, "s": 3460, "text": "To add a breakpoint, click on the left margin to. In the figure given below, line number 7 has a break point." }, { "code": null, "e": 3686, "s": 3570, "text": "Run the program in debug mode. In the project explorer right click on the dart program in our case TestString.dart." }, { "code": null, "e": 3966, "s": 3686, "text": "Once the program runs in debug mode, you will get the Debugger window as shown in the following screenshot. The variables tab shows the values of variables in the current context. You can add watchers for specific variables and listen to that values changes using watches window." }, { "code": null, "e": 4138, "s": 3966, "text": "Step Into (F7) arrow icon on debug menu helps to Executes code one statement at a time. If main methods call a subroutine, then this will go into the subroutine code also." }, { "code": null, "e": 4385, "s": 4138, "text": "Step over (F8): It is similar to Step Into. The difference in use occurs when the current statement contains a call to a subroutine. If the main method calls a subroutine, step over will not drill into the subroutine. it will skip the subroutine." }, { "code": null, "e": 4569, "s": 4385, "text": "Step Out (Shift+F8): Executes the remaining lines of a function in which the current execution point lies. The next statement displayed is the statement following the subroutine call." }, { "code": null, "e": 4639, "s": 4569, "text": "After running in debug mode, the program gives the following output −" }, { "code": null, "e": 4702, "s": 4639, "text": "10 + 20 = 30 \n10 % 20 = 10 \n10 * 20 = 200 \n10 / 20 = 0.5 \n125\n" }, { "code": null, "e": 4737, "s": 4702, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4757, "s": 4737, "text": " Sriyank Siddhartha" }, { "code": null, "e": 4790, "s": 4757, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 4810, "s": 4790, "text": " Sriyank Siddhartha" }, { "code": null, "e": 4843, "s": 4810, "text": "\n 69 Lectures \n 4 hours \n" }, { "code": null, "e": 4860, "s": 4843, "text": " Frahaan Hussain" }, { "code": null, "e": 4895, "s": 4860, "text": "\n 117 Lectures \n 10 hours \n" }, { "code": null, "e": 4912, "s": 4895, "text": " Frahaan Hussain" }, { "code": null, "e": 4947, "s": 4912, "text": "\n 22 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4967, "s": 4947, "text": " Pranjal Srivastava" }, { "code": null, "e": 5000, "s": 4967, "text": "\n 34 Lectures \n 3 hours \n" }, { "code": null, "e": 5020, "s": 5000, "text": " Pranjal Srivastava" }, { "code": null, "e": 5027, "s": 5020, "text": " Print" }, { "code": null, "e": 5038, "s": 5027, "text": " Add Notes" } ]
All possible permutations of N lists in Python
If we have two lists and we need to combine each element of the first element with each element of the second list, then we have the below approaches. In this straight forward approach we create a list of lists containing the permutation of elements from each list. we design a for loop within another for loop. The inner for loop refers to the second list and Outer follow refers to the first list. Live Demo A = [5,8] B = [10,15,20] print ("The given lists : ", A, B) permutations = [[m, n] for m in A for n in B ] Running the above code gives us the following result: The given lists : [5, 8] [10, 15, 20] permutations of the given values are : [[5, 10], [5, 15], [5, 20], [8, 10], [8, 15], [8, 20]] The itertools module has a iterator named product. It does the same thing what the above nested for loop does. Creates nested for loops internally to give the required product. Live Demo import itertools A = [5,8] B = [10,15,20] print ("The given lists : ", A, B) result = list(itertools.product(A,B)) print ("permutations of the given lists are : " + str(result)) Running the above code gives us the following result: The given lists : [5, 8] [10, 15, 20] permutations of the given values are : [(5, 10), (5, 15), (5, 20), (8, 10), (8, 15), (8, 20)]
[ { "code": null, "e": 1213, "s": 1062, "text": "If we have two lists and we need to combine each element of the first element with each element of the second list, then we have the below approaches." }, { "code": null, "e": 1462, "s": 1213, "text": "In this straight forward approach we create a list of lists containing the permutation of elements from each list. we design a for loop within another for loop. The inner for loop refers to the second list and Outer follow refers to the first list." }, { "code": null, "e": 1473, "s": 1462, "text": " Live Demo" }, { "code": null, "e": 1581, "s": 1473, "text": "A = [5,8]\nB = [10,15,20]\n\nprint (\"The given lists : \", A, B)\npermutations = [[m, n] for m in A for n in B ]" }, { "code": null, "e": 1635, "s": 1581, "text": "Running the above code gives us the following result:" }, { "code": null, "e": 1767, "s": 1635, "text": "The given lists : [5, 8] [10, 15, 20]\npermutations of the given values are : [[5, 10], [5, 15], [5, 20], [8, 10], [8, 15], [8, 20]]" }, { "code": null, "e": 1944, "s": 1767, "text": "The itertools module has a iterator named product. It does the same thing what the above nested for loop does. Creates nested for loops internally to give the required product." }, { "code": null, "e": 1955, "s": 1944, "text": " Live Demo" }, { "code": null, "e": 2135, "s": 1955, "text": "import itertools\n\nA = [5,8]\nB = [10,15,20]\n\nprint (\"The given lists : \", A, B)\nresult = list(itertools.product(A,B))\nprint (\"permutations of the given lists are : \" + str(result))" }, { "code": null, "e": 2189, "s": 2135, "text": "Running the above code gives us the following result:" }, { "code": null, "e": 2321, "s": 2189, "text": "The given lists : [5, 8] [10, 15, 20]\npermutations of the given values are : [(5, 10), (5, 15), (5, 20), (8, 10), (8, 15), (8, 20)]" } ]
Move rows from one table to another in MySQL?
You can move rows from one table to another with the help of INSERT INTO SELECT statement. The syntax is as follows − insert into yourDestinationTableName select *from yourOriginalTable where someCondition To understand the above syntax. let us create a table. The following is the query to create a table − mysql> create table StudentTable −> ( −> Id int, −> Name varchar(100) −> ); Query OK, 0 rows affected (0.65 sec) Now, I will create second table. The query is as follows − mysql> create table Employee −> ( −> EmployeeId int −> , −> EmployeeName varchar(100) −> ); Query OK, 0 rows affected (0.54 sec) Inserting some records in the table Employee. The query to insert records is as follows − mysql> insert into Employee values(1,'Carol'); Query OK, 1 row affected (0.18 sec) mysql> insert into Employee values(2,'John'); Query OK, 1 row affected (0.16 sec) mysql> insert into Employee values(3,'Johnson'); Query OK, 1 row affected (0.11 sec) Now you can display all records from Employee table with the help of SELECT statement. The query is as follows: mysql> select *from Employee; The following is the output − +------------+--------------+ | EmployeeId | EmployeeName | +------------+--------------+ | 1 | Carol | | 2 | John | | 3 | Johnson | +------------+--------------+ 3 rows in set (0.00 sec) Implement the syntax we discussed in the beginning to move row in another table. The below query moves row from Employee table to StudentTable − mysql> insert into StudentTable select *from Employee where EmployeeId = 3 and EmployeeName = 'Johnson'; Query OK, 1 row affected (0.17 sec) Records: 1 Duplicates: 0 Warnings: 0 Now, you can check whether the row is present in second table ‘StudentTable’ or not. The query is as follows − mysql> select *from StudentTable; The following is the output − +------+---------+ | Id | Name | +------+---------+ | 3 | Johnson | +------+---------+ 1 row in set (0.00 sec) Look at the above sample output, we have moved row from one table to another. To move all the rows, you just need to remove the “where” condition. The query is as follows − mysql> insert into StudentTable select *from Employee; Query OK, 3 rows affected (0.15 sec) Records: 3 Duplicates: 0 Warnings: 0 The query displays all the updated records in the StudentTable − mysql> select *from StudentTable; The following is the output − +------+---------+ | Id | Name | +------+---------+ | 1 | Carol | | 2 | John | | 3 | Johnson | +------+---------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1153, "s": 1062, "text": "You can move rows from one table to another with the help of INSERT INTO SELECT statement." }, { "code": null, "e": 1180, "s": 1153, "text": "The syntax is as follows −" }, { "code": null, "e": 1268, "s": 1180, "text": "insert into yourDestinationTableName select *from yourOriginalTable where someCondition" }, { "code": null, "e": 1370, "s": 1268, "text": "To understand the above syntax. let us create a table. The following is the query to create a table −" }, { "code": null, "e": 1501, "s": 1370, "text": "mysql> create table StudentTable\n −> (\n −> Id int,\n −> Name varchar(100)\n −> );\nQuery OK, 0 rows affected (0.65 sec)" }, { "code": null, "e": 1560, "s": 1501, "text": "Now, I will create second table. The query is as follows −" }, { "code": null, "e": 1713, "s": 1560, "text": "mysql> create table Employee\n −> (\n −> EmployeeId int\n −> ,\n −> EmployeeName varchar(100)\n −> );\nQuery OK, 0 rows affected (0.54 sec)" }, { "code": null, "e": 1803, "s": 1713, "text": "Inserting some records in the table Employee. The query to insert records is as follows −" }, { "code": null, "e": 2055, "s": 1803, "text": "mysql> insert into Employee values(1,'Carol');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into Employee values(2,'John');\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into Employee values(3,'Johnson');\nQuery OK, 1 row affected (0.11 sec)" }, { "code": null, "e": 2167, "s": 2055, "text": "Now you can display all records from Employee table with the help of SELECT statement. The query is as follows:" }, { "code": null, "e": 2197, "s": 2167, "text": "mysql> select *from Employee;" }, { "code": null, "e": 2227, "s": 2197, "text": "The following is the output −" }, { "code": null, "e": 2462, "s": 2227, "text": "+------------+--------------+\n| EmployeeId | EmployeeName |\n+------------+--------------+\n| 1 | Carol |\n| 2 | John |\n| 3 | Johnson |\n+------------+--------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2607, "s": 2462, "text": "Implement the syntax we discussed in the beginning to move row in another table. The below query moves row from Employee table to StudentTable −" }, { "code": null, "e": 2785, "s": 2607, "text": "mysql> insert into StudentTable select *from Employee where EmployeeId = 3 and EmployeeName = 'Johnson';\nQuery OK, 1 row affected (0.17 sec)\nRecords: 1 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 2896, "s": 2785, "text": "Now, you can check whether the row is present in second table ‘StudentTable’ or not. The query is as follows −" }, { "code": null, "e": 2930, "s": 2896, "text": "mysql> select *from StudentTable;" }, { "code": null, "e": 2960, "s": 2930, "text": "The following is the output −" }, { "code": null, "e": 3079, "s": 2960, "text": "+------+---------+\n| Id | Name |\n+------+---------+\n| 3 | Johnson |\n+------+---------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 3252, "s": 3079, "text": "Look at the above sample output, we have moved row from one table to another. To move all the rows, you just need to remove the “where” condition. The query is as follows −" }, { "code": null, "e": 3381, "s": 3252, "text": "mysql> insert into StudentTable select *from Employee;\nQuery OK, 3 rows affected (0.15 sec)\nRecords: 3 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 3446, "s": 3381, "text": "The query displays all the updated records in the StudentTable −" }, { "code": null, "e": 3480, "s": 3446, "text": "mysql> select *from StudentTable;" }, { "code": null, "e": 3510, "s": 3480, "text": "The following is the output −" }, { "code": null, "e": 3668, "s": 3510, "text": "+------+---------+\n| Id | Name |\n+------+---------+\n| 1 | Carol |\n| 2 | John |\n| 3 | Johnson |\n+------+---------+\n3 rows in set (0.00 sec)" } ]
Python | Named Entity Recognition (NER) using spaCy - GeeksforGeeks
18 Jun, 2019 Named Entity Recognition (NER) is a standard NLP problem which involves spotting named entities (people, places, organizations etc.) from a chunk of text, and classifying them into a predefined set of categories. Some of the practical applications of NER include: Scanning news articles for the people, organizations and locations reported. Providing concise features for search optimization: instead of searching the entire content, one may simply search for the major entities involved. Quickly retrieving geographical locations talked about in Twitter posts. NER with spaCyspaCy is regarded as the fastest NLP framework in Python, with single optimized functions for each of the NLP tasks it implements. Being easy to learn and use, one can easily perform simple tasks using a few lines of code. Installation : pip install spacy python -m spacy download en_core_web_sm Code for NER using spaCy. import spacy nlp = spacy.load('en_core_web_sm') sentence = "Apple is looking at buying U.K. startup for $1 billion" doc = nlp(sentence) for ent in doc.ents: print(ent.text, ent.start_char, ent.end_char, ent.label_) Output Apple 0 5 ORG U.K. 27 31 GPE $1 billion 44 54 MONEY In the output, the first column specifies the entity, the next two columns the start and end characters within the sentence/document, and the final column specifies the category. Further, it is interesting to note that spaCy’s NER model uses capitalization as one of the cues to identify named entities. The same example, when tested with a slight modification, produces a different result. import spacy nlp = spacy.load('en_core_web_sm') sentence = "apple is looking at buying U.K. startup for $1 billion" doc = nlp(sentence) for ent in doc.ents: print(ent.text, ent.start_char, ent.end_char, ent.label_) Output U.K. 27 31 GPE $1 billion 44 54 MONEY The word “apple” no longer shows as a named entity. Therefore, it is important to use NER before the usual normalization or stemming preprocessing steps. One can also use their own examples to train and modify spaCy’s in-built NER model. There are several ways to do this. The following code shows a simple way to feed in new instances and update the model. import spacyfrom spacy.gold import GoldParsefrom spacy.language import EntityRecognizer nlp = spacy.load('en', entity = False, parser = False) doc_list = []doc = nlp('Llamas make great pets.')doc_list.append(doc)gold_list = []gold_list.append(GoldParse(doc, [u'ANIMAL', u'O', u'O', u'O'])) ner = EntityRecognizer(nlp.vocab, entity_types = ['ANIMAL'])ner.update(doc_list, gold_list) By adding a sufficient number of examples in the doc_list, one can produce a customized NER using spaCy. spaCy supports the following entity types:PERSON, NORP (nationalities, religious and political groups), FAC (buildings, airports etc.), ORG (organizations), GPE (countries, cities etc.), LOC (mountain ranges, water bodies etc.), PRODUCT (products), EVENT (event names), WORK_OF_ART (books, song titles), LAW (legal document titles), LANGUAGE (named languages), DATE, TIME, PERCENT, MONEY, QUANTITY, ORDINAL and CARDINAL. References https://spacy.io/ Machine Learning Python Python Programs Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments ML | Linear Regression Python | Decision tree implementation Decision Tree Introduction with example ML | Underfitting and Overfitting Support Vector Machine Algorithm Adding new column to existing DataFrame in Pandas Read JSON file using Python Python map() function Python Dictionary Taking input in Python
[ { "code": null, "e": 24352, "s": 24324, "text": "\n18 Jun, 2019" }, { "code": null, "e": 24616, "s": 24352, "text": "Named Entity Recognition (NER) is a standard NLP problem which involves spotting named entities (people, places, organizations etc.) from a chunk of text, and classifying them into a predefined set of categories. Some of the practical applications of NER include:" }, { "code": null, "e": 24693, "s": 24616, "text": "Scanning news articles for the people, organizations and locations reported." }, { "code": null, "e": 24841, "s": 24693, "text": "Providing concise features for search optimization: instead of searching the entire content, one may simply search for the major entities involved." }, { "code": null, "e": 24914, "s": 24841, "text": "Quickly retrieving geographical locations talked about in Twitter posts." }, { "code": null, "e": 25151, "s": 24914, "text": "NER with spaCyspaCy is regarded as the fastest NLP framework in Python, with single optimized functions for each of the NLP tasks it implements. Being easy to learn and use, one can easily perform simple tasks using a few lines of code." }, { "code": null, "e": 25166, "s": 25151, "text": "Installation :" }, { "code": null, "e": 25225, "s": 25166, "text": "pip install spacy\npython -m spacy download en_core_web_sm\n" }, { "code": null, "e": 25251, "s": 25225, "text": "Code for NER using spaCy." }, { "code": "import spacy nlp = spacy.load('en_core_web_sm') sentence = \"Apple is looking at buying U.K. startup for $1 billion\" doc = nlp(sentence) for ent in doc.ents: print(ent.text, ent.start_char, ent.end_char, ent.label_)", "e": 25473, "s": 25251, "text": null }, { "code": null, "e": 25480, "s": 25473, "text": "Output" }, { "code": null, "e": 25533, "s": 25480, "text": "Apple 0 5 ORG\nU.K. 27 31 GPE\n$1 billion 44 54 MONEY\n" }, { "code": null, "e": 25712, "s": 25533, "text": "In the output, the first column specifies the entity, the next two columns the start and end characters within the sentence/document, and the final column specifies the category." }, { "code": null, "e": 25924, "s": 25712, "text": "Further, it is interesting to note that spaCy’s NER model uses capitalization as one of the cues to identify named entities. The same example, when tested with a slight modification, produces a different result." }, { "code": "import spacy nlp = spacy.load('en_core_web_sm') sentence = \"apple is looking at buying U.K. startup for $1 billion\" doc = nlp(sentence) for ent in doc.ents: print(ent.text, ent.start_char, ent.end_char, ent.label_)", "e": 26146, "s": 25924, "text": null }, { "code": null, "e": 26153, "s": 26146, "text": "Output" }, { "code": null, "e": 26192, "s": 26153, "text": "U.K. 27 31 GPE\n$1 billion 44 54 MONEY\n" }, { "code": null, "e": 26346, "s": 26192, "text": "The word “apple” no longer shows as a named entity. Therefore, it is important to use NER before the usual normalization or stemming preprocessing steps." }, { "code": null, "e": 26550, "s": 26346, "text": "One can also use their own examples to train and modify spaCy’s in-built NER model. There are several ways to do this. The following code shows a simple way to feed in new instances and update the model." }, { "code": "import spacyfrom spacy.gold import GoldParsefrom spacy.language import EntityRecognizer nlp = spacy.load('en', entity = False, parser = False) doc_list = []doc = nlp('Llamas make great pets.')doc_list.append(doc)gold_list = []gold_list.append(GoldParse(doc, [u'ANIMAL', u'O', u'O', u'O'])) ner = EntityRecognizer(nlp.vocab, entity_types = ['ANIMAL'])ner.update(doc_list, gold_list)", "e": 26935, "s": 26550, "text": null }, { "code": null, "e": 27040, "s": 26935, "text": "By adding a sufficient number of examples in the doc_list, one can produce a customized NER using spaCy." }, { "code": null, "e": 27461, "s": 27040, "text": "spaCy supports the following entity types:PERSON, NORP (nationalities, religious and political groups), FAC (buildings, airports etc.), ORG (organizations), GPE (countries, cities etc.), LOC (mountain ranges, water bodies etc.), PRODUCT (products), EVENT (event names), WORK_OF_ART (books, song titles), LAW (legal document titles), LANGUAGE (named languages), DATE, TIME, PERCENT, MONEY, QUANTITY, ORDINAL and CARDINAL." }, { "code": null, "e": 27472, "s": 27461, "text": "References" }, { "code": null, "e": 27490, "s": 27472, "text": "https://spacy.io/" }, { "code": null, "e": 27507, "s": 27490, "text": "Machine Learning" }, { "code": null, "e": 27514, "s": 27507, "text": "Python" }, { "code": null, "e": 27530, "s": 27514, "text": "Python Programs" }, { "code": null, "e": 27547, "s": 27530, "text": "Machine Learning" }, { "code": null, "e": 27645, "s": 27547, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27654, "s": 27645, "text": "Comments" }, { "code": null, "e": 27667, "s": 27654, "text": "Old Comments" }, { "code": null, "e": 27690, "s": 27667, "text": "ML | Linear Regression" }, { "code": null, "e": 27728, "s": 27690, "text": "Python | Decision tree implementation" }, { "code": null, "e": 27768, "s": 27728, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 27802, "s": 27768, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 27835, "s": 27802, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 27885, "s": 27835, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 27913, "s": 27885, "text": "Read JSON file using Python" }, { "code": null, "e": 27935, "s": 27913, "text": "Python map() function" }, { "code": null, "e": 27953, "s": 27935, "text": "Python Dictionary" } ]
Sentiment analysis using RNNs(LSTM) | by Manish Chablani | Towards Data Science
Here we use the example of reviews to predict sentiment (even though it can be applied more generically to other domains for example sentiment analysis for tweets, comments, customer feedback, etc). Whole idea here is that movie reviews are made of sequence of words and order of words encode lot of information that is useful to predict sentiment. Step 1 is to map words to word embeddings (see post 1 and 2 for more context on word embeddings). Step 2 is the RNN that receives a sequence of vectors as input and considers the order of the vectors to generate prediction. The architecture for this network is shown below. Here, we’ll pass in words to an embedding layer. You can actually train up an embedding with word2vec and use it here. But it’s good enough to just have an embedding layer and let the network learn the embedding table on it’s own. From the embedding layer, the new representations will be passed to LSTM cells. These will add recurrent connections to the network so we can include information about the sequence of words in the data. Finally, the LSTM cells will go to a sigmoid output layer here. We’re using the sigmoid because we’re trying to predict if this text has positive or negative sentiment. The output layer will just be a single unit then, with a sigmoid activation function. We don’t care about the sigmoid outputs except for the very last one, we can ignore the rest. We’ll calculate the cost from the output of the last step and the training label. Have fixed length reviews encoded as integers and then converted to embedding vectors passed to LSTM layers in recurrent manner and pick the last prediction as output sentiment. One thing in my experiments I could not explain is when I encode the words to integers if I randomly assign unique integers to words the best accuracy I get is 50–55% (basically the model is not doing much better than random guessing). However if the words are encoded such that highest frequency words get the lowest number then the model accuracy is 80% in 3–5 epochs. My guess is this is necessary to train the embedding layer but cannot find an explanation on why anywhere. https://github.com/mchablani/deep-learning/blob/master/sentiment-rnn/Sentiment_RNN.ipynb Take all the words in reviews and encode them with integers. Now each review is an ordered array of integers. Make each review fixed size (say 200), so shorter reviews get padded with 0’s in front and longer reviews get truncated to 200. Since we are padding with 0’s the corpus of words to int mapping starts with 1. Labels are are encoded as 1s and 0s for ‘positive’ and ‘negative’. lstm_size = 256lstm_layers = 2batch_size = 500learning_rate = 0.001embed_size = 300n_words = len(vocab_to_int) + 1 # Add 1 for 0 added to vocab# Create the graph objecttf.reset_default_graph()with tf.name_scope('inputs'): inputs_ = tf.placeholder(tf.int32, [None, None], name="inputs") labels_ = tf.placeholder(tf.int32, [None, None], name="labels") keep_prob = tf.placeholder(tf.float32, name="keep_prob")# Sizeof embedding vectors (number of units in the embedding layer)with tf.name_scope("Embeddings"): embedding = tf.Variable(tf.random_uniform((n_words, embed_size), -1, 1)) embed = tf.nn.embedding_lookup(embedding, inputs_)def lstm_cell(): # Your basic LSTM cell lstm = tf.contrib.rnn.BasicLSTMCell(lstm_size, reuse=tf.get_variable_scope().reuse) # Add dropout to the cell return tf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=keep_prob)with tf.name_scope("RNN_layers"): # Stack up multiple LSTM layers, for deep learning cell = tf.contrib.rnn.MultiRNNCell([lstm_cell() for _ in range(lstm_layers)]) # Getting an initial state of all zeros initial_state = cell.zero_state(batch_size, tf.float32)with tf.name_scope("RNN_forward"): outputs, final_state = tf.nn.dynamic_rnn(cell, embed, initial_state=initial_state)with tf.name_scope('predictions'): predictions = tf.contrib.layers.fully_connected(outputs[:, -1], 1, activation_fn=tf.sigmoid) tf.summary.histogram('predictions', predictions)with tf.name_scope('cost'): cost = tf.losses.mean_squared_error(labels_, predictions) tf.summary.scalar('cost', cost)with tf.name_scope('train'): optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost) def get_batches(x, y, batch_size=100): n_batches = len(x)//batch_size x, y = x[:n_batches*batch_size], y[:n_batches*batch_size] for ii in range(0, len(x), batch_size): yield x[ii:ii+batch_size], y[ii:ii+batch_size]epochs = 10# with graph.as_default():saver = tf.train.Saver()with tf.Session() as sess: sess.run(tf.global_variables_initializer()) train_writer = tf.summary.FileWriter('./logs/tb/train', sess.graph) test_writer = tf.summary.FileWriter('./logs/tb/test', sess.graph) iteration = 1 for e in range(epochs): state = sess.run(initial_state) for ii, (x, y) in enumerate(get_batches(train_x, train_y, batch_size), 1): feed = {inputs_: x, labels_: y[:, None], keep_prob: 0.5, initial_state: state} summary, loss, state, _ = sess.run([merged, cost, final_state, optimizer], feed_dict=feed)# loss, state, _ = sess.run([cost, final_state, optimizer], feed_dict=feed)train_writer.add_summary(summary, iteration) if iteration%5==0: print("Epoch: {}/{}".format(e, epochs), "Iteration: {}".format(iteration), "Train loss: {:.3f}".format(loss))if iteration%25==0: val_acc = [] val_state = sess.run(cell.zero_state(batch_size, tf.float32)) for x, y in get_batches(val_x, val_y, batch_size): feed = {inputs_: x, labels_: y[:, None], keep_prob: 1, initial_state: val_state}# batch_acc, val_state = sess.run([accuracy, final_state], feed_dict=feed) summary, batch_acc, val_state = sess.run([merged, accuracy, final_state], feed_dict=feed) val_acc.append(batch_acc) print("Val acc: {:.3f}".format(np.mean(val_acc))) iteration +=1 test_writer.add_summary(summary, iteration) saver.save(sess, "checkpoints/sentiment_manish.ckpt") saver.save(sess, "checkpoints/sentiment_manish.ckpt") Credits: From lecture notes: https://classroom.udacity.com/nanodegrees/nd101/syllabus
[ { "code": null, "e": 745, "s": 172, "text": "Here we use the example of reviews to predict sentiment (even though it can be applied more generically to other domains for example sentiment analysis for tweets, comments, customer feedback, etc). Whole idea here is that movie reviews are made of sequence of words and order of words encode lot of information that is useful to predict sentiment. Step 1 is to map words to word embeddings (see post 1 and 2 for more context on word embeddings). Step 2 is the RNN that receives a sequence of vectors as input and considers the order of the vectors to generate prediction." }, { "code": null, "e": 795, "s": 745, "text": "The architecture for this network is shown below." }, { "code": null, "e": 1026, "s": 795, "text": "Here, we’ll pass in words to an embedding layer. You can actually train up an embedding with word2vec and use it here. But it’s good enough to just have an embedding layer and let the network learn the embedding table on it’s own." }, { "code": null, "e": 1484, "s": 1026, "text": "From the embedding layer, the new representations will be passed to LSTM cells. These will add recurrent connections to the network so we can include information about the sequence of words in the data. Finally, the LSTM cells will go to a sigmoid output layer here. We’re using the sigmoid because we’re trying to predict if this text has positive or negative sentiment. The output layer will just be a single unit then, with a sigmoid activation function." }, { "code": null, "e": 1660, "s": 1484, "text": "We don’t care about the sigmoid outputs except for the very last one, we can ignore the rest. We’ll calculate the cost from the output of the last step and the training label." }, { "code": null, "e": 1838, "s": 1660, "text": "Have fixed length reviews encoded as integers and then converted to embedding vectors passed to LSTM layers in recurrent manner and pick the last prediction as output sentiment." }, { "code": null, "e": 2316, "s": 1838, "text": "One thing in my experiments I could not explain is when I encode the words to integers if I randomly assign unique integers to words the best accuracy I get is 50–55% (basically the model is not doing much better than random guessing). However if the words are encoded such that highest frequency words get the lowest number then the model accuracy is 80% in 3–5 epochs. My guess is this is necessary to train the embedding layer but cannot find an explanation on why anywhere." }, { "code": null, "e": 2405, "s": 2316, "text": "https://github.com/mchablani/deep-learning/blob/master/sentiment-rnn/Sentiment_RNN.ipynb" }, { "code": null, "e": 2790, "s": 2405, "text": "Take all the words in reviews and encode them with integers. Now each review is an ordered array of integers. Make each review fixed size (say 200), so shorter reviews get padded with 0’s in front and longer reviews get truncated to 200. Since we are padding with 0’s the corpus of words to int mapping starts with 1. Labels are are encoded as 1s and 0s for ‘positive’ and ‘negative’." }, { "code": null, "e": 4463, "s": 2790, "text": "lstm_size = 256lstm_layers = 2batch_size = 500learning_rate = 0.001embed_size = 300n_words = len(vocab_to_int) + 1 # Add 1 for 0 added to vocab# Create the graph objecttf.reset_default_graph()with tf.name_scope('inputs'): inputs_ = tf.placeholder(tf.int32, [None, None], name=\"inputs\") labels_ = tf.placeholder(tf.int32, [None, None], name=\"labels\") keep_prob = tf.placeholder(tf.float32, name=\"keep_prob\")# Sizeof embedding vectors (number of units in the embedding layer)with tf.name_scope(\"Embeddings\"): embedding = tf.Variable(tf.random_uniform((n_words, embed_size), -1, 1)) embed = tf.nn.embedding_lookup(embedding, inputs_)def lstm_cell(): # Your basic LSTM cell lstm = tf.contrib.rnn.BasicLSTMCell(lstm_size, reuse=tf.get_variable_scope().reuse) # Add dropout to the cell return tf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=keep_prob)with tf.name_scope(\"RNN_layers\"): # Stack up multiple LSTM layers, for deep learning cell = tf.contrib.rnn.MultiRNNCell([lstm_cell() for _ in range(lstm_layers)]) # Getting an initial state of all zeros initial_state = cell.zero_state(batch_size, tf.float32)with tf.name_scope(\"RNN_forward\"): outputs, final_state = tf.nn.dynamic_rnn(cell, embed, initial_state=initial_state)with tf.name_scope('predictions'): predictions = tf.contrib.layers.fully_connected(outputs[:, -1], 1, activation_fn=tf.sigmoid) tf.summary.histogram('predictions', predictions)with tf.name_scope('cost'): cost = tf.losses.mean_squared_error(labels_, predictions) tf.summary.scalar('cost', cost)with tf.name_scope('train'): optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost)" }, { "code": null, "e": 6616, "s": 4463, "text": "def get_batches(x, y, batch_size=100): n_batches = len(x)//batch_size x, y = x[:n_batches*batch_size], y[:n_batches*batch_size] for ii in range(0, len(x), batch_size): yield x[ii:ii+batch_size], y[ii:ii+batch_size]epochs = 10# with graph.as_default():saver = tf.train.Saver()with tf.Session() as sess: sess.run(tf.global_variables_initializer()) train_writer = tf.summary.FileWriter('./logs/tb/train', sess.graph) test_writer = tf.summary.FileWriter('./logs/tb/test', sess.graph) iteration = 1 for e in range(epochs): state = sess.run(initial_state) for ii, (x, y) in enumerate(get_batches(train_x, train_y, batch_size), 1): feed = {inputs_: x, labels_: y[:, None], keep_prob: 0.5, initial_state: state} summary, loss, state, _ = sess.run([merged, cost, final_state, optimizer], feed_dict=feed)# loss, state, _ = sess.run([cost, final_state, optimizer], feed_dict=feed)train_writer.add_summary(summary, iteration) if iteration%5==0: print(\"Epoch: {}/{}\".format(e, epochs), \"Iteration: {}\".format(iteration), \"Train loss: {:.3f}\".format(loss))if iteration%25==0: val_acc = [] val_state = sess.run(cell.zero_state(batch_size, tf.float32)) for x, y in get_batches(val_x, val_y, batch_size): feed = {inputs_: x, labels_: y[:, None], keep_prob: 1, initial_state: val_state}# batch_acc, val_state = sess.run([accuracy, final_state], feed_dict=feed) summary, batch_acc, val_state = sess.run([merged, accuracy, final_state], feed_dict=feed) val_acc.append(batch_acc) print(\"Val acc: {:.3f}\".format(np.mean(val_acc))) iteration +=1 test_writer.add_summary(summary, iteration) saver.save(sess, \"checkpoints/sentiment_manish.ckpt\") saver.save(sess, \"checkpoints/sentiment_manish.ckpt\")" } ]
Selects all <p> elements where the parent is a <div> element with CSS
Use the element > element selector to select an element with a parent element. You can try to run the following code to select all <p> elements where the parent is a <div> element, Live Demo <!DOCTYPE html> <html> <head> <style> div > p { color: white; background-color: blue; } </style> </head> <body> <h1>Demo Website</h1> <h2>Fruits</h2> <p>Fruits are good for health.</p> <div> <p>This is demo text.</p> </div> </body> </html>
[ { "code": null, "e": 1141, "s": 1062, "text": "Use the element > element selector to select an element with a parent element." }, { "code": null, "e": 1243, "s": 1141, "text": "You can try to run the following code to select all <p> elements where the parent is a <div> element," }, { "code": null, "e": 1253, "s": 1243, "text": "Live Demo" }, { "code": null, "e": 1599, "s": 1253, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n div > p {\n color: white;\n background-color: blue;\n }\n </style>\n </head>\n\n <body>\n <h1>Demo Website</h1>\n <h2>Fruits</h2>\n <p>Fruits are good for health.</p>\n <div>\n <p>This is demo text.</p>\n </div>\n </body>\n</html>" } ]
12 Ways to Apply a Function to Each Row in Pandas DataFrame | Towards Data Science
Applying a function to all rows in a Pandas DataFrame is one of the most common operations during data wrangling. Pandas DataFrame apply function is the most obvious choice for doing it. It takes a function as an argument and applies it along an axis of the DataFrame. However, it is not always the best choice. In this article, you will measure the performance of 12 alternatives. With a companion Code Lab, you can try it all in your browser. No need to install anything on your machine. Recently, I was analyzing user behavior data for an e-commerce app. Depending on the number of times a user did text and voice searches, I assigned each user to one of four cohorts: No Search: Users who did no search at all Text Only: Users who did text searches only Voice Only: Users who did voice searches only Both: Users who did both text and voice search It was a huge data set with 100k to a million users depending upon the chosen time slice. Computing it with Pandas apply function was excruciatingly slow, so I evaluated alternatives. This article is the distilled lessons from that. I can’t share that dataset. So I am picking another similar problem to show the solutions: the Eisenhower method. Based on a task’s importance and urgency, the Eisenhower Method assigns it into one of 4 bins. Each bin has an associated action: Important and Urgent: Do right away Important but not Urgent: Schedule for later Not Important but Urgent: Delegate to someone else Neither Important nor Urgent: Delete time wasters. We will use the boolean matrix shown in the adjacent figure. Importance and urgency booleans make the binary integer value for each action: DO(3), SCHEDULE(2), DELEGATE(1), DELETE(0). We will profile the performance of mapping tasks to one of the actions. We will measure which of the 12 alternatives take the least amount of time. And we will plot the performance for up to a million tasks. It is a good time to open the companion notebook at Google Colab or Kaggle. If you want to see the code in action, you can execute the cells in the Code Lab as you read along. Go ahead, execute all the cells in the Setup section. Faker is a handy library to generate data. In the Code Lab, it is used for generating a DataFrame with a million tasks. Each task is a row in the DataFrame. It consists of task_name (str), due_date (datetime.date), and priority (str). Priority can be one of the three values: LOW, MEDIUM, HIGH. We will minimize the storage size to eliminate its effect on any of the alternatives. The DataFrame with ~2 million rows is taking 48MB: >>> test_data_set.info()<class 'pandas.core.frame.DataFrame'>RangeIndex: 2097153 entries, 0 to 2097152Data columns (total 3 columns): # Column Dtype --- ------ ----- 0 task_name object 1 due_date object 2 priority objectdtypes: object(3)memory usage: 48.0+ MB Instead of str, priority can be stored as Pandas categorical type: priority_dtype = pd.api.types.CategoricalDtype( categories=['LOW', 'MEDIUM', 'HIGH'], ordered=True)test_data_set['priority'] = test_data_set['priority'].astype(priority_dtype) Let’s check out the DataFrame size now: >>> test_data_set.info()<class 'pandas.core.frame.DataFrame'>RangeIndex: 2097153 entries, 0 to 2097152Data columns (total 3 columns): # Column Dtype --- ------ ----- 0 task_name object 1 due_date object 2 priority categorydtypes: category(1), object(2)memory usage: 34.0+MB Size is reduced to 34MB. Given importance and urgency, eisenhower_action computes an integer value between 0 and 3. def eisenhower_action(is_important: bool, is_urgent: bool) -> int: return 2 * is_important + is_urgent For this exercise, we will assume that a task with HIGH priority is important. If the due date is in the next two days, then the task is urgent. The Eisenhower Action for a task (i.e. a row in the DataFrame) is computed by using the due_date and priority columns: >>> cutoff_date = datetime.date.today() + datetime.timedelta(days=2)>>> eisenhower_action( test_data_set.loc[0].priority == 'HIGH', test_data_set.loc[0].due_date <= cutoff_date)2 The integer 2 means that the needed action is to SCHEDULE. In the rest of the article, we will evaluate 12 alternatives for applying eisenhower_action function to DataFrame rows. First, we will measure the time for a sample of 100k rows. Then, we will measure and plot the time for up to a million rows. The simplest method to process each row in the good old Python loop. This is obviously the worst way, and nobody in the right mind will ever do it. def loop_impl(df): cutoff_date = datetime.date.today() + datetime.timedelta(days=2) result = [] for i in range(len(df)): row = df.iloc[i] result.append( eisenhower_action( row.priority == 'HIGH', row.due_date <= cutoff_date) ) return pd.Series(result) As expected, it takes a horrendous amount of time: 56.6 seconds. %timeit data_sample['action_loop'] = loop_impl(data_sample)1 loop, best of 5: 56.6 s per loop It establishes the worst-case performance upper bound. Since its cost is linear, i.e. O(n), it provides a good baseline to compare other alternatives. Let’s find out what is taking so long using the line_profiler, but for a smaller sample of 100 rows: %lprun -f loop_impl loop_impl(test_data_sample(100)) Its output is shown in the following figure: Extracting a row from DataFrame (line #6) takes 90% of the time. That is understandable because Pandas DataFrame storage is column-major: consecutive elements in a column are stored sequentially in memory. So pulling together elements of a row is expensive. Even if we take out that 90% cost from 56.6s for 100k rows, it would take 5.66s. That is still a lot. Instead of processing each row in a Python loop, let’s try Pandas iterrows function. def iterrows_impl(df): cutoff_date = datetime.date.today() + datetime.timedelta(days=2) return pd.Series( eisenhower_action( row.priority == 'HIGH', row.due_date <= cutoff_date) for index, row in df.iterrows() ) It takes 9.04 seconds, approx. one-fourth of the time taken by the loop: %timeit data_sample['action_iterrow'] = iterrows_impl(data_sample)1 loop, best of 5: 9.04 s per loop Pandas has another method, itertuples, that processes rows as tuples. def itertuples_impl(df): cutoff_date = datetime.date.today() + datetime.timedelta(days=2) return pd.Series( eisenhower_action( row.priority == 'HIGH', row.due_date <= cutoff_date) for row in df.itertuples() ) Its performance threw a surprise, it took only 211 milliseconds. %timeit data_sample['action_itertuples'] = itertuples_impl(data_sample)1 loops, best of 5: 211 ms per loop Pandas DataFrame apply function is quite versatile and is a popular choice. To make it process the rows, you have to pass axis=1 argument. def apply_impl(df): cutoff_date = datetime.date.today() + datetime.timedelta(days=2) return df.apply( lambda row: eisenhower_action( row.priority == 'HIGH', row.due_date <= cutoff_date), axis=1 ) This also threw a surprise for me. It took 1.85 seconds. 10x worse than itertuples! %timeit data_sample['action_impl'] = apply_impl(data_sample)1 loop, best of 5: 1.85 s per loop A column in DataFrame is a Series that can be used as a list in a list comprehension expression: [ foo(x) for x in df['x'] ] If multiple columns are needed, then zip can be used to make a list of tuples. def list_impl(df): cutoff_date = datetime.date.today() + datetime.timedelta(days=2) return pd.Series([ eisenhower_action(priority == 'HIGH', due_date <= cutoff_date) for (priority, due_date) in zip(df['priority'], df['due_date']) ]) This also threw a surprise. It took only 78.4 milliseconds, even better than itertuples! %timeit data_sample['action_list'] = list_impl(data_sample)10 loops, best of 5: 78.4 ms per loop Python’s map function that takes in function and iterables of parameters, and yields results. def map_impl(df): cutoff_date = datetime.date.today() + datetime.timedelta(days=2) return pd.Series( map(eisenhower_action, df['priority'] == 'HIGH', df['due_date'] <= cutoff_date) ) This performed slightly better than list comprehension. %timeit data_sample['action_map'] = map_impl(data_sample)10 loops, best of 5: 71.5 ms per loop The real power of Pandas shows up in vectorization. But it requires unpacking the function as a vector expression. def vec_impl(df): cutoff_date = datetime.date.today() + datetime.timedelta(days=2) return ( 2*(df['priority'] == 'HIGH') + (df['due_date'] <= cutoff_date)) It gives the best performance: only 20 milliseconds. %timeit data_sample['action_vec'] = vec_impl(data_sample)10 loops, best of 5: 20 ms per loop Vectorizing, depending upon the complexity of the function, can take significant effort. Sometimes, it may not even be feasible. NumPy offers alternatives for migrating from Python to Numpy through vectorization. For example, it has a vectorize() function that vectorzie any scalar function to accept and return NumPy arrays. def np_vec_impl(df): cutoff_date = datetime.date.today() + datetime.timedelta(days=2) return np.vectorize(eisenhower_action)( df['priority'] == 'HIGH', df['due_date'] <= cutoff_date ) Not surprisingly, its performance is second to only Pandas vectorization: 35.7 milliseconds. %timeit data_sample['action_np_vec'] = np_vec_impl(data_sample)10 loops, best of 5: 35.7 ms per loop So far, only Pandas and NumPy packages were used. But there are more alternatives if you are open to having additional package dependencies. Numba is commonly used to speed up applying mathematical functions. It has various decorators for JIT compilation and vectorization. import numba@numba.vectorizedef eisenhower_action(is_important: bool, is_urgent: bool) -> int: return 2 * is_important + is_urgentdef numba_impl(df): cutoff_date = datetime.date.today() + datetime.timedelta(days=2) return eisenhower_action( (df['priority'] == 'HIGH').to_numpy(), (df['due_date'] <= cutoff_date).to_numpy() ) Its vectorize decorator is similar to NumPy vectorize function but offers better performance: 18.9 milliseconds (similar to Pandas vectorization). But it also gives cache warning. %timeit data_sample['action_numba'] = numba_impl(data_sample)The slowest run took 11.66 times longer than the fastest. This could mean that an intermediate result is being cached.1 loop, best of 5: 18.9 ms per loop The pandarallel package utilizes multiple CPUs and split the work into multiple threads. from pandarallel import pandarallelpandarallel.initialize()def pandarallel_impl(df): cutoff_date = datetime.date.today() + datetime.timedelta(days=2) return df.parallel_apply( lambda row: eisenhower_action( row.priority == 'HIGH', row.due_date <= cutoff_date), axis=1 ) In 2-CPU machine, it took 2.27 seconds. The splitting and bookkeeping overheads don’t seem to pay off for 100k records and 2-CPU. %timeit data_sample['action_pandarallel'] = pandarallel_impl(data_sample)1 loop, best of 5: 2.27 s per loop Dask is a parallel computing library that supports scaling up NumPy, Pandas, Scikit-learn, and many other Python libraries. It offers efficient infra for processing a massive amount of data on multi-node clusters. import dask.dataframe as dddef dask_impl(df): cutoff_date = datetime.date.today() + datetime.timedelta(days=2) return dd.from_pandas(df, npartitions=CPU_COUNT).apply( lambda row: eisenhower_action( row.priority == 'HIGH', row.due_date <= cutoff_date), axis=1, meta=(int) ).compute() In 2-CPU machine, it took 2.13 seconds. Like pandarallel, payoffs are meaningful only when processing a large amount of data on many machines. %timeit data_sample['action_dask'] = dask_impl(data_sample)1 loop, best of 5: 2.13 s per loop Swifter automatically decides which is faster: to use Dask parallel processing or a simple Pandas apply. It is very simple to use: just all one word to how one uses Pandas apply function: df.swifter.apply. import swifterdef swifter_impl(df): cutoff_date = datetime.date.today() + datetime.timedelta(days=2) return df.swifter.apply( lambda row: eisenhower_action( row.priority == 'HIGH', row.due_date <= cutoff_date), axis=1 ) Its performance for this use case is expectedly quite close to Pandas vectorization. %timeit data_sample['action_swifter'] = swifter_impl(data_sample)10 loops, best of 5: 22.9 ms per loop+ Plotting is helpful in understanding the relative performance of alternatives over input size. Perfplot is a handy tool for that. It requires a setup to generate input of a given size and a list of implementations to compare. kernels = [ loop_impl, iterrows_impl, itertuples_impl, apply_impl, list_impl, vec_impl, np_vec_impl, numba_impl, pandarallel_impl, dask_impl, swifter_impl]labels = [str(k.__name__)[:-5] for k in kernels]perfplot.show( setup=lambda n: test_data_sample(n), kernels=kernels, labels=labels, n_range=[2**k for k in range(K_MAX)], xlabel='N', logx=True, logy=True, #equality_check=None) It generates a plot like the one shown below. Here are some observations from the plot: For this use case, the asymptotic performance order stabilizes at about 10k rows in the DataFrame. Since all lines in the plot become parallel, the perf difference might not be apparent in the log-log scale plot. The itertuples is as simple to use as apply but with 10x better performance. List Comprehension is ~2.5x better than itertuples, though it can be verbose to write for a complex function. NumPy vectorize is 2x better than the List comprehension, and is as simple to use as itertuples and apply functions. Pandas vectorization is ~2x better than NumPy vectorize. Overheads of parallel processing pay off only when a huge amount of data is processed on many machines. Performing an operation independently to all Pandas rows is a common need. Here are my recommendations: Vectorize DataFrame expression: Go for this whenever possible.NumPy vectorize: Its API is not very complicated. It does not require additional packages. It offers almost the best performance. Choose this if vectorizing DataFrame isn’t infeasible.List Comprehension: Opt for this alternative when needing only 2–3 DataFrame columns, and DataFrame vectorization and NumPy vectorize not infeasible for some reason.Pandas itertuples function: Its API is like apply function, but offers 10x better performance than apply. It is the easiest and most readable option. It offers reasonable performance. Do this if the previous three do not work out.Numba or Swift: Use this to exploit parallelization without code complexity. Vectorize DataFrame expression: Go for this whenever possible. NumPy vectorize: Its API is not very complicated. It does not require additional packages. It offers almost the best performance. Choose this if vectorizing DataFrame isn’t infeasible. List Comprehension: Opt for this alternative when needing only 2–3 DataFrame columns, and DataFrame vectorization and NumPy vectorize not infeasible for some reason. Pandas itertuples function: Its API is like apply function, but offers 10x better performance than apply. It is the easiest and most readable option. It offers reasonable performance. Do this if the previous three do not work out. Numba or Swift: Use this to exploit parallelization without code complexity. Understanding the cost of various alternatives is critical for making an informed choice. Use timeit, line_profiler, and perfplot to measure the performance of these alternatives. Balance performance with ease of use for deciding the best alternative for your use case. If you enjoyed this, please: Share it with this infographic:
[ { "code": null, "e": 483, "s": 171, "text": "Applying a function to all rows in a Pandas DataFrame is one of the most common operations during data wrangling. Pandas DataFrame apply function is the most obvious choice for doing it. It takes a function as an argument and applies it along an axis of the DataFrame. However, it is not always the best choice." }, { "code": null, "e": 661, "s": 483, "text": "In this article, you will measure the performance of 12 alternatives. With a companion Code Lab, you can try it all in your browser. No need to install anything on your machine." }, { "code": null, "e": 843, "s": 661, "text": "Recently, I was analyzing user behavior data for an e-commerce app. Depending on the number of times a user did text and voice searches, I assigned each user to one of four cohorts:" }, { "code": null, "e": 885, "s": 843, "text": "No Search: Users who did no search at all" }, { "code": null, "e": 929, "s": 885, "text": "Text Only: Users who did text searches only" }, { "code": null, "e": 975, "s": 929, "text": "Voice Only: Users who did voice searches only" }, { "code": null, "e": 1022, "s": 975, "text": "Both: Users who did both text and voice search" }, { "code": null, "e": 1255, "s": 1022, "text": "It was a huge data set with 100k to a million users depending upon the chosen time slice. Computing it with Pandas apply function was excruciatingly slow, so I evaluated alternatives. This article is the distilled lessons from that." }, { "code": null, "e": 1369, "s": 1255, "text": "I can’t share that dataset. So I am picking another similar problem to show the solutions: the Eisenhower method." }, { "code": null, "e": 1499, "s": 1369, "text": "Based on a task’s importance and urgency, the Eisenhower Method assigns it into one of 4 bins. Each bin has an associated action:" }, { "code": null, "e": 1535, "s": 1499, "text": "Important and Urgent: Do right away" }, { "code": null, "e": 1580, "s": 1535, "text": "Important but not Urgent: Schedule for later" }, { "code": null, "e": 1631, "s": 1580, "text": "Not Important but Urgent: Delegate to someone else" }, { "code": null, "e": 1682, "s": 1631, "text": "Neither Important nor Urgent: Delete time wasters." }, { "code": null, "e": 1866, "s": 1682, "text": "We will use the boolean matrix shown in the adjacent figure. Importance and urgency booleans make the binary integer value for each action: DO(3), SCHEDULE(2), DELEGATE(1), DELETE(0)." }, { "code": null, "e": 2074, "s": 1866, "text": "We will profile the performance of mapping tasks to one of the actions. We will measure which of the 12 alternatives take the least amount of time. And we will plot the performance for up to a million tasks." }, { "code": null, "e": 2304, "s": 2074, "text": "It is a good time to open the companion notebook at Google Colab or Kaggle. If you want to see the code in action, you can execute the cells in the Code Lab as you read along. Go ahead, execute all the cells in the Setup section." }, { "code": null, "e": 2599, "s": 2304, "text": "Faker is a handy library to generate data. In the Code Lab, it is used for generating a DataFrame with a million tasks. Each task is a row in the DataFrame. It consists of task_name (str), due_date (datetime.date), and priority (str). Priority can be one of the three values: LOW, MEDIUM, HIGH." }, { "code": null, "e": 2736, "s": 2599, "text": "We will minimize the storage size to eliminate its effect on any of the alternatives. The DataFrame with ~2 million rows is taking 48MB:" }, { "code": null, "e": 3019, "s": 2736, "text": ">>> test_data_set.info()<class 'pandas.core.frame.DataFrame'>RangeIndex: 2097153 entries, 0 to 2097152Data columns (total 3 columns): # Column Dtype --- ------ ----- 0 task_name object 1 due_date object 2 priority objectdtypes: object(3)memory usage: 48.0+ MB" }, { "code": null, "e": 3086, "s": 3019, "text": "Instead of str, priority can be stored as Pandas categorical type:" }, { "code": null, "e": 3264, "s": 3086, "text": "priority_dtype = pd.api.types.CategoricalDtype( categories=['LOW', 'MEDIUM', 'HIGH'], ordered=True)test_data_set['priority'] = test_data_set['priority'].astype(priority_dtype)" }, { "code": null, "e": 3304, "s": 3264, "text": "Let’s check out the DataFrame size now:" }, { "code": null, "e": 3609, "s": 3304, "text": ">>> test_data_set.info()<class 'pandas.core.frame.DataFrame'>RangeIndex: 2097153 entries, 0 to 2097152Data columns (total 3 columns): # Column Dtype --- ------ ----- 0 task_name object 1 due_date object 2 priority categorydtypes: category(1), object(2)memory usage: 34.0+MB" }, { "code": null, "e": 3634, "s": 3609, "text": "Size is reduced to 34MB." }, { "code": null, "e": 3725, "s": 3634, "text": "Given importance and urgency, eisenhower_action computes an integer value between 0 and 3." }, { "code": null, "e": 3829, "s": 3725, "text": "def eisenhower_action(is_important: bool, is_urgent: bool) -> int: return 2 * is_important + is_urgent" }, { "code": null, "e": 3974, "s": 3829, "text": "For this exercise, we will assume that a task with HIGH priority is important. If the due date is in the next two days, then the task is urgent." }, { "code": null, "e": 4093, "s": 3974, "text": "The Eisenhower Action for a task (i.e. a row in the DataFrame) is computed by using the due_date and priority columns:" }, { "code": null, "e": 4274, "s": 4093, "text": ">>> cutoff_date = datetime.date.today() + datetime.timedelta(days=2)>>> eisenhower_action( test_data_set.loc[0].priority == 'HIGH', test_data_set.loc[0].due_date <= cutoff_date)2" }, { "code": null, "e": 4333, "s": 4274, "text": "The integer 2 means that the needed action is to SCHEDULE." }, { "code": null, "e": 4578, "s": 4333, "text": "In the rest of the article, we will evaluate 12 alternatives for applying eisenhower_action function to DataFrame rows. First, we will measure the time for a sample of 100k rows. Then, we will measure and plot the time for up to a million rows." }, { "code": null, "e": 4726, "s": 4578, "text": "The simplest method to process each row in the good old Python loop. This is obviously the worst way, and nobody in the right mind will ever do it." }, { "code": null, "e": 5003, "s": 4726, "text": "def loop_impl(df): cutoff_date = datetime.date.today() + datetime.timedelta(days=2) result = [] for i in range(len(df)): row = df.iloc[i] result.append( eisenhower_action( row.priority == 'HIGH', row.due_date <= cutoff_date) ) return pd.Series(result)" }, { "code": null, "e": 5068, "s": 5003, "text": "As expected, it takes a horrendous amount of time: 56.6 seconds." }, { "code": null, "e": 5162, "s": 5068, "text": "%timeit data_sample['action_loop'] = loop_impl(data_sample)1 loop, best of 5: 56.6 s per loop" }, { "code": null, "e": 5313, "s": 5162, "text": "It establishes the worst-case performance upper bound. Since its cost is linear, i.e. O(n), it provides a good baseline to compare other alternatives." }, { "code": null, "e": 5414, "s": 5313, "text": "Let’s find out what is taking so long using the line_profiler, but for a smaller sample of 100 rows:" }, { "code": null, "e": 5468, "s": 5414, "text": "%lprun -f loop_impl loop_impl(test_data_sample(100))" }, { "code": null, "e": 5513, "s": 5468, "text": "Its output is shown in the following figure:" }, { "code": null, "e": 5771, "s": 5513, "text": "Extracting a row from DataFrame (line #6) takes 90% of the time. That is understandable because Pandas DataFrame storage is column-major: consecutive elements in a column are stored sequentially in memory. So pulling together elements of a row is expensive." }, { "code": null, "e": 5873, "s": 5771, "text": "Even if we take out that 90% cost from 56.6s for 100k rows, it would take 5.66s. That is still a lot." }, { "code": null, "e": 5958, "s": 5873, "text": "Instead of processing each row in a Python loop, let’s try Pandas iterrows function." }, { "code": null, "e": 6184, "s": 5958, "text": "def iterrows_impl(df): cutoff_date = datetime.date.today() + datetime.timedelta(days=2) return pd.Series( eisenhower_action( row.priority == 'HIGH', row.due_date <= cutoff_date) for index, row in df.iterrows() )" }, { "code": null, "e": 6257, "s": 6184, "text": "It takes 9.04 seconds, approx. one-fourth of the time taken by the loop:" }, { "code": null, "e": 6358, "s": 6257, "text": "%timeit data_sample['action_iterrow'] = iterrows_impl(data_sample)1 loop, best of 5: 9.04 s per loop" }, { "code": null, "e": 6428, "s": 6358, "text": "Pandas has another method, itertuples, that processes rows as tuples." }, { "code": null, "e": 6651, "s": 6428, "text": "def itertuples_impl(df): cutoff_date = datetime.date.today() + datetime.timedelta(days=2) return pd.Series( eisenhower_action( row.priority == 'HIGH', row.due_date <= cutoff_date) for row in df.itertuples() )" }, { "code": null, "e": 6716, "s": 6651, "text": "Its performance threw a surprise, it took only 211 milliseconds." }, { "code": null, "e": 6823, "s": 6716, "text": "%timeit data_sample['action_itertuples'] = itertuples_impl(data_sample)1 loops, best of 5: 211 ms per loop" }, { "code": null, "e": 6962, "s": 6823, "text": "Pandas DataFrame apply function is quite versatile and is a popular choice. To make it process the rows, you have to pass axis=1 argument." }, { "code": null, "e": 7187, "s": 6962, "text": "def apply_impl(df): cutoff_date = datetime.date.today() + datetime.timedelta(days=2) return df.apply( lambda row: eisenhower_action( row.priority == 'HIGH', row.due_date <= cutoff_date), axis=1 )" }, { "code": null, "e": 7271, "s": 7187, "text": "This also threw a surprise for me. It took 1.85 seconds. 10x worse than itertuples!" }, { "code": null, "e": 7366, "s": 7271, "text": "%timeit data_sample['action_impl'] = apply_impl(data_sample)1 loop, best of 5: 1.85 s per loop" }, { "code": null, "e": 7463, "s": 7366, "text": "A column in DataFrame is a Series that can be used as a list in a list comprehension expression:" }, { "code": null, "e": 7491, "s": 7463, "text": "[ foo(x) for x in df['x'] ]" }, { "code": null, "e": 7570, "s": 7491, "text": "If multiple columns are needed, then zip can be used to make a list of tuples." }, { "code": null, "e": 7812, "s": 7570, "text": "def list_impl(df): cutoff_date = datetime.date.today() + datetime.timedelta(days=2) return pd.Series([ eisenhower_action(priority == 'HIGH', due_date <= cutoff_date) for (priority, due_date) in zip(df['priority'], df['due_date']) ])" }, { "code": null, "e": 7901, "s": 7812, "text": "This also threw a surprise. It took only 78.4 milliseconds, even better than itertuples!" }, { "code": null, "e": 7998, "s": 7901, "text": "%timeit data_sample['action_list'] = list_impl(data_sample)10 loops, best of 5: 78.4 ms per loop" }, { "code": null, "e": 8092, "s": 7998, "text": "Python’s map function that takes in function and iterables of parameters, and yields results." }, { "code": null, "e": 8291, "s": 8092, "text": "def map_impl(df): cutoff_date = datetime.date.today() + datetime.timedelta(days=2) return pd.Series( map(eisenhower_action, df['priority'] == 'HIGH', df['due_date'] <= cutoff_date) )" }, { "code": null, "e": 8347, "s": 8291, "text": "This performed slightly better than list comprehension." }, { "code": null, "e": 8442, "s": 8347, "text": "%timeit data_sample['action_map'] = map_impl(data_sample)10 loops, best of 5: 71.5 ms per loop" }, { "code": null, "e": 8557, "s": 8442, "text": "The real power of Pandas shows up in vectorization. But it requires unpacking the function as a vector expression." }, { "code": null, "e": 8718, "s": 8557, "text": "def vec_impl(df): cutoff_date = datetime.date.today() + datetime.timedelta(days=2) return ( 2*(df['priority'] == 'HIGH') + (df['due_date'] <= cutoff_date))" }, { "code": null, "e": 8771, "s": 8718, "text": "It gives the best performance: only 20 milliseconds." }, { "code": null, "e": 8864, "s": 8771, "text": "%timeit data_sample['action_vec'] = vec_impl(data_sample)10 loops, best of 5: 20 ms per loop" }, { "code": null, "e": 8993, "s": 8864, "text": "Vectorizing, depending upon the complexity of the function, can take significant effort. Sometimes, it may not even be feasible." }, { "code": null, "e": 9190, "s": 8993, "text": "NumPy offers alternatives for migrating from Python to Numpy through vectorization. For example, it has a vectorize() function that vectorzie any scalar function to accept and return NumPy arrays." }, { "code": null, "e": 9383, "s": 9190, "text": "def np_vec_impl(df): cutoff_date = datetime.date.today() + datetime.timedelta(days=2) return np.vectorize(eisenhower_action)( df['priority'] == 'HIGH', df['due_date'] <= cutoff_date )" }, { "code": null, "e": 9476, "s": 9383, "text": "Not surprisingly, its performance is second to only Pandas vectorization: 35.7 milliseconds." }, { "code": null, "e": 9577, "s": 9476, "text": "%timeit data_sample['action_np_vec'] = np_vec_impl(data_sample)10 loops, best of 5: 35.7 ms per loop" }, { "code": null, "e": 9718, "s": 9577, "text": "So far, only Pandas and NumPy packages were used. But there are more alternatives if you are open to having additional package dependencies." }, { "code": null, "e": 9851, "s": 9718, "text": "Numba is commonly used to speed up applying mathematical functions. It has various decorators for JIT compilation and vectorization." }, { "code": null, "e": 10186, "s": 9851, "text": "import numba@numba.vectorizedef eisenhower_action(is_important: bool, is_urgent: bool) -> int: return 2 * is_important + is_urgentdef numba_impl(df): cutoff_date = datetime.date.today() + datetime.timedelta(days=2) return eisenhower_action( (df['priority'] == 'HIGH').to_numpy(), (df['due_date'] <= cutoff_date).to_numpy() )" }, { "code": null, "e": 10366, "s": 10186, "text": "Its vectorize decorator is similar to NumPy vectorize function but offers better performance: 18.9 milliseconds (similar to Pandas vectorization). But it also gives cache warning." }, { "code": null, "e": 10581, "s": 10366, "text": "%timeit data_sample['action_numba'] = numba_impl(data_sample)The slowest run took 11.66 times longer than the fastest. This could mean that an intermediate result is being cached.1 loop, best of 5: 18.9 ms per loop" }, { "code": null, "e": 10670, "s": 10581, "text": "The pandarallel package utilizes multiple CPUs and split the work into multiple threads." }, { "code": null, "e": 10954, "s": 10670, "text": "from pandarallel import pandarallelpandarallel.initialize()def pandarallel_impl(df): cutoff_date = datetime.date.today() + datetime.timedelta(days=2) return df.parallel_apply( lambda row: eisenhower_action( row.priority == 'HIGH', row.due_date <= cutoff_date), axis=1 )" }, { "code": null, "e": 11084, "s": 10954, "text": "In 2-CPU machine, it took 2.27 seconds. The splitting and bookkeeping overheads don’t seem to pay off for 100k records and 2-CPU." }, { "code": null, "e": 11192, "s": 11084, "text": "%timeit data_sample['action_pandarallel'] = pandarallel_impl(data_sample)1 loop, best of 5: 2.27 s per loop" }, { "code": null, "e": 11406, "s": 11192, "text": "Dask is a parallel computing library that supports scaling up NumPy, Pandas, Scikit-learn, and many other Python libraries. It offers efficient infra for processing a massive amount of data on multi-node clusters." }, { "code": null, "e": 11706, "s": 11406, "text": "import dask.dataframe as dddef dask_impl(df): cutoff_date = datetime.date.today() + datetime.timedelta(days=2) return dd.from_pandas(df, npartitions=CPU_COUNT).apply( lambda row: eisenhower_action( row.priority == 'HIGH', row.due_date <= cutoff_date), axis=1, meta=(int) ).compute()" }, { "code": null, "e": 11849, "s": 11706, "text": "In 2-CPU machine, it took 2.13 seconds. Like pandarallel, payoffs are meaningful only when processing a large amount of data on many machines." }, { "code": null, "e": 11943, "s": 11849, "text": "%timeit data_sample['action_dask'] = dask_impl(data_sample)1 loop, best of 5: 2.13 s per loop" }, { "code": null, "e": 12149, "s": 11943, "text": "Swifter automatically decides which is faster: to use Dask parallel processing or a simple Pandas apply. It is very simple to use: just all one word to how one uses Pandas apply function: df.swifter.apply." }, { "code": null, "e": 12383, "s": 12149, "text": "import swifterdef swifter_impl(df): cutoff_date = datetime.date.today() + datetime.timedelta(days=2) return df.swifter.apply( lambda row: eisenhower_action( row.priority == 'HIGH', row.due_date <= cutoff_date), axis=1 )" }, { "code": null, "e": 12468, "s": 12383, "text": "Its performance for this use case is expectedly quite close to Pandas vectorization." }, { "code": null, "e": 12572, "s": 12468, "text": "%timeit data_sample['action_swifter'] = swifter_impl(data_sample)10 loops, best of 5: 22.9 ms per loop+" }, { "code": null, "e": 12798, "s": 12572, "text": "Plotting is helpful in understanding the relative performance of alternatives over input size. Perfplot is a handy tool for that. It requires a setup to generate input of a given size and a list of implementations to compare." }, { "code": null, "e": 13198, "s": 12798, "text": "kernels = [ loop_impl, iterrows_impl, itertuples_impl, apply_impl, list_impl, vec_impl, np_vec_impl, numba_impl, pandarallel_impl, dask_impl, swifter_impl]labels = [str(k.__name__)[:-5] for k in kernels]perfplot.show( setup=lambda n: test_data_sample(n), kernels=kernels, labels=labels, n_range=[2**k for k in range(K_MAX)], xlabel='N', logx=True, logy=True, #equality_check=None)" }, { "code": null, "e": 13244, "s": 13198, "text": "It generates a plot like the one shown below." }, { "code": null, "e": 13286, "s": 13244, "text": "Here are some observations from the plot:" }, { "code": null, "e": 13385, "s": 13286, "text": "For this use case, the asymptotic performance order stabilizes at about 10k rows in the DataFrame." }, { "code": null, "e": 13499, "s": 13385, "text": "Since all lines in the plot become parallel, the perf difference might not be apparent in the log-log scale plot." }, { "code": null, "e": 13576, "s": 13499, "text": "The itertuples is as simple to use as apply but with 10x better performance." }, { "code": null, "e": 13686, "s": 13576, "text": "List Comprehension is ~2.5x better than itertuples, though it can be verbose to write for a complex function." }, { "code": null, "e": 13803, "s": 13686, "text": "NumPy vectorize is 2x better than the List comprehension, and is as simple to use as itertuples and apply functions." }, { "code": null, "e": 13860, "s": 13803, "text": "Pandas vectorization is ~2x better than NumPy vectorize." }, { "code": null, "e": 13964, "s": 13860, "text": "Overheads of parallel processing pay off only when a huge amount of data is processed on many machines." }, { "code": null, "e": 14068, "s": 13964, "text": "Performing an operation independently to all Pandas rows is a common need. Here are my recommendations:" }, { "code": null, "e": 14786, "s": 14068, "text": "Vectorize DataFrame expression: Go for this whenever possible.NumPy vectorize: Its API is not very complicated. It does not require additional packages. It offers almost the best performance. Choose this if vectorizing DataFrame isn’t infeasible.List Comprehension: Opt for this alternative when needing only 2–3 DataFrame columns, and DataFrame vectorization and NumPy vectorize not infeasible for some reason.Pandas itertuples function: Its API is like apply function, but offers 10x better performance than apply. It is the easiest and most readable option. It offers reasonable performance. Do this if the previous three do not work out.Numba or Swift: Use this to exploit parallelization without code complexity." }, { "code": null, "e": 14849, "s": 14786, "text": "Vectorize DataFrame expression: Go for this whenever possible." }, { "code": null, "e": 15034, "s": 14849, "text": "NumPy vectorize: Its API is not very complicated. It does not require additional packages. It offers almost the best performance. Choose this if vectorizing DataFrame isn’t infeasible." }, { "code": null, "e": 15200, "s": 15034, "text": "List Comprehension: Opt for this alternative when needing only 2–3 DataFrame columns, and DataFrame vectorization and NumPy vectorize not infeasible for some reason." }, { "code": null, "e": 15431, "s": 15200, "text": "Pandas itertuples function: Its API is like apply function, but offers 10x better performance than apply. It is the easiest and most readable option. It offers reasonable performance. Do this if the previous three do not work out." }, { "code": null, "e": 15508, "s": 15431, "text": "Numba or Swift: Use this to exploit parallelization without code complexity." }, { "code": null, "e": 15778, "s": 15508, "text": "Understanding the cost of various alternatives is critical for making an informed choice. Use timeit, line_profiler, and perfplot to measure the performance of these alternatives. Balance performance with ease of use for deciding the best alternative for your use case." }, { "code": null, "e": 15807, "s": 15778, "text": "If you enjoyed this, please:" } ]
How to set the output directory of TestNG @BeforeTest?
TestNG supports default report generation when a user runs testng.xml, either from an IDE or the command line. By default, all reports are generated at the Project -> test-output folder. If the test-output folder is not present, then TestNG creates it at runtime and saves all the files related to the result. However, the user can provide a desired location or folder name where TestNG should save the reports. It can be done using native dependency injection. It allows to declare additional parameters in methods. At runtime, TestNG automatically fills these parameters with the correct values. To set up the output directory at @BeforeTest, ITestContext dependency can be used. It creates the folder at a given path or override it, if a folder already exists, to save the reports of the latest run. In this article, we will use ITestContext dependency to illustrate how to set up an output directory to TestNG @BeforeTest. Setp 1 − Create a TestNG class, NewTestngClass. Setp 1 − Create a TestNG class, NewTestngClass. Setp 2 − Write the following code inside @BeforeTest in the class; Setp 2 − Write the following code inside @BeforeTest in the class; public void setOutputDirectory(ITestContext context) { TestRunner runner = (TestRunner) context; String path=System.getProperty("user.dir"); runner.setOutputDirectory(path+"/output-testng"); } Setp 3 − Write a @Test method in the class, NewTestngClass. Setp 3 − Write a @Test method in the class, NewTestngClass. Setp 4 − Create the testNG.xml as given below to run the TestNG class. Setp 4 − Create the testNG.xml as given below to run the TestNG class. Setp 5 − Now, run the testNG.xml or directly testNG class in IDE or compile and run it using command line. Setp 5 − Now, run the testNG.xml or directly testNG class in IDE or compile and run it using command line. Setp 6 − Once the execution is completed, the user can check to ensure whether the output-testng folder has been created at the project path and all the reports are present there for the latest run. In this example, String path=System.getProperty("user.dir"); fetches the absolute path where the TestNG project is present and then adds the folder. The user can provide any path to generate reports in that folder. Setp 6 − Once the execution is completed, the user can check to ensure whether the output-testng folder has been created at the project path and all the reports are present there for the latest run. In this example, String path=System.getProperty("user.dir"); fetches the absolute path where the TestNG project is present and then adds the folder. The user can provide any path to generate reports in that folder. Use the following code for the common TestNG class, NewTestngClass− import org.testng.ITestContext; import org.testng.TestRunner; import org.testng.annotations.*; public class NewTestngClass { @Test() public void testcase1(ITestContext testContext){ System.out.println("Thread ID: "+Thread.currentThread().getId()); int currentCount = testContext.getAllTestMethods()[0].getCurrentInvocationCount(); System.out.println("Executing count: " + currentCount); } @BeforeTest public void setOutputDirectory(ITestContext context) { TestRunner runner = (TestRunner) context; String path=System.getProperty("user.dir"); runner.setOutputDirectory(path+"/output-testng"); } } This is a configuration file that is used to organize and run the TestNG test cases. It is very handy when limited tests are needed to execute rather than the full suite. <?xml version = "1.0" encoding = "UTF-8"?< <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" > <suite name = "Suite1"> <test name = "test1"> <classes> <class name = "NewTestngClass"/>ng="testng"> </classes> </test> </suite> Thread ID: 12 Executing count: 0 =============================================== Suite1 Total tests run: 1, Passes: 1, Failures: 0, Skips: 0 ===============================================
[ { "code": null, "e": 1372, "s": 1062, "text": "TestNG supports default report generation when a user runs testng.xml, either from an IDE or the command line. By default, all reports are generated at the Project -> test-output folder. If the test-output folder is not present, then TestNG creates it at runtime and saves all the files related to the result." }, { "code": null, "e": 1660, "s": 1372, "text": "However, the user can provide a desired location or folder name where TestNG should save the reports. It can be done using native dependency injection. It allows to declare additional parameters in methods. At runtime, TestNG automatically fills these parameters with the correct values." }, { "code": null, "e": 1865, "s": 1660, "text": "To set up the output directory at @BeforeTest, ITestContext dependency can be used. It creates the folder at a given path or override it, if a folder already exists, to save the reports of the latest run." }, { "code": null, "e": 1989, "s": 1865, "text": "In this article, we will use ITestContext dependency to illustrate how to set up an output directory to TestNG @BeforeTest." }, { "code": null, "e": 2037, "s": 1989, "text": "Setp 1 − Create a TestNG class, NewTestngClass." }, { "code": null, "e": 2085, "s": 2037, "text": "Setp 1 − Create a TestNG class, NewTestngClass." }, { "code": null, "e": 2152, "s": 2085, "text": "Setp 2 − Write the following code inside @BeforeTest in the class;" }, { "code": null, "e": 2219, "s": 2152, "text": "Setp 2 − Write the following code inside @BeforeTest in the class;" }, { "code": null, "e": 2421, "s": 2219, "text": "public void setOutputDirectory(ITestContext context) {\n TestRunner runner = (TestRunner) context;\n String path=System.getProperty(\"user.dir\");\n runner.setOutputDirectory(path+\"/output-testng\");\n}" }, { "code": null, "e": 2481, "s": 2421, "text": "Setp 3 − Write a @Test method in the class, NewTestngClass." }, { "code": null, "e": 2541, "s": 2481, "text": "Setp 3 − Write a @Test method in the class, NewTestngClass." }, { "code": null, "e": 2612, "s": 2541, "text": "Setp 4 − Create the testNG.xml as given below to run the TestNG class." }, { "code": null, "e": 2683, "s": 2612, "text": "Setp 4 − Create the testNG.xml as given below to run the TestNG class." }, { "code": null, "e": 2790, "s": 2683, "text": "Setp 5 − Now, run the testNG.xml or directly testNG class in IDE or compile and run it using command line." }, { "code": null, "e": 2897, "s": 2790, "text": "Setp 5 − Now, run the testNG.xml or directly testNG class in IDE or compile and run it using command line." }, { "code": null, "e": 3311, "s": 2897, "text": "Setp 6 − Once the execution is completed, the user can check to ensure whether the output-testng folder has been created at the project path and all the reports are present there for the latest run. In this example, String path=System.getProperty(\"user.dir\"); fetches the absolute path where the TestNG project is present and then adds the folder. The user can provide any path to generate reports in that folder." }, { "code": null, "e": 3725, "s": 3311, "text": "Setp 6 − Once the execution is completed, the user can check to ensure whether the output-testng folder has been created at the project path and all the reports are present there for the latest run. In this example, String path=System.getProperty(\"user.dir\"); fetches the absolute path where the TestNG project is present and then adds the folder. The user can provide any path to generate reports in that folder." }, { "code": null, "e": 3793, "s": 3725, "text": "Use the following code for the common TestNG class, NewTestngClass−" }, { "code": null, "e": 4443, "s": 3793, "text": "import org.testng.ITestContext;\nimport org.testng.TestRunner;\nimport org.testng.annotations.*;\npublic class NewTestngClass {\n @Test()\n public void testcase1(ITestContext testContext){\n System.out.println(\"Thread ID: \"+Thread.currentThread().getId());\n int currentCount = testContext.getAllTestMethods()[0].getCurrentInvocationCount();\n System.out.println(\"Executing count: \" + currentCount);\n }\n @BeforeTest\n public void setOutputDirectory(ITestContext context) {\n TestRunner runner = (TestRunner) context;\n String path=System.getProperty(\"user.dir\");\n runner.setOutputDirectory(path+\"/output-testng\");\n }\n}" }, { "code": null, "e": 4614, "s": 4443, "text": "This is a configuration file that is used to organize and run the TestNG test cases. It is very handy when limited tests are needed to execute rather than the full suite." }, { "code": null, "e": 4874, "s": 4614, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?<\n<!DOCTYPE suite SYSTEM \"http://testng.org/testng-1.0.dtd\" >\n\n<suite name = \"Suite1\">\n <test name = \"test1\">\n <classes>\n <class name = \"NewTestngClass\"/>ng=\"testng\">\n </classes>\n </test>\n</suite>" }, { "code": null, "e": 5063, "s": 4874, "text": "Thread ID: 12\nExecuting count: 0\n===============================================\nSuite1\nTotal tests run: 1, Passes: 1, Failures: 0, Skips: 0\n===============================================" } ]
Number of subsets with zero sum - GeeksforGeeks
13 May, 2021 Given an array ‘arr’ consisting of integers, the task is to find the number of subsets such that their sum is equal to zero. Empty subset should also be considered. Examples: Input : arr[] = {2, 2, -4} Output : 2 All possible subsets: {} = 0 {2} = 2 {2} = 2 {-4} = -4 {2, 2} = 4 {2, -4} = -2 {2, -4} = -4 {2, 2, -4} = 0 Since, {} and {2, 2, -4} are only possible subsets with sum 0, ans will be 2.Input : arr[] = {1, 1, 1, 1} Output : 1 {} is the only possible subset with sum 0, thus ans equals 1. One simple approach is to generate all possible subsets recursively and count the number of subsets with a sum equals to 0. The time complexity of this approach will be O(2^n). A better approach will be using Dynamic programming. Let’s suppose the sum of all the elements we have selected up to index ‘i-1’ is ‘S’. So, starting from index ‘i’, we have to find the number of subsets of the sub-array{i, N-1} with sum equals -S. Let’s define dp[i][S]. It means the number of the subset of the subarray{i, N-1} of ‘arr’ with sum equals ‘-S’. If we are at ith index, we have two choices, i.e. to include it in the sum or leave it. Thus, the required recurrence relation becomes dp[i][s] = dp[i+1][s+arr[i]] + dp[i+1][s] Below is the implementation of the above approach: C++ Java Python3 C# Javascript #include <bits/stdc++.h>#define maxSum 100#define arrSize 51using namespace std; // variable to store// states of dpint dp[arrSize][maxSum];bool visit[arrSize][maxSum]; // To find the number of subsets with sum equal to 0// Since S can be negative, we will maxSum// to it to make it positiveint SubsetCnt(int i, int s, int arr[], int n){ // Base cases if (i == n) { if (s == 0) return 1; else return 0; } // Returns the value if a state is already solved if (visit[i][s + maxSum]) return dp[i][s + maxSum]; // If the state is not visited, then continue visit[i][s + maxSum] = 1; // Recurrence relation dp[i][s + maxSum] = SubsetCnt(i + 1, s + arr[i], arr, n) + SubsetCnt(i + 1, s, arr, n); // Returning the value return dp[i][s + maxSum];} // Driver functionint main(){ int arr[] = { 2, 2, 2, -4, -4 }; int n = sizeof(arr) / sizeof(int); cout << SubsetCnt(0, 0, arr, n);} // Java implementation of above approachclass GFG{ static int maxSum = 100; static int arrSize = 51; // variable to store // states of dp static int[][] dp = new int[arrSize][maxSum]; static boolean[][] visit = new boolean[arrSize][maxSum]; // To find the number of subsets with sum equal to 0 // Since S can be negative, we will maxSum // to it to make it positive static int SubsetCnt(int i, int s, int arr[], int n) { // Base cases if (i == n) { if (s == 0) { return 1; } else { return 0; } } // Returns the value if a state is already solved if (visit[i][s + arrSize]) { return dp[i][s + arrSize]; } // If the state is not visited, then continue visit[i][s + arrSize] = true; // Recurrence relation dp[i][s + arrSize] = SubsetCnt(i + 1, s + arr[i], arr, n) + SubsetCnt(i + 1, s, arr, n); // Returning the value return dp[i][s + arrSize]; } // Driver function public static void main(String[] args) { int arr[] = {2, 2, 2, -4, -4}; int n = arr.length; System.out.println(SubsetCnt(0, 0, arr, n)); }} /* This code contributed by PrinciRaj1992 */ # Python3 implementation of above approachimport numpy as np maxSum = 100arrSize = 51 # variable to store# states of dpdp = np.zeros((arrSize, maxSum));visit = np.zeros((arrSize, maxSum)); # To find the number of subsets# with sum equal to 0.# Since S can be negative,# we will maxSum to it# to make it positivedef SubsetCnt(i, s, arr, n) : # Base cases if (i == n) : if (s == 0) : return 1; else : return 0; # Returns the value # if a state is already solved if (visit[i][s + arrSize]) : return dp[i][s + arrSize]; # If the state is not visited, # then continue visit[i][s + arrSize] = 1; # Recurrence relation dp[i][s + arrSize ] = (SubsetCnt(i + 1, s + arr[i], arr, n) + SubsetCnt(i + 1, s, arr, n)); # Returning the value return dp[i][s + arrSize]; # Driver Codeif __name__ == "__main__" : arr = [ 2, 2, 2, -4, -4 ]; n = len(arr); print(SubsetCnt(0, 0, arr, n)); # This code is contributed by AnkitRai01 // C# implementation of above approachusing System; class GFG{ static int maxSum = 100; static int arrSize = 51; // variable to store // states of dp static int [,]dp = new int[arrSize, maxSum]; static bool [,]visit = new bool[arrSize, maxSum]; // To find the number of subsets with sum equal to 0 // Since S can be negative, we will maxSum // to it to make it positive static int SubsetCnt(int i, int s, int []arr, int n) { // Base cases if (i == n) { if (s == 0) { return 1; } else { return 0; } } // Returns the value if a state is already solved if (visit[i, s + arrSize]) { return dp[i, s + arrSize]; } // If the state is not visited, then continue visit[i, s + arrSize] = true; // Recurrence relation dp[i, s + arrSize] = SubsetCnt(i + 1, s + arr[i], arr, n) + SubsetCnt(i + 1, s, arr, n); // Returning the value return dp[i,s + arrSize]; } // Driver code public static void Main() { int []arr = {2, 2, 2, -4, -4}; int n = arr.Length; Console.WriteLine(SubsetCnt(0, 0, arr, n)); }} // This code contributed by anuj_67.. <script> var maxSum = 100var arrSize = 51 // variable to store// states of dpvar dp = Array.from(Array(arrSize), ()=> Array(maxSum));var visit = Array.from(Array(arrSize), ()=> Array(maxSum)); // To find the number of subsets with sum equal to 0// Since S can be negative, we will maxSum// to it to make it positivefunction SubsetCnt(i, s, arr, n){ // Base cases if (i == n) { if (s == 0) return 1; else return 0; } // Returns the value if a state is already solved if (visit[i][s + maxSum]) return dp[i][s + maxSum]; // If the state is not visited, then continue visit[i][s + maxSum] = 1; // Recurrence relation dp[i][s + maxSum] = SubsetCnt(i + 1, s + arr[i], arr, n) + SubsetCnt(i + 1, s, arr, n); // Returning the value return dp[i][s + maxSum];} // Driver functionvar arr = [2, 2, 2, -4, -4];var n = arr.length;document.write( SubsetCnt(0, 0, arr, n)); </script> 7 Time Complexity: O(n*S), where n is the number of elements in the array and S is the sum of all the elements. princiraj1992 vt_m ankthon itsok subset Arrays Dynamic Programming Recursion Arrays Dynamic Programming Recursion subset Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Introduction to Arrays 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Longest Common Subsequence | DP-4 Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16
[ { "code": null, "e": 24820, "s": 24792, "text": "\n13 May, 2021" }, { "code": null, "e": 24985, "s": 24820, "text": "Given an array ‘arr’ consisting of integers, the task is to find the number of subsets such that their sum is equal to zero. Empty subset should also be considered." }, { "code": null, "e": 24996, "s": 24985, "text": "Examples: " }, { "code": null, "e": 25322, "s": 24996, "text": "Input : arr[] = {2, 2, -4} Output : 2 All possible subsets: {} = 0 {2} = 2 {2} = 2 {-4} = -4 {2, 2} = 4 {2, -4} = -2 {2, -4} = -4 {2, 2, -4} = 0 Since, {} and {2, 2, -4} are only possible subsets with sum 0, ans will be 2.Input : arr[] = {1, 1, 1, 1} Output : 1 {} is the only possible subset with sum 0, thus ans equals 1. " }, { "code": null, "e": 25499, "s": 25322, "text": "One simple approach is to generate all possible subsets recursively and count the number of subsets with a sum equals to 0. The time complexity of this approach will be O(2^n)." }, { "code": null, "e": 25997, "s": 25499, "text": "A better approach will be using Dynamic programming. Let’s suppose the sum of all the elements we have selected up to index ‘i-1’ is ‘S’. So, starting from index ‘i’, we have to find the number of subsets of the sub-array{i, N-1} with sum equals -S. Let’s define dp[i][S]. It means the number of the subset of the subarray{i, N-1} of ‘arr’ with sum equals ‘-S’. If we are at ith index, we have two choices, i.e. to include it in the sum or leave it. Thus, the required recurrence relation becomes " }, { "code": null, "e": 26040, "s": 25997, "text": "dp[i][s] = dp[i+1][s+arr[i]] + dp[i+1][s] " }, { "code": null, "e": 26093, "s": 26040, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26097, "s": 26093, "text": "C++" }, { "code": null, "e": 26102, "s": 26097, "text": "Java" }, { "code": null, "e": 26110, "s": 26102, "text": "Python3" }, { "code": null, "e": 26113, "s": 26110, "text": "C#" }, { "code": null, "e": 26124, "s": 26113, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>#define maxSum 100#define arrSize 51using namespace std; // variable to store// states of dpint dp[arrSize][maxSum];bool visit[arrSize][maxSum]; // To find the number of subsets with sum equal to 0// Since S can be negative, we will maxSum// to it to make it positiveint SubsetCnt(int i, int s, int arr[], int n){ // Base cases if (i == n) { if (s == 0) return 1; else return 0; } // Returns the value if a state is already solved if (visit[i][s + maxSum]) return dp[i][s + maxSum]; // If the state is not visited, then continue visit[i][s + maxSum] = 1; // Recurrence relation dp[i][s + maxSum] = SubsetCnt(i + 1, s + arr[i], arr, n) + SubsetCnt(i + 1, s, arr, n); // Returning the value return dp[i][s + maxSum];} // Driver functionint main(){ int arr[] = { 2, 2, 2, -4, -4 }; int n = sizeof(arr) / sizeof(int); cout << SubsetCnt(0, 0, arr, n);}", "e": 27109, "s": 26124, "text": null }, { "code": "// Java implementation of above approachclass GFG{ static int maxSum = 100; static int arrSize = 51; // variable to store // states of dp static int[][] dp = new int[arrSize][maxSum]; static boolean[][] visit = new boolean[arrSize][maxSum]; // To find the number of subsets with sum equal to 0 // Since S can be negative, we will maxSum // to it to make it positive static int SubsetCnt(int i, int s, int arr[], int n) { // Base cases if (i == n) { if (s == 0) { return 1; } else { return 0; } } // Returns the value if a state is already solved if (visit[i][s + arrSize]) { return dp[i][s + arrSize]; } // If the state is not visited, then continue visit[i][s + arrSize] = true; // Recurrence relation dp[i][s + arrSize] = SubsetCnt(i + 1, s + arr[i], arr, n) + SubsetCnt(i + 1, s, arr, n); // Returning the value return dp[i][s + arrSize]; } // Driver function public static void main(String[] args) { int arr[] = {2, 2, 2, -4, -4}; int n = arr.length; System.out.println(SubsetCnt(0, 0, arr, n)); }} /* This code contributed by PrinciRaj1992 */", "e": 28455, "s": 27109, "text": null }, { "code": "# Python3 implementation of above approachimport numpy as np maxSum = 100arrSize = 51 # variable to store# states of dpdp = np.zeros((arrSize, maxSum));visit = np.zeros((arrSize, maxSum)); # To find the number of subsets# with sum equal to 0.# Since S can be negative,# we will maxSum to it# to make it positivedef SubsetCnt(i, s, arr, n) : # Base cases if (i == n) : if (s == 0) : return 1; else : return 0; # Returns the value # if a state is already solved if (visit[i][s + arrSize]) : return dp[i][s + arrSize]; # If the state is not visited, # then continue visit[i][s + arrSize] = 1; # Recurrence relation dp[i][s + arrSize ] = (SubsetCnt(i + 1, s + arr[i], arr, n) + SubsetCnt(i + 1, s, arr, n)); # Returning the value return dp[i][s + arrSize]; # Driver Codeif __name__ == \"__main__\" : arr = [ 2, 2, 2, -4, -4 ]; n = len(arr); print(SubsetCnt(0, 0, arr, n)); # This code is contributed by AnkitRai01", "e": 29492, "s": 28455, "text": null }, { "code": "// C# implementation of above approachusing System; class GFG{ static int maxSum = 100; static int arrSize = 51; // variable to store // states of dp static int [,]dp = new int[arrSize, maxSum]; static bool [,]visit = new bool[arrSize, maxSum]; // To find the number of subsets with sum equal to 0 // Since S can be negative, we will maxSum // to it to make it positive static int SubsetCnt(int i, int s, int []arr, int n) { // Base cases if (i == n) { if (s == 0) { return 1; } else { return 0; } } // Returns the value if a state is already solved if (visit[i, s + arrSize]) { return dp[i, s + arrSize]; } // If the state is not visited, then continue visit[i, s + arrSize] = true; // Recurrence relation dp[i, s + arrSize] = SubsetCnt(i + 1, s + arr[i], arr, n) + SubsetCnt(i + 1, s, arr, n); // Returning the value return dp[i,s + arrSize]; } // Driver code public static void Main() { int []arr = {2, 2, 2, -4, -4}; int n = arr.Length; Console.WriteLine(SubsetCnt(0, 0, arr, n)); }} // This code contributed by anuj_67..", "e": 30816, "s": 29492, "text": null }, { "code": "<script> var maxSum = 100var arrSize = 51 // variable to store// states of dpvar dp = Array.from(Array(arrSize), ()=> Array(maxSum));var visit = Array.from(Array(arrSize), ()=> Array(maxSum)); // To find the number of subsets with sum equal to 0// Since S can be negative, we will maxSum// to it to make it positivefunction SubsetCnt(i, s, arr, n){ // Base cases if (i == n) { if (s == 0) return 1; else return 0; } // Returns the value if a state is already solved if (visit[i][s + maxSum]) return dp[i][s + maxSum]; // If the state is not visited, then continue visit[i][s + maxSum] = 1; // Recurrence relation dp[i][s + maxSum] = SubsetCnt(i + 1, s + arr[i], arr, n) + SubsetCnt(i + 1, s, arr, n); // Returning the value return dp[i][s + maxSum];} // Driver functionvar arr = [2, 2, 2, -4, -4];var n = arr.length;document.write( SubsetCnt(0, 0, arr, n)); </script>", "e": 31787, "s": 30816, "text": null }, { "code": null, "e": 31789, "s": 31787, "text": "7" }, { "code": null, "e": 31902, "s": 31791, "text": "Time Complexity: O(n*S), where n is the number of elements in the array and S is the sum of all the elements. " }, { "code": null, "e": 31916, "s": 31902, "text": "princiraj1992" }, { "code": null, "e": 31921, "s": 31916, "text": "vt_m" }, { "code": null, "e": 31929, "s": 31921, "text": "ankthon" }, { "code": null, "e": 31935, "s": 31929, "text": "itsok" }, { "code": null, "e": 31942, "s": 31935, "text": "subset" }, { "code": null, "e": 31949, "s": 31942, "text": "Arrays" }, { "code": null, "e": 31969, "s": 31949, "text": "Dynamic Programming" }, { "code": null, "e": 31979, "s": 31969, "text": "Recursion" }, { "code": null, "e": 31986, "s": 31979, "text": "Arrays" }, { "code": null, "e": 32006, "s": 31986, "text": "Dynamic Programming" }, { "code": null, "e": 32016, "s": 32006, "text": "Recursion" }, { "code": null, "e": 32023, "s": 32016, "text": "subset" }, { "code": null, "e": 32121, "s": 32023, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32189, "s": 32121, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 32237, "s": 32189, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 32281, "s": 32237, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 32313, "s": 32281, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 32336, "s": 32313, "text": "Introduction to Arrays" }, { "code": null, "e": 32365, "s": 32336, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 32395, "s": 32365, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 32429, "s": 32395, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 32460, "s": 32429, "text": "Bellman–Ford Algorithm | DP-23" } ]
C++ 2-D Arrays | Set-1 | Practice | GeeksforGeeks
Given an 2-d array ofintegers havingN*Nelements, print the transpose of the array. Example 1: Input : arr[] = {{1,2,3}, {4,5,6}, {7,8,9}} and N = 3Output : 1 4 7 2 5 8 3 6 9Explanation:1 2 3 1 4 74 5 6 ----> 2 5 87 8 9 3 6 9Transpose of array. Example 2: Input : arr[ ] = {{1, 2}, {1, 2}} and N = 2 Output : 1 1 2 2 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 transpose() that takes a two-dimensionarray (arr), sizeOfArray (n), and return the transpose of the array. The driver code takes care of the printing. Expected Time Complexity:O(N2).Expected Auxiliary Space:O(1). Constraints:1 ≤ N ≤ 1000 ≤ A[i] ≤ 1000 0 harshscode1 week ago vector<vector<int>> b(n,vector<int>(n)); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { b[j][i]=a[i][j]; } } return b; +1 rishi1731 week ago vector<vector<int>> transpose(int a[][M], int n){ vector<vector<int>> b(n, vector<int>(n,0));//created a 2D vector and after //that created another vector of size n with all values as 0. for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { b[i][j]=a[j][i]; } } return b;} +2 0niharika22 months ago vector<vector<int>> b(n,vector<int>(n)); for(int i=0; i<n; i++){ for(int j=0; j<n; j++){ b[j][i]=a[i][j]; } } return b; 0 mohammadtanveer75402 months ago vector<vector<int>> transpose(int a[][M], int n) { // Code here vector< vector<int> > transpose; for(int i=0;i<M;i++) { vector<int> temp; for(int j=0;j<n;j++) { int x; x = a[j][i]; temp.push_back(x); } transpose.push_back(temp); } return transpose; } +4 naimatofficial104 months ago // Transport of 2D - array if (n==0) { return {{}}; } int row = n, col = n; vector<vector<int>> A_Transport(n, vector<int>(row)); for (int row = 0; row < n; row++) { for (int col = 0; col < n; col++) { A_Transport[col][row] = a[row][col]; } } // print the Transport of A return A_Transport; 0 mdseraj960885 months ago vector<vector<int>> transpose(int a[][M], int n){ //my code is here if(n==0){ return {{}}; } int row=n; int col=n; vector<vector<int>> v(n,vector<int>(row)); for(int i=0;i<row;i++){ for(int j=0;j<col;j++){ v[j][i]=a[i][j]; } } return v; } +1 badgujarsachin835 months ago vector<vector<int>> transpose(int a[][M], int n) { // Code here] if(n==0){ return {{}}; } int row=n; int col=n; vector<vector<int>> v(n,vector<int>(row)); for(int i=0;i<row;i++){ for(int j=0;j<col;j++){ v[j][i]=a[i][j]; } } return v; } -1 ankita12apr6 months ago int rows = n; if (rows == 0) return {{}}; int cols = n; vector<vector<int>> r(cols, vector<int>(rows)); for (int i = 0; i < rows; ++ i) { for (int j = 0; j < cols; ++ j) { r[j][i] = a[i][j]; } } return r; -2 pankajkumarravi6 months ago ************************ Correct java logic ************* int[][] transpose(int a[][], int n){ // Code here int [][] transpose = new int[n][n]; for (int i=0;i<n;i++){ for(int j=0;j<n;j++){ transpose[j][i] = a[i][j]; } } return transpose;} -1 sparshgoelt267 months ago Please change the test case on Compile and Run. 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": 309, "s": 226, "text": "Given an 2-d array ofintegers havingN*Nelements, print the transpose of the array." }, { "code": null, "e": 320, "s": 309, "text": "Example 1:" }, { "code": null, "e": 490, "s": 320, "text": "Input : arr[] = {{1,2,3}, {4,5,6}, {7,8,9}} and N = 3Output : 1 4 7 2 5 8 3 6 9Explanation:1 2 3 1 4 74 5 6 ----> 2 5 87 8 9 3 6 9Transpose of array." }, { "code": null, "e": 501, "s": 490, "text": "Example 2:" }, { "code": null, "e": 563, "s": 501, "text": "Input : arr[ ] = {{1, 2}, {1, 2}} and N = 2 Output : 1 1 2 2" }, { "code": null, "e": 846, "s": 563, "text": "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 transpose() that takes a two-dimensionarray (arr), sizeOfArray (n), and return the transpose of the array. The driver code takes care of the printing." }, { "code": null, "e": 908, "s": 846, "text": "Expected Time Complexity:O(N2).Expected Auxiliary Space:O(1)." }, { "code": null, "e": 947, "s": 908, "text": "Constraints:1 ≤ N ≤ 1000 ≤ A[i] ≤ 1000" }, { "code": null, "e": 949, "s": 947, "text": "0" }, { "code": null, "e": 970, "s": 949, "text": "harshscode1 week ago" }, { "code": null, "e": 1127, "s": 970, "text": "vector<vector<int>> b(n,vector<int>(n)); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { b[j][i]=a[i][j]; } } return b;" }, { "code": null, "e": 1130, "s": 1127, "text": "+1" }, { "code": null, "e": 1149, "s": 1130, "text": "rishi1731 week ago" }, { "code": null, "e": 1470, "s": 1149, "text": "vector<vector<int>> transpose(int a[][M], int n){ vector<vector<int>> b(n, vector<int>(n,0));//created a 2D vector and after //that created another vector of size n with all values as 0. for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { b[i][j]=a[j][i]; } } return b;}" }, { "code": null, "e": 1475, "s": 1472, "text": "+2" }, { "code": null, "e": 1498, "s": 1475, "text": "0niharika22 months ago" }, { "code": null, "e": 1658, "s": 1498, "text": "vector<vector<int>> b(n,vector<int>(n));\n for(int i=0; i<n; i++){\n for(int j=0; j<n; j++){\n b[j][i]=a[i][j];\n }\n }\n return b;" }, { "code": null, "e": 1660, "s": 1658, "text": "0" }, { "code": null, "e": 1692, "s": 1660, "text": "mohammadtanveer75402 months ago" }, { "code": null, "e": 2091, "s": 1692, "text": "vector<vector<int>> transpose(int a[][M], int n)\n{\n // Code here\n vector< vector<int> > transpose;\n \n for(int i=0;i<M;i++)\n {\n vector<int> temp;\n \n for(int j=0;j<n;j++)\n {\n int x; \n x = a[j][i];\n \n temp.push_back(x);\n }\n \n transpose.push_back(temp);\n }\n \n return transpose;\n \n}\n" }, { "code": null, "e": 2094, "s": 2091, "text": "+4" }, { "code": null, "e": 2123, "s": 2094, "text": "naimatofficial104 months ago" }, { "code": null, "e": 2599, "s": 2123, "text": "// Transport of 2D - array if (n==0) { return {{}}; } int row = n, col = n; vector<vector<int>> A_Transport(n, vector<int>(row)); for (int row = 0; row < n; row++) { for (int col = 0; col < n; col++) { A_Transport[col][row] = a[row][col]; } } // print the Transport of A return A_Transport; " }, { "code": null, "e": 2601, "s": 2599, "text": "0" }, { "code": null, "e": 2626, "s": 2601, "text": "mdseraj960885 months ago" }, { "code": null, "e": 2914, "s": 2626, "text": "vector<vector<int>> transpose(int a[][M], int n){ //my code is here if(n==0){ return {{}}; } int row=n; int col=n; vector<vector<int>> v(n,vector<int>(row)); for(int i=0;i<row;i++){ for(int j=0;j<col;j++){ v[j][i]=a[i][j]; } } return v; }" }, { "code": null, "e": 2917, "s": 2914, "text": "+1" }, { "code": null, "e": 2946, "s": 2917, "text": "badgujarsachin835 months ago" }, { "code": null, "e": 3263, "s": 2946, "text": "vector<vector<int>> transpose(int a[][M], int n)\n{\n // Code here]\n if(n==0){\n return {{}};\n }\n int row=n;\n int col=n;\n vector<vector<int>> v(n,vector<int>(row));\n for(int i=0;i<row;i++){\n for(int j=0;j<col;j++){\n v[j][i]=a[i][j];\n }\n }\n \n return v;\n \n}\n" }, { "code": null, "e": 3266, "s": 3263, "text": "-1" }, { "code": null, "e": 3290, "s": 3266, "text": "ankita12apr6 months ago" }, { "code": null, "e": 3582, "s": 3290, "text": " int rows = n; if (rows == 0) return {{}}; int cols = n; vector<vector<int>> r(cols, vector<int>(rows)); for (int i = 0; i < rows; ++ i) { for (int j = 0; j < cols; ++ j) { r[j][i] = a[i][j]; } } return r;" }, { "code": null, "e": 3585, "s": 3582, "text": "-2" }, { "code": null, "e": 3613, "s": 3585, "text": "pankajkumarravi6 months ago" }, { "code": null, "e": 3671, "s": 3613, "text": "************************ Correct java logic *************" }, { "code": null, "e": 3892, "s": 3673, "text": "int[][] transpose(int a[][], int n){ // Code here int [][] transpose = new int[n][n]; for (int i=0;i<n;i++){ for(int j=0;j<n;j++){ transpose[j][i] = a[i][j]; } } return transpose;}" }, { "code": null, "e": 3895, "s": 3892, "text": "-1" }, { "code": null, "e": 3921, "s": 3895, "text": "sparshgoelt267 months ago" }, { "code": null, "e": 3969, "s": 3921, "text": "Please change the test case on Compile and Run." }, { "code": null, "e": 4115, "s": 3969, "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": 4151, "s": 4115, "text": " Login to access your submissions. " }, { "code": null, "e": 4161, "s": 4151, "text": "\nProblem\n" }, { "code": null, "e": 4171, "s": 4161, "text": "\nContest\n" }, { "code": null, "e": 4234, "s": 4171, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4382, "s": 4234, "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": 4590, "s": 4382, "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": 4696, "s": 4590, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to use Hidden Component in ReactJS?
20 Jun, 2022 Hidden component quickly and responsively toggles the visibility value of components and more with the hidden utilities. Material UI for React has this component available for us and it is very easy to integrate. We can use the Hidden component in ReactJS using the following approach. Creating React Application And Installing Module: Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the material-ui modules using the following command: npm install @material-ui/core Project Structure: It will look like the following. Project Structure Filename-App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react';import { makeStyles } from '@material-ui/core/styles';import Hidden from '@material-ui/core/Hidden';import Paper from '@material-ui/core/Paper'; const App = () => { const useStyles = makeStyles((theme) => ({ paper: { flex: '1 0 auto', margin: theme.spacing(1), padding: theme.spacing(2), color: theme.palette.text.secondary, textAlign: 'center', }, })); const classes = useStyles(); return ( <div style={{ display: 'flex', flexWrap: 'wrap', }}> <div style={{ width: '100%', float: 'left' }}> <h3>How to use Hidden Component in ReactJS?</h3> <br /> </div> <Hidden mdDown> <Paper className={classes.paper}>Small Down</Paper> </Hidden> <Hidden smDown> <Paper className={classes.paper}>Medium Down</Paper> </Hidden> <Hidden xsDown> <Paper className={classes.paper}>Large Down</Paper> </Hidden> </div> );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Now are you start reducing the size of your window, you will notice that the first box will get hidden, followed by the next two. This is how Hidden Component works in ReactJS. JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Jun, 2022" }, { "code": null, "e": 314, "s": 28, "text": "Hidden component quickly and responsively toggles the visibility value of components and more with the hidden utilities. Material UI for React has this component available for us and it is very easy to integrate. We can use the Hidden component in ReactJS using the following approach." }, { "code": null, "e": 364, "s": 314, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 428, "s": 364, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 460, "s": 428, "text": "npx create-react-app foldername" }, { "code": null, "e": 560, "s": 460, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 574, "s": 560, "text": "cd foldername" }, { "code": null, "e": 683, "s": 574, "text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:" }, { "code": null, "e": 713, "s": 683, "text": "npm install @material-ui/core" }, { "code": null, "e": 765, "s": 713, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 783, "s": 765, "text": "Project Structure" }, { "code": null, "e": 921, "s": 783, "text": "Filename-App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 928, "s": 921, "text": "App.js" }, { "code": "import React from 'react';import { makeStyles } from '@material-ui/core/styles';import Hidden from '@material-ui/core/Hidden';import Paper from '@material-ui/core/Paper'; const App = () => { const useStyles = makeStyles((theme) => ({ paper: { flex: '1 0 auto', margin: theme.spacing(1), padding: theme.spacing(2), color: theme.palette.text.secondary, textAlign: 'center', }, })); const classes = useStyles(); return ( <div style={{ display: 'flex', flexWrap: 'wrap', }}> <div style={{ width: '100%', float: 'left' }}> <h3>How to use Hidden Component in ReactJS?</h3> <br /> </div> <Hidden mdDown> <Paper className={classes.paper}>Small Down</Paper> </Hidden> <Hidden smDown> <Paper className={classes.paper}>Medium Down</Paper> </Hidden> <Hidden xsDown> <Paper className={classes.paper}>Large Down</Paper> </Hidden> </div> );} export default App;", "e": 1906, "s": 928, "text": null }, { "code": null, "e": 2019, "s": 1906, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 2029, "s": 2019, "text": "npm start" }, { "code": null, "e": 2128, "s": 2029, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 2305, "s": 2128, "text": "Now are you start reducing the size of your window, you will notice that the first box will get hidden, followed by the next two. This is how Hidden Component works in ReactJS." }, { "code": null, "e": 2316, "s": 2305, "text": "JavaScript" }, { "code": null, "e": 2324, "s": 2316, "text": "ReactJS" }, { "code": null, "e": 2341, "s": 2324, "text": "Web Technologies" } ]
Python | Maximum and Minimum in a Set
28 Dec, 2017 In this article, we will learn how to get the maximum and minimum element in a set in Python, using the built-in functions of Python.Examples: Input : set = ([8, 16, 24, 1, 25, 3, 10, 65, 55]) Output : max is 65 Input : set = ([4, 12, 10, 9, 4, 13]) Output : min is 4 max() in a Set The built-in function max() in Python is used to get the maximum of all the elements in a set. # Python code to get the maximum element from a setdef MAX(sets): return (max(sets)) # Driver Codesets = set([8, 16, 24, 1, 25, 3, 10, 65, 55])print(MAX(sets)) Output: 65 min() in a Set # Python code to get the minimum element from a setdef MIN(sets): return (min(sets)) # Driver Codesets = set([4, 12, 10, 9, 4, 13])print(MIN(sets)) Output: 4 python-set Python python-set Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n28 Dec, 2017" }, { "code": null, "e": 196, "s": 53, "text": "In this article, we will learn how to get the maximum and minimum element in a set in Python, using the built-in functions of Python.Examples:" }, { "code": null, "e": 323, "s": 196, "text": "Input : set = ([8, 16, 24, 1, 25, 3, 10, 65, 55])\nOutput : max is 65\n\nInput : set = ([4, 12, 10, 9, 4, 13])\nOutput : min is 4\n" }, { "code": null, "e": 338, "s": 323, "text": "max() in a Set" }, { "code": null, "e": 433, "s": 338, "text": "The built-in function max() in Python is used to get the maximum of all the elements in a set." }, { "code": "# Python code to get the maximum element from a setdef MAX(sets): return (max(sets)) # Driver Codesets = set([8, 16, 24, 1, 25, 3, 10, 65, 55])print(MAX(sets))", "e": 601, "s": 433, "text": null }, { "code": null, "e": 609, "s": 601, "text": "Output:" }, { "code": null, "e": 613, "s": 609, "text": "65\n" }, { "code": null, "e": 628, "s": 613, "text": "min() in a Set" }, { "code": "# Python code to get the minimum element from a setdef MIN(sets): return (min(sets)) # Driver Codesets = set([4, 12, 10, 9, 4, 13])print(MIN(sets))", "e": 784, "s": 628, "text": null }, { "code": null, "e": 792, "s": 784, "text": "Output:" }, { "code": null, "e": 795, "s": 792, "text": "4\n" }, { "code": null, "e": 806, "s": 795, "text": "python-set" }, { "code": null, "e": 813, "s": 806, "text": "Python" }, { "code": null, "e": 824, "s": 813, "text": "python-set" } ]
Generate all palindromic numbers less than n
24 Jan, 2022 Find all numbers less than n, which are palindromic. Numbers can be printed in any order. Examples : Input : n = 12 Output : 1, 2, 3, 4, 5, 6, 7, 8, 9, 11 Input : n = 104 Output : 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101 [Note that below program prints these numbers in different order] Brute Force: We check all the numbers from 1 to n whether its decimal representation is palindrome or not. Efficient Approach: We start from 1 and create palindromes of odd digit and even digits up to n. For every number (starting from 1), we append its reverse at end if we need even length palindrome numbers. For odd length palindrome, we append reverse of all digits except last one. C++ Java Python3 C# PHP Javascript // A C++ program to generate palindromic numbers// less than n.#include <iostream>using namespace std; // A utility for creating palindromeint createPalindrome(int input, int b, bool isOdd){ int n = input; int palin = input; // checks if number of digits is odd or even // if odd then neglect the last digit of input in // finding reverse as in case of odd number of // digits middle element occur once if (isOdd) n /= b; // Creates palindrome by just appending reverse // of number to itself while (n > 0) { palin = palin * b + (n % b); n /= b; } return palin;} // Function to print decimal palindromic numbervoid generatePalindromes(int n){ int number; // Run two times for odd and even length palindromes for (int j = 0; j < 2; j++) { // Creates palindrome numbers with first half as i. // Value of j decided whether we need an odd length // of even length palindrome. int i = 1; while ((number = createPalindrome(i, 10, j % 2)) < n) { cout << number << " "; i++; } }} // Driver Program to test above functionint main(){ int n = 104; generatePalindromes(n); return 0;} // A Java program to generate palindromic// numbers less than n.class GFG { // A utility for creating palindromestatic int createPalindrome(int input, int b, int isOdd) { int n = input; int palin = input; // checks if number of digits is odd or even // if odd then neglect the last digit of input in // finding reverse as in case of odd number of // digits middle element occur once if (isOdd == 1) n /= b; // Creates palindrome by just appending reverse // of number to itself while (n > 0) { palin = palin * b + (n % b); n /= b; } return palin;} // Function to print decimal// palindromic numberstatic void generatePalindromes(int n) { int number; // Run two times for odd and even // length palindromes for (int j = 0; j < 2; j++) { // Creates palindrome numbers with first // half as i. Value of j decided whether // we need an odd length of even length // palindrome. int i = 1; while ((number = createPalindrome(i, 10, j % 2)) < n) { System.out.print(number + " "); i++; } }} // Driver codepublic static void main(String[] args) { int n = 104; generatePalindromes(n);}}// This code is contributed by Anant Agarwal. # Generate all palindromic numbers less than n# A Python program to generate palindromic numbers# less than n.def createPalindrome(inp, b, isOdd): n = inp palin = inp # checks if number of digits is odd or even # if odd then neglect the last digit of input in # finding reverse as in case of odd number of # digits middle element occur once if (isOdd): n = n // b # Creates palindrome by just appending reverse # of number to itself while (n > 0): palin = palin * b + (n % b) n = n // b return palin # Function to print decimal palindromic numberdef generatePalindromes(n): # Run two times for odd and even length palindromes for j in range(2): # Creates palindrome numbers with first half as i. # Value of j decided whether we need an odd length # of even length palindrome. i = 1 while (createPalindrome(i, 10, j % 2) < n): print (createPalindrome(i, 10, j % 2),end=" ") i = i + 1 # Driver Program to test above functionn = 104generatePalindromes(n) #This code is contributed by Afzal Ansari // A C# program to generate palindromic// numbers less than n.using System; class GFG { // A utility for creating palindromestatic int createPalindrome(int input, int b, int isOdd){ int n = input; int palin = input; // checks if number of digits is odd // or even if odd then neglect the // last digit of input in finding reverse // as in case of odd number of digits // middle element occur once if (isOdd == 1) n /= b; // Creates palindrome by just appending // reverse of number to itself while (n > 0) { palin = palin * b + (n % b); n /= b; } return palin;} // Function to print decimal// palindromic numberstatic void generatePalindromes(int n){ int number; // Run two times for odd and even // length palindromes for (int j = 0; j < 2; j++) { // Creates palindrome numbers with first // half as i. Value of j decided whether // we need an odd length of even length // palindrome. int i = 1; while ((number = createPalindrome(i, 10, j % 2)) < n) { Console.Write(number + " "); i++; } }} // Driver Codepublic static void Main(){ int n = 104; generatePalindromes(n);}} // This code is contributed by Nitin Mittal. <?php// PHP program to generate// palindromic numbers less than n. // A utility function for// creating palindromefunction createPalindrome($input, $b, $isOdd){ $n = $input; $palin = $input; // checks if number of digits is // odd or even if odd then neglect // the last digit of input in finding // reverse as in case of odd number // of digits middle element occur once if ($isOdd) $n = intval($n / $b); // Creates palindrome by just appending // reverse of number to itself while ($n > 0) { $palin = $palin * $b + intval($n % $b); $n = intval($n / $b); } return $palin;} // Function to print decimal// palindromic numberfunction generatePalindromes($n){ $number = 0; // Run two times for odd and // even length palindromes for ($j = 0; $j < 2; $j++) { // Creates palindrome numbers // with first half as i. Value // of j decided whether we need // an odd length of even length // palindrome. $i = 1; while (($number = createPalindrome($i, 10, $j % 2)) < $n) { echo $number . " "; $i++; } }} // Driver Code$n = 104;generatePalindromes($n); // This code is contributed by Sam007?> <script> // A Javascript program to generate palindromic // numbers less than n. // A utility for creating palindrome function createPalindrome(input, b, isOdd) { let n = input; let palin = input; // checks if number of digits is odd // or even if odd then neglect the // last digit of input in finding reverse // as in case of odd number of digits // middle element occur once if (isOdd == 1) n = parseInt(n / b, 10); // Creates palindrome by just appending // reverse of number to itself while (n > 0) { palin = palin * b + (n % b); n = parseInt(n / b, 10); } return palin; } // Function to print decimal // palindromic number function generatePalindromes(n) { let number; // Run two times for odd and even // length palindromes for (let j = 0; j < 2; j++) { // Creates palindrome numbers with first // half as i. Value of j decided whether // we need an odd length of even length // palindrome. let i = 1; while ((number = createPalindrome(i, 10, j % 2)) < n) { document.write(number + " "); i++; } } } let n = 104; generatePalindromes(n); // This code is contributed by divyesh072019.</script> Output : 11 22 33 44 55 66 77 88 99 1 2 3 4 5 6 7 8 9 101 Note that the above program doesn’t print output in sorted order. To print in sorted order, we can store palindromes in a vector and sort it, and don’t forget to use the required header file. This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal Sam007 vaibhav29498 divyesh072019 punnapavankumar9 amartyaghoshgfg Amazon number-digits palindrome Mathematical Amazon Mathematical palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Jan, 2022" }, { "code": null, "e": 144, "s": 54, "text": "Find all numbers less than n, which are palindromic. Numbers can be printed in any order." }, { "code": null, "e": 156, "s": 144, "text": "Examples : " }, { "code": null, "e": 382, "s": 156, "text": "Input : n = 12\nOutput : 1, 2, 3, 4, 5, 6, 7, 8, 9, 11\n\nInput : n = 104\nOutput : 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, \n 22, 33, 44, 55, 66, 77, 88, 99, 101\n[Note that below program prints these numbers\n in different order]\n " }, { "code": null, "e": 490, "s": 382, "text": "Brute Force: We check all the numbers from 1 to n whether its decimal representation is palindrome or not. " }, { "code": null, "e": 772, "s": 490, "text": "Efficient Approach: We start from 1 and create palindromes of odd digit and even digits up to n. For every number (starting from 1), we append its reverse at end if we need even length palindrome numbers. For odd length palindrome, we append reverse of all digits except last one. " }, { "code": null, "e": 776, "s": 772, "text": "C++" }, { "code": null, "e": 781, "s": 776, "text": "Java" }, { "code": null, "e": 789, "s": 781, "text": "Python3" }, { "code": null, "e": 792, "s": 789, "text": "C#" }, { "code": null, "e": 796, "s": 792, "text": "PHP" }, { "code": null, "e": 807, "s": 796, "text": "Javascript" }, { "code": "// A C++ program to generate palindromic numbers// less than n.#include <iostream>using namespace std; // A utility for creating palindromeint createPalindrome(int input, int b, bool isOdd){ int n = input; int palin = input; // checks if number of digits is odd or even // if odd then neglect the last digit of input in // finding reverse as in case of odd number of // digits middle element occur once if (isOdd) n /= b; // Creates palindrome by just appending reverse // of number to itself while (n > 0) { palin = palin * b + (n % b); n /= b; } return palin;} // Function to print decimal palindromic numbervoid generatePalindromes(int n){ int number; // Run two times for odd and even length palindromes for (int j = 0; j < 2; j++) { // Creates palindrome numbers with first half as i. // Value of j decided whether we need an odd length // of even length palindrome. int i = 1; while ((number = createPalindrome(i, 10, j % 2)) < n) { cout << number << \" \"; i++; } }} // Driver Program to test above functionint main(){ int n = 104; generatePalindromes(n); return 0;}", "e": 2037, "s": 807, "text": null }, { "code": "// A Java program to generate palindromic// numbers less than n.class GFG { // A utility for creating palindromestatic int createPalindrome(int input, int b, int isOdd) { int n = input; int palin = input; // checks if number of digits is odd or even // if odd then neglect the last digit of input in // finding reverse as in case of odd number of // digits middle element occur once if (isOdd == 1) n /= b; // Creates palindrome by just appending reverse // of number to itself while (n > 0) { palin = palin * b + (n % b); n /= b; } return palin;} // Function to print decimal// palindromic numberstatic void generatePalindromes(int n) { int number; // Run two times for odd and even // length palindromes for (int j = 0; j < 2; j++) { // Creates palindrome numbers with first // half as i. Value of j decided whether // we need an odd length of even length // palindrome. int i = 1; while ((number = createPalindrome(i, 10, j % 2)) < n) { System.out.print(number + \" \"); i++; } }} // Driver codepublic static void main(String[] args) { int n = 104; generatePalindromes(n);}}// This code is contributed by Anant Agarwal.", "e": 3291, "s": 2037, "text": null }, { "code": "# Generate all palindromic numbers less than n# A Python program to generate palindromic numbers# less than n.def createPalindrome(inp, b, isOdd): n = inp palin = inp # checks if number of digits is odd or even # if odd then neglect the last digit of input in # finding reverse as in case of odd number of # digits middle element occur once if (isOdd): n = n // b # Creates palindrome by just appending reverse # of number to itself while (n > 0): palin = palin * b + (n % b) n = n // b return palin # Function to print decimal palindromic numberdef generatePalindromes(n): # Run two times for odd and even length palindromes for j in range(2): # Creates palindrome numbers with first half as i. # Value of j decided whether we need an odd length # of even length palindrome. i = 1 while (createPalindrome(i, 10, j % 2) < n): print (createPalindrome(i, 10, j % 2),end=\" \") i = i + 1 # Driver Program to test above functionn = 104generatePalindromes(n) #This code is contributed by Afzal Ansari", "e": 4410, "s": 3291, "text": null }, { "code": "// A C# program to generate palindromic// numbers less than n.using System; class GFG { // A utility for creating palindromestatic int createPalindrome(int input, int b, int isOdd){ int n = input; int palin = input; // checks if number of digits is odd // or even if odd then neglect the // last digit of input in finding reverse // as in case of odd number of digits // middle element occur once if (isOdd == 1) n /= b; // Creates palindrome by just appending // reverse of number to itself while (n > 0) { palin = palin * b + (n % b); n /= b; } return palin;} // Function to print decimal// palindromic numberstatic void generatePalindromes(int n){ int number; // Run two times for odd and even // length palindromes for (int j = 0; j < 2; j++) { // Creates palindrome numbers with first // half as i. Value of j decided whether // we need an odd length of even length // palindrome. int i = 1; while ((number = createPalindrome(i, 10, j % 2)) < n) { Console.Write(number + \" \"); i++; } }} // Driver Codepublic static void Main(){ int n = 104; generatePalindromes(n);}} // This code is contributed by Nitin Mittal.", "e": 5754, "s": 4410, "text": null }, { "code": "<?php// PHP program to generate// palindromic numbers less than n. // A utility function for// creating palindromefunction createPalindrome($input, $b, $isOdd){ $n = $input; $palin = $input; // checks if number of digits is // odd or even if odd then neglect // the last digit of input in finding // reverse as in case of odd number // of digits middle element occur once if ($isOdd) $n = intval($n / $b); // Creates palindrome by just appending // reverse of number to itself while ($n > 0) { $palin = $palin * $b + intval($n % $b); $n = intval($n / $b); } return $palin;} // Function to print decimal// palindromic numberfunction generatePalindromes($n){ $number = 0; // Run two times for odd and // even length palindromes for ($j = 0; $j < 2; $j++) { // Creates palindrome numbers // with first half as i. Value // of j decided whether we need // an odd length of even length // palindrome. $i = 1; while (($number = createPalindrome($i, 10, $j % 2)) < $n) { echo $number . \" \"; $i++; } }} // Driver Code$n = 104;generatePalindromes($n); // This code is contributed by Sam007?>", "e": 7087, "s": 5754, "text": null }, { "code": "<script> // A Javascript program to generate palindromic // numbers less than n. // A utility for creating palindrome function createPalindrome(input, b, isOdd) { let n = input; let palin = input; // checks if number of digits is odd // or even if odd then neglect the // last digit of input in finding reverse // as in case of odd number of digits // middle element occur once if (isOdd == 1) n = parseInt(n / b, 10); // Creates palindrome by just appending // reverse of number to itself while (n > 0) { palin = palin * b + (n % b); n = parseInt(n / b, 10); } return palin; } // Function to print decimal // palindromic number function generatePalindromes(n) { let number; // Run two times for odd and even // length palindromes for (let j = 0; j < 2; j++) { // Creates palindrome numbers with first // half as i. Value of j decided whether // we need an odd length of even length // palindrome. let i = 1; while ((number = createPalindrome(i, 10, j % 2)) < n) { document.write(number + \" \"); i++; } } } let n = 104; generatePalindromes(n); // This code is contributed by divyesh072019.</script>", "e": 8536, "s": 7087, "text": null }, { "code": null, "e": 8546, "s": 8536, "text": "Output : " }, { "code": null, "e": 8596, "s": 8546, "text": "11 22 33 44 55 66 77 88 99 1 2 3 4 5 6 7 8 9 101 " }, { "code": null, "e": 8788, "s": 8596, "text": "Note that the above program doesn’t print output in sorted order. To print in sorted order, we can store palindromes in a vector and sort it, and don’t forget to use the required header file." }, { "code": null, "e": 9224, "s": 8788, "text": "This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 9237, "s": 9224, "text": "nitin mittal" }, { "code": null, "e": 9244, "s": 9237, "text": "Sam007" }, { "code": null, "e": 9257, "s": 9244, "text": "vaibhav29498" }, { "code": null, "e": 9271, "s": 9257, "text": "divyesh072019" }, { "code": null, "e": 9288, "s": 9271, "text": "punnapavankumar9" }, { "code": null, "e": 9304, "s": 9288, "text": "amartyaghoshgfg" }, { "code": null, "e": 9311, "s": 9304, "text": "Amazon" }, { "code": null, "e": 9325, "s": 9311, "text": "number-digits" }, { "code": null, "e": 9336, "s": 9325, "text": "palindrome" }, { "code": null, "e": 9349, "s": 9336, "text": "Mathematical" }, { "code": null, "e": 9356, "s": 9349, "text": "Amazon" }, { "code": null, "e": 9369, "s": 9356, "text": "Mathematical" }, { "code": null, "e": 9380, "s": 9369, "text": "palindrome" } ]
Maximum possible XOR of every element in an array with another array
08 Jul, 2021 Two arrays A and B consisting of N elements are given. The task is to compute the maximum possible XOR of every element in array A with array B. Examples: Input : A : 7 3 9 12 B : 1 3 5 2 Output : 6 6 12 15 Explanation : 1 xor 7 = 6, 5 xor 3 = 6, 5 xor 9 = 12, 3 xor 12 = 15. A naive approach to solve this problem would be to check every element of array A with every other element of array B and print the maximum xor.Time Complexity : O(n^2) An efficient solution is to use Trie Data Structure. We maintain a Trie for the binary representation of all elements in array B. Now, for every element of A, we find the maximum xor in trie. Let’s say our number A[i] is {b1, b2...bn}, where b1, b2...bn are binary bits. We start from b1. Now for the xor to be maximum, we’ll try to make most significant bit 1 after performing the xor. So, if b1 is 0, we’ll need a 1 and vice versa. In the trie, we go to the required bit side. If favourable option is not there, we’ll go other side. Doing this all over, we’ll get the maximum XOR possible. Below is the implementation C++ Java Python3 C# Javascript // C++ code to find the maximum possible X-OR of// every array element with another array#include<bits/stdc++.h>using namespace std; // Structure of Trie DSstruct trie{ int value; trie *child[2];}; // Function to initialise a Trie Nodetrie * get(){ trie * root = new trie; root -> value = 0; root -> child[0] = NULL; root -> child[1] = NULL; return root;} // Computing max xorint max_xor(trie * root, int key){ trie * temp = root; // Checking for all bits in integer range for (int i = 31; i >= 0; i--) { // Current bit in the number bool current_bit = ( key & ( 1 << i) ); // Traversing Trie for different bit, if found if (temp -> child[1 - current_bit] != NULL) temp = temp -> child[1 - current_bit]; // Traversing Trie for same bit else temp = temp -> child[current_bit]; } // Returning xor value of maximum bit difference // value. Thus, we get maximum xor value return (key ^ temp -> value);} // Inserting B[] in Trievoid insert(trie * root, int key){ trie * temp = root; // Storing 31 bits as integer representation for (int i = 31; i >= 0; i--) { // Current bit in the number bool current_bit = key & (1 << i); // New node required if (temp -> child[current_bit] == NULL) temp -> child[current_bit] = get(); // Traversing in Trie temp = temp -> child[current_bit]; } // Assigning value to the leaf Node temp -> value = key;} int main(){ int A[] = {7, 3, 9, 12}; int B[] = {1, 3, 5, 2}; int N = sizeof(A)/sizeof(A[0]); // Forming Trie for B[] trie * root = get(); for (int i = 0; i < N; i++) insert(root, B[i]); for (int i = 0; i < N; i++) cout << max_xor(root, A[i]) << endl; return 0;} // Java code to find the maximum possible X-OR of// every array element with another arrayimport java.util.*; class GFG{ // Structure of Trie DSstatic class trie{ int value; trie []child = new trie[2];}; // Function to initialise a Trie Nodestatic trie get(){ trie root = new trie(); root.value = 0; root.child[0] = null; root.child[1] = null; return root;} // Computing max xorstatic int max_xor(trie root, int key){ trie temp = root; // Checking for all bits in integer range for (int i = 31; i >= 0; i--) { // Current bit in the number int current_bit = (key & (1 << i)); if(current_bit > 0) current_bit = 1; // Traversing Trie for different bit, if found if (temp.child[1 - current_bit] != null) temp = temp.child[1 - current_bit]; // Traversing Trie for same bit else temp = temp.child[current_bit]; } // Returning xor value of maximum bit difference // value. Thus, we get maximum xor value return (key ^ temp.value);} // Inserting B[] in Triestatic void insert(trie root, int key){ trie temp = root; // Storing 31 bits as integer representation for (int i = 31; i >= 0; i--) { // Current bit in the number int current_bit = key & (1 << i); if(current_bit > 0) current_bit = 1; //System.out.println(current_bit); // New node required if (temp.child[current_bit] == null) temp.child[current_bit] = get(); // Traversing in Trie temp = temp.child[current_bit]; } // Assigning value to the leaf Node temp.value = key;} // Driver Codepublic static void main(String[] args){ int A[] = {7, 3, 9, 12}; int B[] = {1, 3, 5, 2}; int N = A.length; // Forming Trie for B[] trie root = get(); for (int i = 0; i < N; i++) insert(root, B[i]); for (int i = 0; i < N; i++) System.out.println(max_xor(root, A[i]));}} // This code is contributed by 29AjayKumar # Python3 code to find the maximum# possible X-OR of every array# element with another array # Structure of Trie DSclass trie: def __init__(self, value: int = 0) -> None: self.value = value self.child = [None] * 2 # Function to initialise a Trie Nodedef get() -> trie: root = trie() root.value = 0 root.child[0] = None root.child[1] = None return root # Computing max xordef max_xor(root: trie, key: int) -> int: temp = root # Checking for all bits in integer range for i in range(31, -1, -1): # Current bit in the number current_bit = (key & (1 << i)) if (current_bit > 0): current_bit = 1 # Traversing Trie for different bit, if found if (temp.child[1 - current_bit] != None): temp = temp.child[1 - current_bit] # Traversing Trie for same bit else: temp = temp.child[current_bit] # Returning xor value of maximum bit difference # value. Thus, we get maximum xor value return (key ^ temp.value) # Inserting B[] in Triedef insert(root: trie, key: int) -> None: temp = root # Storing 31 bits as integer representation for i in range(31, -1, -1): # Current bit in the number current_bit = key & (1 << i) if (current_bit > 0): current_bit = 1 # New node required if (temp.child[current_bit] == None): temp.child[current_bit] = get() # Traversing in Trie temp = temp.child[current_bit] # Assigning value to the leaf Node temp.value = key # Driver Codeif __name__ == "__main__": A = [ 7, 3, 9, 12 ] B = [ 1, 3, 5, 2 ] N = len(A) # Forming Trie for B[] root = get() for i in range(N): insert(root, B[i]) for i in range(N): print(max_xor(root, A[i])) # This code is contributed by sanjeev2552 // C# code to find the maximum possible X-OR of// every array element with another arrayusing System; class GFG{ // Structure of Trie DSclass trie{ public int value; public trie []child = new trie[2];}; // Function to initialise a Trie Nodestatic trie get(){ trie root = new trie(); root.value = 0; root.child[0] = null; root.child[1] = null; return root;} // Computing max xorstatic int max_xor(trie root, int key){ trie temp = root; // Checking for all bits in integer range for (int i = 31; i >= 0; i--) { // Current bit in the number int current_bit = (key & (1 << i)); if(current_bit > 0) current_bit = 1; // Traversing Trie for different bit, if found if (temp.child[1 - current_bit] != null) temp = temp.child[1 - current_bit]; // Traversing Trie for same bit else temp = temp.child[current_bit]; } // Returning xor value of maximum bit difference // value. Thus, we get maximum xor value return (key ^ temp.value);} // Inserting B[] in Triestatic void insert(trie root, int key){ trie temp = root; // Storing 31 bits as integer representation for (int i = 31; i >= 0; i--) { // Current bit in the number int current_bit = key & (1 << i); if(current_bit > 0) current_bit = 1; // System.out.println(current_bit); // New node required if (temp.child[current_bit] == null) temp.child[current_bit] = get(); // Traversing in Trie temp = temp.child[current_bit]; } // Assigning value to the leaf Node temp.value = key;} // Driver Codepublic static void Main(String[] args){ int []A = {7, 3, 9, 12}; int []B = {1, 3, 5, 2}; int N = A.Length; // Forming Trie for B[] trie root = get(); for (int i = 0; i < N; i++) insert(root, B[i]); for (int i = 0; i < N; i++) Console.WriteLine(max_xor(root, A[i]));}} // This code is contributed by 29AjayKumar <script> // JavaScript code to find the maximum possible X-OR of// every array element with another array // Structure of Trie DSclass trie{ constructor() { this.value=0; this.child = new Array(2); }} // Function to initialise a Trie Node function get(){ let root = new trie(); root.value = 0; root.child[0] = null; root.child[1] = null; return root;} // Computing max xorfunction max_xor(root,key){ let temp = root; // Checking for all bits in integer range for (let i = 31; i >= 0; i--) { // Current bit in the number let current_bit = (key & (1 << i)); if(current_bit > 0) current_bit = 1; // Traversing Trie for different bit, if found if (temp.child[1 - current_bit] != null) temp = temp.child[1 - current_bit]; // Traversing Trie for same bit else temp = temp.child[current_bit]; } // Returning xor value of maximum bit difference // value. Thus, we get maximum xor value return (key ^ temp.value);} // Inserting B[] in Triefunction insert(root,key){ let temp = root; // Storing 31 bits as integer representation for (let i = 31; i >= 0; i--) { // Current bit in the number let current_bit = key & (1 << i); if(current_bit > 0) current_bit = 1; //System.out.println(current_bit); // New node required if (temp.child[current_bit] == null) temp.child[current_bit] = get(); // Traversing in Trie temp = temp.child[current_bit]; } // Assigning value to the leaf Node temp.value = key;} // Driver Codelet A=[7, 3, 9, 12];let B=[1, 3, 5, 2]; let N = A.length;// Forming Trie for B[]let root = get();for (let i = 0; i < N; i++) insert(root, B[i]); for (let i = 0; i < N; i++) document.write(max_xor(root, A[i])+"<br>"); // This code is contributed by rag2127 </script> Output: 6 6 12 15 Trie formation : O(N x MAX_BITS) where MAX_BITS is maximum number of bits in binary representation of numbers. Calculating max bit difference : O(N x MAX_BITS) Time Complexity : O(N x MAX_BITS) This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 29AjayKumar sanjeev2552 rag2127 Bitwise-XOR Trie Arrays Arrays Trie Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Jul, 2021" }, { "code": null, "e": 199, "s": 54, "text": "Two arrays A and B consisting of N elements are given. The task is to compute the maximum possible XOR of every element in array A with array B." }, { "code": null, "e": 211, "s": 199, "text": "Examples: " }, { "code": null, "e": 332, "s": 211, "text": "Input :\nA : 7 3 9 12\nB : 1 3 5 2\nOutput : 6 6 12 15\nExplanation : 1 xor 7 = 6, 5 xor 3 = 6, 5\nxor 9 = 12, 3 xor 12 = 15." }, { "code": null, "e": 501, "s": 332, "text": "A naive approach to solve this problem would be to check every element of array A with every other element of array B and print the maximum xor.Time Complexity : O(n^2)" }, { "code": null, "e": 1093, "s": 501, "text": "An efficient solution is to use Trie Data Structure. We maintain a Trie for the binary representation of all elements in array B. Now, for every element of A, we find the maximum xor in trie. Let’s say our number A[i] is {b1, b2...bn}, where b1, b2...bn are binary bits. We start from b1. Now for the xor to be maximum, we’ll try to make most significant bit 1 after performing the xor. So, if b1 is 0, we’ll need a 1 and vice versa. In the trie, we go to the required bit side. If favourable option is not there, we’ll go other side. Doing this all over, we’ll get the maximum XOR possible." }, { "code": null, "e": 1123, "s": 1093, "text": "Below is the implementation " }, { "code": null, "e": 1127, "s": 1123, "text": "C++" }, { "code": null, "e": 1132, "s": 1127, "text": "Java" }, { "code": null, "e": 1140, "s": 1132, "text": "Python3" }, { "code": null, "e": 1143, "s": 1140, "text": "C#" }, { "code": null, "e": 1154, "s": 1143, "text": "Javascript" }, { "code": "// C++ code to find the maximum possible X-OR of// every array element with another array#include<bits/stdc++.h>using namespace std; // Structure of Trie DSstruct trie{ int value; trie *child[2];}; // Function to initialise a Trie Nodetrie * get(){ trie * root = new trie; root -> value = 0; root -> child[0] = NULL; root -> child[1] = NULL; return root;} // Computing max xorint max_xor(trie * root, int key){ trie * temp = root; // Checking for all bits in integer range for (int i = 31; i >= 0; i--) { // Current bit in the number bool current_bit = ( key & ( 1 << i) ); // Traversing Trie for different bit, if found if (temp -> child[1 - current_bit] != NULL) temp = temp -> child[1 - current_bit]; // Traversing Trie for same bit else temp = temp -> child[current_bit]; } // Returning xor value of maximum bit difference // value. Thus, we get maximum xor value return (key ^ temp -> value);} // Inserting B[] in Trievoid insert(trie * root, int key){ trie * temp = root; // Storing 31 bits as integer representation for (int i = 31; i >= 0; i--) { // Current bit in the number bool current_bit = key & (1 << i); // New node required if (temp -> child[current_bit] == NULL) temp -> child[current_bit] = get(); // Traversing in Trie temp = temp -> child[current_bit]; } // Assigning value to the leaf Node temp -> value = key;} int main(){ int A[] = {7, 3, 9, 12}; int B[] = {1, 3, 5, 2}; int N = sizeof(A)/sizeof(A[0]); // Forming Trie for B[] trie * root = get(); for (int i = 0; i < N; i++) insert(root, B[i]); for (int i = 0; i < N; i++) cout << max_xor(root, A[i]) << endl; return 0;}", "e": 3023, "s": 1154, "text": null }, { "code": "// Java code to find the maximum possible X-OR of// every array element with another arrayimport java.util.*; class GFG{ // Structure of Trie DSstatic class trie{ int value; trie []child = new trie[2];}; // Function to initialise a Trie Nodestatic trie get(){ trie root = new trie(); root.value = 0; root.child[0] = null; root.child[1] = null; return root;} // Computing max xorstatic int max_xor(trie root, int key){ trie temp = root; // Checking for all bits in integer range for (int i = 31; i >= 0; i--) { // Current bit in the number int current_bit = (key & (1 << i)); if(current_bit > 0) current_bit = 1; // Traversing Trie for different bit, if found if (temp.child[1 - current_bit] != null) temp = temp.child[1 - current_bit]; // Traversing Trie for same bit else temp = temp.child[current_bit]; } // Returning xor value of maximum bit difference // value. Thus, we get maximum xor value return (key ^ temp.value);} // Inserting B[] in Triestatic void insert(trie root, int key){ trie temp = root; // Storing 31 bits as integer representation for (int i = 31; i >= 0; i--) { // Current bit in the number int current_bit = key & (1 << i); if(current_bit > 0) current_bit = 1; //System.out.println(current_bit); // New node required if (temp.child[current_bit] == null) temp.child[current_bit] = get(); // Traversing in Trie temp = temp.child[current_bit]; } // Assigning value to the leaf Node temp.value = key;} // Driver Codepublic static void main(String[] args){ int A[] = {7, 3, 9, 12}; int B[] = {1, 3, 5, 2}; int N = A.length; // Forming Trie for B[] trie root = get(); for (int i = 0; i < N; i++) insert(root, B[i]); for (int i = 0; i < N; i++) System.out.println(max_xor(root, A[i]));}} // This code is contributed by 29AjayKumar", "e": 5089, "s": 3023, "text": null }, { "code": "# Python3 code to find the maximum# possible X-OR of every array# element with another array # Structure of Trie DSclass trie: def __init__(self, value: int = 0) -> None: self.value = value self.child = [None] * 2 # Function to initialise a Trie Nodedef get() -> trie: root = trie() root.value = 0 root.child[0] = None root.child[1] = None return root # Computing max xordef max_xor(root: trie, key: int) -> int: temp = root # Checking for all bits in integer range for i in range(31, -1, -1): # Current bit in the number current_bit = (key & (1 << i)) if (current_bit > 0): current_bit = 1 # Traversing Trie for different bit, if found if (temp.child[1 - current_bit] != None): temp = temp.child[1 - current_bit] # Traversing Trie for same bit else: temp = temp.child[current_bit] # Returning xor value of maximum bit difference # value. Thus, we get maximum xor value return (key ^ temp.value) # Inserting B[] in Triedef insert(root: trie, key: int) -> None: temp = root # Storing 31 bits as integer representation for i in range(31, -1, -1): # Current bit in the number current_bit = key & (1 << i) if (current_bit > 0): current_bit = 1 # New node required if (temp.child[current_bit] == None): temp.child[current_bit] = get() # Traversing in Trie temp = temp.child[current_bit] # Assigning value to the leaf Node temp.value = key # Driver Codeif __name__ == \"__main__\": A = [ 7, 3, 9, 12 ] B = [ 1, 3, 5, 2 ] N = len(A) # Forming Trie for B[] root = get() for i in range(N): insert(root, B[i]) for i in range(N): print(max_xor(root, A[i])) # This code is contributed by sanjeev2552", "e": 6972, "s": 5089, "text": null }, { "code": "// C# code to find the maximum possible X-OR of// every array element with another arrayusing System; class GFG{ // Structure of Trie DSclass trie{ public int value; public trie []child = new trie[2];}; // Function to initialise a Trie Nodestatic trie get(){ trie root = new trie(); root.value = 0; root.child[0] = null; root.child[1] = null; return root;} // Computing max xorstatic int max_xor(trie root, int key){ trie temp = root; // Checking for all bits in integer range for (int i = 31; i >= 0; i--) { // Current bit in the number int current_bit = (key & (1 << i)); if(current_bit > 0) current_bit = 1; // Traversing Trie for different bit, if found if (temp.child[1 - current_bit] != null) temp = temp.child[1 - current_bit]; // Traversing Trie for same bit else temp = temp.child[current_bit]; } // Returning xor value of maximum bit difference // value. Thus, we get maximum xor value return (key ^ temp.value);} // Inserting B[] in Triestatic void insert(trie root, int key){ trie temp = root; // Storing 31 bits as integer representation for (int i = 31; i >= 0; i--) { // Current bit in the number int current_bit = key & (1 << i); if(current_bit > 0) current_bit = 1; // System.out.println(current_bit); // New node required if (temp.child[current_bit] == null) temp.child[current_bit] = get(); // Traversing in Trie temp = temp.child[current_bit]; } // Assigning value to the leaf Node temp.value = key;} // Driver Codepublic static void Main(String[] args){ int []A = {7, 3, 9, 12}; int []B = {1, 3, 5, 2}; int N = A.Length; // Forming Trie for B[] trie root = get(); for (int i = 0; i < N; i++) insert(root, B[i]); for (int i = 0; i < N; i++) Console.WriteLine(max_xor(root, A[i]));}} // This code is contributed by 29AjayKumar", "e": 9046, "s": 6972, "text": null }, { "code": "<script> // JavaScript code to find the maximum possible X-OR of// every array element with another array // Structure of Trie DSclass trie{ constructor() { this.value=0; this.child = new Array(2); }} // Function to initialise a Trie Node function get(){ let root = new trie(); root.value = 0; root.child[0] = null; root.child[1] = null; return root;} // Computing max xorfunction max_xor(root,key){ let temp = root; // Checking for all bits in integer range for (let i = 31; i >= 0; i--) { // Current bit in the number let current_bit = (key & (1 << i)); if(current_bit > 0) current_bit = 1; // Traversing Trie for different bit, if found if (temp.child[1 - current_bit] != null) temp = temp.child[1 - current_bit]; // Traversing Trie for same bit else temp = temp.child[current_bit]; } // Returning xor value of maximum bit difference // value. Thus, we get maximum xor value return (key ^ temp.value);} // Inserting B[] in Triefunction insert(root,key){ let temp = root; // Storing 31 bits as integer representation for (let i = 31; i >= 0; i--) { // Current bit in the number let current_bit = key & (1 << i); if(current_bit > 0) current_bit = 1; //System.out.println(current_bit); // New node required if (temp.child[current_bit] == null) temp.child[current_bit] = get(); // Traversing in Trie temp = temp.child[current_bit]; } // Assigning value to the leaf Node temp.value = key;} // Driver Codelet A=[7, 3, 9, 12];let B=[1, 3, 5, 2]; let N = A.length;// Forming Trie for B[]let root = get();for (let i = 0; i < N; i++) insert(root, B[i]); for (let i = 0; i < N; i++) document.write(max_xor(root, A[i])+\"<br>\"); // This code is contributed by rag2127 </script>", "e": 11024, "s": 9046, "text": null }, { "code": null, "e": 11033, "s": 11024, "text": "Output: " }, { "code": null, "e": 11043, "s": 11033, "text": "6\n6\n12\n15" }, { "code": null, "e": 11204, "s": 11043, "text": "Trie formation : O(N x MAX_BITS) where MAX_BITS is maximum number of bits in binary representation of numbers. Calculating max bit difference : O(N x MAX_BITS) " }, { "code": null, "e": 11238, "s": 11204, "text": "Time Complexity : O(N x MAX_BITS)" }, { "code": null, "e": 11662, "s": 11238, "text": "This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 11674, "s": 11662, "text": "29AjayKumar" }, { "code": null, "e": 11686, "s": 11674, "text": "sanjeev2552" }, { "code": null, "e": 11694, "s": 11686, "text": "rag2127" }, { "code": null, "e": 11706, "s": 11694, "text": "Bitwise-XOR" }, { "code": null, "e": 11711, "s": 11706, "text": "Trie" }, { "code": null, "e": 11718, "s": 11711, "text": "Arrays" }, { "code": null, "e": 11725, "s": 11718, "text": "Arrays" }, { "code": null, "e": 11730, "s": 11725, "text": "Trie" } ]
How to get value from address in Python ?
23 Aug, 2021 In this article, we will discuss how to get the value from the address in Python. First, we have to calculate the memory address of the variable or python object which can be done by using the id() function. Syntax: id(python_object) where, python_object is any python variable or data structure like list, tuple set, etc. Example: Python program to get the memory address of particular python objects Python3 #import ctypesimport ctypes # variable declarationval = 20 # get the memory address of the python # object for variableprint(id(val)) # get the memory address of the python # object for listprint(id([1, 2, 3, 4, 5])) # get the memory address of the python # object for tupleprint(id((1, 2, 3, 4, 5))) # get the memory address of the python # object for setprint(id({1, 2, 3, 4, 5})) Output: 93937093504096 140292920620368 140292954508752 140292954711056 Now that we have addresses, we can get value/python objects again from the memory address using ctypes module. ctypes stands for compatible data types, which allows calling functions in DLLs or shared libraries. It can be used to wrap these libraries in pure Python. It is used to get the value/Python objects using memory address Syntax: ctypes.cast(memory_address,ctypes.py_object).value where, memeory_address is the memory address of the variable value is the method which is used to extract a value Example 1: Python program to access the value from memory address Python3 #import ctypesimport ctypes # variable declarationval = 20 # display variableprint("Actual value -", val) # get the memory address of the python object # for variablex = id(val) # display memory addressprint("Memory address - ", x) # get the value through memory addressa = ctypes.cast(x, ctypes.py_object).value # displayprint("Value - ", a) Output: Actual value - 20 Memory address - 93937093504096 Value - 20 Example 2: Python program to get the value from memory address of python data structures Python3 #import ctypesimport ctypes # variable declarationval = [1, 2, 3, 4, 5] # display variableprint("Actual value -", val) # get the memory address of the python object # for variable listx = id(val) # display memory addressprint("Memory address - ", x) # get the value through memory addressa = ctypes.cast(x, ctypes.py_object).value # displayprint("Value - ", a) print("____________________________________") # variable declarationval = (1, 2, 3, 4, 5) # display variableprint("Actual value -", val) # get the memory address of the python object# for variable tuplex = id(val) # display memory addressprint("Memory address - ", x) # get the value through memory addressa = ctypes.cast(x, ctypes.py_object).value # displayprint("Value - ", a) print("____________________________________") # variable declarationval = {1, 2, 3, 4, 5} # display variableprint("Actual value -", val) # get the memory address of the python object # for variable setx = id(val) # display memory addressprint("Memory address - ", x) # get the value through memory addressa = ctypes.cast(x, ctypes.py_object).value # displayprint("Value - ", a) print("____________________________________") # variable declarationval = {'id': 1, "name": "sravan kumar", "address": "kakumanu"} # display variableprint("Actual value -", val) # get the memory address of the python object # for variable dictionaryx = id(val) # display memory addressprint("Memory address - ", x) # get the value through memory addressa = ctypes.cast(x, ctypes.py_object).value # displayprint("Value - ", a) print("____________________________________") Output: Actual value – [1, 2, 3, 4, 5] Memory address – 140292824840224 Value – [1, 2, 3, 4, 5] ____________________________________ Actual value – (1, 2, 3, 4, 5) Memory address – 140292853914128 Value – (1, 2, 3, 4, 5) ____________________________________ Actual value – {1, 2, 3, 4, 5} Memory address – 140292824862304 Value – {1, 2, 3, 4, 5} ____________________________________ Actual value – {‘id’: 1, ‘name’: ‘sravan kumar’, ‘address’: ‘kakumanu’} Memory address – 140292825009760 Value – {‘id’: 1, ‘name’: ‘sravan kumar’, ‘address’: ‘kakumanu’} ____________________________________ Picked python-basics Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Aug, 2021" }, { "code": null, "e": 236, "s": 28, "text": "In this article, we will discuss how to get the value from the address in Python. First, we have to calculate the memory address of the variable or python object which can be done by using the id() function." }, { "code": null, "e": 244, "s": 236, "text": "Syntax:" }, { "code": null, "e": 262, "s": 244, "text": "id(python_object)" }, { "code": null, "e": 351, "s": 262, "text": "where, python_object is any python variable or data structure like list, tuple set, etc." }, { "code": null, "e": 430, "s": 351, "text": "Example: Python program to get the memory address of particular python objects" }, { "code": null, "e": 438, "s": 430, "text": "Python3" }, { "code": "#import ctypesimport ctypes # variable declarationval = 20 # get the memory address of the python # object for variableprint(id(val)) # get the memory address of the python # object for listprint(id([1, 2, 3, 4, 5])) # get the memory address of the python # object for tupleprint(id((1, 2, 3, 4, 5))) # get the memory address of the python # object for setprint(id({1, 2, 3, 4, 5}))", "e": 826, "s": 438, "text": null }, { "code": null, "e": 834, "s": 826, "text": "Output:" }, { "code": null, "e": 897, "s": 834, "text": "93937093504096\n140292920620368\n140292954508752\n140292954711056" }, { "code": null, "e": 1008, "s": 897, "text": "Now that we have addresses, we can get value/python objects again from the memory address using ctypes module." }, { "code": null, "e": 1228, "s": 1008, "text": "ctypes stands for compatible data types, which allows calling functions in DLLs or shared libraries. It can be used to wrap these libraries in pure Python. It is used to get the value/Python objects using memory address" }, { "code": null, "e": 1236, "s": 1228, "text": "Syntax:" }, { "code": null, "e": 1287, "s": 1236, "text": "ctypes.cast(memory_address,ctypes.py_object).value" }, { "code": null, "e": 1294, "s": 1287, "text": "where," }, { "code": null, "e": 1348, "s": 1294, "text": "memeory_address is the memory address of the variable" }, { "code": null, "e": 1401, "s": 1348, "text": "value is the method which is used to extract a value" }, { "code": null, "e": 1467, "s": 1401, "text": "Example 1: Python program to access the value from memory address" }, { "code": null, "e": 1475, "s": 1467, "text": "Python3" }, { "code": "#import ctypesimport ctypes # variable declarationval = 20 # display variableprint(\"Actual value -\", val) # get the memory address of the python object # for variablex = id(val) # display memory addressprint(\"Memory address - \", x) # get the value through memory addressa = ctypes.cast(x, ctypes.py_object).value # displayprint(\"Value - \", a)", "e": 1824, "s": 1475, "text": null }, { "code": null, "e": 1832, "s": 1824, "text": "Output:" }, { "code": null, "e": 1895, "s": 1832, "text": "Actual value - 20\nMemory address - 93937093504096\nValue - 20" }, { "code": null, "e": 1984, "s": 1895, "text": "Example 2: Python program to get the value from memory address of python data structures" }, { "code": null, "e": 1992, "s": 1984, "text": "Python3" }, { "code": "#import ctypesimport ctypes # variable declarationval = [1, 2, 3, 4, 5] # display variableprint(\"Actual value -\", val) # get the memory address of the python object # for variable listx = id(val) # display memory addressprint(\"Memory address - \", x) # get the value through memory addressa = ctypes.cast(x, ctypes.py_object).value # displayprint(\"Value - \", a) print(\"____________________________________\") # variable declarationval = (1, 2, 3, 4, 5) # display variableprint(\"Actual value -\", val) # get the memory address of the python object# for variable tuplex = id(val) # display memory addressprint(\"Memory address - \", x) # get the value through memory addressa = ctypes.cast(x, ctypes.py_object).value # displayprint(\"Value - \", a) print(\"____________________________________\") # variable declarationval = {1, 2, 3, 4, 5} # display variableprint(\"Actual value -\", val) # get the memory address of the python object # for variable setx = id(val) # display memory addressprint(\"Memory address - \", x) # get the value through memory addressa = ctypes.cast(x, ctypes.py_object).value # displayprint(\"Value - \", a) print(\"____________________________________\") # variable declarationval = {'id': 1, \"name\": \"sravan kumar\", \"address\": \"kakumanu\"} # display variableprint(\"Actual value -\", val) # get the memory address of the python object # for variable dictionaryx = id(val) # display memory addressprint(\"Memory address - \", x) # get the value through memory addressa = ctypes.cast(x, ctypes.py_object).value # displayprint(\"Value - \", a) print(\"____________________________________\")", "e": 3612, "s": 1992, "text": null }, { "code": null, "e": 3620, "s": 3612, "text": "Output:" }, { "code": null, "e": 3651, "s": 3620, "text": "Actual value – [1, 2, 3, 4, 5]" }, { "code": null, "e": 3685, "s": 3651, "text": "Memory address – 140292824840224" }, { "code": null, "e": 3710, "s": 3685, "text": "Value – [1, 2, 3, 4, 5]" }, { "code": null, "e": 3747, "s": 3710, "text": "____________________________________" }, { "code": null, "e": 3778, "s": 3747, "text": "Actual value – (1, 2, 3, 4, 5)" }, { "code": null, "e": 3812, "s": 3778, "text": "Memory address – 140292853914128" }, { "code": null, "e": 3837, "s": 3812, "text": "Value – (1, 2, 3, 4, 5)" }, { "code": null, "e": 3874, "s": 3837, "text": "____________________________________" }, { "code": null, "e": 3905, "s": 3874, "text": "Actual value – {1, 2, 3, 4, 5}" }, { "code": null, "e": 3939, "s": 3905, "text": "Memory address – 140292824862304" }, { "code": null, "e": 3964, "s": 3939, "text": "Value – {1, 2, 3, 4, 5}" }, { "code": null, "e": 4001, "s": 3964, "text": "____________________________________" }, { "code": null, "e": 4073, "s": 4001, "text": "Actual value – {‘id’: 1, ‘name’: ‘sravan kumar’, ‘address’: ‘kakumanu’}" }, { "code": null, "e": 4107, "s": 4073, "text": "Memory address – 140292825009760" }, { "code": null, "e": 4173, "s": 4107, "text": "Value – {‘id’: 1, ‘name’: ‘sravan kumar’, ‘address’: ‘kakumanu’}" }, { "code": null, "e": 4210, "s": 4173, "text": "____________________________________" }, { "code": null, "e": 4217, "s": 4210, "text": "Picked" }, { "code": null, "e": 4231, "s": 4217, "text": "python-basics" }, { "code": null, "e": 4238, "s": 4231, "text": "Python" } ]
Python Program for Linear Search
22 Jun, 2022 Problem: Given an array arr[] of n elements, write a function to search a given element x in arr[]. Examples : Input : arr[] = {10, 20, 80, 30, 60, 50, 110, 100, 130, 170} x = 110; Output : 6 Element x is present at index 6 Input : arr[] = {10, 20, 80, 30, 60, 50, 110, 100, 130, 170} x = 175; Output : -1 Element x is not present in arr[]. A simple approach is to do a linear search, i.e Start from the leftmost element of arr[] and one by one compare x with each element of arr[] If x matches with an element, return the index. If x doesn’t match with any of the elements, return -1. Example: Iterative Approach: Python # Searching an element in a list/array in python# can be simply done using \'in\' operator# Example:# if x in arr:# print arr.index(x) # If you want to implement Linear Search in python # Linearly search x in arr[]# If x is present then return its location# else return -1 def search(arr, x): for i in range(len(arr)): if arr[i] == x: return i return -1 Recursive Approach: Python # This is similar to the above one, with the only difference# being that it is using the recursive approach instead of iterative. def search(arr, curr_index, key): if curr_index == -1: return -1 if arr[curr_index] == key: return curr_index return search(arr, curr_index-1, key) The time complexity of the above algorithm is O(n). Auxiliary Space: O(1) for iterative and O(n) for recursive. Please refer complete article on Linear Search and Difference Between Recursive and Iterative Algorithms for more details! talktoanmol chandramauliguptach python searching-exercises Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jun, 2022" }, { "code": null, "e": 153, "s": 52, "text": "Problem: Given an array arr[] of n elements, write a function to search a given element x in arr[]. " }, { "code": null, "e": 164, "s": 153, "text": "Examples :" }, { "code": null, "e": 460, "s": 164, "text": "Input : arr[] = {10, 20, 80, 30, 60, 50, \n 110, 100, 130, 170}\n x = 110;\nOutput : 6\nElement x is present at index 6\n\nInput : arr[] = {10, 20, 80, 30, 60, 50, \n 110, 100, 130, 170}\n x = 175;\nOutput : -1\nElement x is not present in arr[]." }, { "code": null, "e": 508, "s": 460, "text": "A simple approach is to do a linear search, i.e" }, { "code": null, "e": 601, "s": 508, "text": "Start from the leftmost element of arr[] and one by one compare x with each element of arr[]" }, { "code": null, "e": 649, "s": 601, "text": "If x matches with an element, return the index." }, { "code": null, "e": 705, "s": 649, "text": "If x doesn’t match with any of the elements, return -1." }, { "code": null, "e": 735, "s": 705, "text": "Example: Iterative Approach:" }, { "code": null, "e": 742, "s": 735, "text": "Python" }, { "code": "# Searching an element in a list/array in python# can be simply done using \\'in\\' operator# Example:# if x in arr:# print arr.index(x) # If you want to implement Linear Search in python # Linearly search x in arr[]# If x is present then return its location# else return -1 def search(arr, x): for i in range(len(arr)): if arr[i] == x: return i return -1", "e": 1125, "s": 742, "text": null }, { "code": null, "e": 1146, "s": 1125, "text": "Recursive Approach: " }, { "code": null, "e": 1153, "s": 1146, "text": "Python" }, { "code": "# This is similar to the above one, with the only difference# being that it is using the recursive approach instead of iterative. def search(arr, curr_index, key): if curr_index == -1: return -1 if arr[curr_index] == key: return curr_index return search(arr, curr_index-1, key)", "e": 1455, "s": 1153, "text": null }, { "code": null, "e": 1508, "s": 1455, "text": "The time complexity of the above algorithm is O(n). " }, { "code": null, "e": 1568, "s": 1508, "text": "Auxiliary Space: O(1) for iterative and O(n) for recursive." }, { "code": null, "e": 1691, "s": 1568, "text": "Please refer complete article on Linear Search and Difference Between Recursive and Iterative Algorithms for more details!" }, { "code": null, "e": 1703, "s": 1691, "text": "talktoanmol" }, { "code": null, "e": 1723, "s": 1703, "text": "chandramauliguptach" }, { "code": null, "e": 1750, "s": 1723, "text": "python searching-exercises" }, { "code": null, "e": 1766, "s": 1750, "text": "Python Programs" } ]
fc Command in Linux with Examples
15 May, 2019 As we all know that LINUX is command friendly and while working on LINUX, you may deal with very long commands that may include long paths or really difficult syntax, and imagine what if working with such commands you do a minor mistake which will require re-writing of the entire command synopsis and its arguments in order to execute it again successfully. Now, there are two solutions to this – either re-write the entire syntax or simply use fc command that allows you to edit and re-execute the commands previously entered to a shell without re-writing them again. This command line utility really comes to help while editing long commands. So, the fc command is used to list, edit or re-execute the commands previously entered into an interactive shell.Here’s the syntax of fc command : //syntax of fc command fc [-e ename] [-lnr] [first] [last] or fc -s [pat=rep] [command] where the -lnr refers to the options available for fc and -e ename refers to the editor you want to use for editing. first and last here is for specifying the range . To easily understand the use of fc command and how does it work let’s take a simple example where you want to change your working directory to kt/kartik/thakral and by mistake while changing your directory you write karik instead of kartik, in this case you can simply use fc command to edit the previously entered path. After you enter the incorrect directory path you’ll see something like this : then you can just simply type fc command and after writing fc command your editor will open up so that you can now edit the previously entered command like shown below : after editing your path you can exit your editor and after exiting fc command will re-execute the cd kt/kartik/thakral like shown below : Using -l option : This option allows you to see some of the previously entered commands in your terminal i.e this lists the lines of previously entered commands instead of editing. Using -n option : As shown above while using -l option fc command lists the lines along with the line numbers, but in case if you want to list the lines without line numbers you can simply use -n option with -l option as shown below : Using -r option : This option can also be used with -l option to just reverse the order of lines i.e newest commands are listed first now as shown below : Using first and last : Suppose you want to just edit a particular set of commands, in that case you can use first and last arguments as shown below : Using -e option : The choice of editor to edit the demands totally depends on user and with the help of -e option user can choose editor of his choice, you just have to pass the name of editor with -e option as shown below : fc command is the best way to edit the previously entered commands in the case of a minor mistake without re-writing the entire command syntax and argument again. It can also be used to list the previously entered commands in the terminal which can be helpful in case you are working with some new commands. fc command in a way lets you know the command history. linux-command Linux-misc-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n15 May, 2019" }, { "code": null, "e": 699, "s": 53, "text": "As we all know that LINUX is command friendly and while working on LINUX, you may deal with very long commands that may include long paths or really difficult syntax, and imagine what if working with such commands you do a minor mistake which will require re-writing of the entire command synopsis and its arguments in order to execute it again successfully. Now, there are two solutions to this – either re-write the entire syntax or simply use fc command that allows you to edit and re-execute the commands previously entered to a shell without re-writing them again. This command line utility really comes to help while editing long commands." }, { "code": null, "e": 846, "s": 699, "text": "So, the fc command is used to list, edit or re-execute the commands previously entered into an interactive shell.Here’s the syntax of fc command :" }, { "code": null, "e": 949, "s": 846, "text": " \n//syntax of fc command\n\nfc [-e ename] [-lnr] [first] [last]\n or\nfc -s [pat=rep] [command]\n" }, { "code": null, "e": 1116, "s": 949, "text": "where the -lnr refers to the options available for fc and -e ename refers to the editor you want to use for editing. first and last here is for specifying the range ." }, { "code": null, "e": 1437, "s": 1116, "text": "To easily understand the use of fc command and how does it work let’s take a simple example where you want to change your working directory to kt/kartik/thakral and by mistake while changing your directory you write karik instead of kartik, in this case you can simply use fc command to edit the previously entered path." }, { "code": null, "e": 1515, "s": 1437, "text": "After you enter the incorrect directory path you’ll see something like this :" }, { "code": null, "e": 1685, "s": 1515, "text": "then you can just simply type fc command and after writing fc command your editor will open up so that you can now edit the previously entered command like shown below :" }, { "code": null, "e": 1823, "s": 1685, "text": "after editing your path you can exit your editor and after exiting fc command will re-execute the cd kt/kartik/thakral like shown below :" }, { "code": null, "e": 2004, "s": 1823, "text": "Using -l option : This option allows you to see some of the previously entered commands in your terminal i.e this lists the lines of previously entered commands instead of editing." }, { "code": null, "e": 2239, "s": 2004, "text": "Using -n option : As shown above while using -l option fc command lists the lines along with the line numbers, but in case if you want to list the lines without line numbers you can simply use -n option with -l option as shown below :" }, { "code": null, "e": 2394, "s": 2239, "text": "Using -r option : This option can also be used with -l option to just reverse the order of lines i.e newest commands are listed first now as shown below :" }, { "code": null, "e": 2544, "s": 2394, "text": "Using first and last : Suppose you want to just edit a particular set of commands, in that case you can use first and last arguments as shown below :" }, { "code": null, "e": 2769, "s": 2544, "text": "Using -e option : The choice of editor to edit the demands totally depends on user and with the help of -e option user can choose editor of his choice, you just have to pass the name of editor with -e option as shown below :" }, { "code": null, "e": 2932, "s": 2769, "text": "fc command is the best way to edit the previously entered commands in the case of a minor mistake without re-writing the entire command syntax and argument again." }, { "code": null, "e": 3077, "s": 2932, "text": "It can also be used to list the previously entered commands in the terminal which can be helpful in case you are working with some new commands." }, { "code": null, "e": 3132, "s": 3077, "text": "fc command in a way lets you know the command history." }, { "code": null, "e": 3146, "s": 3132, "text": "linux-command" }, { "code": null, "e": 3166, "s": 3146, "text": "Linux-misc-commands" }, { "code": null, "e": 3177, "s": 3166, "text": "Linux-Unix" } ]
Set Cover Problem | Set 1 (Greedy Approximate Algorithm)
22 Mar, 2017 Given a universe U of n elements, a collection of subsets of U say S = {S1, S2...,Sm} where every subset Si has an associated cost. Find a minimum cost subcollection of S that covers all elements of U. Example: U = {1,2,3,4,5} S = {S1,S2,S3} S1 = {4,1,3}, Cost(S1) = 5 S2 = {2,5}, Cost(S2) = 10 S3 = {1,4,3,2}, Cost(S3) = 3 Output: Minimum cost of set cover is 13 and set cover is {S2, S3} There are two possible set covers {S1, S2} with cost 15 and {S2, S3} with cost 13. Why is it useful?It was one of Karp’s NP-complete problems, shown to be so in 1972. Other applications: edge covering, vertex coverInteresting example: IBM finds computer viruses (wikipedia)Elements- 5000 known virusesSets- 9000 substrings of 20 or more consecutive bytes from viruses, not found in ‘good’ code.A set cover of 180 was found. It suffices to search for these 180 substrings to verify the existence of known computer viruses. Another example: Consider General Motors needs to buy a certain amount of varied supplies and there are suppliers that offer various deals for different combinations of materials (Supplier A: 2 tons of steel + 500 tiles for $x; Supplier B: 1 ton of steel + 2000 tiles for $y; etc.). You could use set covering to find the best way to get all the materials while minimizing costSource: http://math.mit.edu/~goemans/18434S06/setcover-tamara.pdf Set Cover is NP-Hard:There is no polynomial time solution available for this problem as the problem is a known NP-Hard problem. There is a polynomial time Greedy approximate algorithm, the greedy algorithm provides a Logn approximate algorithm. 2-Approximate Greedy Algorithm:Let U be the universe of elements, {S1, S2, ... Sm} be collection of subsets of U and Cost(S1), C(S2), ... Cost(Sm) be costs of subsets. 1) Let I represents set of elements included so far. Initialize I = {} 2) Do following while I is not same as U. a) Find the set Si in {S1, S2, ... Sm} whose cost effectiveness is smallest, i.e., the ratio of cost C(Si) and number of newly added elements is minimum. Basically we pick the set for which following value is minimum. Cost(Si) / |Si - I| b) Add elements of above picked Si to I, i.e., I = I U Si Example:Let us consider the above example to understand Greedy Algorithm. First Iteration:I = {} The per new element cost for S1 = Cost(S1)/|S1 – I| = 5/3 The per new element cost for S2 = Cost(S2)/|S2 – I| = 10/2 The per new element cost for S3 = Cost(S3)/|S3 – I| = 3/4 Since S3 has minimum value S3 is added, I becomes {1,4,3,2}. Second Iteration:I = {1,4,3,2} The per new element cost for S1 = Cost(S1)/|S1 – I| = 5/0Note that S1 doesn’t add any new element to I. The per new element cost for S2 = Cost(S2)/|S2 – I| = 10/1Note that S2 adds only 5 to I. The greedy algorithm provides the optimal solution for above example, but it may not provide optimal solution all the time. Consider the following example. S1 = {1, 2} S2 = {2, 3, 4, 5} S3 = {6, 7, 8, 9, 10, 11, 12, 13} S4 = {1, 3, 5, 7, 9, 11, 13} S5 = {2, 4, 6, 8, 10, 12, 13} Let the cost of every set be same. The greedy algorithm produces result as {S3, S2, S1} The optimal solution is {S4, S5} Proof that the above greedy algorithm is Logn approximate.Let OPT be the cost of optimal solution. Say (k-1) elements are covered before an iteration of above greedy algorithm. The cost of the k’th element <= OPT / (n-k+1) (Note that cost of an element is evaluated by cost of its set divided by number of elements added by its set). How did we get this result? Since k'th element is not covered yet, there is a Si that has not been covered before the current step of greedy algorithm and it is there in OPT. Since greedy algorithm picks the most cost effective Si, per-element-cost in the picked set must be smaller than OPT divided by remaining elements. Therefore cost of k’th element <= OPT/|U-I| (Note that U-I is set of not yet covered elements in Greedy Algorithm). The value of |U-I| is n - (k-1) which is n-k+1. Cost of Greedy Algorithm = Sum of costs of n elements [putting k = 1, 2..n in above formula] <= (OPT/n + OPT(n-1) + ... + OPT/n) <= OPT(1 + 1/2 + ...... 1/n) [Since 1 + 1/2 + .. 1/n ≈ Log n] <= OPT * Logn Source:http://math.mit.edu/~goemans/18434S06/setcover-tamara.pdf This article is contributed by Harshit. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. NPHard Greedy Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for array rotation Write a program to print all permutations of a given string Coin Change | DP-7 Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) Minimum Number of Platforms Required for a Railway/Bus Station Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8 Maximize difference between the Sum of the two halves of the Array after removal of N elements Difference between Prim's and Kruskal's algorithm for MST 3 Different ways to print Fibonacci series in Java Greedy Algorithm to find Minimum number of Coins
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Mar, 2017" }, { "code": null, "e": 256, "s": 54, "text": "Given a universe U of n elements, a collection of subsets of U say S = {S1, S2...,Sm} where every subset Si has an associated cost. Find a minimum cost subcollection of S that covers all elements of U." }, { "code": null, "e": 265, "s": 256, "text": "Example:" }, { "code": null, "e": 567, "s": 265, "text": " U = {1,2,3,4,5}\n S = {S1,S2,S3}\n \n S1 = {4,1,3}, Cost(S1) = 5\n S2 = {2,5}, Cost(S2) = 10\n S3 = {1,4,3,2}, Cost(S3) = 3\n\nOutput: Minimum cost of set cover is 13 and \n set cover is {S2, S3}\n\nThere are two possible set covers {S1, S2} with cost 15\nand {S2, S3} with cost 13.\n" }, { "code": null, "e": 1006, "s": 567, "text": "Why is it useful?It was one of Karp’s NP-complete problems, shown to be so in 1972. Other applications: edge covering, vertex coverInteresting example: IBM finds computer viruses (wikipedia)Elements- 5000 known virusesSets- 9000 substrings of 20 or more consecutive bytes from viruses, not found in ‘good’ code.A set cover of 180 was found. It suffices to search for these 180 substrings to verify the existence of known computer viruses." }, { "code": null, "e": 1449, "s": 1006, "text": "Another example: Consider General Motors needs to buy a certain amount of varied supplies and there are suppliers that offer various deals for different combinations of materials (Supplier A: 2 tons of steel + 500 tiles for $x; Supplier B: 1 ton of steel + 2000 tiles for $y; etc.). You could use set covering to find the best way to get all the materials while minimizing costSource: http://math.mit.edu/~goemans/18434S06/setcover-tamara.pdf" }, { "code": null, "e": 1694, "s": 1449, "text": "Set Cover is NP-Hard:There is no polynomial time solution available for this problem as the problem is a known NP-Hard problem. There is a polynomial time Greedy approximate algorithm, the greedy algorithm provides a Logn approximate algorithm." }, { "code": null, "e": 1862, "s": 1694, "text": "2-Approximate Greedy Algorithm:Let U be the universe of elements, {S1, S2, ... Sm} be collection of subsets of U and Cost(S1), C(S2), ... Cost(Sm) be costs of subsets." }, { "code": null, "e": 2318, "s": 1862, "text": "1) Let I represents set of elements included so far. Initialize I = {}\n\n2) Do following while I is not same as U.\n a) Find the set Si in {S1, S2, ... Sm} whose cost effectiveness is \n smallest, i.e., the ratio of cost C(Si) and number of newly added \n elements is minimum. \n Basically we pick the set for which following value is minimum.\n Cost(Si) / |Si - I|\n b) Add elements of above picked Si to I, i.e., I = I U Si\n" }, { "code": null, "e": 2392, "s": 2318, "text": "Example:Let us consider the above example to understand Greedy Algorithm." }, { "code": null, "e": 2415, "s": 2392, "text": "First Iteration:I = {}" }, { "code": null, "e": 2473, "s": 2415, "text": "The per new element cost for S1 = Cost(S1)/|S1 – I| = 5/3" }, { "code": null, "e": 2532, "s": 2473, "text": "The per new element cost for S2 = Cost(S2)/|S2 – I| = 10/2" }, { "code": null, "e": 2590, "s": 2532, "text": "The per new element cost for S3 = Cost(S3)/|S3 – I| = 3/4" }, { "code": null, "e": 2651, "s": 2590, "text": "Since S3 has minimum value S3 is added, I becomes {1,4,3,2}." }, { "code": null, "e": 2682, "s": 2651, "text": "Second Iteration:I = {1,4,3,2}" }, { "code": null, "e": 2786, "s": 2682, "text": "The per new element cost for S1 = Cost(S1)/|S1 – I| = 5/0Note that S1 doesn’t add any new element to I." }, { "code": null, "e": 2875, "s": 2786, "text": "The per new element cost for S2 = Cost(S2)/|S2 – I| = 10/1Note that S2 adds only 5 to I." }, { "code": null, "e": 3031, "s": 2875, "text": "The greedy algorithm provides the optimal solution for above example, but it may not provide optimal solution all the time. Consider the following example." }, { "code": null, "e": 3279, "s": 3031, "text": "S1 = {1, 2}\nS2 = {2, 3, 4, 5}\nS3 = {6, 7, 8, 9, 10, 11, 12, 13}\nS4 = {1, 3, 5, 7, 9, 11, 13}\nS5 = {2, 4, 6, 8, 10, 12, 13}\n\nLet the cost of every set be same.\n\nThe greedy algorithm produces result as {S3, S2, S1}\n\nThe optimal solution is {S4, S5} " }, { "code": null, "e": 4100, "s": 3279, "text": "Proof that the above greedy algorithm is Logn approximate.Let OPT be the cost of optimal solution. Say (k-1) elements are covered before an iteration of above greedy algorithm. The cost of the k’th element <= OPT / (n-k+1) (Note that cost of an element is evaluated by cost of its set divided by number of elements added by its set). How did we get this result?\nSince k'th element is not covered yet, there is a Si that has not been covered before the current step of greedy algorithm and it is there in OPT. Since greedy algorithm picks the most cost effective Si, per-element-cost in the picked set must be smaller than OPT divided by remaining elements. Therefore cost of k’th element <= OPT/|U-I| (Note that U-I is set of not yet covered elements in Greedy Algorithm). The value of |U-I| is n - (k-1) which is n-k+1." }, { "code": null, "e": 4431, "s": 4100, "text": "Cost of Greedy Algorithm = Sum of costs of n elements \n [putting k = 1, 2..n in above formula]\n <= (OPT/n + OPT(n-1) + ... + OPT/n) \n <= OPT(1 + 1/2 + ...... 1/n)\n [Since 1 + 1/2 + .. 1/n ≈ Log n]\n <= OPT * Logn\n" }, { "code": null, "e": 4496, "s": 4431, "text": "Source:http://math.mit.edu/~goemans/18434S06/setcover-tamara.pdf" }, { "code": null, "e": 4661, "s": 4496, "text": "This article is contributed by Harshit. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 4668, "s": 4661, "text": "NPHard" }, { "code": null, "e": 4675, "s": 4668, "text": "Greedy" }, { "code": null, "e": 4682, "s": 4675, "text": "Greedy" }, { "code": null, "e": 4780, "s": 4682, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4807, "s": 4780, "text": "Program for array rotation" }, { "code": null, "e": 4867, "s": 4807, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 4886, "s": 4867, "text": "Coin Change | DP-7" }, { "code": null, "e": 4967, "s": 4886, "text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)" }, { "code": null, "e": 5030, "s": 4967, "text": "Minimum Number of Platforms Required for a Railway/Bus Station" }, { "code": null, "e": 5101, "s": 5030, "text": "Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8" }, { "code": null, "e": 5196, "s": 5101, "text": "Maximize difference between the Sum of the two halves of the Array after removal of N elements" }, { "code": null, "e": 5254, "s": 5196, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 5305, "s": 5254, "text": "3 Different ways to print Fibonacci series in Java" } ]
How to create a simple Responsive Footer in React JS ?
26 Feb, 2021 A footer is an important element of a website’s design since it signals to the user that they have reached the end of the webpage and provides useful links to other areas of the website that the user may want to visit. Problem Statement: Create a responsive footer using React styled-components and compound components. Prerequisite: Basic knowledge of npm & create-react-app command. Basic knowledge of styled-components. Basic Setup: You will start a new project using create-react-app so open your terminal and type: npx create-react-app react-footer Now go to your react-footer folder by typing the given command in the terminal: cd react-footer Required module: Install the dependencies required in this project by typing the given command in the terminal. npm install --save styled-components Now create the components folder in src then go to the components folder and create two files by the name Footer.js and FooterStyles.js Project Structure: The file structure in the project will look like this. Example: In this example we will design a footer, for that we will need to manipulate the App.js file and other created components file. Footer.js import React from "react";import { Box, Container, Row, Column, FooterLink, Heading,} from "./FooterStyles"; const Footer = () => { return ( <Box> <h1 style={{ color: "green", textAlign: "center", marginTop: "-50px" }}> GeeksforGeeks: A Computer Science Portal for Geeks </h1> <Container> <Row> <Column> <Heading>About Us</Heading> <FooterLink href="#">Aim</FooterLink> <FooterLink href="#">Vision</FooterLink> <FooterLink href="#">Testimonials</FooterLink> </Column> <Column> <Heading>Services</Heading> <FooterLink href="#">Writing</FooterLink> <FooterLink href="#">Internships</FooterLink> <FooterLink href="#">Coding</FooterLink> <FooterLink href="#">Teaching</FooterLink> </Column> <Column> <Heading>Contact Us</Heading> <FooterLink href="#">Uttar Pradesh</FooterLink> <FooterLink href="#">Ahemdabad</FooterLink> <FooterLink href="#">Indore</FooterLink> <FooterLink href="#">Mumbai</FooterLink> </Column> <Column> <Heading>Social Media</Heading> <FooterLink href="#"> <i className="fab fa-facebook-f"> <span style={{ marginLeft: "10px" }}> Facebook </span> </i> </FooterLink> <FooterLink href="#"> <i className="fab fa-instagram"> <span style={{ marginLeft: "10px" }}> Instagram </span> </i> </FooterLink> <FooterLink href="#"> <i className="fab fa-twitter"> <span style={{ marginLeft: "10px" }}> Twitter </span> </i> </FooterLink> <FooterLink href="#"> <i className="fab fa-youtube"> <span style={{ marginLeft: "10px" }}> Youtube </span> </i> </FooterLink> </Column> </Row> </Container> </Box> );};export default Footer; FooterStyles.js import styled from 'styled-components'; export const Box = styled.div` padding: 80px 60px; background: black; position: absolute; bottom: 0; width: 100%; @media (max-width: 1000px) { padding: 70px 30px; }`; export const Container = styled.div` display: flex; flex-direction: column; justify-content: center; max-width: 1000px; margin: 0 auto; /* background: red; */` export const Column = styled.div` display: flex; flex-direction: column; text-align: left; margin-left: 60px;`; export const Row = styled.div` display: grid; grid-template-columns: repeat(auto-fill, minmax(185px, 1fr)); grid-gap: 20px; @media (max-width: 1000px) { grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); }`; export const FooterLink = styled.a` color: #fff; margin-bottom: 20px; font-size: 18px; text-decoration: none; &:hover { color: green; transition: 200ms ease-in; }`; export const Heading = styled.p` font-size: 24px; color: #fff; margin-bottom: 40px; font-weight: bold;`; App.js import React from 'react';import Footer from './components/Footer';function App() { return ( <Footer /> );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project. npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: React-Questions Technical Scripter 2020 ReactJS Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n26 Feb, 2021" }, { "code": null, "e": 271, "s": 52, "text": "A footer is an important element of a website’s design since it signals to the user that they have reached the end of the webpage and provides useful links to other areas of the website that the user may want to visit." }, { "code": null, "e": 372, "s": 271, "text": "Problem Statement: Create a responsive footer using React styled-components and compound components." }, { "code": null, "e": 386, "s": 372, "text": "Prerequisite:" }, { "code": null, "e": 437, "s": 386, "text": "Basic knowledge of npm & create-react-app command." }, { "code": null, "e": 475, "s": 437, "text": "Basic knowledge of styled-components." }, { "code": null, "e": 572, "s": 475, "text": "Basic Setup: You will start a new project using create-react-app so open your terminal and type:" }, { "code": null, "e": 606, "s": 572, "text": "npx create-react-app react-footer" }, { "code": null, "e": 686, "s": 606, "text": "Now go to your react-footer folder by typing the given command in the terminal:" }, { "code": null, "e": 702, "s": 686, "text": "cd react-footer" }, { "code": null, "e": 814, "s": 702, "text": "Required module: Install the dependencies required in this project by typing the given command in the terminal." }, { "code": null, "e": 851, "s": 814, "text": "npm install --save styled-components" }, { "code": null, "e": 987, "s": 851, "text": "Now create the components folder in src then go to the components folder and create two files by the name Footer.js and FooterStyles.js" }, { "code": null, "e": 1061, "s": 987, "text": "Project Structure: The file structure in the project will look like this." }, { "code": null, "e": 1198, "s": 1061, "text": "Example: In this example we will design a footer, for that we will need to manipulate the App.js file and other created components file." }, { "code": null, "e": 1208, "s": 1198, "text": "Footer.js" }, { "code": "import React from \"react\";import { Box, Container, Row, Column, FooterLink, Heading,} from \"./FooterStyles\"; const Footer = () => { return ( <Box> <h1 style={{ color: \"green\", textAlign: \"center\", marginTop: \"-50px\" }}> GeeksforGeeks: A Computer Science Portal for Geeks </h1> <Container> <Row> <Column> <Heading>About Us</Heading> <FooterLink href=\"#\">Aim</FooterLink> <FooterLink href=\"#\">Vision</FooterLink> <FooterLink href=\"#\">Testimonials</FooterLink> </Column> <Column> <Heading>Services</Heading> <FooterLink href=\"#\">Writing</FooterLink> <FooterLink href=\"#\">Internships</FooterLink> <FooterLink href=\"#\">Coding</FooterLink> <FooterLink href=\"#\">Teaching</FooterLink> </Column> <Column> <Heading>Contact Us</Heading> <FooterLink href=\"#\">Uttar Pradesh</FooterLink> <FooterLink href=\"#\">Ahemdabad</FooterLink> <FooterLink href=\"#\">Indore</FooterLink> <FooterLink href=\"#\">Mumbai</FooterLink> </Column> <Column> <Heading>Social Media</Heading> <FooterLink href=\"#\"> <i className=\"fab fa-facebook-f\"> <span style={{ marginLeft: \"10px\" }}> Facebook </span> </i> </FooterLink> <FooterLink href=\"#\"> <i className=\"fab fa-instagram\"> <span style={{ marginLeft: \"10px\" }}> Instagram </span> </i> </FooterLink> <FooterLink href=\"#\"> <i className=\"fab fa-twitter\"> <span style={{ marginLeft: \"10px\" }}> Twitter </span> </i> </FooterLink> <FooterLink href=\"#\"> <i className=\"fab fa-youtube\"> <span style={{ marginLeft: \"10px\" }}> Youtube </span> </i> </FooterLink> </Column> </Row> </Container> </Box> );};export default Footer;", "e": 3446, "s": 1208, "text": null }, { "code": null, "e": 3462, "s": 3446, "text": "FooterStyles.js" }, { "code": "import styled from 'styled-components'; export const Box = styled.div` padding: 80px 60px; background: black; position: absolute; bottom: 0; width: 100%; @media (max-width: 1000px) { padding: 70px 30px; }`; export const Container = styled.div` display: flex; flex-direction: column; justify-content: center; max-width: 1000px; margin: 0 auto; /* background: red; */` export const Column = styled.div` display: flex; flex-direction: column; text-align: left; margin-left: 60px;`; export const Row = styled.div` display: grid; grid-template-columns: repeat(auto-fill, minmax(185px, 1fr)); grid-gap: 20px; @media (max-width: 1000px) { grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); }`; export const FooterLink = styled.a` color: #fff; margin-bottom: 20px; font-size: 18px; text-decoration: none; &:hover { color: green; transition: 200ms ease-in; }`; export const Heading = styled.p` font-size: 24px; color: #fff; margin-bottom: 40px; font-weight: bold;`;", "e": 4565, "s": 3462, "text": null }, { "code": null, "e": 4572, "s": 4565, "text": "App.js" }, { "code": "import React from 'react';import Footer from './components/Footer';function App() { return ( <Footer /> );} export default App;", "e": 4707, "s": 4572, "text": null }, { "code": null, "e": 4820, "s": 4707, "text": "Step to Run Application: Run the application using the following command from the root directory of the project." }, { "code": null, "e": 4830, "s": 4820, "text": "npm start" }, { "code": null, "e": 4929, "s": 4830, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 4945, "s": 4929, "text": "React-Questions" }, { "code": null, "e": 4969, "s": 4945, "text": "Technical Scripter 2020" }, { "code": null, "e": 4977, "s": 4969, "text": "ReactJS" }, { "code": null, "e": 4996, "s": 4977, "text": "Technical Scripter" }, { "code": null, "e": 5013, "s": 4996, "text": "Web Technologies" } ]
PostgreSQL – INNER JOIN
28 Aug, 2020 In PostgreSQL the INNER JOIN keyword selects all rows from both the tables as long as the condition satisfies. This keyword will create the result-set by combining all rows from both the tables where the condition satisfies i.e value of the common field will be the same. Syntax: SELECT table1.column1, table1.column2, table2.column1, .... FROM table1 INNER JOIN table2 ON table1.matching_column = table2.matching_column; table1: First table. table2: Second table matching_column: Column common to both the tables. Let’s analyze the above syntax: Firstly, using the SELECT statement we specify the tables from where we want the data to be selected. Second, we specify the main table. Third, we specify the table that the main table joins to. The below Venn Diagram illustrates the working of PostgreSQL INNER JOIN clause:For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link in our examples. Now, let’s look into a few examples. Example 1:Here we will be joining the “customer” table to “payment” table using the INNER JOIN clause. SELECT customer.customer_id, first_name, last_name, email, amount, payment_date FROM customer INNER JOIN payment ON payment.customer_id = customer.customer_id; Output: Example 2: Here we will be joining the “customer” table to “payment” table using the INNER JOIN clause and sort them with the ORDER BY clause: SELECT customer.customer_id, first_name, last_name, email, amount, payment_date FROM customer INNER JOIN payment ON payment.customer_id = customer.customer_id ORDER BY customer.customer_id; Output: Example 3:Here we will be joining the “customer” table to “payment” table using the INNER JOIN clause and filter them with the WHERE clause: SELECT customer.customer_id, first_name, last_name, email, amount, payment_date FROM customer INNER JOIN payment ON payment.customer_id = customer.customer_id WHERE customer.customer_id = 15; Output: Example 4:Here we will establish the relationship between three tables: staff, payment, and customer using the INNER JOIN clause. SELECT customer.customer_id, customer.first_name customer_first_name, customer.last_name customer_last_name, customer.email, staff.first_name staff_first_name, staff.last_name staff_last_name, amount, payment_date FROM customer INNER JOIN payment ON payment.customer_id = customer.customer_id INNER JOIN staff ON payment.staff_id = staff.staff_id; Output: postgreSQL-joins Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Aug, 2020" }, { "code": null, "e": 300, "s": 28, "text": "In PostgreSQL the INNER JOIN keyword selects all rows from both the tables as long as the condition satisfies. This keyword will create the result-set by combining all rows from both the tables where the condition satisfies i.e value of the common field will be the same." }, { "code": null, "e": 546, "s": 300, "text": "Syntax:\nSELECT table1.column1, table1.column2, table2.column1, ....\nFROM table1 \nINNER JOIN table2\nON table1.matching_column = table2.matching_column;\n\n\ntable1: First table.\ntable2: Second table\nmatching_column: Column common to both the tables." }, { "code": null, "e": 578, "s": 546, "text": "Let’s analyze the above syntax:" }, { "code": null, "e": 680, "s": 578, "text": "Firstly, using the SELECT statement we specify the tables from where we want the data to be selected." }, { "code": null, "e": 715, "s": 680, "text": "Second, we specify the main table." }, { "code": null, "e": 773, "s": 715, "text": "Third, we specify the table that the main table joins to." }, { "code": null, "e": 1018, "s": 773, "text": "The below Venn Diagram illustrates the working of PostgreSQL INNER JOIN clause:For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link in our examples." }, { "code": null, "e": 1055, "s": 1018, "text": "Now, let’s look into a few examples." }, { "code": null, "e": 1158, "s": 1055, "text": "Example 1:Here we will be joining the “customer” table to “payment” table using the INNER JOIN clause." }, { "code": null, "e": 1346, "s": 1158, "text": "SELECT\n customer.customer_id,\n first_name,\n last_name,\n email,\n amount,\n payment_date\nFROM\n customer\nINNER JOIN payment ON payment.customer_id = customer.customer_id;" }, { "code": null, "e": 1354, "s": 1346, "text": "Output:" }, { "code": null, "e": 1365, "s": 1354, "text": "Example 2:" }, { "code": null, "e": 1497, "s": 1365, "text": "Here we will be joining the “customer” table to “payment” table using the INNER JOIN clause and sort them with the ORDER BY clause:" }, { "code": null, "e": 1719, "s": 1497, "text": "SELECT\n customer.customer_id,\n first_name,\n last_name,\n email,\n amount,\n payment_date\nFROM\n customer\nINNER JOIN payment ON payment.customer_id = customer.customer_id\nORDER BY\n customer.customer_id;" }, { "code": null, "e": 1727, "s": 1719, "text": "Output:" }, { "code": null, "e": 1868, "s": 1727, "text": "Example 3:Here we will be joining the “customer” table to “payment” table using the INNER JOIN clause and filter them with the WHERE clause:" }, { "code": null, "e": 2092, "s": 1868, "text": "SELECT\n customer.customer_id,\n first_name,\n last_name,\n email,\n amount,\n payment_date\nFROM\n customer\nINNER JOIN payment ON payment.customer_id = customer.customer_id\nWHERE\n customer.customer_id = 15;" }, { "code": null, "e": 2100, "s": 2092, "text": "Output:" }, { "code": null, "e": 2230, "s": 2100, "text": "Example 4:Here we will establish the relationship between three tables: staff, payment, and customer using the INNER JOIN clause." }, { "code": null, "e": 2614, "s": 2230, "text": "SELECT\n customer.customer_id,\n customer.first_name customer_first_name,\n customer.last_name customer_last_name,\n customer.email,\n staff.first_name staff_first_name,\n staff.last_name staff_last_name,\n amount,\n payment_date\nFROM\n customer\nINNER JOIN payment ON payment.customer_id = customer.customer_id\nINNER JOIN staff ON payment.staff_id = staff.staff_id;" }, { "code": null, "e": 2622, "s": 2614, "text": "Output:" }, { "code": null, "e": 2639, "s": 2622, "text": "postgreSQL-joins" }, { "code": null, "e": 2644, "s": 2639, "text": "Misc" }, { "code": null, "e": 2649, "s": 2644, "text": "Misc" }, { "code": null, "e": 2654, "s": 2649, "text": "Misc" } ]
Univariate Linear Regression in Python
29 Sep, 2021 Univariate data is the type of data in which the result depends only on one variable. For instance, dataset of points on a line can be considered as a univariate data where abscissa can be considered as input feature and ordinate can be considered as output/result.For example:For line Y = 2X + 3;Input feature will be X and Y will be the result. Concept:For univariate linear regression, there is only one input feature vector. The line of regression will be in the form of: Y = b0 + b1 * XWhere,b0 and b1 are the coefficients of regression. Hence, it is being tried to predict regression coefficients b0 and b1 by training a model. Utility functions Predictdef predict(x, b0, b1): """Predicts the value of prediction based on current value of regression coefficients when input is x""" # Y = b0 + b1 * X return b0 + b1 * xCost function :Cost function computes the error percentage with the current value of regression coefficients. It quantitatively defines how far the model is wrt actual regression coefficients which has lowest rate of error.def cost(x, y, b0, b1): # y is a list of expected value errors = [] for x, y in zip(x, y): prediction = predict(x, b0, b1) expected = y difference = prediction-expected errors.append(difference) # Now, we have errors for all the observations, # for some input, the value of error might be positive # and for some input might be negative, # and if we directly add them up, # the values might cancel out leading to wrong output." # Hence, we use concept of mean squared error. # in mse, we return mean of square of all the errors. mse = sum([e * e for e in errors])/len(errors) return mseCost DerivativeAfter each iteration, the cost is upgraded in proportion to the error. The nature of error is very data sensitive. By data-sensitive i mean the error value changes very fast because we had square in error function. Hence, to make it more tolerant to high values of errors, we derivate the error function.The mathematics is as follows: Code:def cost_derivative(x, y, b0, b1, i): return sum([ 2*(predict(xi, b0, b1)-yi)*1 if i == 0 else 2*(predict(xi, b0, b1)-yi)*xi for xi, yi in zip(x, y) ])/len(x)Update Coefficients :At each iteration (epoch), the values of the regression coefficient are updated by a specific value wrt to the error from the previous iteration. This updation is very crucial and is the crux of the machine learning applications that you write.Updating the coefficients with exact an update of a coefficient is done by penalizing its value with a fraction of error that its previous values caused.This fraction is called as learning rate. This defines how fast our model reaches out to point of convergence(point where error is ideally 0). Python function for the same is as follows:def update_coeff(x, y, b0, b1, i, alpha): bi -= alpha * cost_derivative(x, y, b0, b1, i) return biStop Iterations:This is the function that is used to specify when should the iterations should stop.As per user, the algorithm stop_iteration generally returns true in following conditions:Max Iteration : Model is trained for a specified number of iterations.Error value : Depending upon the value of previous error, the algorithm decides whether to continue or stop.Accuracy : Depending upon the last accuracy of the model, if it is larger than the mentioned accuracy, the algorithm returns True,Hybrid : This is more often used. This combines more than one above mentioned conditions along with an exceptional break option. Exceptional break is condition where training continues until when something bad happens. Something bad might include overflow of result, time constraints exceeded, etc. Predictdef predict(x, b0, b1): """Predicts the value of prediction based on current value of regression coefficients when input is x""" # Y = b0 + b1 * X return b0 + b1 * x def predict(x, b0, b1): """Predicts the value of prediction based on current value of regression coefficients when input is x""" # Y = b0 + b1 * X return b0 + b1 * x Cost function :Cost function computes the error percentage with the current value of regression coefficients. It quantitatively defines how far the model is wrt actual regression coefficients which has lowest rate of error.def cost(x, y, b0, b1): # y is a list of expected value errors = [] for x, y in zip(x, y): prediction = predict(x, b0, b1) expected = y difference = prediction-expected errors.append(difference) # Now, we have errors for all the observations, # for some input, the value of error might be positive # and for some input might be negative, # and if we directly add them up, # the values might cancel out leading to wrong output." # Hence, we use concept of mean squared error. # in mse, we return mean of square of all the errors. mse = sum([e * e for e in errors])/len(errors) return mse def cost(x, y, b0, b1): # y is a list of expected value errors = [] for x, y in zip(x, y): prediction = predict(x, b0, b1) expected = y difference = prediction-expected errors.append(difference) # Now, we have errors for all the observations, # for some input, the value of error might be positive # and for some input might be negative, # and if we directly add them up, # the values might cancel out leading to wrong output." # Hence, we use concept of mean squared error. # in mse, we return mean of square of all the errors. mse = sum([e * e for e in errors])/len(errors) return mse Cost DerivativeAfter each iteration, the cost is upgraded in proportion to the error. The nature of error is very data sensitive. By data-sensitive i mean the error value changes very fast because we had square in error function. Hence, to make it more tolerant to high values of errors, we derivate the error function.The mathematics is as follows: Code:def cost_derivative(x, y, b0, b1, i): return sum([ 2*(predict(xi, b0, b1)-yi)*1 if i == 0 else 2*(predict(xi, b0, b1)-yi)*xi for xi, yi in zip(x, y) ])/len(x) Code: def cost_derivative(x, y, b0, b1, i): return sum([ 2*(predict(xi, b0, b1)-yi)*1 if i == 0 else 2*(predict(xi, b0, b1)-yi)*xi for xi, yi in zip(x, y) ])/len(x) Update Coefficients :At each iteration (epoch), the values of the regression coefficient are updated by a specific value wrt to the error from the previous iteration. This updation is very crucial and is the crux of the machine learning applications that you write.Updating the coefficients with exact an update of a coefficient is done by penalizing its value with a fraction of error that its previous values caused.This fraction is called as learning rate. This defines how fast our model reaches out to point of convergence(point where error is ideally 0). Python function for the same is as follows:def update_coeff(x, y, b0, b1, i, alpha): bi -= alpha * cost_derivative(x, y, b0, b1, i) return bi Python function for the same is as follows: def update_coeff(x, y, b0, b1, i, alpha): bi -= alpha * cost_derivative(x, y, b0, b1, i) return bi Stop Iterations:This is the function that is used to specify when should the iterations should stop.As per user, the algorithm stop_iteration generally returns true in following conditions:Max Iteration : Model is trained for a specified number of iterations.Error value : Depending upon the value of previous error, the algorithm decides whether to continue or stop.Accuracy : Depending upon the last accuracy of the model, if it is larger than the mentioned accuracy, the algorithm returns True,Hybrid : This is more often used. This combines more than one above mentioned conditions along with an exceptional break option. Exceptional break is condition where training continues until when something bad happens. Something bad might include overflow of result, time constraints exceeded, etc. Max Iteration : Model is trained for a specified number of iterations.Error value : Depending upon the value of previous error, the algorithm decides whether to continue or stop.Accuracy : Depending upon the last accuracy of the model, if it is larger than the mentioned accuracy, the algorithm returns True,Hybrid : This is more often used. This combines more than one above mentioned conditions along with an exceptional break option. Exceptional break is condition where training continues until when something bad happens. Something bad might include overflow of result, time constraints exceeded, etc. Max Iteration : Model is trained for a specified number of iterations. Error value : Depending upon the value of previous error, the algorithm decides whether to continue or stop. Accuracy : Depending upon the last accuracy of the model, if it is larger than the mentioned accuracy, the algorithm returns True, Hybrid : This is more often used. This combines more than one above mentioned conditions along with an exceptional break option. Exceptional break is condition where training continues until when something bad happens. Something bad might include overflow of result, time constraints exceeded, etc. Having all the utility functions defined, lets see the pseudo code followed by its implementation: Code : x, y is the given data.(b0, b1) <-- (0, 0)i = 0while True: if stop_iteration(i): break else: b0 = update_coeff(x, y, b0, b1, 0, alpha) b1 = update_coeff(x, y, b0, b1, 1, alpha) Final Oop implementation : class LinearRegressor: def __init__(self, x, y, alpha = 0.01, b0 = 0, b1 = 0): """ x: input feature y: result / target alpha: learning rate, default is 0.01 b0, b1: linear regression coefficient. """ self.i = 0 self.x = x self.y = y self.alpha = alpha self.b0 = b0 self.b1 = b1 if len(x) != len(y): raise TypeError("x and y should have same number of rows.") def predict(model, x): """Predicts the value of prediction based on current value of regression coefficients when input is x""" # Y = b0 + b1 * X return model.b0 + model.b1 * x def cost_derivative(model, i): x, y, b0, b1 = model.x, model.y, model.b0, model.b1 predict = model.predict return sum([ 2 * (predict(xi) - yi) * 1 if i == 0 else (predict(xi) - yi) * xi for xi, yi in zip(x, y) ]) / len(x) def update_coeff(model, i): cost_derivative = model.cost_derivative if i == 0: model.b0 -= model.alpha * cost_derivative(i) elif i == 1: model.b1 -= model.alpha * cost_derivative(i) def stop_iteration(model, max_epochs = 1000): model.i += 1 if model.i == max_epochs: return True else: return False def fit(model): update_coeff = model.update_coeff model.i = 0 while True: if model.stop_iteration(): break else: update_coeff(0) update_coeff(1) if __name__ == '__main__': linearRegressor = LinearRegressor( x =[i for i in range(12)], y =[2 * i + 3 for i in range(12)], alpha = 0.03 ) linearRegressor.fit() print(linearRegressor.predict(12)) # expects 2 * 12 + 3 = 27 vaibhavsinghtanwar Project Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Sep, 2021" }, { "code": null, "e": 401, "s": 54, "text": "Univariate data is the type of data in which the result depends only on one variable. For instance, dataset of points on a line can be considered as a univariate data where abscissa can be considered as input feature and ordinate can be considered as output/result.For example:For line Y = 2X + 3;Input feature will be X and Y will be the result." }, { "code": null, "e": 530, "s": 401, "text": "Concept:For univariate linear regression, there is only one input feature vector. The line of regression will be in the form of:" }, { "code": null, "e": 597, "s": 530, "text": "Y = b0 + b1 * XWhere,b0 and b1 are the coefficients of regression." }, { "code": null, "e": 688, "s": 597, "text": "Hence, it is being tried to predict regression coefficients b0 and b1 by training a model." }, { "code": null, "e": 706, "s": 688, "text": "Utility functions" }, { "code": null, "e": 3889, "s": 706, "text": "Predictdef predict(x, b0, b1): \"\"\"Predicts the value of prediction based on current value of regression coefficients when input is x\"\"\" # Y = b0 + b1 * X return b0 + b1 * xCost function :Cost function computes the error percentage with the current value of regression coefficients. It quantitatively defines how far the model is wrt actual regression coefficients which has lowest rate of error.def cost(x, y, b0, b1): # y is a list of expected value errors = [] for x, y in zip(x, y): prediction = predict(x, b0, b1) expected = y difference = prediction-expected errors.append(difference) # Now, we have errors for all the observations, # for some input, the value of error might be positive # and for some input might be negative, # and if we directly add them up, # the values might cancel out leading to wrong output.\" # Hence, we use concept of mean squared error. # in mse, we return mean of square of all the errors. mse = sum([e * e for e in errors])/len(errors) return mseCost DerivativeAfter each iteration, the cost is upgraded in proportion to the error. The nature of error is very data sensitive. By data-sensitive i mean the error value changes very fast because we had square in error function. Hence, to make it more tolerant to high values of errors, we derivate the error function.The mathematics is as follows: Code:def cost_derivative(x, y, b0, b1, i): return sum([ 2*(predict(xi, b0, b1)-yi)*1 if i == 0 else 2*(predict(xi, b0, b1)-yi)*xi for xi, yi in zip(x, y) ])/len(x)Update Coefficients :At each iteration (epoch), the values of the regression coefficient are updated by a specific value wrt to the error from the previous iteration. This updation is very crucial and is the crux of the machine learning applications that you write.Updating the coefficients with exact an update of a coefficient is done by penalizing its value with a fraction of error that its previous values caused.This fraction is called as learning rate. This defines how fast our model reaches out to point of convergence(point where error is ideally 0). Python function for the same is as follows:def update_coeff(x, y, b0, b1, i, alpha): bi -= alpha * cost_derivative(x, y, b0, b1, i) return biStop Iterations:This is the function that is used to specify when should the iterations should stop.As per user, the algorithm stop_iteration generally returns true in following conditions:Max Iteration : Model is trained for a specified number of iterations.Error value : Depending upon the value of previous error, the algorithm decides whether to continue or stop.Accuracy : Depending upon the last accuracy of the model, if it is larger than the mentioned accuracy, the algorithm returns True,Hybrid : This is more often used. This combines more than one above mentioned conditions along with an exceptional break option. Exceptional break is condition where training continues until when something bad happens. Something bad might include overflow of result, time constraints exceeded, etc." }, { "code": null, "e": 4078, "s": 3889, "text": "Predictdef predict(x, b0, b1): \"\"\"Predicts the value of prediction based on current value of regression coefficients when input is x\"\"\" # Y = b0 + b1 * X return b0 + b1 * x" }, { "code": "def predict(x, b0, b1): \"\"\"Predicts the value of prediction based on current value of regression coefficients when input is x\"\"\" # Y = b0 + b1 * X return b0 + b1 * x", "e": 4260, "s": 4078, "text": null }, { "code": null, "e": 5149, "s": 4260, "text": "Cost function :Cost function computes the error percentage with the current value of regression coefficients. It quantitatively defines how far the model is wrt actual regression coefficients which has lowest rate of error.def cost(x, y, b0, b1): # y is a list of expected value errors = [] for x, y in zip(x, y): prediction = predict(x, b0, b1) expected = y difference = prediction-expected errors.append(difference) # Now, we have errors for all the observations, # for some input, the value of error might be positive # and for some input might be negative, # and if we directly add them up, # the values might cancel out leading to wrong output.\" # Hence, we use concept of mean squared error. # in mse, we return mean of square of all the errors. mse = sum([e * e for e in errors])/len(errors) return mse" }, { "code": "def cost(x, y, b0, b1): # y is a list of expected value errors = [] for x, y in zip(x, y): prediction = predict(x, b0, b1) expected = y difference = prediction-expected errors.append(difference) # Now, we have errors for all the observations, # for some input, the value of error might be positive # and for some input might be negative, # and if we directly add them up, # the values might cancel out leading to wrong output.\" # Hence, we use concept of mean squared error. # in mse, we return mean of square of all the errors. mse = sum([e * e for e in errors])/len(errors) return mse", "e": 5815, "s": 5149, "text": null }, { "code": null, "e": 6416, "s": 5815, "text": "Cost DerivativeAfter each iteration, the cost is upgraded in proportion to the error. The nature of error is very data sensitive. By data-sensitive i mean the error value changes very fast because we had square in error function. Hence, to make it more tolerant to high values of errors, we derivate the error function.The mathematics is as follows: Code:def cost_derivative(x, y, b0, b1, i): return sum([ 2*(predict(xi, b0, b1)-yi)*1 if i == 0 else 2*(predict(xi, b0, b1)-yi)*xi for xi, yi in zip(x, y) ])/len(x)" }, { "code": null, "e": 6427, "s": 6421, "text": "Code:" }, { "code": "def cost_derivative(x, y, b0, b1, i): return sum([ 2*(predict(xi, b0, b1)-yi)*1 if i == 0 else 2*(predict(xi, b0, b1)-yi)*xi for xi, yi in zip(x, y) ])/len(x)", "e": 6670, "s": 6427, "text": null }, { "code": null, "e": 7382, "s": 6670, "text": "Update Coefficients :At each iteration (epoch), the values of the regression coefficient are updated by a specific value wrt to the error from the previous iteration. This updation is very crucial and is the crux of the machine learning applications that you write.Updating the coefficients with exact an update of a coefficient is done by penalizing its value with a fraction of error that its previous values caused.This fraction is called as learning rate. This defines how fast our model reaches out to point of convergence(point where error is ideally 0). Python function for the same is as follows:def update_coeff(x, y, b0, b1, i, alpha): bi -= alpha * cost_derivative(x, y, b0, b1, i) return bi" }, { "code": null, "e": 7431, "s": 7387, "text": "Python function for the same is as follows:" }, { "code": "def update_coeff(x, y, b0, b1, i, alpha): bi -= alpha * cost_derivative(x, y, b0, b1, i) return bi", "e": 7536, "s": 7431, "text": null }, { "code": null, "e": 8332, "s": 7536, "text": "Stop Iterations:This is the function that is used to specify when should the iterations should stop.As per user, the algorithm stop_iteration generally returns true in following conditions:Max Iteration : Model is trained for a specified number of iterations.Error value : Depending upon the value of previous error, the algorithm decides whether to continue or stop.Accuracy : Depending upon the last accuracy of the model, if it is larger than the mentioned accuracy, the algorithm returns True,Hybrid : This is more often used. This combines more than one above mentioned conditions along with an exceptional break option. Exceptional break is condition where training continues until when something bad happens. Something bad might include overflow of result, time constraints exceeded, etc." }, { "code": null, "e": 8939, "s": 8332, "text": "Max Iteration : Model is trained for a specified number of iterations.Error value : Depending upon the value of previous error, the algorithm decides whether to continue or stop.Accuracy : Depending upon the last accuracy of the model, if it is larger than the mentioned accuracy, the algorithm returns True,Hybrid : This is more often used. This combines more than one above mentioned conditions along with an exceptional break option. Exceptional break is condition where training continues until when something bad happens. Something bad might include overflow of result, time constraints exceeded, etc." }, { "code": null, "e": 9010, "s": 8939, "text": "Max Iteration : Model is trained for a specified number of iterations." }, { "code": null, "e": 9119, "s": 9010, "text": "Error value : Depending upon the value of previous error, the algorithm decides whether to continue or stop." }, { "code": null, "e": 9250, "s": 9119, "text": "Accuracy : Depending upon the last accuracy of the model, if it is larger than the mentioned accuracy, the algorithm returns True," }, { "code": null, "e": 9549, "s": 9250, "text": "Hybrid : This is more often used. This combines more than one above mentioned conditions along with an exceptional break option. Exceptional break is condition where training continues until when something bad happens. Something bad might include overflow of result, time constraints exceeded, etc." }, { "code": null, "e": 9648, "s": 9549, "text": "Having all the utility functions defined, lets see the pseudo code followed by its implementation:" }, { "code": null, "e": 9655, "s": 9648, "text": "Code :" }, { "code": "x, y is the given data.(b0, b1) <-- (0, 0)i = 0while True: if stop_iteration(i): break else: b0 = update_coeff(x, y, b0, b1, 0, alpha) b1 = update_coeff(x, y, b0, b1, 1, alpha)", "e": 9859, "s": 9655, "text": null }, { "code": null, "e": 9886, "s": 9859, "text": "Final Oop implementation :" }, { "code": "class LinearRegressor: def __init__(self, x, y, alpha = 0.01, b0 = 0, b1 = 0): \"\"\" x: input feature y: result / target alpha: learning rate, default is 0.01 b0, b1: linear regression coefficient. \"\"\" self.i = 0 self.x = x self.y = y self.alpha = alpha self.b0 = b0 self.b1 = b1 if len(x) != len(y): raise TypeError(\"x and y should have same number of rows.\") def predict(model, x): \"\"\"Predicts the value of prediction based on current value of regression coefficients when input is x\"\"\" # Y = b0 + b1 * X return model.b0 + model.b1 * x def cost_derivative(model, i): x, y, b0, b1 = model.x, model.y, model.b0, model.b1 predict = model.predict return sum([ 2 * (predict(xi) - yi) * 1 if i == 0 else (predict(xi) - yi) * xi for xi, yi in zip(x, y) ]) / len(x) def update_coeff(model, i): cost_derivative = model.cost_derivative if i == 0: model.b0 -= model.alpha * cost_derivative(i) elif i == 1: model.b1 -= model.alpha * cost_derivative(i) def stop_iteration(model, max_epochs = 1000): model.i += 1 if model.i == max_epochs: return True else: return False def fit(model): update_coeff = model.update_coeff model.i = 0 while True: if model.stop_iteration(): break else: update_coeff(0) update_coeff(1) if __name__ == '__main__': linearRegressor = LinearRegressor( x =[i for i in range(12)], y =[2 * i + 3 for i in range(12)], alpha = 0.03 ) linearRegressor.fit() print(linearRegressor.predict(12)) # expects 2 * 12 + 3 = 27", "e": 11775, "s": 9886, "text": null }, { "code": null, "e": 11794, "s": 11775, "text": "vaibhavsinghtanwar" }, { "code": null, "e": 11802, "s": 11794, "text": "Project" }, { "code": null, "e": 11809, "s": 11802, "text": "Python" }, { "code": null, "e": 11825, "s": 11809, "text": "Python Programs" } ]
Program to calculate area of a rhombus whose one side and diagonal are given
19 Mar, 2022 Given the length of diagonal ‘d1’ of a rhombus and a side ‘a’, the task is to find the area of that rhombus. A rhombus is a polygon having 4 equal sides in which both the opposite sides are parallel, and opposite angles are equal. Examples: Input: d = 15, a = 10 Output: 99.21567416492215 Input: d = 20, a = 18 Output: 299.3325909419153 Approach: Get the diagonal ‘d1’ and side ‘a’ of the rhombus We know that, But since we don’t know the other diagonal d2, we cannot use this formula yet So we first find the second diagonal d2 with the help of d1 and a Now we can use the area formula to compute the area of the Rhombus C++ Java Python3 C# Javascript // C++ program to calculate the area of a rhombus// whose one side and one diagonal is given#include<bits/stdc++.h>using namespace std; // function to calculate the area of the rhombusdouble area(double d1, double a){ // Second diagonal double d2 = sqrt(4 * (a * a) - d1 * d1); // area of rhombus double area = 0.5 * d1 * d2; // return the area return area;} // Driver codeint main(){ double d = 7.07; double a = 5; printf("%0.8f", area(d, a));} // This code is contributed by Mohit Kumar // Java program to calculate the area of a rhombus// whose one side and one diagonal is givenclass GFG{ // function to calculate the area of the rhombus static double area(double d1, double a) { // Second diagonal double d2 = Math.sqrt(4 * (a * a) - d1 * d1); // area of rhombus double area = 0.5 * d1 * d2; // return the area return area; } // Driver code public static void main (String[] args) { double d = 7.07; double a = 5; System.out.println(area(d, a)); }} // This code is contributed by AnkitRai01 # Python program to calculate# the area of a rhombus# whose one side and# one diagonal is given # function to calculate# the area of the rhombusdef area(d1, a): # Second diagonal d2 = (4*(a**2) - d1**2)**0.5 # area of rhombus area = 0.5 * d1 * d2 # return the area return(area) # driver coded = 7.07a = 5print(area(d, a)) // C# program to calculate the area of a rhombus// whose one side and one diagonal is givenusing System; class GFG{ // function to calculate the area of the rhombus static double area(double d1, double a) { // Second diagonal double d2 = Math.Sqrt(4 * (a * a) - d1 * d1); // area of rhombus double area = 0.5 * d1 * d2; // return the area return area; } // Driver code public static void Main (String []args) { double d = 7.07; double a = 5; Console.WriteLine(area(d, a)); }} // This code is contributed by Arnab Kundu <script>// javascript program to calculate the area of a rhombus// whose one side and one diagonal is given // function to calculate the area of the rhombusfunction area(d1 , a){ // Second diagonal var d2 = Math.sqrt(4 * (a * a) - d1 * d1); // area of rhombus var area = 0.5 * d1 * d2; // return the area return area;} // Driver codevar d = 7.07;var a = 5;document.write(area(d, a)); // This code is contributed by 29AjayKumar</script> 24.999998859949972 Time Complexity: O(1) Auxiliary Space: O(1) mohit kumar 29 ankthon andrew1234 29AjayKumar subham348 area-volume-programs Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Mar, 2022" }, { "code": null, "e": 164, "s": 54, "text": "Given the length of diagonal ‘d1’ of a rhombus and a side ‘a’, the task is to find the area of that rhombus. " }, { "code": null, "e": 286, "s": 164, "text": "A rhombus is a polygon having 4 equal sides in which both the opposite sides are parallel, and opposite angles are equal." }, { "code": null, "e": 300, "s": 288, "text": "Examples: " }, { "code": null, "e": 397, "s": 300, "text": "Input: d = 15, a = 10\nOutput: 99.21567416492215\n\nInput: d = 20, a = 18\nOutput: 299.3325909419153" }, { "code": null, "e": 410, "s": 399, "text": "Approach: " }, { "code": null, "e": 460, "s": 410, "text": "Get the diagonal ‘d1’ and side ‘a’ of the rhombus" }, { "code": null, "e": 476, "s": 460, "text": "We know that, " }, { "code": null, "e": 556, "s": 478, "text": "But since we don’t know the other diagonal d2, we cannot use this formula yet" }, { "code": null, "e": 623, "s": 556, "text": "So we first find the second diagonal d2 with the help of d1 and a " }, { "code": null, "e": 692, "s": 625, "text": "Now we can use the area formula to compute the area of the Rhombus" }, { "code": null, "e": 698, "s": 694, "text": "C++" }, { "code": null, "e": 703, "s": 698, "text": "Java" }, { "code": null, "e": 711, "s": 703, "text": "Python3" }, { "code": null, "e": 714, "s": 711, "text": "C#" }, { "code": null, "e": 725, "s": 714, "text": "Javascript" }, { "code": "// C++ program to calculate the area of a rhombus// whose one side and one diagonal is given#include<bits/stdc++.h>using namespace std; // function to calculate the area of the rhombusdouble area(double d1, double a){ // Second diagonal double d2 = sqrt(4 * (a * a) - d1 * d1); // area of rhombus double area = 0.5 * d1 * d2; // return the area return area;} // Driver codeint main(){ double d = 7.07; double a = 5; printf(\"%0.8f\", area(d, a));} // This code is contributed by Mohit Kumar", "e": 1248, "s": 725, "text": null }, { "code": "// Java program to calculate the area of a rhombus// whose one side and one diagonal is givenclass GFG{ // function to calculate the area of the rhombus static double area(double d1, double a) { // Second diagonal double d2 = Math.sqrt(4 * (a * a) - d1 * d1); // area of rhombus double area = 0.5 * d1 * d2; // return the area return area; } // Driver code public static void main (String[] args) { double d = 7.07; double a = 5; System.out.println(area(d, a)); }} // This code is contributed by AnkitRai01", "e": 1867, "s": 1248, "text": null }, { "code": "# Python program to calculate# the area of a rhombus# whose one side and# one diagonal is given # function to calculate# the area of the rhombusdef area(d1, a): # Second diagonal d2 = (4*(a**2) - d1**2)**0.5 # area of rhombus area = 0.5 * d1 * d2 # return the area return(area) # driver coded = 7.07a = 5print(area(d, a))", "e": 2222, "s": 1867, "text": null }, { "code": "// C# program to calculate the area of a rhombus// whose one side and one diagonal is givenusing System; class GFG{ // function to calculate the area of the rhombus static double area(double d1, double a) { // Second diagonal double d2 = Math.Sqrt(4 * (a * a) - d1 * d1); // area of rhombus double area = 0.5 * d1 * d2; // return the area return area; } // Driver code public static void Main (String []args) { double d = 7.07; double a = 5; Console.WriteLine(area(d, a)); }} // This code is contributed by Arnab Kundu", "e": 2853, "s": 2222, "text": null }, { "code": "<script>// javascript program to calculate the area of a rhombus// whose one side and one diagonal is given // function to calculate the area of the rhombusfunction area(d1 , a){ // Second diagonal var d2 = Math.sqrt(4 * (a * a) - d1 * d1); // area of rhombus var area = 0.5 * d1 * d2; // return the area return area;} // Driver codevar d = 7.07;var a = 5;document.write(area(d, a)); // This code is contributed by 29AjayKumar</script>", "e": 3315, "s": 2853, "text": null }, { "code": null, "e": 3334, "s": 3315, "text": "24.999998859949972" }, { "code": null, "e": 3358, "s": 3336, "text": "Time Complexity: O(1)" }, { "code": null, "e": 3380, "s": 3358, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 3395, "s": 3380, "text": "mohit kumar 29" }, { "code": null, "e": 3403, "s": 3395, "text": "ankthon" }, { "code": null, "e": 3414, "s": 3403, "text": "andrew1234" }, { "code": null, "e": 3426, "s": 3414, "text": "29AjayKumar" }, { "code": null, "e": 3436, "s": 3426, "text": "subham348" }, { "code": null, "e": 3457, "s": 3436, "text": "area-volume-programs" }, { "code": null, "e": 3467, "s": 3457, "text": "Geometric" }, { "code": null, "e": 3480, "s": 3467, "text": "Mathematical" }, { "code": null, "e": 3493, "s": 3480, "text": "Mathematical" }, { "code": null, "e": 3503, "s": 3493, "text": "Geometric" } ]
Creating a Pandas DataFrame
22 Jun, 2021 In the real world, a Pandas DataFrame will be created by loading the datasets from existing storage, storage can be SQL Database, CSV file, and Excel file. Pandas DataFrame can be created from the lists, dictionary, and from a list of dictionary etc. A Dataframe is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns. In dataframe datasets arrange in rows and columns, we can store any number of datasets in a dataframe. We can perform many operations on these datasets like arithmetic operation, columns/rows selection, columns/rows addition etc. Pandas DataFrame can be created in multiple ways. Let’s discuss different ways to create a DataFrame one by one.Creating an empty dataframe : A basic DataFrame, which can be created is an Empty Dataframe. An Empty Dataframe is created just by calling a dataframe constructor. Python3 # import pandas as pdimport pandas as pd # Calling DataFrame constructordf = pd.DataFrame() print(df) Output : Empty DataFrame Columns: [] Index: [] Creating a dataframe using List: DataFrame can be created using a single list or a list of lists. Python3 # import pandas as pdimport pandas as pd # list of stringslst = ['Geeks', 'For', 'Geeks', 'is', 'portal', 'for', 'Geeks'] # Calling DataFrame constructor on listdf = pd.DataFrame(lst)print(df) Output: Creating DataFrame from dict of ndarray/lists: To create DataFrame from dict of narray/list, all the narray must be of same length. If index is passed then the length index should be equal to the length of arrays. If no index is passed, then by default, index will be range(n) where n is the array length. Python3 # Python code demonstrate creating# DataFrame from dict narray / lists# By default addresses. import pandas as pd # initialise data of lists.data = {'Name':['Tom', 'nick', 'krish', 'jack'], 'Age':[20, 21, 19, 18]} # Create DataFramedf = pd.DataFrame(data) # Print the output.print(df) Output: Create pandas dataframe from lists using dictionary: Creating pandas data-frame from lists using dictionary can be achieved in different ways. We can create pandas dataframe from lists using dictionary using pandas.DataFrame. With this method in Pandas we can transform a dictionary of list to a dataframe. Python3 # importing pandas as pdimport pandas as pd # dictionary of listsdict = {'name':["aparna", "pankaj", "sudhir", "Geeku"], 'degree': ["MBA", "BCA", "M.Tech", "MBA"], 'score':[90, 40, 80, 98]} df = pd.DataFrame(dict) print(df) Output: Multiple ways of creating dataframe : Different ways to create Pandas Dataframe Create pandas dataframe from lists using zip Create a Pandas DataFrame from List of Dicts Create a Pandas Dataframe from a dict of equal length lists Creating a dataframe using List Create pandas dataframe from lists using dictionary anikaseth98 Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jun, 2021" }, { "code": null, "e": 305, "s": 52, "text": "In the real world, a Pandas DataFrame will be created by loading the datasets from existing storage, storage can be SQL Database, CSV file, and Excel file. Pandas DataFrame can be created from the lists, dictionary, and from a list of dictionary etc. " }, { "code": null, "e": 650, "s": 305, "text": "A Dataframe is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns. In dataframe datasets arrange in rows and columns, we can store any number of datasets in a dataframe. We can perform many operations on these datasets like arithmetic operation, columns/rows selection, columns/rows addition etc. " }, { "code": null, "e": 928, "s": 650, "text": "Pandas DataFrame can be created in multiple ways. Let’s discuss different ways to create a DataFrame one by one.Creating an empty dataframe : A basic DataFrame, which can be created is an Empty Dataframe. An Empty Dataframe is created just by calling a dataframe constructor. " }, { "code": null, "e": 936, "s": 928, "text": "Python3" }, { "code": "# import pandas as pdimport pandas as pd # Calling DataFrame constructordf = pd.DataFrame() print(df)", "e": 1038, "s": 936, "text": null }, { "code": null, "e": 1049, "s": 1038, "text": "Output : " }, { "code": null, "e": 1087, "s": 1049, "text": "Empty DataFrame\nColumns: []\nIndex: []" }, { "code": null, "e": 1189, "s": 1087, "text": " Creating a dataframe using List: DataFrame can be created using a single list or a list of lists. " }, { "code": null, "e": 1197, "s": 1189, "text": "Python3" }, { "code": "# import pandas as pdimport pandas as pd # list of stringslst = ['Geeks', 'For', 'Geeks', 'is', 'portal', 'for', 'Geeks'] # Calling DataFrame constructor on listdf = pd.DataFrame(lst)print(df)", "e": 1401, "s": 1197, "text": null }, { "code": null, "e": 1411, "s": 1401, "text": "Output: " }, { "code": null, "e": 1721, "s": 1411, "text": " Creating DataFrame from dict of ndarray/lists: To create DataFrame from dict of narray/list, all the narray must be of same length. If index is passed then the length index should be equal to the length of arrays. If no index is passed, then by default, index will be range(n) where n is the array length. " }, { "code": null, "e": 1729, "s": 1721, "text": "Python3" }, { "code": "# Python code demonstrate creating# DataFrame from dict narray / lists# By default addresses. import pandas as pd # initialise data of lists.data = {'Name':['Tom', 'nick', 'krish', 'jack'], 'Age':[20, 21, 19, 18]} # Create DataFramedf = pd.DataFrame(data) # Print the output.print(df)", "e": 2014, "s": 1729, "text": null }, { "code": null, "e": 2024, "s": 2014, "text": "Output: " }, { "code": null, "e": 2334, "s": 2024, "text": " Create pandas dataframe from lists using dictionary: Creating pandas data-frame from lists using dictionary can be achieved in different ways. We can create pandas dataframe from lists using dictionary using pandas.DataFrame. With this method in Pandas we can transform a dictionary of list to a dataframe. " }, { "code": null, "e": 2342, "s": 2334, "text": "Python3" }, { "code": "# importing pandas as pdimport pandas as pd # dictionary of listsdict = {'name':[\"aparna\", \"pankaj\", \"sudhir\", \"Geeku\"], 'degree': [\"MBA\", \"BCA\", \"M.Tech\", \"MBA\"], 'score':[90, 40, 80, 98]} df = pd.DataFrame(dict) print(df)", "e": 2580, "s": 2342, "text": null }, { "code": null, "e": 2590, "s": 2580, "text": "Output: " }, { "code": null, "e": 2631, "s": 2590, "text": " Multiple ways of creating dataframe : " }, { "code": null, "e": 2673, "s": 2631, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2718, "s": 2673, "text": "Create pandas dataframe from lists using zip" }, { "code": null, "e": 2763, "s": 2718, "text": "Create a Pandas DataFrame from List of Dicts" }, { "code": null, "e": 2823, "s": 2763, "text": "Create a Pandas Dataframe from a dict of equal length lists" }, { "code": null, "e": 2855, "s": 2823, "text": "Creating a dataframe using List" }, { "code": null, "e": 2907, "s": 2855, "text": "Create pandas dataframe from lists using dictionary" }, { "code": null, "e": 2921, "s": 2909, "text": "anikaseth98" }, { "code": null, "e": 2945, "s": 2921, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2959, "s": 2945, "text": "Python-pandas" }, { "code": null, "e": 2966, "s": 2959, "text": "Python" } ]
Int16.CompareTo() Method in C#
The Int16.CompareTo() method in C# is used to compare this instance to a specified object or another Int16 instance and returns an integer that indicates whether the value of this instance is less than, equal to, or greater than the value of the specified object or the other Int16 instance. Following is the syntax − public int CompareTo (short val); public int CompareTo (object val); Above, in the 1st syntax, the value val is an integer to compare, whereas Val in the 2nd syntax is an object to compare. The return value is less than zero if the current instance is less than the value. It’s zero, if the current instance is equal to value, whereas return value is more than zero if the current instance is more than value. Let us now see an example to implement the Int16.CompareTo() method − using System; public class Demo { public static void Main(){ short val1 = 20; short val2 = 18; Console.WriteLine("Value 1 = "+val1); Console.WriteLine("Value 2 = "+val2); Console.WriteLine("Return value (comparison) = "+val1.CompareTo(val2)); } } This will produce the following output − Value 1 = 20 Value 2 = 18 Return value (comparison) = 2 Let us now see another example to implement the Int16.CompareTo() method − using System; public class Demo { public static void Main(){ short val1 = 10; short val2 = 10; Console.WriteLine("Value 1 = "+val1); Console.WriteLine("Value 2 = "+val2); Console.WriteLine("Return value (comparison) = "+val1.CompareTo(val2)); } } This will produce the following output − Value 1 = 10 Value 2 = 10 Return value (comparison) = 0
[ { "code": null, "e": 1354, "s": 1062, "text": "The Int16.CompareTo() method in C# is used to compare this instance to a specified object or another Int16 instance and returns an integer that indicates whether the value of this instance is less than, equal to, or greater than the value of the specified object or the other Int16 instance." }, { "code": null, "e": 1380, "s": 1354, "text": "Following is the syntax −" }, { "code": null, "e": 1449, "s": 1380, "text": "public int CompareTo (short val);\npublic int CompareTo (object val);" }, { "code": null, "e": 1570, "s": 1449, "text": "Above, in the 1st syntax, the value val is an integer to compare, whereas Val in the 2nd syntax is an object to compare." }, { "code": null, "e": 1790, "s": 1570, "text": "The return value is less than zero if the current instance is less than the value. It’s zero, if the current instance is equal to value, whereas return value is more than zero if the current instance is more than value." }, { "code": null, "e": 1860, "s": 1790, "text": "Let us now see an example to implement the Int16.CompareTo() method −" }, { "code": null, "e": 2143, "s": 1860, "text": "using System;\npublic class Demo {\n public static void Main(){\n short val1 = 20;\n short val2 = 18;\n Console.WriteLine(\"Value 1 = \"+val1);\n Console.WriteLine(\"Value 2 = \"+val2);\n Console.WriteLine(\"Return value (comparison) = \"+val1.CompareTo(val2));\n }\n}" }, { "code": null, "e": 2184, "s": 2143, "text": "This will produce the following output −" }, { "code": null, "e": 2240, "s": 2184, "text": "Value 1 = 20\nValue 2 = 18\nReturn value (comparison) = 2" }, { "code": null, "e": 2315, "s": 2240, "text": "Let us now see another example to implement the Int16.CompareTo() method −" }, { "code": null, "e": 2598, "s": 2315, "text": "using System;\npublic class Demo {\n public static void Main(){\n short val1 = 10;\n short val2 = 10;\n Console.WriteLine(\"Value 1 = \"+val1);\n Console.WriteLine(\"Value 2 = \"+val2);\n Console.WriteLine(\"Return value (comparison) = \"+val1.CompareTo(val2));\n }\n}" }, { "code": null, "e": 2639, "s": 2598, "text": "This will produce the following output −" }, { "code": null, "e": 2695, "s": 2639, "text": "Value 1 = 10\nValue 2 = 10\nReturn value (comparison) = 0" } ]
Enrich your train fold with a custom sampler inside an imblearn pipeline | by Nils Flaschel | Towards Data Science
When it comes to small data sets, life can get complicated. In medicine, a data set can easily consist of less than 100 patients/rows. But in the other dimension it can become pretty large — easily over 3000 features. However, sometimes you will find a way to augment your data, which — in my case — means that you multiply your data set with slightly different feature values. That way you can multiply your training data. Of course this is a simplified version of what I really did, but that’s a different story. There are different ways to augment your data, but this article is not intended to cover the wide field of data augmentation. But you have to be careful, data augmentation is a powerful weapon that has to be used with caution. And even used correctly it is not guaranteed to boost the performance of your estimator. Btw, I wouldn’t be able to write this article without the help of my colleagues and people from StackOverflow! Once you have a set of augmented data to enrich your original data set, you will ask yourself how and at which point to merge them. Typically you are using sklearn and its modules to evaluate your estimator or search for optimal hyper-parameters. Popular modules including RandomizedSearchCV or cross_validate have the option to pass a cross validation method like KFold. By utilizing a cross validation method to measure the performance of your estimator, your data is split in a train and a test set. This is done dynamically under the hood of the sklearn methods. This is usually fine and it means that you don’t have to bother with it more than necessary. There is just one problem when you want to use augmented data with a cross validation method — you don’t want to have augmented data in your test fold. Why is that? You want to know how your estimator performes in reality, and your augmented data does not reflect the reality. Additionally, you want to only augment the data in your train set and don’t want to have augmented data in your train fold. Back to the question, is it possible to influence the train test split in your cross validation? Yes, imblearn.pipeline.Pipeline to the rescue. This pipeline is similar to the one you may know from sklearn, you can chain processing steps and estimators in a so called pipeline. The big difference and advantage for us is the way it works inside a cross validation. It operates only on the train set! This is great news, but you still need to define a method to enrich your original data and pass it in the pipeline. The easiest way is using imblearn’s FunctionSampler to turn any function into a sampler that can be passed in a pipeline. There is plenty of documentation on the imblearn website. But maybe you want to do something more sophisticated and build your own sampler. This is where sklearn’s BaseEstimator comes into play, which is a base class for a custom estimator. We can use it to build our sampler. import pandas as pdfrom sklearn.base import BaseEstimatorclass EnrichWithAugmentedData(BaseEstimator): """ Resampler to pass augmented data in a imblearn pipeline In this example I pass a list of augmented data frames with identical endpoints y to be merged with the original data X """ def __init__(self, augmented_sets): self.augmented_sets = augmented_sets def fit_resample(self, X, y): return self.resample(X, y) def resample(self, X, y): self.data = [] for i, df in enumerate(self.augmented_sets): self.data.append(self.augmented_sets[i].copy()) for i, df in enumerate(self.data): self.data[i] = self.data[i].loc[X.index, :] X = pd.concat([X, *self.data], axis=0) n = len(self.data) + 1 y = pd.concat([y]*n, axis=0) return X, y# Feel free to comment my code, I am a physicist :D Now, we can use our sampler to build a pipeline with any estimator: from xgboost import XGBClassifierfrom imblearn.pipeline import Pipelineaugmented_sets = [df_augmented_01, df_augmented_02]model = XGBClassifier()ewad = EnrichWithAugmentedData(augmented_sets)pipeline = Pipeline([('ewad', ewad), ('model', model)]) Let’s say that we want to conduct a RandomizedSearchCV utilizing a RepeatedStratifiedKFold with our pipeline: cv = RepeatedStratifiedKFold( n_splits=5, n_repeats=10, random_state=101 )# make sure that you have the suffix with the name of your pipeline step in front of your parameter name!parameter_grid = { 'model__max_depth':[2, 3, 4], 'model__learning_rate':np.arange(0.005, 0.5, 0.05),}# make sure that you do not refit, because the refit will be without your augmented data!gs = RandomizedSearchCV( estimator=pipeline, n_iter=3000, param_distributions=parameter_grid, scoring='roc_auc', n_jobs=-1, cv=cv, verbose=1, random_state=101, refit=False)grid_result = gs.fit(X, y)print("Best: {:.2f} using {}".format( grid_result.best_score_, grid_result.best_params_)) You can also use the same procedure with cross_validate and get the best model and the feature importance to be used as feature selection method with pipeline.steps[1][1]. If you train with augmented data, chances will be high that it influences the features selected by your estimator. I hope this article helps some fellow Data Scientists.
[ { "code": null, "e": 390, "s": 172, "text": "When it comes to small data sets, life can get complicated. In medicine, a data set can easily consist of less than 100 patients/rows. But in the other dimension it can become pretty large — easily over 3000 features." }, { "code": null, "e": 813, "s": 390, "text": "However, sometimes you will find a way to augment your data, which — in my case — means that you multiply your data set with slightly different feature values. That way you can multiply your training data. Of course this is a simplified version of what I really did, but that’s a different story. There are different ways to augment your data, but this article is not intended to cover the wide field of data augmentation." }, { "code": null, "e": 1003, "s": 813, "text": "But you have to be careful, data augmentation is a powerful weapon that has to be used with caution. And even used correctly it is not guaranteed to boost the performance of your estimator." }, { "code": null, "e": 1114, "s": 1003, "text": "Btw, I wouldn’t be able to write this article without the help of my colleagues and people from StackOverflow!" }, { "code": null, "e": 1681, "s": 1114, "text": "Once you have a set of augmented data to enrich your original data set, you will ask yourself how and at which point to merge them. Typically you are using sklearn and its modules to evaluate your estimator or search for optimal hyper-parameters. Popular modules including RandomizedSearchCV or cross_validate have the option to pass a cross validation method like KFold. By utilizing a cross validation method to measure the performance of your estimator, your data is split in a train and a test set. This is done dynamically under the hood of the sklearn methods." }, { "code": null, "e": 2175, "s": 1681, "text": "This is usually fine and it means that you don’t have to bother with it more than necessary. There is just one problem when you want to use augmented data with a cross validation method — you don’t want to have augmented data in your test fold. Why is that? You want to know how your estimator performes in reality, and your augmented data does not reflect the reality. Additionally, you want to only augment the data in your train set and don’t want to have augmented data in your train fold." }, { "code": null, "e": 2575, "s": 2175, "text": "Back to the question, is it possible to influence the train test split in your cross validation? Yes, imblearn.pipeline.Pipeline to the rescue. This pipeline is similar to the one you may know from sklearn, you can chain processing steps and estimators in a so called pipeline. The big difference and advantage for us is the way it works inside a cross validation. It operates only on the train set!" }, { "code": null, "e": 3090, "s": 2575, "text": "This is great news, but you still need to define a method to enrich your original data and pass it in the pipeline. The easiest way is using imblearn’s FunctionSampler to turn any function into a sampler that can be passed in a pipeline. There is plenty of documentation on the imblearn website. But maybe you want to do something more sophisticated and build your own sampler. This is where sklearn’s BaseEstimator comes into play, which is a base class for a custom estimator. We can use it to build our sampler." }, { "code": null, "e": 4000, "s": 3090, "text": "import pandas as pdfrom sklearn.base import BaseEstimatorclass EnrichWithAugmentedData(BaseEstimator): \"\"\" Resampler to pass augmented data in a imblearn pipeline In this example I pass a list of augmented data frames with identical endpoints y to be merged with the original data X \"\"\" def __init__(self, augmented_sets): self.augmented_sets = augmented_sets def fit_resample(self, X, y): return self.resample(X, y) def resample(self, X, y): self.data = [] for i, df in enumerate(self.augmented_sets): self.data.append(self.augmented_sets[i].copy()) for i, df in enumerate(self.data): self.data[i] = self.data[i].loc[X.index, :] X = pd.concat([X, *self.data], axis=0) n = len(self.data) + 1 y = pd.concat([y]*n, axis=0) return X, y# Feel free to comment my code, I am a physicist :D" }, { "code": null, "e": 4068, "s": 4000, "text": "Now, we can use our sampler to build a pipeline with any estimator:" }, { "code": null, "e": 4315, "s": 4068, "text": "from xgboost import XGBClassifierfrom imblearn.pipeline import Pipelineaugmented_sets = [df_augmented_01, df_augmented_02]model = XGBClassifier()ewad = EnrichWithAugmentedData(augmented_sets)pipeline = Pipeline([('ewad', ewad), ('model', model)])" }, { "code": null, "e": 4425, "s": 4315, "text": "Let’s say that we want to conduct a RandomizedSearchCV utilizing a RepeatedStratifiedKFold with our pipeline:" }, { "code": null, "e": 5141, "s": 4425, "text": "cv = RepeatedStratifiedKFold( n_splits=5, n_repeats=10, random_state=101 )# make sure that you have the suffix with the name of your pipeline step in front of your parameter name!parameter_grid = { 'model__max_depth':[2, 3, 4], 'model__learning_rate':np.arange(0.005, 0.5, 0.05),}# make sure that you do not refit, because the refit will be without your augmented data!gs = RandomizedSearchCV( estimator=pipeline, n_iter=3000, param_distributions=parameter_grid, scoring='roc_auc', n_jobs=-1, cv=cv, verbose=1, random_state=101, refit=False)grid_result = gs.fit(X, y)print(\"Best: {:.2f} using {}\".format( grid_result.best_score_, grid_result.best_params_))" }, { "code": null, "e": 5428, "s": 5141, "text": "You can also use the same procedure with cross_validate and get the best model and the feature importance to be used as feature selection method with pipeline.steps[1][1]. If you train with augmented data, chances will be high that it influences the features selected by your estimator." } ]
How to get full path of current file's directory in Python?
To know the complete path to current file use the os module. >>> import os >>> print(os.path.realpath(__file__)) /home/ayush/qna/path.py
[ { "code": null, "e": 1123, "s": 1062, "text": "To know the complete path to current file use the os module." }, { "code": null, "e": 1199, "s": 1123, "text": ">>> import os\n>>> print(os.path.realpath(__file__))\n/home/ayush/qna/path.py" } ]
Python’s Dictionary In Details: Python Programming | by Rashida Nasrin Sucky | Towards Data Science
Dictionary is a composite datatype in the Python programming language. In a way, it is similar to lists. Lists are a collection of elements. Dictionaries are a collection of key, value pairs. Solutions to many programming problems can be easy and more concise with dictionaries. Here I am going to explain all the important methods in the dictionary and some problem-solving with examples. Let’s define a simple dictionary. d = {'a': 1, 'b':5, 'c': 3, 'd': 2, 'e': 8, 'f': 6} Add a new element in this dictionary: Add a new element in this dictionary: d['s'] = 12print(d) Dictionary d looks like this now: {'a': 1, 'b': 5, 'c': 3, 'd': 2, 'f': 6, 's': 12} 2. delete the element e from the dictionary d. del d['e'] 3. Get the value of the key a. d['a']#Output: 1 4. The value of ‘a’ looks too small. Update the value of element a to 10. d['a'] = 10 5. Add 3 to the value of the element s. d['s'] += d['s'] + 3 6. Check the length of the dictionary d. If it is less than 9, then add three more elements to it. if len(d) < 8: d.update({'t': 21, 'h': 9, 'p':14})print(d)'''Output:{'a': 10, 'b': 5, 'c': 3, 'd': 2, 'f': 6, 's': 12, 't': 21, 'h': 9, 'p': 14}''' 7. Make a list of all the keys. d.keys()##Output looks like this:dict_keys([‘a’, ‘b’, ‘c’, ‘d’, ‘f’, ‘s’, ‘t’, ‘h’, ‘p’]) 8. Make a list of all the values. d.values()##Output looks like this:dict_values([10, 5, 3, 2, 6, 27, 21, 9, 14]) 9. Find out which alphabet has the biggest value. max = 0max_key = 'a'for k, v in d.items(): if v > max: max_key = k max = d[max_key]print(max_key) The answer came out to be ‘t’. 10. Sort the keys of the dictionary d by the values in ascending order. sorted(d, key=lambda x: d[x])#Output:['d', 'c', 'b', 'f', 'h', 'p', 't', 's'] 11. Find out how many times each word appeared in the following sentences. sentences = "I love my country. My country is the best in the world. We have the best athletes in the world." Let’s make a dictionary where the keys will be the words in these sentences and the values will be the frequency that the words appeared. These are steps to solve this problem: a. Initialize an empty dictionary ‘sen_map’ b. Make the sentences all lower case c. Iterate over each word in the sentences d. Check if a word exists in the sen_map e. If not then add the word with a value of 1 f. Otherwise, update the value of that word by 1 sen_map = {} sentences = sentences.lower() for i in sentences.split(): if i not in sen_map: sen_map[i] = 1 sen_map[i] += 1 sen_map'''Output{'i': 2, 'love': 2, 'my': 3, 'country.': 2, 'country': 2, 'is': 2, 'the': 5, 'best': 3, 'in': 3, 'world.': 3, 'we': 2, 'have': 2, 'athletes': 2}''' Dictionaries can be nested like lists. Here is an example: Gold_medals = {'USA': {'Wrestling': 3, 'Long Jump': 3, 'Basketball': 5}, 'China': {'Wrestling': 1, 'Long Jump': 5, 'Basketball': 3}, 'England': {'Wrestling': 2, 'Long Jump': 7, 'Basketball': 0}} 12. How many gold medals did the USA win in the long jump? Gold_medals['USA']['Long Jump'] The output is 3 as we can see in the dictionary above. Another way of organizing information in dictionaries is on a list. Here is an example: students = [{'Name': 'John Smith', 'Age': 12, 'Score': 90}, {'Name': 'Laila Jones', 'Age': 11, 'Score': 82}, {'Name': 'Omar Martinez', 'Age': 10, 'Score': 70}, {'Name': 'Romana Raha', 'Age': 13, 'Score': 78},] 13. Return the name of the student who scored the highest in the class. Let’s solve this step by step. First sort ‘students’ in descending order. sorted(students, key=lambda x: x['Score'], reverse=True)#Output:'''[{'Name': 'John Smith', 'Age': 12, 'Score': 90}, {'Name': 'Laila Jones', 'Age': 11, 'Score': 82}, {'Name': 'Romana Raha', 'Age': 13, 'Score': 78}, {'Name': 'Omar Martinez', 'Age': 10, 'Score': 70}]''' Capture the first dictionary of the list ‘students’. sorted(students, key=lambda x: x['Score'], reverse=True)[0]'''Output{'Name': 'John Smith', 'Age': 12, 'Score': 90}''' Finally, get the name of the student. sorted(students, key=lambda x: x['Score'], reverse=True)[0]['Name'] This one line of code will return the name of the student. That is, ‘John Smith’. I tried to explain the methods of dictionaries first and then presented some examples to show how to work with dictionaries. I hope this was helpful. Here is the video tutorial on Dictionary:
[ { "code": null, "e": 562, "s": 172, "text": "Dictionary is a composite datatype in the Python programming language. In a way, it is similar to lists. Lists are a collection of elements. Dictionaries are a collection of key, value pairs. Solutions to many programming problems can be easy and more concise with dictionaries. Here I am going to explain all the important methods in the dictionary and some problem-solving with examples." }, { "code": null, "e": 596, "s": 562, "text": "Let’s define a simple dictionary." }, { "code": null, "e": 648, "s": 596, "text": "d = {'a': 1, 'b':5, 'c': 3, 'd': 2, 'e': 8, 'f': 6}" }, { "code": null, "e": 686, "s": 648, "text": "Add a new element in this dictionary:" }, { "code": null, "e": 724, "s": 686, "text": "Add a new element in this dictionary:" }, { "code": null, "e": 744, "s": 724, "text": "d['s'] = 12print(d)" }, { "code": null, "e": 778, "s": 744, "text": "Dictionary d looks like this now:" }, { "code": null, "e": 828, "s": 778, "text": "{'a': 1, 'b': 5, 'c': 3, 'd': 2, 'f': 6, 's': 12}" }, { "code": null, "e": 875, "s": 828, "text": "2. delete the element e from the dictionary d." }, { "code": null, "e": 886, "s": 875, "text": "del d['e']" }, { "code": null, "e": 917, "s": 886, "text": "3. Get the value of the key a." }, { "code": null, "e": 934, "s": 917, "text": "d['a']#Output: 1" }, { "code": null, "e": 1008, "s": 934, "text": "4. The value of ‘a’ looks too small. Update the value of element a to 10." }, { "code": null, "e": 1020, "s": 1008, "text": "d['a'] = 10" }, { "code": null, "e": 1060, "s": 1020, "text": "5. Add 3 to the value of the element s." }, { "code": null, "e": 1081, "s": 1060, "text": "d['s'] += d['s'] + 3" }, { "code": null, "e": 1180, "s": 1081, "text": "6. Check the length of the dictionary d. If it is less than 9, then add three more elements to it." }, { "code": null, "e": 1331, "s": 1180, "text": "if len(d) < 8: d.update({'t': 21, 'h': 9, 'p':14})print(d)'''Output:{'a': 10, 'b': 5, 'c': 3, 'd': 2, 'f': 6, 's': 12, 't': 21, 'h': 9, 'p': 14}'''" }, { "code": null, "e": 1363, "s": 1331, "text": "7. Make a list of all the keys." }, { "code": null, "e": 1453, "s": 1363, "text": "d.keys()##Output looks like this:dict_keys([‘a’, ‘b’, ‘c’, ‘d’, ‘f’, ‘s’, ‘t’, ‘h’, ‘p’])" }, { "code": null, "e": 1487, "s": 1453, "text": "8. Make a list of all the values." }, { "code": null, "e": 1567, "s": 1487, "text": "d.values()##Output looks like this:dict_values([10, 5, 3, 2, 6, 27, 21, 9, 14])" }, { "code": null, "e": 1617, "s": 1567, "text": "9. Find out which alphabet has the biggest value." }, { "code": null, "e": 1732, "s": 1617, "text": "max = 0max_key = 'a'for k, v in d.items(): if v > max: max_key = k max = d[max_key]print(max_key)" }, { "code": null, "e": 1763, "s": 1732, "text": "The answer came out to be ‘t’." }, { "code": null, "e": 1835, "s": 1763, "text": "10. Sort the keys of the dictionary d by the values in ascending order." }, { "code": null, "e": 1913, "s": 1835, "text": "sorted(d, key=lambda x: d[x])#Output:['d', 'c', 'b', 'f', 'h', 'p', 't', 's']" }, { "code": null, "e": 1988, "s": 1913, "text": "11. Find out how many times each word appeared in the following sentences." }, { "code": null, "e": 2098, "s": 1988, "text": "sentences = \"I love my country. My country is the best in the world. We have the best athletes in the world.\"" }, { "code": null, "e": 2236, "s": 2098, "text": "Let’s make a dictionary where the keys will be the words in these sentences and the values will be the frequency that the words appeared." }, { "code": null, "e": 2275, "s": 2236, "text": "These are steps to solve this problem:" }, { "code": null, "e": 2319, "s": 2275, "text": "a. Initialize an empty dictionary ‘sen_map’" }, { "code": null, "e": 2356, "s": 2319, "text": "b. Make the sentences all lower case" }, { "code": null, "e": 2399, "s": 2356, "text": "c. Iterate over each word in the sentences" }, { "code": null, "e": 2440, "s": 2399, "text": "d. Check if a word exists in the sen_map" }, { "code": null, "e": 2486, "s": 2440, "text": "e. If not then add the word with a value of 1" }, { "code": null, "e": 2535, "s": 2486, "text": "f. Otherwise, update the value of that word by 1" }, { "code": null, "e": 2855, "s": 2535, "text": "sen_map = {} sentences = sentences.lower() for i in sentences.split(): if i not in sen_map: sen_map[i] = 1 sen_map[i] += 1 sen_map'''Output{'i': 2, 'love': 2, 'my': 3, 'country.': 2, 'country': 2, 'is': 2, 'the': 5, 'best': 3, 'in': 3, 'world.': 3, 'we': 2, 'have': 2, 'athletes': 2}'''" }, { "code": null, "e": 2914, "s": 2855, "text": "Dictionaries can be nested like lists. Here is an example:" }, { "code": null, "e": 3135, "s": 2914, "text": "Gold_medals = {'USA': {'Wrestling': 3, 'Long Jump': 3, 'Basketball': 5}, 'China': {'Wrestling': 1, 'Long Jump': 5, 'Basketball': 3}, 'England': {'Wrestling': 2, 'Long Jump': 7, 'Basketball': 0}}" }, { "code": null, "e": 3194, "s": 3135, "text": "12. How many gold medals did the USA win in the long jump?" }, { "code": null, "e": 3226, "s": 3194, "text": "Gold_medals['USA']['Long Jump']" }, { "code": null, "e": 3281, "s": 3226, "text": "The output is 3 as we can see in the dictionary above." }, { "code": null, "e": 3349, "s": 3281, "text": "Another way of organizing information in dictionaries is on a list." }, { "code": null, "e": 3369, "s": 3349, "text": "Here is an example:" }, { "code": null, "e": 3609, "s": 3369, "text": "students = [{'Name': 'John Smith', 'Age': 12, 'Score': 90}, {'Name': 'Laila Jones', 'Age': 11, 'Score': 82}, {'Name': 'Omar Martinez', 'Age': 10, 'Score': 70}, {'Name': 'Romana Raha', 'Age': 13, 'Score': 78},]" }, { "code": null, "e": 3681, "s": 3609, "text": "13. Return the name of the student who scored the highest in the class." }, { "code": null, "e": 3755, "s": 3681, "text": "Let’s solve this step by step. First sort ‘students’ in descending order." }, { "code": null, "e": 4026, "s": 3755, "text": "sorted(students, key=lambda x: x['Score'], reverse=True)#Output:'''[{'Name': 'John Smith', 'Age': 12, 'Score': 90}, {'Name': 'Laila Jones', 'Age': 11, 'Score': 82}, {'Name': 'Romana Raha', 'Age': 13, 'Score': 78}, {'Name': 'Omar Martinez', 'Age': 10, 'Score': 70}]'''" }, { "code": null, "e": 4079, "s": 4026, "text": "Capture the first dictionary of the list ‘students’." }, { "code": null, "e": 4197, "s": 4079, "text": "sorted(students, key=lambda x: x['Score'], reverse=True)[0]'''Output{'Name': 'John Smith', 'Age': 12, 'Score': 90}'''" }, { "code": null, "e": 4235, "s": 4197, "text": "Finally, get the name of the student." }, { "code": null, "e": 4303, "s": 4235, "text": "sorted(students, key=lambda x: x['Score'], reverse=True)[0]['Name']" }, { "code": null, "e": 4385, "s": 4303, "text": "This one line of code will return the name of the student. That is, ‘John Smith’." }, { "code": null, "e": 4535, "s": 4385, "text": "I tried to explain the methods of dictionaries first and then presented some examples to show how to work with dictionaries. I hope this was helpful." } ]
Find Harmonic mean using Arithmetic mean and Geometric mean using C++.
Here we will see how to get the Harmonic mean using the arithmetic mean and the geometric mean. The formula for these three means are like below − Arithmetic Mean − (a + b)/2 Geometric Mean − ⟮a∗b⟯ Harmonic Mean − 2ab/(a+b) The Harmonic Mean can be expressed using arithmetic mean and geometric mean using this formula − HM=GM2AM Live Demo #include <iostream> #include <cmath> using namespace std; double getHarmonicMean(int a, int b) { double AM, GM, HM; AM = (a + b) / 2; GM = sqrt(a * b); HM = (GM * GM) / AM; return HM; } int main() { int a = 5, b = 15; double res = getHarmonicMean(a, b); cout << "Harmonic Mean of " << a << " and " << b << " is " << res ; } Harmonic Mean of 5 and 15 is 7.5
[ { "code": null, "e": 1209, "s": 1062, "text": "Here we will see how to get the Harmonic mean using the arithmetic mean and the geometric mean. The formula for these three means are like below −" }, { "code": null, "e": 1237, "s": 1209, "text": "Arithmetic Mean − (a + b)/2" }, { "code": null, "e": 1260, "s": 1237, "text": "Geometric Mean − ⟮a∗b⟯" }, { "code": null, "e": 1286, "s": 1260, "text": "Harmonic Mean − 2ab/(a+b)" }, { "code": null, "e": 1383, "s": 1286, "text": "The Harmonic Mean can be expressed using arithmetic mean and geometric mean using this formula −" }, { "code": null, "e": 1392, "s": 1383, "text": "HM=GM2AM" }, { "code": null, "e": 1403, "s": 1392, "text": " Live Demo" }, { "code": null, "e": 1751, "s": 1403, "text": "#include <iostream>\n#include <cmath>\nusing namespace std;\ndouble getHarmonicMean(int a, int b) {\n double AM, GM, HM;\n AM = (a + b) / 2;\n GM = sqrt(a * b);\n HM = (GM * GM) / AM;\n return HM;\n}\nint main() {\n int a = 5, b = 15;\n double res = getHarmonicMean(a, b);\n cout << \"Harmonic Mean of \" << a << \" and \" << b << \" is \" << res ;\n}" }, { "code": null, "e": 1784, "s": 1751, "text": "Harmonic Mean of 5 and 15 is 7.5" } ]
Pytorch [Basics] — Intro to RNN. This blog post takes you through the... | by Akshaj Verma | Towards Data Science
This blog post takes you through the implementation of Vanilla RNNs, Stacked RNNs, Bidirectional RNNs, and Stacked Bidirectional RNNs in PyTorch by predicting a sequence of numbers. import numpy as npimport torchimport torch.nn as nnimport torch.optim as optimfrom torch.utils.data import Dataset, DataLoader RNNs are mainly used in case of sequential data such as time series or NLP. There are multiple different types of RNNs which are used for different applications. For Time Series - Forecasting - many-to-many or many-to-one Classification - many-to-one For NLP - Text Classification: many-to-one Text Generation: many-to-many Machine Translation: many-to-many Named Entity Recognition: many-to-many Image Captioning: one-to-many We often stack RNNs together for better performance. Bidirectional RNN is essentially using 2 RNNs where the input sequence is fed in the normal order to 1 RNN and in reverse to the other RNN. Here the data is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] We divide it into 4 batches of sequence length = 5. [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]] Batch Size = 4Sequence Length = 5Input Size = 1 (Since, only one dimension) In our case, we’re looking at 5 (seq_len) previous value to predict the next 2 values. data = torch.Tensor([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])print("Data: ", data.shape, "\n\n", data)###################### OUTPUT ######################Data: tensor([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20.]) Data Shape: torch.Size([20]) # Number of features used as input. (Number of columns)INPUT_SIZE = 1# Number of previous time stamps taken into account.SEQ_LENGTH = 5# Number of features in last hidden state ie. number of output time-# steps to predict.See image below for more clarity.HIDDEN_SIZE = 2# Number of stacked rnn layers.NUM_LAYERS = 1# We have total of 20 rows in our input. # We divide the input into 4 batches where each batch has only 1# row. Each row corresponds to a sequence of length 5. BATCH_SIZE = 4 torch.nn.RNN has two inputs - input and h_0 ie. the input sequence and the hidden-layer at t=0. If we don't initialize the hidden layer, it will be auto-initiliased by PyTorch to be all zeros. input is the sequence which is fed into the network. It should be of size (seq_len, batch, input_size). If batch_first=True, the input size is (batch, seq_len, input_size). h_0 is the initial hidden state of the network. It is of the size (num_layers * num_directions, batch, input_size) where num_layers is the number of stacked RNNs. num_directions = 2 for bidirectional RNNs and 1 otherwise. torch.nn.RNN has two outputs - out and hidden. out is the output of the RNN from all timesteps from the last RNN layer. It is of the size (seq_len, batch, num_directions * hidden_size). If batch_first=True, the output size is (batch, seq_len, num_directions * hidden_size). h_n is the hidden value from the last time-step of all RNN layers. It is of the size (num_layers * num_directions, batch, hidden_size). h_n is unaffected by batch_first=True. Github Issue. The following diagram explains it more clearly. Here the batch=1. The diagram is for an LSTM which as two hidden parameters (h, c). RNN and GRU both have only h. To reiterate — out is the output of the RNN from all timesteps from the last RNN layer.h_n is the hidden value from the last time-step of all RNN layers. # Initialize the RNN.rnn = nn.RNN(input_size=INPUT_SIZE, hidden_size=HIDDEN_SIZE, num_layers = 1, batch_first=True)# input size : (batch, seq_len, input_size)inputs = data.view(BATCH_SIZE, SEQ_LENGTH, INPUT_SIZE)# out shape = (batch, seq_len, num_directions * hidden_size)# h_n shape = (num_layers * num_directions, batch, hidden_size)out, h_n = rnn(inputs) input shape = [4, 5, 1]out shape = [4, 5, 2]h_n shape = [1, 4, 2] In the input We have 4 batches as our output because we set the BATCH_SIZE=4. Each batch contains 5 rows because out SEQ_LENGTH = 5. We are using only a single feature as input INPUT_SIZE = 1. In the out, we get values from all 4 batches where number of time-steps (seq_len) is 5 and the number of predictions are 2. For each batch, we're predicting 2 outputs. In the h_n, we get values from each of the 4 batches of the last time-step of the single RNN layer. print('Input: ', inputs.shape, '\n', inputs)print('\nOutput: ', out.shape, '\n', out)print('\nHidden: ', h_n.shape, '\n', h_n)###################### OUTPUT ######################Input: torch.Size([4, 5, 1]) tensor([[[ 1.], [ 2.], [ 3.], [ 4.], [ 5.]], [[ 6.], [ 7.], [ 8.], [ 9.], [10.]], [[11.], [12.], [13.], [14.], [15.]], [[16.], [17.], [18.], [19.], [20.]]])Output: torch.Size([4, 5, 2]) tensor([[[-0.0819, 0.8100], [-0.4311, 0.9332], [-0.3162, 0.9748], [-0.3979, 0.9875], [-0.3675, 0.9944]], [[-0.1081, 0.9953], [-0.5145, 0.9986], [-0.3269, 0.9995], [-0.4254, 0.9997], [-0.3820, 0.9999]], [[-0.1342, 0.9999], [-0.5245, 1.0000], [-0.3458, 1.0000], [-0.4382, 1.0000], [-0.3982, 1.0000]], [[-0.1601, 1.0000], [-0.5328, 1.0000], [-0.3648, 1.0000], [-0.4506, 1.0000], [-0.4143, 1.0000]]], grad_fn=<TransposeBackward1>)Hidden: torch.Size([1, 4, 2]) tensor([[[-0.3675, 0.9944], [-0.3820, 0.9999], [-0.3982, 1.0000], [-0.4143, 1.0000]]], grad_fn=<StackBackward>) In the output above, notice the last row in each batch of out is present in h_n. out is the output value at all time-steps of the last RNN layer for each batch. h_n is the hidden value at the last time-step of all RNN layers for each batch. If I change the num_layers = 3, we will have 3 RNN layers stacked next to each other. See how the out, and h_n tensors change in the example below. We now have 3 batches in the h_n tensor. The last batch contains the end-rows of each batch in the out tensor. # Initialize the RNN.rnn = nn.RNN(input_size=INPUT_SIZE, hidden_size=HIDDEN_SIZE, num_layers = 3, batch_first=True)# input size : (batch_size , seq_len, input_size)inputs = data.view(BATCH_SIZE, SEQ_LENGTH, INPUT_SIZE)# out shape = (batch, seq_len, num_directions * hidden_size)# h_n shape = (num_layers * num_directions, batch, hidden_size)out, h_n = rnn(inputs) input shape = [4, 5, 1]out shape = [4, 5, 2]h_n shape = [3, 4, 2] In the input, We have 4 batches as our output because we set the BATCH_SIZE=4. Each batch contains 5 rows because out SEQ_LENGTH = 5. We are using only a single feature as input INPUT_SIZE = 1. In the out, we get values from all 4 batches where number of time-steps (seq_len) is 5 and the number of predictions are 2. For each batch, we're predicting 2 outputs. In the h_n, we get values from each of the 4 batches of the last time-steps of the 3 stacked RNN layers. print('Input: ', inputs.shape, '\n', inputs)print('\nOutput: ', out.shape, '\n', out)print('\nHidden: ', h_n.shape, '\n', h_n)###################### OUTPUT ######################Input: torch.Size([4, 5, 1]) tensor([[[ 1.], [ 2.], [ 3.], [ 4.], [ 5.]], [[ 6.], [ 7.], [ 8.], [ 9.], [10.]], [[11.], [12.], [13.], [14.], [15.]], [[16.], [17.], [18.], [19.], [20.]]])Output: torch.Size([4, 5, 2]) tensor([[[ 0.3144, -0.7527], [-0.0597, -0.6038], [ 0.0896, -0.7646], [ 0.0608, -0.6358], [ 0.1084, -0.6783]], [[ 0.4442, -0.6350], [ 0.0949, -0.3948], [ 0.2715, -0.5962], [ 0.1819, -0.4580], [ 0.2529, -0.5213]], [[ 0.4907, -0.5688], [ 0.1671, -0.2976], [ 0.3462, -0.4922], [ 0.2388, -0.3768], [ 0.3078, -0.4418]], [[ 0.5041, -0.5466], [ 0.1883, -0.2675], [ 0.3684, -0.4576], [ 0.2572, -0.3502], [ 0.3238, -0.4167]]], grad_fn=<TransposeBackward1>)Hidden: torch.Size([3, 4, 2]) tensor([[[-0.6480, -0.4044], [-0.8912, -0.7801], [-0.9808, -0.9366], [-0.9975, -0.9836]], [[-0.7848, -0.0118], [-0.8707, -0.1721], [-0.8955, -0.2411], [-0.9016, -0.2605]], [[ 0.1084, -0.6783], [ 0.2529, -0.5213], [ 0.3078, -0.4418], [ 0.3238, -0.4167]]], grad_fn=<StackBackward>) For Bidirectional RNN, we set the bidirectional=True. rnn = nn.RNN(input_size=INPUT_SIZE, hidden_size=HIDDEN_SIZE, batch_first=True, num_layers = 1, bidirectional = True)# input size : (batch_size , seq_len, input_size)inputs = data.view(BATCH_SIZE, SEQ_LENGTH, INPUT_SIZE)# out shape = (batch, seq_len, num_directions * hidden_size)# h_n shape = (num_layers * num_directions, batch, hidden_size)out, h_n = rnn(inputs) input shape = [4, 5, 1]out shape = [4, 5, 4]h_n shape = [2, 4, 2] In the input We have 4 batches as our output because we set the BATCH_SIZE=4. Each batch contains 5 rows because out SEQ_LENGTH = 5. We are using only a single feature as input INPUT_SIZE = 1. In the out, we get values from all 4 batches where number of time-steps (seq_len) is 5 and the number of predictions are 2. For each batch, we're predicting 2 outputs. Since, it's a bidirectional RNN, we get 2 sets of predictions. Hence, the shape is [4, 5, 4] and not [4, 5, 2] (which we observed in the case of a unidirectional RNN above). In the h_n, we get values from each of the 4 batches of the last time-steps of the single RNN layers. Since, it's a bidirectional RNN, we get 2 sets of predictions. Hence, the shape is [2, 4, 2] and not [1, 4, 2] (which we observed in the case of a unidirectional RNN above). print('Input: ', inputs.shape, '\n', inputs)print('\nOutput: ', out.shape, '\n', out)print('\nHidden: ', h_n.shape, '\n', h_n)###################### OUTPUT ######################Input: torch.Size([4, 5, 1]) tensor([[[ 1.], [ 2.], [ 3.], [ 4.], [ 5.]], [[ 6.], [ 7.], [ 8.], [ 9.], [10.]], [[11.], [12.], [13.], [14.], [15.]], [[16.], [17.], [18.], [19.], [20.]]])Output: torch.Size([4, 5, 4]) tensor([[[ 0.2184, 0.4086, 0.6418, -0.1677], [-0.0222, -0.0095, 0.8794, -0.4927], [-0.6716, -0.2802, 0.9585, -0.7248], [-0.9387, -0.4152, 0.9846, -0.8646], [-0.9841, -0.6164, 0.9789, -0.9192]], [[-0.9813, -0.8829, 0.9979, -0.9721], [-0.9986, -0.8902, 0.9992, -0.9877], [-0.9995, -0.9449, 0.9997, -0.9946], [-0.9998, -0.9729, 0.9999, -0.9977], [-0.9999, -0.9868, 0.9998, -0.9987]], [[-0.9999, -0.9968, 1.0000, -0.9996], [-1.0000, -0.9969, 1.0000, -0.9998], [-1.0000, -0.9985, 1.0000, -0.9999], [-1.0000, -0.9993, 1.0000, -1.0000], [-1.0000, -0.9997, 1.0000, -1.0000]], [[-1.0000, -0.9999, 1.0000, -1.0000], [-1.0000, -0.9999, 1.0000, -1.0000], [-1.0000, -1.0000, 1.0000, -1.0000], [-1.0000, -1.0000, 1.0000, -1.0000], [-1.0000, -1.0000, 1.0000, -1.0000]]], grad_fn=<TransposeBackward1>)Hidden: torch.Size([2, 4, 2]) tensor([[[-0.9841, -0.6164], [-0.9999, -0.9868], [-1.0000, -0.9997], [-1.0000, -1.0000]], [[ 0.6418, -0.1677], [ 0.9979, -0.9721], [ 1.0000, -0.9996], [ 1.0000, -1.0000]]], grad_fn=<StackBackward>) Let us now try to understand the output in a little more detail. According to the docs, to separate the directions (forward and backward), we can do the following - out.view(seq_len, batch, num_directions, hidden_size) with forward and backward being direction 0 and 1 respectively. Keep in mind that if you used batch_first=True, then it would be out.view(batch, seq_len, num_directions, hidden_size). h_n.view(num_layers, num_directions, batch, hidden_size) with forward and backward being direction 0 and 1 respectively. Let’s reshape the BiRNN output to separate out forward and backward values using out.view(batch, seq_len, num_directions, hidden_size). out_reshaped = out.view(BATCH_SIZE, SEQ_LENGTH, 2, HIDDEN_SIZE)print("Shape of the output after directions are separated: ", out_reshaped.shape)###################### OUTPUT ######################Shape of the output after directions are separated: torch.Size([4, 5, 2, 2]) The shape is now — (batch, seq_len, num_directions, hidden_size). num_directions is the 2nd dimension. To obtain forward and backward outputs, we can do the following - out_forward = (batch, seq_len, 0, hidden_size) out_backward = (batch, seq_len, 1, hidden_size) out_forward = out_reshaped[:, :, 0, :]out_backward = out_reshaped[:, :, 1, :]print("Forward output: ", out_forward.shape, "\n", out_forward)print("\n\nBackward output: ", out_backward.shape, "\n", out_backward)###################### OUTPUT ######################Forward output: torch.Size([4, 5, 2]) tensor([[[ 0.2184, 0.4086], [-0.0222, -0.0095], [-0.6716, -0.2802], [-0.9387, -0.4152], [-0.9841, -0.6164]], [[-0.9813, -0.8829], [-0.9986, -0.8902], [-0.9995, -0.9449], [-0.9998, -0.9729], [-0.9999, -0.9868]], [[-0.9999, -0.9968], [-1.0000, -0.9969], [-1.0000, -0.9985], [-1.0000, -0.9993], [-1.0000, -0.9997]], [[-1.0000, -0.9999], [-1.0000, -0.9999], [-1.0000, -1.0000], [-1.0000, -1.0000], [-1.0000, -1.0000]]], grad_fn=<SliceBackward>)Backward output: torch.Size([4, 5, 2]) tensor([[[ 0.6418, -0.1677], [ 0.8794, -0.4927], [ 0.9585, -0.7248], [ 0.9846, -0.8646], [ 0.9789, -0.9192]], [[ 0.9979, -0.9721], [ 0.9992, -0.9877], [ 0.9997, -0.9946], [ 0.9999, -0.9977], [ 0.9998, -0.9987]], [[ 1.0000, -0.9996], [ 1.0000, -0.9998], [ 1.0000, -0.9999], [ 1.0000, -1.0000], [ 1.0000, -1.0000]], [[ 1.0000, -1.0000], [ 1.0000, -1.0000], [ 1.0000, -1.0000], [ 1.0000, -1.0000], [ 1.0000, -1.0000]]], grad_fn=<SliceBackward>) Let’s reshape the BiRNN hidden to separate out forward and backward values using h_n.view(num_layers, num_directions, batch, hidden_size). h_n_reshaped = h_n.view(1, 2, BATCH_SIZE, HIDDEN_SIZE)print("Shape of the hidden after directions are separated: ", h_n_reshaped.shape)###################### OUTPUT ######################Shape of the hidden after directions are separated: torch.Size([1, 2, 4, 2]) The shape is now — (num_layers, num_directions, batch, hidden_size). num_directions is the 1st dimension. To obtain forward and backward hidden, we can do the following - hidden_forward = (num_layers, 0, batch, hidden_size) hidden_backward = (num_layers, 1, batch, hidden_size) h_n_forward = h_n_reshaped[:, 0, :, :]h_n_backward = h_n_reshaped[:, 1, :, :]print("Forward h_n: ", h_n_forward.shape, "\n", h_n_forward)print("\n\nBackward h_n: ", h_n_backward.shape, "\n", h_n_backward)###################### OUTPUT ######################Forward h_n: torch.Size([1, 4, 2]) tensor([[[-0.9841, -0.6164], [-0.9999, -0.9868], [-1.0000, -0.9997], [-1.0000, -1.0000]]], grad_fn=<SliceBackward>)Backward h_n: torch.Size([1, 4, 2]) tensor([[[ 0.6418, -0.1677], [ 0.9979, -0.9721], [ 1.0000, -0.9996], [ 1.0000, -1.0000]]], grad_fn=<SliceBackward>) For a Stacked Bidirectional RNN, we set the bidirectional=True and num_layers = 3. rnn = nn.RNN(input_size=INPUT_SIZE, hidden_size=HIDDEN_SIZE, batch_first=True, num_layers = 3, bidirectional = True)# input size : (batch_size , seq_len, input_size)inputs = data.view(BATCH_SIZE, SEQ_LENGTH, INPUT_SIZE)# out shape = (batch, seq_len, num_directions * hidden_size)# h_n shape = (num_layers * num_directions, batch, hidden_size)out, h_n = rnn(inputs) input shape = [4, 5, 1]out shape = [4, 5, 4]h_n shape = [6, 4, 2] In the input We have 4 batches as our output because we set the BATCH_SIZE=4. Each batch contains 5 rows because out SEQ_LENGTH = 5. We are using only a single feature as input INPUT_SIZE = 1. In the out, we get values from all 4 batches where number of time-steps (seq_len) is 5 and the number of predictions are 2. For each batch, we're predicting 2 outputs. Since, it's a bidirectional RNN, we get 2 sets of predictions. Hence, the shape is [4, 5, 4] and not [4, 5, 2] (which we observed in the case of a stacked-unidirectional RNN above). In the h_n, we get values from each of the 4 batches of the last time-steps of the single RNN layers. Since, it's a bidirectional RNN, we get 2 sets of predictions. Hence, the shape is [6, 4, 2] and not [3, 4, 2] (which we observed in the case of a stacked-unidirectional RNN above). print('Input: ', inputs.shape, '\n', inputs)print('\nOutput: ', out.shape, '\n', out)print('\nHidden: ', h_n.shape, '\n', h_n)###################### OUTPUT ######################Input: torch.Size([4, 5, 1]) tensor([[[ 1.], [ 2.], [ 3.], [ 4.], [ 5.]], [[ 6.], [ 7.], [ 8.], [ 9.], [10.]], [[11.], [12.], [13.], [14.], [15.]], [[16.], [17.], [18.], [19.], [20.]]])Output: torch.Size([4, 5, 4]) tensor([[[-0.4175, -0.6278, -0.0101, -0.4025], [ 0.1271, -0.5579, 0.2162, -0.4832], [-0.2557, -0.6714, 0.3084, -0.4927], [ 0.0556, -0.6295, 0.3194, -0.4467], [-0.1510, -0.6863, 0.3917, -0.6299]], [[-0.4311, -0.6939, -0.2381, -0.6894], [ 0.1423, -0.5335, -0.0872, -0.6471], [-0.2943, -0.6468, 0.0076, -0.6274], [ 0.0392, -0.5691, 0.0595, -0.5576], [-0.2070, -0.6238, 0.2187, -0.6570]], [[-0.4458, -0.6581, -0.6259, -0.8299], [ 0.0999, -0.4501, -0.5715, -0.8090], [-0.3441, -0.5669, -0.4723, -0.7729], [-0.0133, -0.4705, -0.3131, -0.6745], [-0.2617, -0.5444, 0.0042, -0.6820]], [[-0.4556, -0.6330, -0.7035, -0.8531], [ 0.0780, -0.4118, -0.6690, -0.8358], [-0.3608, -0.5393, -0.5730, -0.7989], [-0.0285, -0.4442, -0.3958, -0.6973], [-0.2739, -0.5259, -0.0447, -0.6868]]], grad_fn=<TransposeBackward1>)Hidden: torch.Size([6, 4, 2]) tensor([[[ 0.9455, 0.5653], [ 0.9986, -0.1385], [ 1.0000, -0.7900], [ 1.0000, -0.9272]], [[ 0.1570, 0.2765], [ 0.9959, 0.9972], [ 1.0000, 1.0000], [ 1.0000, 1.0000]], [[-0.6463, 0.5301], [-0.5393, 0.6556], [-0.4089, 0.7277], [-0.3732, 0.7372]], [[ 0.0474, -0.5973], [ 0.0082, -0.9715], [-0.1373, -0.9681], [-0.2362, -0.9658]], [[-0.1510, -0.6863], [-0.2070, -0.6238], [-0.2617, -0.5444], [-0.2739, -0.5259]], [[-0.0101, -0.4025], [-0.2381, -0.6894], [-0.6259, -0.8299], [-0.7035, -0.8531]]], grad_fn=<StackBackward>) Let us now try to understand the output in a little more detail. According to the docs, to separate the directions (forward and backward), we can do the following - out.view(seq_len, batch, num_directions, hidden_size) with forward and backward being direction 0 and 1 respectively. Keep in mind that if you used batch_first=True, then it would be out.view(batch, seq_len, num_directions, hidden_size). h_n.view(num_layers, num_directions, batch, hidden_size) with forward and backward being direction 0 and 1 respectively. Let’s reshape the Stacked BiRNN output to separate out forward and backward values using out.view(batch, seq_len, num_directions, hidden_size). out_reshaped = out.view(BATCH_SIZE, SEQ_LENGTH, 2, HIDDEN_SIZE)print("Shape of the output after directions are separated: ", out_reshaped.shape)###################### OUTPUT ######################Shape of the output after directions are separated: torch.Size([4, 5, 2, 2]) The shape is now — (batch, seq_len, num_directions, hidden_size). num_directions is the 2nd dimension. To obtain forward and backward outputs, we can do the following - out_forward = (batch, seq_len, 0, hidden_size) out_backward = (batch, seq_len, 1, hidden_size) out_forward = out_reshaped[:, :, 0, :]out_backward = out_reshaped[:, :, 1, :]print("Forward output: ", out_forward.shape, "\n", out_forward)print("\n\nBackward output: ", out_backward.shape, "\n", out_backward)###################### OUTPUT ######################Forward output: torch.Size([4, 5, 2]) tensor([[[-0.4175, -0.6278], [ 0.1271, -0.5579], [-0.2557, -0.6714], [ 0.0556, -0.6295], [-0.1510, -0.6863]], [[-0.4311, -0.6939], [ 0.1423, -0.5335], [-0.2943, -0.6468], [ 0.0392, -0.5691], [-0.2070, -0.6238]], [[-0.4458, -0.6581], [ 0.0999, -0.4501], [-0.3441, -0.5669], [-0.0133, -0.4705], [-0.2617, -0.5444]], [[-0.4556, -0.6330], [ 0.0780, -0.4118], [-0.3608, -0.5393], [-0.0285, -0.4442], [-0.2739, -0.5259]]], grad_fn=<SliceBackward>)Backward output: torch.Size([4, 5, 2]) tensor([[[-0.0101, -0.4025], [ 0.2162, -0.4832], [ 0.3084, -0.4927], [ 0.3194, -0.4467], [ 0.3917, -0.6299]], [[-0.2381, -0.6894], [-0.0872, -0.6471], [ 0.0076, -0.6274], [ 0.0595, -0.5576], [ 0.2187, -0.6570]], [[-0.6259, -0.8299], [-0.5715, -0.8090], [-0.4723, -0.7729], [-0.3131, -0.6745], [ 0.0042, -0.6820]], [[-0.7035, -0.8531], [-0.6690, -0.8358], [-0.5730, -0.7989], [-0.3958, -0.6973], [-0.0447, -0.6868]]], grad_fn=<SliceBackward>) Let’s reshape the Stacked BiRNN hidden to separate out forward and backward values using h_n.view(num_layers, num_directions, batch, hidden_size). h_n_reshaped = h_n.view(3, 2, BATCH_SIZE, HIDDEN_SIZE)print("Shape of the hidden after directions are separated: ", h_n_reshaped.shape)###################### OUTPUT ######################Shape of the hidden after directions are separated: torch.Size([3, 2, 4, 2]) The shape is now — (num_layers, num_directions, batch, hidden_size). num_directions is the 1st dimension. To obtain forward and backward hidden, we can do the following - hidden_forward = (num_layers, 0, batch, hidden_size) hidden_backward = (num_layers, 1, batch, hidden_size) h_n_forward = h_n_reshaped[:, 0, :, :]h_n_backward = h_n_reshaped[:, 1, :, :]print("Forward h_n: ", h_n_forward.shape, "\n", h_n_forward)print("\n\nBackward h_n: ", h_n_backward.shape, "\n", h_n_backward)###################### OUTPUT ######################Forward h_n: torch.Size([3, 4, 2]) tensor([[[ 0.9455, 0.5653], [ 0.9986, -0.1385], [ 1.0000, -0.7900], [ 1.0000, -0.9272]], [[-0.6463, 0.5301], [-0.5393, 0.6556], [-0.4089, 0.7277], [-0.3732, 0.7372]], [[-0.1510, -0.6863], [-0.2070, -0.6238], [-0.2617, -0.5444], [-0.2739, -0.5259]]], grad_fn=<SliceBackward>)Backward h_n: torch.Size([3, 4, 2]) tensor([[[ 0.1570, 0.2765], [ 0.9959, 0.9972], [ 1.0000, 1.0000], [ 1.0000, 1.0000]], [[ 0.0474, -0.5973], [ 0.0082, -0.9715], [-0.1373, -0.9681], [-0.2362, -0.9658]], [[-0.0101, -0.4025], [-0.2381, -0.6894], [-0.6259, -0.8299], [-0.7035, -0.8531]]], grad_fn=<SliceBackward>) Thank you for reading. Suggestions and constructive criticism are welcome. :) You can find me on LinkedIn and Twitter. If you liked this, check out my other blogposts.
[ { "code": null, "e": 354, "s": 172, "text": "This blog post takes you through the implementation of Vanilla RNNs, Stacked RNNs, Bidirectional RNNs, and Stacked Bidirectional RNNs in PyTorch by predicting a sequence of numbers." }, { "code": null, "e": 481, "s": 354, "text": "import numpy as npimport torchimport torch.nn as nnimport torch.optim as optimfrom torch.utils.data import Dataset, DataLoader" }, { "code": null, "e": 643, "s": 481, "text": "RNNs are mainly used in case of sequential data such as time series or NLP. There are multiple different types of RNNs which are used for different applications." }, { "code": null, "e": 661, "s": 643, "text": "For Time Series -" }, { "code": null, "e": 703, "s": 661, "text": "Forecasting - many-to-many or many-to-one" }, { "code": null, "e": 732, "s": 703, "text": "Classification - many-to-one" }, { "code": null, "e": 742, "s": 732, "text": "For NLP -" }, { "code": null, "e": 775, "s": 742, "text": "Text Classification: many-to-one" }, { "code": null, "e": 805, "s": 775, "text": "Text Generation: many-to-many" }, { "code": null, "e": 839, "s": 805, "text": "Machine Translation: many-to-many" }, { "code": null, "e": 878, "s": 839, "text": "Named Entity Recognition: many-to-many" }, { "code": null, "e": 908, "s": 878, "text": "Image Captioning: one-to-many" }, { "code": null, "e": 961, "s": 908, "text": "We often stack RNNs together for better performance." }, { "code": null, "e": 1101, "s": 961, "text": "Bidirectional RNN is essentially using 2 RNNs where the input sequence is fed in the normal order to 1 RNN and in reverse to the other RNN." }, { "code": null, "e": 1119, "s": 1101, "text": "Here the data is:" }, { "code": null, "e": 1191, "s": 1119, "text": "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]" }, { "code": null, "e": 1243, "s": 1191, "text": "We divide it into 4 batches of sequence length = 5." }, { "code": null, "e": 1323, "s": 1243, "text": "[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]" }, { "code": null, "e": 1399, "s": 1323, "text": "Batch Size = 4Sequence Length = 5Input Size = 1 (Since, only one dimension)" }, { "code": null, "e": 1486, "s": 1399, "text": "In our case, we’re looking at 5 (seq_len) previous value to predict the next 2 values." }, { "code": null, "e": 1816, "s": 1486, "text": "data = torch.Tensor([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])print(\"Data: \", data.shape, \"\\n\\n\", data)###################### OUTPUT ######################Data: tensor([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20.]) Data Shape: torch.Size([20])" }, { "code": null, "e": 2306, "s": 1816, "text": "# Number of features used as input. (Number of columns)INPUT_SIZE = 1# Number of previous time stamps taken into account.SEQ_LENGTH = 5# Number of features in last hidden state ie. number of output time-# steps to predict.See image below for more clarity.HIDDEN_SIZE = 2# Number of stacked rnn layers.NUM_LAYERS = 1# We have total of 20 rows in our input. # We divide the input into 4 batches where each batch has only 1# row. Each row corresponds to a sequence of length 5. BATCH_SIZE = 4" }, { "code": null, "e": 2499, "s": 2306, "text": "torch.nn.RNN has two inputs - input and h_0 ie. the input sequence and the hidden-layer at t=0. If we don't initialize the hidden layer, it will be auto-initiliased by PyTorch to be all zeros." }, { "code": null, "e": 2672, "s": 2499, "text": "input is the sequence which is fed into the network. It should be of size (seq_len, batch, input_size). If batch_first=True, the input size is (batch, seq_len, input_size)." }, { "code": null, "e": 2894, "s": 2672, "text": "h_0 is the initial hidden state of the network. It is of the size (num_layers * num_directions, batch, input_size) where num_layers is the number of stacked RNNs. num_directions = 2 for bidirectional RNNs and 1 otherwise." }, { "code": null, "e": 2941, "s": 2894, "text": "torch.nn.RNN has two outputs - out and hidden." }, { "code": null, "e": 3168, "s": 2941, "text": "out is the output of the RNN from all timesteps from the last RNN layer. It is of the size (seq_len, batch, num_directions * hidden_size). If batch_first=True, the output size is (batch, seq_len, num_directions * hidden_size)." }, { "code": null, "e": 3357, "s": 3168, "text": "h_n is the hidden value from the last time-step of all RNN layers. It is of the size (num_layers * num_directions, batch, hidden_size). h_n is unaffected by batch_first=True. Github Issue." }, { "code": null, "e": 3519, "s": 3357, "text": "The following diagram explains it more clearly. Here the batch=1. The diagram is for an LSTM which as two hidden parameters (h, c). RNN and GRU both have only h." }, { "code": null, "e": 3534, "s": 3519, "text": "To reiterate —" }, { "code": null, "e": 3673, "s": 3534, "text": "out is the output of the RNN from all timesteps from the last RNN layer.h_n is the hidden value from the last time-step of all RNN layers." }, { "code": null, "e": 4032, "s": 3673, "text": "# Initialize the RNN.rnn = nn.RNN(input_size=INPUT_SIZE, hidden_size=HIDDEN_SIZE, num_layers = 1, batch_first=True)# input size : (batch, seq_len, input_size)inputs = data.view(BATCH_SIZE, SEQ_LENGTH, INPUT_SIZE)# out shape = (batch, seq_len, num_directions * hidden_size)# h_n shape = (num_layers * num_directions, batch, hidden_size)out, h_n = rnn(inputs)" }, { "code": null, "e": 4098, "s": 4032, "text": "input shape = [4, 5, 1]out shape = [4, 5, 2]h_n shape = [1, 4, 2]" }, { "code": null, "e": 4291, "s": 4098, "text": "In the input We have 4 batches as our output because we set the BATCH_SIZE=4. Each batch contains 5 rows because out SEQ_LENGTH = 5. We are using only a single feature as input INPUT_SIZE = 1." }, { "code": null, "e": 4459, "s": 4291, "text": "In the out, we get values from all 4 batches where number of time-steps (seq_len) is 5 and the number of predictions are 2. For each batch, we're predicting 2 outputs." }, { "code": null, "e": 4559, "s": 4459, "text": "In the h_n, we get values from each of the 4 batches of the last time-step of the single RNN layer." }, { "code": null, "e": 5872, "s": 4559, "text": "print('Input: ', inputs.shape, '\\n', inputs)print('\\nOutput: ', out.shape, '\\n', out)print('\\nHidden: ', h_n.shape, '\\n', h_n)###################### OUTPUT ######################Input: torch.Size([4, 5, 1]) tensor([[[ 1.], [ 2.], [ 3.], [ 4.], [ 5.]], [[ 6.], [ 7.], [ 8.], [ 9.], [10.]], [[11.], [12.], [13.], [14.], [15.]], [[16.], [17.], [18.], [19.], [20.]]])Output: torch.Size([4, 5, 2]) tensor([[[-0.0819, 0.8100], [-0.4311, 0.9332], [-0.3162, 0.9748], [-0.3979, 0.9875], [-0.3675, 0.9944]], [[-0.1081, 0.9953], [-0.5145, 0.9986], [-0.3269, 0.9995], [-0.4254, 0.9997], [-0.3820, 0.9999]], [[-0.1342, 0.9999], [-0.5245, 1.0000], [-0.3458, 1.0000], [-0.4382, 1.0000], [-0.3982, 1.0000]], [[-0.1601, 1.0000], [-0.5328, 1.0000], [-0.3648, 1.0000], [-0.4506, 1.0000], [-0.4143, 1.0000]]], grad_fn=<TransposeBackward1>)Hidden: torch.Size([1, 4, 2]) tensor([[[-0.3675, 0.9944], [-0.3820, 0.9999], [-0.3982, 1.0000], [-0.4143, 1.0000]]], grad_fn=<StackBackward>)" }, { "code": null, "e": 5953, "s": 5872, "text": "In the output above, notice the last row in each batch of out is present in h_n." }, { "code": null, "e": 6033, "s": 5953, "text": "out is the output value at all time-steps of the last RNN layer for each batch." }, { "code": null, "e": 6113, "s": 6033, "text": "h_n is the hidden value at the last time-step of all RNN layers for each batch." }, { "code": null, "e": 6261, "s": 6113, "text": "If I change the num_layers = 3, we will have 3 RNN layers stacked next to each other. See how the out, and h_n tensors change in the example below." }, { "code": null, "e": 6372, "s": 6261, "text": "We now have 3 batches in the h_n tensor. The last batch contains the end-rows of each batch in the out tensor." }, { "code": null, "e": 6737, "s": 6372, "text": "# Initialize the RNN.rnn = nn.RNN(input_size=INPUT_SIZE, hidden_size=HIDDEN_SIZE, num_layers = 3, batch_first=True)# input size : (batch_size , seq_len, input_size)inputs = data.view(BATCH_SIZE, SEQ_LENGTH, INPUT_SIZE)# out shape = (batch, seq_len, num_directions * hidden_size)# h_n shape = (num_layers * num_directions, batch, hidden_size)out, h_n = rnn(inputs)" }, { "code": null, "e": 6803, "s": 6737, "text": "input shape = [4, 5, 1]out shape = [4, 5, 2]h_n shape = [3, 4, 2]" }, { "code": null, "e": 6997, "s": 6803, "text": "In the input, We have 4 batches as our output because we set the BATCH_SIZE=4. Each batch contains 5 rows because out SEQ_LENGTH = 5. We are using only a single feature as input INPUT_SIZE = 1." }, { "code": null, "e": 7165, "s": 6997, "text": "In the out, we get values from all 4 batches where number of time-steps (seq_len) is 5 and the number of predictions are 2. For each batch, we're predicting 2 outputs." }, { "code": null, "e": 7270, "s": 7165, "text": "In the h_n, we get values from each of the 4 batches of the last time-steps of the 3 stacked RNN layers." }, { "code": null, "e": 8809, "s": 7270, "text": "print('Input: ', inputs.shape, '\\n', inputs)print('\\nOutput: ', out.shape, '\\n', out)print('\\nHidden: ', h_n.shape, '\\n', h_n)###################### OUTPUT ######################Input: torch.Size([4, 5, 1]) tensor([[[ 1.], [ 2.], [ 3.], [ 4.], [ 5.]], [[ 6.], [ 7.], [ 8.], [ 9.], [10.]], [[11.], [12.], [13.], [14.], [15.]], [[16.], [17.], [18.], [19.], [20.]]])Output: torch.Size([4, 5, 2]) tensor([[[ 0.3144, -0.7527], [-0.0597, -0.6038], [ 0.0896, -0.7646], [ 0.0608, -0.6358], [ 0.1084, -0.6783]], [[ 0.4442, -0.6350], [ 0.0949, -0.3948], [ 0.2715, -0.5962], [ 0.1819, -0.4580], [ 0.2529, -0.5213]], [[ 0.4907, -0.5688], [ 0.1671, -0.2976], [ 0.3462, -0.4922], [ 0.2388, -0.3768], [ 0.3078, -0.4418]], [[ 0.5041, -0.5466], [ 0.1883, -0.2675], [ 0.3684, -0.4576], [ 0.2572, -0.3502], [ 0.3238, -0.4167]]], grad_fn=<TransposeBackward1>)Hidden: torch.Size([3, 4, 2]) tensor([[[-0.6480, -0.4044], [-0.8912, -0.7801], [-0.9808, -0.9366], [-0.9975, -0.9836]], [[-0.7848, -0.0118], [-0.8707, -0.1721], [-0.8955, -0.2411], [-0.9016, -0.2605]], [[ 0.1084, -0.6783], [ 0.2529, -0.5213], [ 0.3078, -0.4418], [ 0.3238, -0.4167]]], grad_fn=<StackBackward>)" }, { "code": null, "e": 8863, "s": 8809, "text": "For Bidirectional RNN, we set the bidirectional=True." }, { "code": null, "e": 9229, "s": 8863, "text": "rnn = nn.RNN(input_size=INPUT_SIZE, hidden_size=HIDDEN_SIZE, batch_first=True, num_layers = 1, bidirectional = True)# input size : (batch_size , seq_len, input_size)inputs = data.view(BATCH_SIZE, SEQ_LENGTH, INPUT_SIZE)# out shape = (batch, seq_len, num_directions * hidden_size)# h_n shape = (num_layers * num_directions, batch, hidden_size)out, h_n = rnn(inputs)" }, { "code": null, "e": 9295, "s": 9229, "text": "input shape = [4, 5, 1]out shape = [4, 5, 4]h_n shape = [2, 4, 2]" }, { "code": null, "e": 9488, "s": 9295, "text": "In the input We have 4 batches as our output because we set the BATCH_SIZE=4. Each batch contains 5 rows because out SEQ_LENGTH = 5. We are using only a single feature as input INPUT_SIZE = 1." }, { "code": null, "e": 9830, "s": 9488, "text": "In the out, we get values from all 4 batches where number of time-steps (seq_len) is 5 and the number of predictions are 2. For each batch, we're predicting 2 outputs. Since, it's a bidirectional RNN, we get 2 sets of predictions. Hence, the shape is [4, 5, 4] and not [4, 5, 2] (which we observed in the case of a unidirectional RNN above)." }, { "code": null, "e": 10106, "s": 9830, "text": "In the h_n, we get values from each of the 4 batches of the last time-steps of the single RNN layers. Since, it's a bidirectional RNN, we get 2 sets of predictions. Hence, the shape is [2, 4, 2] and not [1, 4, 2] (which we observed in the case of a unidirectional RNN above)." }, { "code": null, "e": 11892, "s": 10106, "text": "print('Input: ', inputs.shape, '\\n', inputs)print('\\nOutput: ', out.shape, '\\n', out)print('\\nHidden: ', h_n.shape, '\\n', h_n)###################### OUTPUT ######################Input: torch.Size([4, 5, 1]) tensor([[[ 1.], [ 2.], [ 3.], [ 4.], [ 5.]], [[ 6.], [ 7.], [ 8.], [ 9.], [10.]], [[11.], [12.], [13.], [14.], [15.]], [[16.], [17.], [18.], [19.], [20.]]])Output: torch.Size([4, 5, 4]) tensor([[[ 0.2184, 0.4086, 0.6418, -0.1677], [-0.0222, -0.0095, 0.8794, -0.4927], [-0.6716, -0.2802, 0.9585, -0.7248], [-0.9387, -0.4152, 0.9846, -0.8646], [-0.9841, -0.6164, 0.9789, -0.9192]], [[-0.9813, -0.8829, 0.9979, -0.9721], [-0.9986, -0.8902, 0.9992, -0.9877], [-0.9995, -0.9449, 0.9997, -0.9946], [-0.9998, -0.9729, 0.9999, -0.9977], [-0.9999, -0.9868, 0.9998, -0.9987]], [[-0.9999, -0.9968, 1.0000, -0.9996], [-1.0000, -0.9969, 1.0000, -0.9998], [-1.0000, -0.9985, 1.0000, -0.9999], [-1.0000, -0.9993, 1.0000, -1.0000], [-1.0000, -0.9997, 1.0000, -1.0000]], [[-1.0000, -0.9999, 1.0000, -1.0000], [-1.0000, -0.9999, 1.0000, -1.0000], [-1.0000, -1.0000, 1.0000, -1.0000], [-1.0000, -1.0000, 1.0000, -1.0000], [-1.0000, -1.0000, 1.0000, -1.0000]]], grad_fn=<TransposeBackward1>)Hidden: torch.Size([2, 4, 2]) tensor([[[-0.9841, -0.6164], [-0.9999, -0.9868], [-1.0000, -0.9997], [-1.0000, -1.0000]], [[ 0.6418, -0.1677], [ 0.9979, -0.9721], [ 1.0000, -0.9996], [ 1.0000, -1.0000]]], grad_fn=<StackBackward>)" }, { "code": null, "e": 12057, "s": 11892, "text": "Let us now try to understand the output in a little more detail. According to the docs, to separate the directions (forward and backward), we can do the following -" }, { "code": null, "e": 12295, "s": 12057, "text": "out.view(seq_len, batch, num_directions, hidden_size) with forward and backward being direction 0 and 1 respectively. Keep in mind that if you used batch_first=True, then it would be out.view(batch, seq_len, num_directions, hidden_size)." }, { "code": null, "e": 12416, "s": 12295, "text": "h_n.view(num_layers, num_directions, batch, hidden_size) with forward and backward being direction 0 and 1 respectively." }, { "code": null, "e": 12552, "s": 12416, "text": "Let’s reshape the BiRNN output to separate out forward and backward values using out.view(batch, seq_len, num_directions, hidden_size)." }, { "code": null, "e": 12826, "s": 12552, "text": "out_reshaped = out.view(BATCH_SIZE, SEQ_LENGTH, 2, HIDDEN_SIZE)print(\"Shape of the output after directions are separated: \", out_reshaped.shape)###################### OUTPUT ######################Shape of the output after directions are separated: torch.Size([4, 5, 2, 2])" }, { "code": null, "e": 12892, "s": 12826, "text": "The shape is now — (batch, seq_len, num_directions, hidden_size)." }, { "code": null, "e": 12995, "s": 12892, "text": "num_directions is the 2nd dimension. To obtain forward and backward outputs, we can do the following -" }, { "code": null, "e": 13042, "s": 12995, "text": "out_forward = (batch, seq_len, 0, hidden_size)" }, { "code": null, "e": 13090, "s": 13042, "text": "out_backward = (batch, seq_len, 1, hidden_size)" }, { "code": null, "e": 14614, "s": 13090, "text": "out_forward = out_reshaped[:, :, 0, :]out_backward = out_reshaped[:, :, 1, :]print(\"Forward output: \", out_forward.shape, \"\\n\", out_forward)print(\"\\n\\nBackward output: \", out_backward.shape, \"\\n\", out_backward)###################### OUTPUT ######################Forward output: torch.Size([4, 5, 2]) tensor([[[ 0.2184, 0.4086], [-0.0222, -0.0095], [-0.6716, -0.2802], [-0.9387, -0.4152], [-0.9841, -0.6164]], [[-0.9813, -0.8829], [-0.9986, -0.8902], [-0.9995, -0.9449], [-0.9998, -0.9729], [-0.9999, -0.9868]], [[-0.9999, -0.9968], [-1.0000, -0.9969], [-1.0000, -0.9985], [-1.0000, -0.9993], [-1.0000, -0.9997]], [[-1.0000, -0.9999], [-1.0000, -0.9999], [-1.0000, -1.0000], [-1.0000, -1.0000], [-1.0000, -1.0000]]], grad_fn=<SliceBackward>)Backward output: torch.Size([4, 5, 2]) tensor([[[ 0.6418, -0.1677], [ 0.8794, -0.4927], [ 0.9585, -0.7248], [ 0.9846, -0.8646], [ 0.9789, -0.9192]], [[ 0.9979, -0.9721], [ 0.9992, -0.9877], [ 0.9997, -0.9946], [ 0.9999, -0.9977], [ 0.9998, -0.9987]], [[ 1.0000, -0.9996], [ 1.0000, -0.9998], [ 1.0000, -0.9999], [ 1.0000, -1.0000], [ 1.0000, -1.0000]], [[ 1.0000, -1.0000], [ 1.0000, -1.0000], [ 1.0000, -1.0000], [ 1.0000, -1.0000], [ 1.0000, -1.0000]]], grad_fn=<SliceBackward>)" }, { "code": null, "e": 14753, "s": 14614, "text": "Let’s reshape the BiRNN hidden to separate out forward and backward values using h_n.view(num_layers, num_directions, batch, hidden_size)." }, { "code": null, "e": 15018, "s": 14753, "text": "h_n_reshaped = h_n.view(1, 2, BATCH_SIZE, HIDDEN_SIZE)print(\"Shape of the hidden after directions are separated: \", h_n_reshaped.shape)###################### OUTPUT ######################Shape of the hidden after directions are separated: torch.Size([1, 2, 4, 2])" }, { "code": null, "e": 15087, "s": 15018, "text": "The shape is now — (num_layers, num_directions, batch, hidden_size)." }, { "code": null, "e": 15189, "s": 15087, "text": "num_directions is the 1st dimension. To obtain forward and backward hidden, we can do the following -" }, { "code": null, "e": 15242, "s": 15189, "text": "hidden_forward = (num_layers, 0, batch, hidden_size)" }, { "code": null, "e": 15296, "s": 15242, "text": "hidden_backward = (num_layers, 1, batch, hidden_size)" }, { "code": null, "e": 15906, "s": 15296, "text": "h_n_forward = h_n_reshaped[:, 0, :, :]h_n_backward = h_n_reshaped[:, 1, :, :]print(\"Forward h_n: \", h_n_forward.shape, \"\\n\", h_n_forward)print(\"\\n\\nBackward h_n: \", h_n_backward.shape, \"\\n\", h_n_backward)###################### OUTPUT ######################Forward h_n: torch.Size([1, 4, 2]) tensor([[[-0.9841, -0.6164], [-0.9999, -0.9868], [-1.0000, -0.9997], [-1.0000, -1.0000]]], grad_fn=<SliceBackward>)Backward h_n: torch.Size([1, 4, 2]) tensor([[[ 0.6418, -0.1677], [ 0.9979, -0.9721], [ 1.0000, -0.9996], [ 1.0000, -1.0000]]], grad_fn=<SliceBackward>)" }, { "code": null, "e": 15989, "s": 15906, "text": "For a Stacked Bidirectional RNN, we set the bidirectional=True and num_layers = 3." }, { "code": null, "e": 16355, "s": 15989, "text": "rnn = nn.RNN(input_size=INPUT_SIZE, hidden_size=HIDDEN_SIZE, batch_first=True, num_layers = 3, bidirectional = True)# input size : (batch_size , seq_len, input_size)inputs = data.view(BATCH_SIZE, SEQ_LENGTH, INPUT_SIZE)# out shape = (batch, seq_len, num_directions * hidden_size)# h_n shape = (num_layers * num_directions, batch, hidden_size)out, h_n = rnn(inputs)" }, { "code": null, "e": 16421, "s": 16355, "text": "input shape = [4, 5, 1]out shape = [4, 5, 4]h_n shape = [6, 4, 2]" }, { "code": null, "e": 16614, "s": 16421, "text": "In the input We have 4 batches as our output because we set the BATCH_SIZE=4. Each batch contains 5 rows because out SEQ_LENGTH = 5. We are using only a single feature as input INPUT_SIZE = 1." }, { "code": null, "e": 16964, "s": 16614, "text": "In the out, we get values from all 4 batches where number of time-steps (seq_len) is 5 and the number of predictions are 2. For each batch, we're predicting 2 outputs. Since, it's a bidirectional RNN, we get 2 sets of predictions. Hence, the shape is [4, 5, 4] and not [4, 5, 2] (which we observed in the case of a stacked-unidirectional RNN above)." }, { "code": null, "e": 17248, "s": 16964, "text": "In the h_n, we get values from each of the 4 batches of the last time-steps of the single RNN layers. Since, it's a bidirectional RNN, we get 2 sets of predictions. Hence, the shape is [6, 4, 2] and not [3, 4, 2] (which we observed in the case of a stacked-unidirectional RNN above)." }, { "code": null, "e": 19486, "s": 17248, "text": "print('Input: ', inputs.shape, '\\n', inputs)print('\\nOutput: ', out.shape, '\\n', out)print('\\nHidden: ', h_n.shape, '\\n', h_n)###################### OUTPUT ######################Input: torch.Size([4, 5, 1]) tensor([[[ 1.], [ 2.], [ 3.], [ 4.], [ 5.]], [[ 6.], [ 7.], [ 8.], [ 9.], [10.]], [[11.], [12.], [13.], [14.], [15.]], [[16.], [17.], [18.], [19.], [20.]]])Output: torch.Size([4, 5, 4]) tensor([[[-0.4175, -0.6278, -0.0101, -0.4025], [ 0.1271, -0.5579, 0.2162, -0.4832], [-0.2557, -0.6714, 0.3084, -0.4927], [ 0.0556, -0.6295, 0.3194, -0.4467], [-0.1510, -0.6863, 0.3917, -0.6299]], [[-0.4311, -0.6939, -0.2381, -0.6894], [ 0.1423, -0.5335, -0.0872, -0.6471], [-0.2943, -0.6468, 0.0076, -0.6274], [ 0.0392, -0.5691, 0.0595, -0.5576], [-0.2070, -0.6238, 0.2187, -0.6570]], [[-0.4458, -0.6581, -0.6259, -0.8299], [ 0.0999, -0.4501, -0.5715, -0.8090], [-0.3441, -0.5669, -0.4723, -0.7729], [-0.0133, -0.4705, -0.3131, -0.6745], [-0.2617, -0.5444, 0.0042, -0.6820]], [[-0.4556, -0.6330, -0.7035, -0.8531], [ 0.0780, -0.4118, -0.6690, -0.8358], [-0.3608, -0.5393, -0.5730, -0.7989], [-0.0285, -0.4442, -0.3958, -0.6973], [-0.2739, -0.5259, -0.0447, -0.6868]]], grad_fn=<TransposeBackward1>)Hidden: torch.Size([6, 4, 2]) tensor([[[ 0.9455, 0.5653], [ 0.9986, -0.1385], [ 1.0000, -0.7900], [ 1.0000, -0.9272]], [[ 0.1570, 0.2765], [ 0.9959, 0.9972], [ 1.0000, 1.0000], [ 1.0000, 1.0000]], [[-0.6463, 0.5301], [-0.5393, 0.6556], [-0.4089, 0.7277], [-0.3732, 0.7372]], [[ 0.0474, -0.5973], [ 0.0082, -0.9715], [-0.1373, -0.9681], [-0.2362, -0.9658]], [[-0.1510, -0.6863], [-0.2070, -0.6238], [-0.2617, -0.5444], [-0.2739, -0.5259]], [[-0.0101, -0.4025], [-0.2381, -0.6894], [-0.6259, -0.8299], [-0.7035, -0.8531]]], grad_fn=<StackBackward>)" }, { "code": null, "e": 19651, "s": 19486, "text": "Let us now try to understand the output in a little more detail. According to the docs, to separate the directions (forward and backward), we can do the following -" }, { "code": null, "e": 19889, "s": 19651, "text": "out.view(seq_len, batch, num_directions, hidden_size) with forward and backward being direction 0 and 1 respectively. Keep in mind that if you used batch_first=True, then it would be out.view(batch, seq_len, num_directions, hidden_size)." }, { "code": null, "e": 20010, "s": 19889, "text": "h_n.view(num_layers, num_directions, batch, hidden_size) with forward and backward being direction 0 and 1 respectively." }, { "code": null, "e": 20154, "s": 20010, "text": "Let’s reshape the Stacked BiRNN output to separate out forward and backward values using out.view(batch, seq_len, num_directions, hidden_size)." }, { "code": null, "e": 20428, "s": 20154, "text": "out_reshaped = out.view(BATCH_SIZE, SEQ_LENGTH, 2, HIDDEN_SIZE)print(\"Shape of the output after directions are separated: \", out_reshaped.shape)###################### OUTPUT ######################Shape of the output after directions are separated: torch.Size([4, 5, 2, 2])" }, { "code": null, "e": 20494, "s": 20428, "text": "The shape is now — (batch, seq_len, num_directions, hidden_size)." }, { "code": null, "e": 20597, "s": 20494, "text": "num_directions is the 2nd dimension. To obtain forward and backward outputs, we can do the following -" }, { "code": null, "e": 20644, "s": 20597, "text": "out_forward = (batch, seq_len, 0, hidden_size)" }, { "code": null, "e": 20692, "s": 20644, "text": "out_backward = (batch, seq_len, 1, hidden_size)" }, { "code": null, "e": 22216, "s": 20692, "text": "out_forward = out_reshaped[:, :, 0, :]out_backward = out_reshaped[:, :, 1, :]print(\"Forward output: \", out_forward.shape, \"\\n\", out_forward)print(\"\\n\\nBackward output: \", out_backward.shape, \"\\n\", out_backward)###################### OUTPUT ######################Forward output: torch.Size([4, 5, 2]) tensor([[[-0.4175, -0.6278], [ 0.1271, -0.5579], [-0.2557, -0.6714], [ 0.0556, -0.6295], [-0.1510, -0.6863]], [[-0.4311, -0.6939], [ 0.1423, -0.5335], [-0.2943, -0.6468], [ 0.0392, -0.5691], [-0.2070, -0.6238]], [[-0.4458, -0.6581], [ 0.0999, -0.4501], [-0.3441, -0.5669], [-0.0133, -0.4705], [-0.2617, -0.5444]], [[-0.4556, -0.6330], [ 0.0780, -0.4118], [-0.3608, -0.5393], [-0.0285, -0.4442], [-0.2739, -0.5259]]], grad_fn=<SliceBackward>)Backward output: torch.Size([4, 5, 2]) tensor([[[-0.0101, -0.4025], [ 0.2162, -0.4832], [ 0.3084, -0.4927], [ 0.3194, -0.4467], [ 0.3917, -0.6299]], [[-0.2381, -0.6894], [-0.0872, -0.6471], [ 0.0076, -0.6274], [ 0.0595, -0.5576], [ 0.2187, -0.6570]], [[-0.6259, -0.8299], [-0.5715, -0.8090], [-0.4723, -0.7729], [-0.3131, -0.6745], [ 0.0042, -0.6820]], [[-0.7035, -0.8531], [-0.6690, -0.8358], [-0.5730, -0.7989], [-0.3958, -0.6973], [-0.0447, -0.6868]]], grad_fn=<SliceBackward>)" }, { "code": null, "e": 22363, "s": 22216, "text": "Let’s reshape the Stacked BiRNN hidden to separate out forward and backward values using h_n.view(num_layers, num_directions, batch, hidden_size)." }, { "code": null, "e": 22628, "s": 22363, "text": "h_n_reshaped = h_n.view(3, 2, BATCH_SIZE, HIDDEN_SIZE)print(\"Shape of the hidden after directions are separated: \", h_n_reshaped.shape)###################### OUTPUT ######################Shape of the hidden after directions are separated: torch.Size([3, 2, 4, 2])" }, { "code": null, "e": 22697, "s": 22628, "text": "The shape is now — (num_layers, num_directions, batch, hidden_size)." }, { "code": null, "e": 22799, "s": 22697, "text": "num_directions is the 1st dimension. To obtain forward and backward hidden, we can do the following -" }, { "code": null, "e": 22852, "s": 22799, "text": "hidden_forward = (num_layers, 0, batch, hidden_size)" }, { "code": null, "e": 22906, "s": 22852, "text": "hidden_backward = (num_layers, 1, batch, hidden_size)" }, { "code": null, "e": 23968, "s": 22906, "text": "h_n_forward = h_n_reshaped[:, 0, :, :]h_n_backward = h_n_reshaped[:, 1, :, :]print(\"Forward h_n: \", h_n_forward.shape, \"\\n\", h_n_forward)print(\"\\n\\nBackward h_n: \", h_n_backward.shape, \"\\n\", h_n_backward)###################### OUTPUT ######################Forward h_n: torch.Size([3, 4, 2]) tensor([[[ 0.9455, 0.5653], [ 0.9986, -0.1385], [ 1.0000, -0.7900], [ 1.0000, -0.9272]], [[-0.6463, 0.5301], [-0.5393, 0.6556], [-0.4089, 0.7277], [-0.3732, 0.7372]], [[-0.1510, -0.6863], [-0.2070, -0.6238], [-0.2617, -0.5444], [-0.2739, -0.5259]]], grad_fn=<SliceBackward>)Backward h_n: torch.Size([3, 4, 2]) tensor([[[ 0.1570, 0.2765], [ 0.9959, 0.9972], [ 1.0000, 1.0000], [ 1.0000, 1.0000]], [[ 0.0474, -0.5973], [ 0.0082, -0.9715], [-0.1373, -0.9681], [-0.2362, -0.9658]], [[-0.0101, -0.4025], [-0.2381, -0.6894], [-0.6259, -0.8299], [-0.7035, -0.8531]]], grad_fn=<SliceBackward>)" } ]
How to return table from MySQL function?
You cannot return table from MySQL function. The function can return string, integer, char etc. To return table from MySQL, use stored procedure, not function. Let us first create a table − mysql> create table DemoTable696 ( Id int, Name varchar(100) ); Query OK, 0 rows affected (0.77 sec) Insert some records in the table using insert command − mysql> insert into DemoTable696 values(100,'Mike'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable696 values(101,'Sam'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable696 values(102,'Adam'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable696 values(103,'Carol'); Query OK, 1 row affected (0.20 sec) Display all records from the table using select statement − mysql> select *from DemoTable696; This will produce the following output - +------+-------+ | Id | Name | +------+-------+ | 100 | Mike | | 101 | Sam | | 102 | Adam | | 103 | Carol | +------+-------+ 4 rows in set (0.00 sec) Following is the query to return table from MySQL. The stored procedure is as follows − mysql> DELIMITER // mysql> CREATE PROCEDURE getResultSet(studId int ) BEGIN select *from DemoTable696 where Id=studId; END // Query OK, 0 rows affected (0.14 sec) mysql> DELIMITER ; Now you can call the stored procedure using call command − mysql> call getResultSet(103); This will produce the following output - +------+-------+ | Id | Name | +------+-------+ | 103 | Carol | +------+-------+ 1 row in set (0.00 sec) Query OK, 0 rows affected (0.01 sec)
[ { "code": null, "e": 1222, "s": 1062, "text": "You cannot return table from MySQL function. The function can return string, integer, char etc. To return table from MySQL, use stored procedure, not function." }, { "code": null, "e": 1252, "s": 1222, "text": "Let us first create a table −" }, { "code": null, "e": 1359, "s": 1252, "text": "mysql> create table DemoTable696 (\n Id int,\n Name varchar(100)\n);\nQuery OK, 0 rows affected (0.77 sec)" }, { "code": null, "e": 1415, "s": 1359, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1767, "s": 1415, "text": "mysql> insert into DemoTable696 values(100,'Mike');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable696 values(101,'Sam');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable696 values(102,'Adam');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable696 values(103,'Carol');\nQuery OK, 1 row affected (0.20 sec)" }, { "code": null, "e": 1827, "s": 1767, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1861, "s": 1827, "text": "mysql> select *from DemoTable696;" }, { "code": null, "e": 1902, "s": 1861, "text": "This will produce the following output -" }, { "code": null, "e": 2063, "s": 1902, "text": "+------+-------+\n| Id | Name |\n+------+-------+\n| 100 | Mike |\n| 101 | Sam |\n| 102 | Adam |\n| 103 | Carol |\n+------+-------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2114, "s": 2063, "text": "Following is the query to return table from MySQL." }, { "code": null, "e": 2151, "s": 2114, "text": "The stored procedure is as follows −" }, { "code": null, "e": 2348, "s": 2151, "text": "mysql> DELIMITER //\nmysql> CREATE PROCEDURE getResultSet(studId int )\n BEGIN\n select *from DemoTable696 where Id=studId;\n END\n //\nQuery OK, 0 rows affected (0.14 sec)\nmysql> DELIMITER ;" }, { "code": null, "e": 2407, "s": 2348, "text": "Now you can call the stored procedure using call command −" }, { "code": null, "e": 2438, "s": 2407, "text": "mysql> call getResultSet(103);" }, { "code": null, "e": 2479, "s": 2438, "text": "This will produce the following output -" }, { "code": null, "e": 2625, "s": 2479, "text": "+------+-------+\n| Id | Name |\n+------+-------+\n| 103 | Carol |\n+------+-------+\n1 row in set (0.00 sec)\nQuery OK, 0 rows affected (0.01 sec)" } ]
SQLAlchemy - Quick Guide
SQLAlchemy is a popular SQL toolkit and Object Relational Mapper. It is written in Python and gives full power and flexibility of SQL to an application developer. It is an open source and cross-platform software released under MIT license. SQLAlchemy is famous for its object-relational mapper (ORM), using which, classes can be mapped to the database, thereby allowing the object model and database schema to develop in a cleanly decoupled way from the beginning. As size and performance of SQL databases start to matter, they behave less like object collections. On the other hand, as abstraction in object collections starts to matter, they behave less like tables and rows. SQLAlchemy aims to accommodate both of these principles. For this reason, it has adopted the data mapper pattern (like Hibernate) rather than the active record pattern used by a number of other ORMs. Databases and SQL will be viewed in a different perspective using SQLAlchemy. Michael Bayer is the original author of SQLAlchemy. Its initial version was released in February 2006. Latest version is numbered as 1.2.7, released as recently as in April 2018. ORM (Object Relational Mapping) is a programming technique for converting data between incompatible type systems in object-oriented programming languages. Usually, the type system used in an Object Oriented (OO) language like Python contains non-scalar types. These cannot be expressed as primitive types such as integers and strings. Hence, the OO programmer has to convert objects in scalar data to interact with backend database. However, data types in most of the database products such as Oracle, MySQL, etc., are primary. In an ORM system, each class maps to a table in the underlying database. Instead of writing tedious database interfacing code yourself, an ORM takes care of these issues for you while you can focus on programming the logics of the system. Let us discuss the environmental setup required to use SQLAlchemy. Any version of Python higher than 2.7 is necessary to install SQLAlchemy. The easiest way to install is by using Python Package Manager, pip. This utility is bundled with standard distribution of Python. pip install sqlalchemy Using the above command, we can download the latest released version of SQLAlchemy from python.org and install it to your system. In case of anaconda distribution of Python, SQLAlchemy can be installed from conda terminal using the below command − conda install -c anaconda sqlalchemy It is also possible to install SQLAlchemy from below source code − python setup.py install SQLAlchemy is designed to operate with a DBAPI implementation built for a particular database. It uses dialect system to communicate with various types of DBAPI implementations and databases. All dialects require that an appropriate DBAPI driver is installed. The following are the dialects included − Firebird Microsoft SQL Server MySQL Oracle PostgreSQL SQLite Sybase To check if SQLAlchemy is properly installed and to know its version, enter the following command in the Python prompt − >>> import sqlalchemy >>>sqlalchemy.__version__ '1.2.7' SQLAlchemy core includes SQL rendering engine, DBAPI integration, transaction integration, and schema description services. SQLAlchemy core uses SQL Expression Language that provides a schema-centric usage paradigm whereas SQLAlchemy ORM is a domain-centric mode of usage. The SQL Expression Language presents a system of representing relational database structures and expressions using Python constructs. It presents a system of representing the primitive constructs of the relational database directly without opinion, which is in contrast to ORM that presents a high level and abstracted pattern of usage, which itself is an example of applied usage of the Expression Language. Expression Language is one of the core components of SQLAlchemy. It allows the programmer to specify SQL statements in Python code and use it directly in more complex queries. Expression language is independent of backend and comprehensively covers every aspect of raw SQL. It is closer to raw SQL than any other component in SQLAlchemy. Expression Language represents the primitive constructs of the relational database directly. Because the ORM is based on top of Expression language, a typical Python database application may have overlapped use of both. The application may use expression language alone, though it has to define its own system of translating application concepts into individual database queries. Statements of Expression language will be translated into corresponding raw SQL queries by SQLAlchemy engine. We shall now learn how to create the engine and execute various SQL queries with its help. In the previous chapter, we have discussed about expression Language in SQLAlchemy. Now let us proceed towards the steps involved in connecting to a database. Engine class connects a Pool and Dialect together to provide a source of database connectivity and behavior. An object of Engine class is instantiated using the create_engine() function. The create_engine() function takes the database as one argument. The database is not needed to be defined anywhere. The standard calling form has to send the URL as the first positional argument, usually a string that indicates database dialect and connection arguments. Using the code given below, we can create a database. >>> from sqlalchemy import create_engine >>> engine = create_engine('sqlite:///college.db', echo = True) For a MySQL database, use the below command − engine = create_engine("mysql://user:pwd@localhost/college",echo = True) To specifically mention DB-API to be used for connection, the URL string takes the form as follows − dialect[+driver]://user:password@host/dbname For example, if you are using PyMySQL driver with MySQL, use the following command − mysql+pymysql://<username>:<password>@<host>/<dbname> The echo flag is a shortcut to set up SQLAlchemy logging, which is accomplished via Python’s standard logging module. In the subsequent chapters, we will learn all the generated SQLs. To hide the verbose output, set echo attribute to None. Other arguments to create_engine() function may be dialect specific. The create_engine() function returns an Engine object. Some important methods of Engine class are − connect() Returns connection object execute() Executes a SQL statement construct begin() Returns a context manager delivering a Connection with a Transaction established. Upon successful operation, the Transaction is committed, else it is rolled back dispose() Disposes of the connection pool used by the Engine driver() Driver name of the Dialect in use by the Engine table_names() Returns a list of all table names available in the database transaction() Executes the given function within a transaction boundary Let us now discuss how to use the create table function. The SQL Expression Language constructs its expressions against table columns. SQLAlchemy Column object represents a column in a database table which is in turn represented by a Tableobject. Metadata contains definitions of tables and associated objects such as index, view, triggers, etc. Hence an object of MetaData class from SQLAlchemy Metadata is a collection of Table objects and their associated schema constructs. It holds a collection of Table objects as well as an optional binding to an Engine or Connection. from sqlalchemy import MetaData meta = MetaData() Constructor of MetaData class can have bind and schema parameters which are by default None. Next, we define our tables all within above metadata catalog, using the Table construct, which resembles regular SQL CREATE TABLE statement. An object of Table class represents corresponding table in a database. The constructor takes the following parameters − Column object represents a column in a database table. Constructor takes name, type and other parameters such as primary_key, autoincrement and other constraints. SQLAlchemy matches Python data to the best possible generic column data types defined in it. Some of the generic data types are − BigInteger Boolean Date DateTime Float Integer Numeric SmallInteger String Text Time To create a students table in college database, use the following snippet − from sqlalchemy import Table, Column, Integer, String, MetaData meta = MetaData() students = Table( 'students', meta, Column('id', Integer, primary_key = True), Column('name', String), Column('lastname', String), ) The create_all() function uses the engine object to create all the defined table objects and stores the information in metadata. meta.create_all(engine) Complete code is given below which will create a SQLite database college.db with a students table in it. from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String engine = create_engine('sqlite:///college.db', echo = True) meta = MetaData() students = Table( 'students', meta, Column('id', Integer, primary_key = True), Column('name', String), Column('lastname', String), ) meta.create_all(engine) Because echo attribute of create_engine() function is set to True, the console will display the actual SQL query for table creation as follows − CREATE TABLE students ( id INTEGER NOT NULL, name VARCHAR, lastname VARCHAR, PRIMARY KEY (id) ) The college.db will be created in current working directory. To check if the students table is created, you can open the database using any SQLite GUI tool such as SQLiteStudio. The below image shows the students table that is created in the database − In this chapter, we will briefly focus on the SQL Expressions and their functions. SQL expressions are constructed using corresponding methods relative to target table object. For example, the INSERT statement is created by executing insert() method as follows − ins = students.insert() The result of above method is an insert object that can be verified by using str() function. The below code inserts details like student id, name, lastname. 'INSERT INTO students (id, name, lastname) VALUES (:id, :name, :lastname)' It is possible to insert value in a specific field by values() method to insert object. The code for the same is given below − >>> ins = users.insert().values(name = 'Karan') >>> str(ins) 'INSERT INTO users (name) VALUES (:name)' The SQL echoed on Python console doesn’t show the actual value (‘Karan’ in this case). Instead, SQLALchemy generates a bind parameter which is visible in compiled form of the statement. ins.compile().params {'name': 'Karan'} Similarly, methods like update(), delete() and select() create UPDATE, DELETE and SELECT expressions respectively. We shall learn about them in later chapters. In the previous chapter, we have learnt SQL Expressions. In this chapter, we shall look into the execution of these expressions. In order to execute the resulting SQL expressions, we have to obtain a connection object representing an actively checked out DBAPI connection resource and then feed the expression object as shown in the code below. conn = engine.connect() The following insert() object can be used for execute() method − ins = students.insert().values(name = 'Ravi', lastname = 'Kapoor') result = conn.execute(ins) The console shows the result of execution of SQL expression as below − INSERT INTO students (name, lastname) VALUES (?, ?) ('Ravi', 'Kapoor') COMMIT Following is the entire snippet that shows the execution of INSERT query using SQLAlchemy’s core technique − from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String engine = create_engine('sqlite:///college.db', echo = True) meta = MetaData() students = Table( 'students', meta, Column('id', Integer, primary_key = True), Column('name', String), Column('lastname', String), ) ins = students.insert() ins = students.insert().values(name = 'Ravi', lastname = 'Kapoor') conn = engine.connect() result = conn.execute(ins) The result can be verified by opening the database using SQLite Studio as shown in the below screenshot − The result variable is known as a ResultProxy object. It is analogous to the DBAPI cursor object. We can acquire information about the primary key values which were generated from our statement using ResultProxy.inserted_primary_key as shown below − result.inserted_primary_key [1] To issue many inserts using DBAPI’s execute many() method, we can send in a list of dictionaries each containing a distinct set of parameters to be inserted. conn.execute(students.insert(), [ {'name':'Rajiv', 'lastname' : 'Khanna'}, {'name':'Komal','lastname' : 'Bhandari'}, {'name':'Abdul','lastname' : 'Sattar'}, {'name':'Priya','lastname' : 'Rajhans'}, ]) This is reflected in the data view of the table as shown in the following figure − In this chapter, we will discuss about the concept of selecting rows in the table object. The select() method of table object enables us to construct SELECT expression. s = students.select() The select object translates to SELECT query by str(s) function as shown below − 'SELECT students.id, students.name, students.lastname FROM students' We can use this select object as a parameter to execute() method of connection object as shown in the code below − result = conn.execute(s) When the above statement is executed, Python shell echoes following equivalent SQL expression − SELECT students.id, students.name, students.lastname FROM students The resultant variable is an equivalent of cursor in DBAPI. We can now fetch records using fetchone() method. row = result.fetchone() All selected rows in the table can be printed by a for loop as given below − for row in result: print (row) The complete code to print all rows from students table is shown below − from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String engine = create_engine('sqlite:///college.db', echo = True) meta = MetaData() students = Table( 'students', meta, Column('id', Integer, primary_key = True), Column('name', String), Column('lastname', String), ) s = students.select() conn = engine.connect() result = conn.execute(s) for row in result: print (row) The output shown in Python shell is as follows − (1, 'Ravi', 'Kapoor') (2, 'Rajiv', 'Khanna') (3, 'Komal', 'Bhandari') (4, 'Abdul', 'Sattar') (5, 'Priya', 'Rajhans') The WHERE clause of SELECT query can be applied by using Select.where(). For example, if we want to display rows with id >2 s = students.select().where(students.c.id>2) result = conn.execute(s) for row in result: print (row) Here c attribute is an alias for column. Following output will be displayed on the shell − (3, 'Komal', 'Bhandari') (4, 'Abdul', 'Sattar') (5, 'Priya', 'Rajhans') Here, we have to note that select object can also be obtained by select() function in sqlalchemy.sql module. The select() function requires the table object as argument. from sqlalchemy.sql import select s = select([users]) result = conn.execute(s) SQLAlchemy lets you just use strings, for those cases when the SQL is already known and there isn’t a strong need for the statement to support dynamic features. The text() construct is used to compose a textual statement that is passed to the database mostly unchanged. It constructs a new TextClause, representing a textual SQL string directly as shown in the below code − from sqlalchemy import text t = text("SELECT * FROM students") result = connection.execute(t) The advantages text() provides over a plain string are − backend-neutral support for bind parameters per-statement execution options result-column typing behaviour The text()function requires Bound parameters in the named colon format. They are consistent regardless of database backend. To send values in for the parameters, we pass them into the execute() method as additional arguments. The following example uses bound parameters in textual SQL − from sqlalchemy.sql import text s = text("select students.name, students.lastname from students where students.name between :x and :y") conn.execute(s, x = 'A', y = 'L').fetchall() The text() function constructs SQL expression as follows − select students.name, students.lastname from students where students.name between ? and ? The values of x = ’A’ and y = ’L’ are passed as parameters. Result is a list of rows with names between ‘A’ and ‘L’ − [('Komal', 'Bhandari'), ('Abdul', 'Sattar')] The text() construct supports pre-established bound values using the TextClause.bindparams() method. The parameters can also be explicitly typed as follows − stmt = text("SELECT * FROM students WHERE students.name BETWEEN :x AND :y") stmt = stmt.bindparams( bindparam("x", type_= String), bindparam("y", type_= String) ) result = conn.execute(stmt, {"x": "A", "y": "L"}) The text() function also be produces fragments of SQL within a select() object that accepts text() objects as an arguments. The “geometry” of the statement is provided by select() construct , and the textual content by text() construct. We can build a statement without the need to refer to any pre-established Table metadata. from sqlalchemy.sql import select s = select([text("students.name, students.lastname from students")]).where(text("students.name between :x and :y")) conn.execute(s, x = 'A', y = 'L').fetchall() You can also use and_() function to combine multiple conditions in WHERE clause created with the help of text() function. from sqlalchemy import and_ from sqlalchemy.sql import select s = select([text("* from students")]) \ .where( and_( text("students.name between :x and :y"), text("students.id>2") ) ) conn.execute(s, x = 'A', y = 'L').fetchall() Above code fetches rows with names between “A” and “L” with id greater than 2. The output of the code is given below − [(3, 'Komal', 'Bhandari'), (4, 'Abdul', 'Sattar')] The alias in SQL corresponds to a “renamed” version of a table or SELECT statement, which occurs anytime you say “SELECT * FROM table1 AS a”. The AS creates a new name for the table. Aliases allow any table or subquery to be referenced by a unique name. In case of a table, this allows the same table to be named in the FROM clause multiple times. It provides a parent name for the columns represented by the statement, allowing them to be referenced relative to this name. In SQLAlchemy, any Table, select() construct, or other selectable object can be turned into an alias using the From Clause.alias() method, which produces an Alias construct. The alias() function in sqlalchemy.sql module represents an alias, as typically applied to any table or sub-select within a SQL statement using the AS keyword. from sqlalchemy.sql import alias st = students.alias("a") This alias can now be used in select() construct to refer to students table − s = select([st]).where(st.c.id>2) This translates to SQL expression as follows − SELECT a.id, a.name, a.lastname FROM students AS a WHERE a.id > 2 We can now execute this SQL query with the execute() method of connection object. The complete code is as follows − from sqlalchemy.sql import alias, select st = students.alias("a") s = select([st]).where(st.c.id > 2) conn.execute(s).fetchall() When above line of code is executed, it generates the following output − [(3, 'Komal', 'Bhandari'), (4, 'Abdul', 'Sattar'), (5, 'Priya', 'Rajhans')] The update() method on target table object constructs equivalent UPDATE SQL expression. table.update().where(conditions).values(SET expressions) The values() method on the resultant update object is used to specify the SET conditions of the UPDATE. If left as None, the SET conditions are determined from those parameters passed to the statement during the execution and/or compilation of the statement. The where clause is an Optional expression describing the WHERE condition of the UPDATE statement. Following code snippet changes value of ‘lastname’ column from ‘Khanna’ to ‘Kapoor’ in students table − stmt = students.update().where(students.c.lastname == 'Khanna').values(lastname = 'Kapoor') The stmt object is an update object that translates to − 'UPDATE students SET lastname = :lastname WHERE students.lastname = :lastname_1' The bound parameter lastname_1 will be substituted when execute() method is invoked. The complete update code is given below − from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String engine = create_engine('sqlite:///college.db', echo = True) meta = MetaData() students = Table( 'students', meta, Column('id', Integer, primary_key = True), Column('name', String), Column('lastname', String), ) conn = engine.connect() stmt=students.update().where(students.c.lastname=='Khanna').values(lastname='Kapoor') conn.execute(stmt) s = students.select() conn.execute(s).fetchall() The above code displays following output with second row showing effect of update operation as in the screenshot given − [ (1, 'Ravi', 'Kapoor'), (2, 'Rajiv', 'Kapoor'), (3, 'Komal', 'Bhandari'), (4, 'Abdul', 'Sattar'), (5, 'Priya', 'Rajhans') ] Note that similar functionality can also be achieved by using update() function in sqlalchemy.sql.expression module as shown below − from sqlalchemy.sql.expression import update stmt = update(students).where(students.c.lastname == 'Khanna').values(lastname = 'Kapoor') In the previous chapter, we have understood what an Update expression does. The next expression that we are going to learn is Delete. The delete operation can be achieved by running delete() method on target table object as given in the following statement − stmt = students.delete() In case of students table, the above line of code constructs a SQL expression as following − 'DELETE FROM students' However, this will delete all rows in students table. Usually DELETE query is associated with a logical expression specified by WHERE clause. The following statement shows where parameter − stmt = students.delete().where(students.c.id > 2) The resultant SQL expression will have a bound parameter which will be substituted at runtime when the statement is executed. 'DELETE FROM students WHERE students.id > :id_1' Following code example will delete those rows from students table having lastname as ‘Khanna’ − from sqlalchemy.sql.expression import update from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String engine = create_engine('sqlite:///college.db', echo = True) meta = MetaData() students = Table( 'students', meta, Column('id', Integer, primary_key = True), Column('name', String), Column('lastname', String), ) conn = engine.connect() stmt = students.delete().where(students.c.lastname == 'Khanna') conn.execute(stmt) s = students.select() conn.execute(s).fetchall() To verify the result, refresh the data view of students table in SQLiteStudio. One of the important features of RDBMS is establishing relation between tables. SQL operations like SELECT, UPDATE and DELETE can be performed on related tables. This section describes these operations using SQLAlchemy. For this purpose, two tables are created in our SQLite database (college.db). The students table has the same structure as given in the previous section; whereas the addresses table has st_id column which is mapped to id column in students table using foreign key constraint. The following code will create two tables in college.db − from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, ForeignKey engine = create_engine('sqlite:///college.db', echo=True) meta = MetaData() students = Table( 'students', meta, Column('id', Integer, primary_key = True), Column('name', String), Column('lastname', String), ) addresses = Table( 'addresses', meta, Column('id', Integer, primary_key = True), Column('st_id', Integer, ForeignKey('students.id')), Column('postal_add', String), Column('email_add', String)) meta.create_all(engine) Above code will translate to CREATE TABLE queries for students and addresses table as below − CREATE TABLE students ( id INTEGER NOT NULL, name VARCHAR, lastname VARCHAR, PRIMARY KEY (id) ) CREATE TABLE addresses ( id INTEGER NOT NULL, st_id INTEGER, postal_add VARCHAR, email_add VARCHAR, PRIMARY KEY (id), FOREIGN KEY(st_id) REFERENCES students (id) ) The following screenshots present the above code very clearly − These tables are populated with data by executing insert() method of table objects. To insert 5 rows in students table, you can use the code given below − from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String engine = create_engine('sqlite:///college.db', echo = True) meta = MetaData() conn = engine.connect() students = Table( 'students', meta, Column('id', Integer, primary_key = True), Column('name', String), Column('lastname', String), ) conn.execute(students.insert(), [ {'name':'Ravi', 'lastname':'Kapoor'}, {'name':'Rajiv', 'lastname' : 'Khanna'}, {'name':'Komal','lastname' : 'Bhandari'}, {'name':'Abdul','lastname' : 'Sattar'}, {'name':'Priya','lastname' : 'Rajhans'}, ]) Rows are added in addresses table with the help of the following code − from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String engine = create_engine('sqlite:///college.db', echo = True) meta = MetaData() conn = engine.connect() addresses = Table( 'addresses', meta, Column('id', Integer, primary_key = True), Column('st_id', Integer), Column('postal_add', String), Column('email_add', String) ) conn.execute(addresses.insert(), [ {'st_id':1, 'postal_add':'Shivajinagar Pune', 'email_add':'ravi@gmail.com'}, {'st_id':1, 'postal_add':'ChurchGate Mumbai', 'email_add':'kapoor@gmail.com'}, {'st_id':3, 'postal_add':'Jubilee Hills Hyderabad', 'email_add':'komal@gmail.com'}, {'st_id':5, 'postal_add':'MG Road Bangaluru', 'email_add':'as@yahoo.com'}, {'st_id':2, 'postal_add':'Cannought Place new Delhi', 'email_add':'admin@khanna.com'}, ]) Note that the st_id column in addresses table refers to id column in students table. We can now use this relation to fetch data from both the tables. We want to fetch name and lastname from students table corresponding to st_id in the addresses table. from sqlalchemy.sql import select s = select([students, addresses]).where(students.c.id == addresses.c.st_id) result = conn.execute(s) for row in result: print (row) The select objects will effectively translate into following SQL expression joining two tables on common relation − SELECT students.id, students.name, students.lastname, addresses.id, addresses.st_id, addresses.postal_add, addresses.email_add FROM students, addresses WHERE students.id = addresses.st_id This will produce output extracting corresponding data from both tables as follows − (1, 'Ravi', 'Kapoor', 1, 1, 'Shivajinagar Pune', 'ravi@gmail.com') (1, 'Ravi', 'Kapoor', 2, 1, 'ChurchGate Mumbai', 'kapoor@gmail.com') (3, 'Komal', 'Bhandari', 3, 3, 'Jubilee Hills Hyderabad', 'komal@gmail.com') (5, 'Priya', 'Rajhans', 4, 5, 'MG Road Bangaluru', 'as@yahoo.com') (2, 'Rajiv', 'Khanna', 5, 2, 'Cannought Place new Delhi', 'admin@khanna.com') In the previous chapter, we have discussed about how to use multiple tables. So we proceed a step further and learn multiple table updates in this chapter. Using SQLAlchemy’s table object, more than one table can be specified in WHERE clause of update() method. The PostgreSQL and Microsoft SQL Server support UPDATE statements that refer to multiple tables. This implements “UPDATE FROM” syntax, which updates one table at a time. However, additional tables can be referenced in an additional “FROM” clause in the WHERE clause directly. The following lines of codes explain the concept of multiple table updates clearly. stmt = students.update().\ values({ students.c.name:'xyz', addresses.c.email_add:'abc@xyz.com' }).\ where(students.c.id == addresses.c.id) The update object is equivalent to the following UPDATE query − UPDATE students SET email_add = :addresses_email_add, name = :name FROM addresses WHERE students.id = addresses.id As far as MySQL dialect is concerned, multiple tables can be embedded into a single UPDATE statement separated by a comma as given below − stmt = students.update().\ values(name = 'xyz').\ where(students.c.id == addresses.c.id) The following code depicts the resulting UPDATE query − 'UPDATE students SET name = :name FROM addresses WHERE students.id = addresses.id' SQLite dialect however doesn’t support multiple-table criteria within UPDATE and shows following error − NotImplementedError: This backend does not support multiple-table criteria within UPDATE The UPDATE query of raw SQL has SET clause. It is rendered by the update() construct using the column ordering given in the originating Table object. Therefore, a particular UPDATE statement with particular columns will be rendered the same each time. Since the parameters themselves are passed to the Update.values() method as Python dictionary keys, there is no other fixed ordering available. In some cases, the order of parameters rendered in the SET clause are significant. In MySQL, providing updates to column values is based on that of other column values. Following statement’s result − UPDATE table1 SET x = y + 10, y = 20 will have a different result than − UPDATE table1 SET y = 20, x = y + 10 SET clause in MySQL is evaluated on a per-value basis and not on per-row basis. For this purpose, the preserve_parameter_order is used. Python list of 2-tuples is given as argument to the Update.values() method − stmt = table1.update(preserve_parameter_order = True).\ values([(table1.c.y, 20), (table1.c.x, table1.c.y + 10)]) The List object is similar to dictionary except that it is ordered. This ensures that the “y” column’s SET clause will render first, then the “x” column’s SET clause. In this chapter, we will look into the Multiple Table Deletes expression which is similar to using Multiple Table Updates function. More than one table can be referred in WHERE clause of DELETE statement in many DBMS dialects. For PG and MySQL, “DELETE USING” syntax is used; and for SQL Server, using “DELETE FROM” expression refers to more than one table. The SQLAlchemy delete() construct supports both of these modes implicitly, by specifying multiple tables in the WHERE clause as follows − stmt = users.delete().\ where(users.c.id == addresses.c.id).\ where(addresses.c.email_address.startswith('xyz%')) conn.execute(stmt) On a PostgreSQL backend, the resulting SQL from the above statement would render as − DELETE FROM users USING addresses WHERE users.id = addresses.id AND (addresses.email_address LIKE %(email_address_1)s || '%%') If this method is used with a database that doesn’t support this behaviour, the compiler will raise NotImplementedError. In this chapter, we will learn how to use Joins in SQLAlchemy. Effect of joining is achieved by just placing two tables in either the columns clause or the where clause of the select() construct. Now we use the join() and outerjoin() methods. The join() method returns a join object from one table object to another. join(right, onclause = None, isouter = False, full = False) The functions of the parameters mentioned in the above code are as follows − right − the right side of the join; this is any Table object right − the right side of the join; this is any Table object onclause − a SQL expression representing the ON clause of the join. If left at None, it attempts to join the two tables based on a foreign key relationship onclause − a SQL expression representing the ON clause of the join. If left at None, it attempts to join the two tables based on a foreign key relationship isouter − if True, renders a LEFT OUTER JOIN, instead of JOIN isouter − if True, renders a LEFT OUTER JOIN, instead of JOIN full − if True, renders a FULL OUTER JOIN, instead of LEFT OUTER JOIN full − if True, renders a FULL OUTER JOIN, instead of LEFT OUTER JOIN For example, following use of join() method will automatically result in join based on the foreign key. >>> print(students.join(addresses)) This is equivalent to following SQL expression − students JOIN addresses ON students.id = addresses.st_id You can explicitly mention joining criteria as follows − j = students.join(addresses, students.c.id == addresses.c.st_id) If we now build the below select construct using this join as − stmt = select([students]).select_from(j) This will result in following SQL expression − SELECT students.id, students.name, students.lastname FROM students JOIN addresses ON students.id = addresses.st_id If this statement is executed using the connection representing engine, data belonging to selected columns will be displayed. The complete code is as follows − from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, ForeignKey engine = create_engine('sqlite:///college.db', echo = True) meta = MetaData() conn = engine.connect() students = Table( 'students', meta, Column('id', Integer, primary_key = True), Column('name', String), Column('lastname', String), ) addresses = Table( 'addresses', meta, Column('id', Integer, primary_key = True), Column('st_id', Integer,ForeignKey('students.id')), Column('postal_add', String), Column('email_add', String) ) from sqlalchemy import join from sqlalchemy.sql import select j = students.join(addresses, students.c.id == addresses.c.st_id) stmt = select([students]).select_from(j) result = conn.execute(stmt) result.fetchall() The following is the output of the above code − [ (1, 'Ravi', 'Kapoor'), (1, 'Ravi', 'Kapoor'), (3, 'Komal', 'Bhandari'), (5, 'Priya', 'Rajhans'), (2, 'Rajiv', 'Khanna') ] Conjunctions are functions in SQLAlchemy module that implement relational operators used in WHERE clause of SQL expressions. The operators AND, OR, NOT, etc., are used to form a compound expression combining two individual logical expressions. A simple example of using AND in SELECT statement is as follows − SELECT * from EMPLOYEE WHERE salary>10000 AND age>30 SQLAlchemy functions and_(), or_() and not_() respectively implement AND, OR and NOT operators. It produces a conjunction of expressions joined by AND. An example is given below for better understanding − from sqlalchemy import and_ print( and_( students.c.name == 'Ravi', students.c.id <3 ) ) This translates to − students.name = :name_1 AND students.id < :id_1 To use and_() in a select() construct on a students table, use the following line of code − stmt = select([students]).where(and_(students.c.name == 'Ravi', students.c.id <3)) SELECT statement of the following nature will be constructed − SELECT students.id, students.name, students.lastname FROM students WHERE students.name = :name_1 AND students.id < :id_1 The complete code that displays output of the above SELECT query is as follows − from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, ForeignKey, select engine = create_engine('sqlite:///college.db', echo = True) meta = MetaData() conn = engine.connect() students = Table( 'students', meta, Column('id', Integer, primary_key = True), Column('name', String), Column('lastname', String), ) from sqlalchemy import and_, or_ stmt = select([students]).where(and_(students.c.name == 'Ravi', students.c.id <3)) result = conn.execute(stmt) print (result.fetchall()) Following row will be selected assuming that students table is populated with data used in previous example − [(1, 'Ravi', 'Kapoor')] It produces conjunction of expressions joined by OR. We shall replace the stmt object in the above example with the following one using or_() stmt = select([students]).where(or_(students.c.name == 'Ravi', students.c.id <3)) Which will be effectively equivalent to following SELECT query − SELECT students.id, students.name, students.lastname FROM students WHERE students.name = :name_1 OR students.id < :id_1 Once you make the substitution and run the above code, the result will be two rows falling in the OR condition − [(1, 'Ravi', 'Kapoor'), (2, 'Rajiv', 'Khanna')] It produces an ascending ORDER BY clause. The function takes the column to apply the function as a parameter. from sqlalchemy import asc stmt = select([students]).order_by(asc(students.c.name)) The statement implements following SQL expression − SELECT students.id, students.name, students.lastname FROM students ORDER BY students.name ASC Following code lists out all records in students table in ascending order of name column − from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, ForeignKey, select engine = create_engine('sqlite:///college.db', echo = True) meta = MetaData() conn = engine.connect() students = Table( 'students', meta, Column('id', Integer, primary_key = True), Column('name', String), Column('lastname', String), ) from sqlalchemy import asc stmt = select([students]).order_by(asc(students.c.name)) result = conn.execute(stmt) for row in result: print (row) Above code produces following output − (4, 'Abdul', 'Sattar') (3, 'Komal', 'Bhandari') (5, 'Priya', 'Rajhans') (2, 'Rajiv', 'Khanna') (1, 'Ravi', 'Kapoor') Similarly desc() function produces descending ORDER BY clause as follows − from sqlalchemy import desc stmt = select([students]).order_by(desc(students.c.lastname)) The equivalent SQL expression is − SELECT students.id, students.name, students.lastname FROM students ORDER BY students.lastname DESC And the output for the above lines of code is − (4, 'Abdul', 'Sattar') (5, 'Priya', 'Rajhans') (2, 'Rajiv', 'Khanna') (1, 'Ravi', 'Kapoor') (3, 'Komal', 'Bhandari') It produces a BETWEEN predicate clause. This is generally used to validate if value of a certain column falls between a range. For example, following code selects rows for which id column is between 2 and 4 − from sqlalchemy import between stmt = select([students]).where(between(students.c.id,2,4)) print (stmt) The resulting SQL expression resembles − SELECT students.id, students.name, students.lastname FROM students WHERE students.id BETWEEN :id_1 AND :id_2 and the result is as follows − (2, 'Rajiv', 'Khanna') (3, 'Komal', 'Bhandari') (4, 'Abdul', 'Sattar') Some of the important functions used in SQLAlchemy are discussed in this chapter. Standard SQL has recommended many functions which are implemented by most dialects. They return a single value based on the arguments passed to it. Some SQL functions take columns as arguments whereas some are generic. Thefunc keyword in SQLAlchemy API is used to generate these functions. In SQL, now() is a generic function. Following statements renders the now() function using func − from sqlalchemy.sql import func result = conn.execute(select([func.now()])) print (result.fetchone()) Sample result of above code may be as shown below − (datetime.datetime(2018, 6, 16, 6, 4, 40),) On the other hand, count() function which returns number of rows selected from a table, is rendered by following usage of func − from sqlalchemy.sql import func result = conn.execute(select([func.count(students.c.id)])) print (result.fetchone()) From the above code, count of number of rows in students table will be fetched. Some built-in SQL functions are demonstrated using Employee table with following data − The max() function is implemented by following usage of func from SQLAlchemy which will result in 85, the total maximum marks obtained − from sqlalchemy.sql import func result = conn.execute(select([func.max(employee.c.marks)])) print (result.fetchone()) Similarly, min() function that will return 56, minimum marks, will be rendered by following code − from sqlalchemy.sql import func result = conn.execute(select([func.min(employee.c.marks)])) print (result.fetchone()) So, the AVG() function can also be implemented by using the below code − from sqlalchemy.sql import func result = conn.execute(select([func.avg(employee.c.marks)])) print (result.fetchone()) Functions are normally used in the columns clause of a select statement. They can also be given label as well as a type. A label to function allows the result to be targeted in a result row based on a string name, and a type is required when you need result-set processing to occur.from sqlalchemy.sql import func result = conn.execute(select([func.max(students.c.lastname).label('Name')])) print (result.fetchone()) In the last chapter, we have learnt about various functions such as max(), min(), count(), etc., here, we will learn about set operations and their uses. Set operations such as UNION and INTERSECT are supported by standard SQL and most of its dialect. SQLAlchemy implements them with the help of following functions − While combining results of two or more SELECT statements, UNION eliminates duplicates from the resultset. The number of columns and datatype must be same in both the tables. The union() function returns a CompoundSelect object from multiple tables. Following example demonstrates its use − from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, union engine = create_engine('sqlite:///college.db', echo = True) meta = MetaData() conn = engine.connect() addresses = Table( 'addresses', meta, Column('id', Integer, primary_key = True), Column('st_id', Integer), Column('postal_add', String), Column('email_add', String) ) u = union(addresses.select().where(addresses.c.email_add.like('%@gmail.com addresses.select().where(addresses.c.email_add.like('%@yahoo.com')))) result = conn.execute(u) result.fetchall() The union construct translates to following SQL expression − SELECT addresses.id, addresses.st_id, addresses.postal_add, addresses.email_add FROM addresses WHERE addresses.email_add LIKE ? UNION SELECT addresses.id, addresses.st_id, addresses.postal_add, addresses.email_add FROM addresses WHERE addresses.email_add LIKE ? From our addresses table, following rows represent the union operation − [ (1, 1, 'Shivajinagar Pune', 'ravi@gmail.com'), (2, 1, 'ChurchGate Mumbai', 'kapoor@gmail.com'), (3, 3, 'Jubilee Hills Hyderabad', 'komal@gmail.com'), (4, 5, 'MG Road Bangaluru', 'as@yahoo.com') ] UNION ALL operation cannot remove the duplicates and cannot sort the data in the resultset. For example, in above query, UNION is replaced by UNION ALL to see the effect. u = union_all(addresses.select().where(addresses.c.email_add.like('%@gmail.com')), addresses.select().where(addresses.c.email_add.like('%@yahoo.com'))) The corresponding SQL expression is as follows − SELECT addresses.id, addresses.st_id, addresses.postal_add, addresses.email_add FROM addresses WHERE addresses.email_add LIKE ? UNION ALL SELECT addresses.id, addresses.st_id, addresses.postal_add, addresses.email_add FROM addresses WHERE addresses.email_add LIKE ? The SQL EXCEPT clause/operator is used to combine two SELECT statements and return rows from the first SELECT statement that are not returned by the second SELECT statement. The except_() function generates a SELECT expression with EXCEPT clause. In the following example, the except_() function returns only those records from addresses table that have ‘gmail.com’ in email_add field but excludes those which have ‘Pune’ as part of postal_add field. u = except_(addresses.select().where(addresses.c.email_add.like('%@gmail.com')), addresses.select().where(addresses.c.postal_add.like('%Pune'))) Result of the above code is the following SQL expression − SELECT addresses.id, addresses.st_id, addresses.postal_add, addresses.email_add FROM addresses WHERE addresses.email_add LIKE ? EXCEPT SELECT addresses.id, addresses.st_id, addresses.postal_add, addresses.email_add FROM addresses WHERE addresses.postal_add LIKE ? Assuming that addresses table contains data used in earlier examples, it will display following output − [(2, 1, 'ChurchGate Mumbai', 'kapoor@gmail.com'), (3, 3, 'Jubilee Hills Hyderabad', 'komal@gmail.com')] Using INTERSECT operator, SQL displays common rows from both the SELECT statements. The intersect() function implements this behaviour. In following examples, two SELECT constructs are parameters to intersect() function. One returns rows containing ‘gmail.com’ as part of email_add column, and other returns rows having ‘Pune’ as part of postal_add column. The result will be common rows from both resultsets. u = intersect(addresses.select().where(addresses.c.email_add.like('%@gmail.com')), addresses.select().where(addresses.c.postal_add.like('%Pune'))) In effect, this is equivalent to following SQL statement − SELECT addresses.id, addresses.st_id, addresses.postal_add, addresses.email_add FROM addresses WHERE addresses.email_add LIKE ? INTERSECT SELECT addresses.id, addresses.st_id, addresses.postal_add, addresses.email_add FROM addresses WHERE addresses.postal_add LIKE ? The two bound parameters ‘%gmail.com’ and ‘%Pune’ generate a single row from original data in addresses table as shown below − [(1, 1, 'Shivajinagar Pune', 'ravi@gmail.com')] The main objective of the Object Relational Mapper API of SQLAlchemy is to facilitate associating user-defined Python classes with database tables, and objects of those classes with rows in their corresponding tables. Changes in states of objects and rows are synchronously matched with each other. SQLAlchemy enables expressing database queries in terms of user defined classes and their defined relationships. The ORM is constructed on top of the SQL Expression Language. It is a high level and abstracted pattern of usage. In fact, ORM is an applied usage of the Expression Language. Although a successful application may be constructed using the Object Relational Mapper exclusively, sometimes an application constructed with the ORM may use the Expression Language directly where specific database interactions are required. First of all, create_engine() function is called to set up an engine object which is subsequently used to perform SQL operations. The function has two arguments, one is the name of database and other is an echo parameter when set to True will generate the activity log. If it doesn’t exist, the database will be created. In the following example, a SQLite database is created. from sqlalchemy import create_engine engine = create_engine('sqlite:///sales.db', echo = True) The Engine establishes a real DBAPI connection to the database when a method like Engine.execute() or Engine.connect() is called. It is then used to emit the SQLORM which does not use the Engine directly; instead, it is used behind the scenes by the ORM. In case of ORM, the configurational process starts by describing the database tables and then by defining classes which will be mapped to those tables. In SQLAlchemy, these two tasks are performed together. This is done by using Declarative system; the classes created include directives to describe the actual database table they are mapped to. A base class stores a catlog of classes and mapped tables in the Declarative system. This is called as the declarative base class. There will be usually just one instance of this base in a commonly imported module. The declarative_base() function is used to create base class. This function is defined in sqlalchemy.ext.declarative module. from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() Once base classis declared, any number of mapped classes can be defined in terms of it. Following code defines a Customer’s class. It contains the table to be mapped to, and names and datatypes of columns in it. class Customers(Base): __tablename__ = 'customers' id = Column(Integer, primary_key = True) name = Column(String) address = Column(String) email = Column(String) A class in Declarative must have a __tablename__ attribute, and at least one Column which is part of a primary key. Declarative replaces all the Column objects with special Python accessors known as descriptors. This process is known as instrumentation which provides the means to refer to the table in a SQL context and enables persisting and loading the values of columns from the database. This mapped class like a normal Python class has attributes and methods as per the requirement. The information about class in Declarative system, is called as table metadata. SQLAlchemy uses Table object to represent this information for a specific table created by Declarative. The Table object is created according to the specifications, and is associated with the class by constructing a Mapper object. This mapper object is not directly used but is used internally as interface between mapped class and table. Each Table object is a member of larger collection known as MetaData and this object is available using the .metadata attribute of declarative base class. The MetaData.create_all() method is, passing in our Engine as a source of database connectivity. For all tables that haven’t been created yet, it issues CREATE TABLE statements to the database. Base.metadata.create_all(engine) The complete script to create a database and a table, and to map Python class is given below − from sqlalchemy import Column, Integer, String from sqlalchemy import create_engine engine = create_engine('sqlite:///sales.db', echo = True) from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Customers(Base): __tablename__ = 'customers' id = Column(Integer, primary_key=True) name = Column(String) address = Column(String) email = Column(String) Base.metadata.create_all(engine) When executed, Python console will echo following SQL expression being executed − CREATE TABLE customers ( id INTEGER NOT NULL, name VARCHAR, address VARCHAR, email VARCHAR, PRIMARY KEY (id) ) If we open the Sales.db using SQLiteStudio graphic tool, it shows customers table inside it with above mentioned structure. In order to interact with the database, we need to obtain its handle. A session object is the handle to database. Session class is defined using sessionmaker() – a configurable session factory method which is bound to the engine object created earlier. from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind = engine) The session object is then set up using its default constructor as follows − session = Session() Some of the frequently required methods of session class are listed below − begin() begins a transaction on this session add() places an object in the session. Its state is persisted in the database on next flush operation add_all() adds a collection of objects to the session commit() flushes all items and any transaction in progress delete() marks a transaction as deleted execute() executes a SQL expression expire() marks attributes of an instance as out of date flush() flushes all object changes to the database invalidate() closes the session using connection invalidation rollback() rolls back the current transaction in progress close() Closes current session by clearing all items and ending any transaction in progress In the previous chapters of SQLAlchemy ORM, we have learnt how to declare mapping and create sessions. In this chapter, we will learn how to add objects to the table. We have declared Customer class that has been mapped to customers table. We have to declare an object of this class and persistently add it to the table by add() method of session object. c1 = Sales(name = 'Ravi Kumar', address = 'Station Road Nanded', email = 'ravi@gmail.com') session.add(c1) Note that this transaction is pending until the same is flushed using commit() method. session.commit() Following is the complete script to add a record in customers table − from sqlalchemy import Column, Integer, String from sqlalchemy import create_engine engine = create_engine('sqlite:///sales.db', echo = True) from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Customers(Base): __tablename__ = 'customers' id = Column(Integer, primary_key=True) name = Column(String) address = Column(String) email = Column(String) from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind = engine) session = Session() c1 = Customers(name = 'Ravi Kumar', address = 'Station Road Nanded', email = 'ravi@gmail.com') session.add(c1) session.commit() To add multiple records, we can use add_all() method of the session class. session.add_all([ Customers(name = 'Komal Pande', address = 'Koti, Hyderabad', email = 'komal@gmail.com'), Customers(name = 'Rajender Nath', address = 'Sector 40, Gurgaon', email = 'nath@gmail.com'), Customers(name = 'S.M.Krishna', address = 'Budhwar Peth, Pune', email = 'smk@gmail.com')] ) session.commit() Table view of SQLiteStudio shows that the records are persistently added in customers table. The following image shows the result − All SELECT statements generated by SQLAlchemy ORM are constructed by Query object. It provides a generative interface, hence successive calls return a new Query object, a copy of the former with additional criteria and options associated with it. Query objects are initially generated using the query() method of the Session as follows − q = session.query(mapped class) Following statement is also equivalent to the above given statement − q = Query(mappedClass, session) The query object has all() method which returns a resultset in the form of list of objects. If we execute it on our customers table − result = session.query(Customers).all() This statement is effectively equivalent to following SQL expression − SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers The result object can be traversed using For loop as below to obtain all records in underlying customers table. Here is the complete code to display all records in Customers table − from sqlalchemy import Column, Integer, String from sqlalchemy import create_engine engine = create_engine('sqlite:///sales.db', echo = True) from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Customers(Base): __tablename__ = 'customers' id = Column(Integer, primary_key = True) name = Column(String) address = Column(String) email = Column(String) from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind = engine) session = Session() result = session.query(Customers).all() for row in result: print ("Name: ",row.name, "Address:",row.address, "Email:",row.email) Python console shows list of records as below − Name: Ravi Kumar Address: Station Road Nanded Email: ravi@gmail.com Name: Komal Pande Address: Koti, Hyderabad Email: komal@gmail.com Name: Rajender Nath Address: Sector 40, Gurgaon Email: nath@gmail.com Name: S.M.Krishna Address: Budhwar Peth, Pune Email: smk@gmail.com The Query object also has following useful methods − add_columns() It adds one or more column expressions to the list of result columns to be returned. add_entity() It adds a mapped entity to the list of result columns to be returned. count() It returns a count of rows this Query would return. delete() It performs a bulk delete query. Deletes rows matched by this query from the database. distinct() It applies a DISTINCT clause to the query and return the newly resulting Query. filter() It applies the given filtering criterion to a copy of this Query, using SQL expressions. first() It returns the first result of this Query or None if the result doesn’t contain any row. get() It returns an instance based on the given primary key identifier providing direct access to the identity map of the owning Session. group_by() It applies one or more GROUP BY criterion to the query and return the newly resulting Query join() It creates a SQL JOIN against this Query object’s criterion and apply generatively, returning the newly resulting Query. one() It returns exactly one result or raise an exception. order_by() It applies one or more ORDER BY criterion to the query and returns the newly resulting Query. update() It performs a bulk update query and updates rows matched by this query in the database. In this chapter, we will see how to modify or update the table with desired values. To modify data of a certain attribute of any object, we have to assign new value to it and commit the changes to make the change persistent. Let us fetch an object from the table whose primary key identifier, in our Customers table with ID=2. We can use get() method of session as follows − x = session.query(Customers).get(2) We can display contents of the selected object with the below given code − print ("Name: ", x.name, "Address:", x.address, "Email:", x.email) From our customers table, following output should be displayed − Name: Komal Pande Address: Koti, Hyderabad Email: komal@gmail.com Now we need to update the Address field by assigning new value as given below − x.address = 'Banjara Hills Secunderabad' session.commit() The change will be persistently reflected in the database. Now we fetch object corresponding to first row in the table by using first() method as follows − x = session.query(Customers).first() This will execute following SQL expression − SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers LIMIT ? OFFSET ? The bound parameters will be LIMIT = 1 and OFFSET = 0 respectively which means first row will be selected. print ("Name: ", x.name, "Address:", x.address, "Email:", x.email) Now, the output for the above code displaying the first row is as follows − Name: Ravi Kumar Address: Station Road Nanded Email: ravi@gmail.com Now change name attribute and display the contents using the below code − x.name = 'Ravi Shrivastava' print ("Name: ", x.name, "Address:", x.address, "Email:", x.email) The output of the above code is − Name: Ravi Shrivastava Address: Station Road Nanded Email: ravi@gmail.com Even though the change is displayed, it is not committed. You can retain the earlier persistent position by using rollback() method with the code below. session.rollback() print ("Name: ", x.name, "Address:", x.address, "Email:", x.email) Original contents of first record will be displayed. For bulk updates, we shall use update() method of the Query object. Let us try and give a prefix, ‘Mr.’ to name in each row (except ID = 2). The corresponding update() statement is as follows − session.query(Customers).filter(Customers.id! = 2). update({Customers.name:"Mr."+Customers.name}, synchronize_session = False) The update() method requires two parameters as follows − A dictionary of key-values with key being the attribute to be updated, and value being the new contents of attribute. A dictionary of key-values with key being the attribute to be updated, and value being the new contents of attribute. synchronize_session attribute mentioning the strategy to update attributes in the session. Valid values are false: for not synchronizing the session, fetch: performs a select query before the update to find objects that are matched by the update query; and evaluate: evaluate criteria on objects in the session. synchronize_session attribute mentioning the strategy to update attributes in the session. Valid values are false: for not synchronizing the session, fetch: performs a select query before the update to find objects that are matched by the update query; and evaluate: evaluate criteria on objects in the session. Three out of 4 rows in the table will have name prefixed with ‘Mr.’ However, the changes are not committed and hence will not be reflected in the table view of SQLiteStudio. It will be refreshed only when we commit the session. In this chapter, we will discuss how to apply filter and also certain filter operations along with their codes. Resultset represented by Query object can be subjected to certain criteria by using filter() method. The general usage of filter method is as follows − session.query(class).filter(criteria) In the following example, resultset obtained by SELECT query on Customers table is filtered by a condition, (ID>2) − result = session.query(Customers).filter(Customers.id>2) This statement will translate into following SQL expression − SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers WHERE customers.id > ? Since the bound parameter (?) is given as 2, only those rows with ID column>2 will be displayed. The complete code is given below − from sqlalchemy import Column, Integer, String from sqlalchemy import create_engine engine = create_engine('sqlite:///sales.db', echo = True) from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Customers(Base): __tablename__ = 'customers' id = Column(Integer, primary_key = True) name = Column(String) address = Column(String) email = Column(String) from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind = engine) session = Session() result = session.query(Customers).filter(Customers.id>2) for row in result: print ("ID:", row.id, "Name: ",row.name, "Address:",row.address, "Email:",row.email) The output displayed in the Python console is as follows − ID: 3 Name: Rajender Nath Address: Sector 40, Gurgaon Email: nath@gmail.com ID: 4 Name: S.M.Krishna Address: Budhwar Peth, Pune Email: smk@gmail.com Now, we will learn the filter operations with their respective codes and output. The usual operator used is == and it applies the criteria to check equality. result = session.query(Customers).filter(Customers.id == 2) for row in result: print ("ID:", row.id, "Name: ",row.name, "Address:",row.address, "Email:",row.email) SQLAlchemy will send following SQL expression − SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers WHERE customers.id = ? The output for the above code is as follows − ID: 2 Name: Komal Pande Address: Banjara Hills Secunderabad Email: komal@gmail.com The operator used for not equals is != and it provides not equals criteria. result = session.query(Customers).filter(Customers.id! = 2) for row in result: print ("ID:", row.id, "Name: ",row.name, "Address:",row.address, "Email:",row.email) The resulting SQL expression is − SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers WHERE customers.id != ? The output for the above lines of code is as follows − ID: 1 Name: Ravi Kumar Address: Station Road Nanded Email: ravi@gmail.com ID: 3 Name: Rajender Nath Address: Sector 40, Gurgaon Email: nath@gmail.com ID: 4 Name: S.M.Krishna Address: Budhwar Peth, Pune Email: smk@gmail.com like() method itself produces the LIKE criteria for WHERE clause in the SELECT expression. result = session.query(Customers).filter(Customers.name.like('Ra%')) for row in result: print ("ID:", row.id, "Name: ",row.name, "Address:",row.address, "Email:",row.email) Above SQLAlchemy code is equivalent to following SQL expression − SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers WHERE customers.name LIKE ? And the output for the above code is − ID: 1 Name: Ravi Kumar Address: Station Road Nanded Email: ravi@gmail.com ID: 3 Name: Rajender Nath Address: Sector 40, Gurgaon Email: nath@gmail.com This operator checks whether the column value belongs to a collection of items in a list. It is provided by in_() method. result = session.query(Customers).filter(Customers.id.in_([1,3])) for row in result: print ("ID:", row.id, "Name: ",row.name, "Address:",row.address, "Email:",row.email) Here, the SQL expression evaluated by SQLite engine will be as follows − SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers WHERE customers.id IN (?, ?) The output for the above code is as follows − ID: 1 Name: Ravi Kumar Address: Station Road Nanded Email: ravi@gmail.com ID: 3 Name: Rajender Nath Address: Sector 40, Gurgaon Email: nath@gmail.com This conjunction is generated by either putting multiple commas separated criteria in the filter or using and_() method as given below − result = session.query(Customers).filter(Customers.id>2, Customers.name.like('Ra%')) for row in result: print ("ID:", row.id, "Name: ",row.name, "Address:",row.address, "Email:",row.email) from sqlalchemy import and_ result = session.query(Customers).filter(and_(Customers.id>2, Customers.name.like('Ra%'))) for row in result: print ("ID:", row.id, "Name: ",row.name, "Address:",row.address, "Email:",row.email) Both the above approaches result in similar SQL expression − SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers WHERE customers.id > ? AND customers.name LIKE ? The output for the above lines of code is − ID: 3 Name: Rajender Nath Address: Sector 40, Gurgaon Email: nath@gmail.com This conjunction is implemented by or_() method. from sqlalchemy import or_ result = session.query(Customers).filter(or_(Customers.id>2, Customers.name.like('Ra%'))) for row in result: print ("ID:", row.id, "Name: ",row.name, "Address:",row.address, "Email:",row.email) As a result, SQLite engine gets following equivalent SQL expression − SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers WHERE customers.id > ? OR customers.name LIKE ? The output for the above code is as follows − ID: 1 Name: Ravi Kumar Address: Station Road Nanded Email: ravi@gmail.com ID: 3 Name: Rajender Nath Address: Sector 40, Gurgaon Email: nath@gmail.com ID: 4 Name: S.M.Krishna Address: Budhwar Peth, Pune Email: smk@gmail.com There are a number of methods of Query object that immediately issue SQL and return a value containing loaded database results. Here’s a brief rundown of returning list and scalars − It returns a list. Given below is the line of code for all() function. session.query(Customers).all() Python console displays following SQL expression emitted − SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers It applies a limit of one and returns the first result as a scalar. SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers LIMIT ? OFFSET ? The bound parameters for LIMIT is 1 and for OFFSET is 0. This command fully fetches all rows, and if there is not exactly one object identity or composite row present in the result, it raises an error. session.query(Customers).one() With multiple rows found − MultipleResultsFound: Multiple rows were found for one() With no rows found − NoResultFound: No row was found for one() The one() method is useful for systems that expect to handle “no items found” versus “multiple items found” differently. It invokes the one() method, and upon success returns the first column of the row as follows − session.query(Customers).filter(Customers.id == 3).scalar() This generates following SQL statement − SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers WHERE customers.id = ? Earlier, textual SQL using text() function has been explained from the perspective of core expression language of SQLAlchemy. Now we shall discuss it from ORM point of view. Literal strings can be used flexibly with Query object by specifying their use with the text() construct. Most applicable methods accept it. For example, filter() and order_by(). In the example given below, the filter() method translates the string “id<3” to the WHERE id<3 from sqlalchemy import text for cust in session.query(Customers).filter(text("id<3")): print(cust.name) The raw SQL expression generated shows conversion of filter to WHERE clause with the code illustrated below − SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers WHERE id<3 From our sample data in Customers table, two rows will be selected and name column will be printed as follows − Ravi Kumar Komal Pande To specify bind parameters with string-based SQL, use a colon,and to specify the values, use the params() method. cust = session.query(Customers).filter(text("id = :value")).params(value = 1).one() The effective SQL displayed on Python console will be as given below − SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers WHERE id = ? To use an entirely string-based statement, a text() construct representing a complete statement can be passed to from_statement(). session.query(Customers).from_statement(text("SELECT * FROM customers")).all() The result of above code will be a basic SELECT statement as given below − SELECT * FROM customers Obviously, all records in customers table will be selected. The text() construct allows us to link its textual SQL to Core or ORM-mapped column expressions positionally. We can achieve this by passing column expressions as positional arguments to the TextClause.columns() method. stmt = text("SELECT name, id, name, address, email FROM customers") stmt = stmt.columns(Customers.id, Customers.name) session.query(Customers.id, Customers.name).from_statement(stmt).all() The id and name columns of all rows will be selected even though the SQLite engine executes following expression generated by above code shows all columns in text() method − SELECT name, id, name, address, email FROM customers This session describes creation of another table which is related to already existing one in our database. The customers table contains master data of customers. We now need to create invoices table which may have any number of invoices belonging to a customer. This is a case of one to many relationships. Using declarative, we define this table along with its mapped class, Invoices as given below − from sqlalchemy import create_engine, ForeignKey, Column, Integer, String engine = create_engine('sqlite:///sales.db', echo = True) from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() from sqlalchemy.orm import relationship class Customer(Base): __tablename__ = 'customers' id = Column(Integer, primary_key = True) name = Column(String) address = Column(String) email = Column(String) class Invoice(Base): __tablename__ = 'invoices' id = Column(Integer, primary_key = True) custid = Column(Integer, ForeignKey('customers.id')) invno = Column(Integer) amount = Column(Integer) customer = relationship("Customer", back_populates = "invoices") Customer.invoices = relationship("Invoice", order_by = Invoice.id, back_populates = "customer") Base.metadata.create_all(engine) This will send a CREATE TABLE query to SQLite engine as below − CREATE TABLE invoices ( id INTEGER NOT NULL, custid INTEGER, invno INTEGER, amount INTEGER, PRIMARY KEY (id), FOREIGN KEY(custid) REFERENCES customers (id) ) We can check that new table is created in sales.db with the help of SQLiteStudio tool. Invoices class applies ForeignKey construct on custid attribute. This directive indicates that values in this column should be constrained to be values present in id column in customers table. This is a core feature of relational databases, and is the “glue” that transforms unconnected collection of tables to have rich overlapping relationships. A second directive, known as relationship(), tells the ORM that the Invoice class should be linked to the Customer class using the attribute Invoice.customer. The relationship() uses the foreign key relationships between the two tables to determine the nature of this linkage, determining that it is many to one. An additional relationship() directive is placed on the Customer mapped class under the attribute Customer.invoices. The parameter relationship.back_populates is assigned to refer to the complementary attribute names, so that each relationship() can make intelligent decision about the same relationship as expressed in reverse. On one side, Invoices.customer refers to Invoices instance, and on the other side, Customer.invoices refers to a list of Customers instances. The relationship function is a part of Relationship API of SQLAlchemy ORM package. It provides a relationship between two mapped classes. This corresponds to a parent-child or associative table relationship. Following are the basic Relationship Patterns found − A One to Many relationship refers to parent with the help of a foreign key on the child table. relationship() is then specified on the parent, as referencing a collection of items represented by the child. The relationship.back_populates parameter is used to establish a bidirectional relationship in one-to-many, where the “reverse” side is a many to one. On the other hand, Many to One relationship places a foreign key in the parent table to refer to the child. relationship() is declared on the parent, where a new scalar-holding attribute will be created. Here again the relationship.back_populates parameter is used for Bidirectionalbehaviour. One To One relationship is essentially a bidirectional relationship in nature. The uselist flag indicates the placement of a scalar attribute instead of a collection on the “many” side of the relationship. To convert one-to-many into one-to-one type of relation, set uselist parameter to false. Many to Many relationship is established by adding an association table related to two classes by defining attributes with their foreign keys. It is indicated by the secondary argument to relationship(). Usually, the Table uses the MetaData object associated with the declarative base class, so that the ForeignKey directives can locate the remote tables with which to link. The relationship.back_populates parameter for each relationship() establishes a bidirectional relationship. Both sides of the relationship contain a collection. In this chapter, we will focus on the related objects in SQLAlchemy ORM. Now when we create a Customer object, a blank invoice collection will be present in the form of Python List. c1 = Customer(name = "Gopal Krishna", address = "Bank Street Hydarebad", email = "gk@gmail.com") The invoices attribute of c1.invoices will be an empty list. We can assign items in the list as − c1.invoices = [Invoice(invno = 10, amount = 15000), Invoice(invno = 14, amount = 3850)] Let us commit this object to the database using Session object as follows − from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind = engine) session = Session() session.add(c1) session.commit() This will automatically generate INSERT queries for customers and invoices tables − INSERT INTO customers (name, address, email) VALUES (?, ?, ?) ('Gopal Krishna', 'Bank Street Hydarebad', 'gk@gmail.com') INSERT INTO invoices (custid, invno, amount) VALUES (?, ?, ?) (2, 10, 15000) INSERT INTO invoices (custid, invno, amount) VALUES (?, ?, ?) (2, 14, 3850) Let us now look at contents of customers table and invoices table in the table view of SQLiteStudio − You can construct Customer object by providing mapped attribute of invoices in the constructor itself by using the below command − c2 = [ Customer( name = "Govind Pant", address = "Gulmandi Aurangabad", email = "gpant@gmail.com", invoices = [Invoice(invno = 3, amount = 10000), Invoice(invno = 4, amount = 5000)] ) ] Or a list of objects to be added using add_all() function of session object as shown below − rows = [ Customer( name = "Govind Kala", address = "Gulmandi Aurangabad", email = "kala@gmail.com", invoices = [Invoice(invno = 7, amount = 12000), Invoice(invno = 8, amount = 18500)]), Customer( name = "Abdul Rahman", address = "Rohtak", email = "abdulr@gmail.com", invoices = [Invoice(invno = 9, amount = 15000), Invoice(invno = 11, amount = 6000) ]) ] session.add_all(rows) session.commit() Now that we have two tables, we will see how to create queries on both tables at the same time. To construct a simple implicit join between Customer and Invoice, we can use Query.filter() to equate their related columns together. Below, we load the Customer and Invoice entities at once using this method − from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind = engine) session = Session() for c, i in session.query(Customer, Invoice).filter(Customer.id == Invoice.custid).all(): print ("ID: {} Name: {} Invoice No: {} Amount: {}".format(c.id,c.name, i.invno, i.amount)) The SQL expression emitted by SQLAlchemy is as follows − SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email, invoices.id AS invoices_id, invoices.custid AS invoices_custid, invoices.invno AS invoices_invno, invoices.amount AS invoices_amount FROM customers, invoices WHERE customers.id = invoices.custid And the result of the above lines of code is as follows − ID: 2 Name: Gopal Krishna Invoice No: 10 Amount: 15000 ID: 2 Name: Gopal Krishna Invoice No: 14 Amount: 3850 ID: 3 Name: Govind Pant Invoice No: 3 Amount: 10000 ID: 3 Name: Govind Pant Invoice No: 4 Amount: 5000 ID: 4 Name: Govind Kala Invoice No: 7 Amount: 12000 ID: 4 Name: Govind Kala Invoice No: 8 Amount: 8500 ID: 5 Name: Abdul Rahman Invoice No: 9 Amount: 15000 ID: 5 Name: Abdul Rahman Invoice No: 11 Amount: 6000 The actual SQL JOIN syntax is easily achieved using the Query.join() method as follows − session.query(Customer).join(Invoice).filter(Invoice.amount == 8500).all() The SQL expression for join will be displayed on the console − SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers JOIN invoices ON customers.id = invoices.custid WHERE invoices.amount = ? We can iterate through the result using for loop − result = session.query(Customer).join(Invoice).filter(Invoice.amount == 8500) for row in result: for inv in row.invoices: print (row.id, row.name, inv.invno, inv.amount) With 8500 as the bind parameter, following output is displayed − 4 Govind Kala 8 8500 Query.join() knows how to join between these tables because there’s only one foreign key between them. If there were no foreign keys, or more foreign keys, Query.join() works better when one of the following forms are used − Similarly outerjoin() function is available to achieve left outer join. query.outerjoin(Customer.invoices) The subquery() method produces a SQL expression representing SELECT statement embedded within an alias. from sqlalchemy.sql import func stmt = session.query( Invoice.custid, func.count('*').label('invoice_count') ).group_by(Invoice.custid).subquery() The stmt object will contain a SQL statement as below − SELECT invoices.custid, count(:count_1) AS invoice_count FROM invoices GROUP BY invoices.custid Once we have our statement, it behaves like a Table construct. The columns on the statement are accessible through an attribute called c as shown in the below code − for u, count in session.query(Customer, stmt.c.invoice_count).outerjoin(stmt, Customer.id == stmt.c.custid).order_by(Customer.id): print(u.name, count) The above for loop displays name-wise count of invoices as follows − Arjun Pandit None Gopal Krishna 2 Govind Pant 2 Govind Kala 2 Abdul Rahman 2 In this chapter, we will discuss about the operators which build on relationships. The above operator is a many-to-one “equals” comparison. The line of code for this operator is as shown below − s = session.query(Customer).filter(Invoice.invno.__eq__(12)) The equivalent SQL query for the above line of code is − SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers, invoices WHERE invoices.invno = ? This operator is a many-to-one “not equals” comparison. The line of code for this operator is as shown below − s = session.query(Customer).filter(Invoice.custid.__ne__(2)) The equivalent SQL query for the above line of code is given below − SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers, invoices WHERE invoices.custid != ? This operator is used for one-to-many collections and given below is the code for contains() − s = session.query(Invoice).filter(Invoice.invno.contains([3,4,5])) The equivalent SQL query for the above line of code is − SELECT invoices.id AS invoices_id, invoices.custid AS invoices_custid, invoices.invno AS invoices_invno, invoices.amount AS invoices_amount FROM invoices WHERE (invoices.invno LIKE '%' + ? || '%') any() operator is used for collections as shown below − s = session.query(Customer).filter(Customer.invoices.any(Invoice.invno==11)) The equivalent SQL query for the above line of code is shown below − SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers WHERE EXISTS ( SELECT 1 FROM invoices WHERE customers.id = invoices.custid AND invoices.invno = ?) This operator is used for scalar references as follows − s = session.query(Invoice).filter(Invoice.customer.has(name = 'Arjun Pandit')) The equivalent SQL query for the above line of code is − SELECT invoices.id AS invoices_id, invoices.custid AS invoices_custid, invoices.invno AS invoices_invno, invoices.amount AS invoices_amount FROM invoices WHERE EXISTS ( SELECT 1 FROM customers WHERE customers.id = invoices.custid AND customers.name = ?) Eager load reduces the number of queries. SQLAlchemy offers eager loading functions invoked via query options which give additional instructions to the Query. These options determine how to load various attributes via the Query.options() method. We want that Customer.invoices should load eagerly. The orm.subqueryload() option gives a second SELECT statement that fully loads the collections associated with the results just loaded. The name “subquery” causes the SELECT statement to be constructed directly via the Query re-used and embedded as a subquery into a SELECT against the related table. from sqlalchemy.orm import subqueryload c1 = session.query(Customer).options(subqueryload(Customer.invoices)).filter_by(name = 'Govind Pant').one() This results in the following two SQL expressions − SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers WHERE customers.name = ? ('Govind Pant',) SELECT invoices.id AS invoices_id, invoices.custid AS invoices_custid, invoices.invno AS invoices_invno, invoices.amount AS invoices_amount, anon_1.customers_id AS anon_1_customers_id FROM ( SELECT customers.id AS customers_id FROM customers WHERE customers.name = ?) AS anon_1 JOIN invoices ON anon_1.customers_id = invoices.custid ORDER BY anon_1.customers_id, invoices.id 2018-06-25 18:24:47,479 INFO sqlalchemy.engine.base.Engine ('Govind Pant',) To access the data from two tables, we can use the below program − print (c1.name, c1.address, c1.email) for x in c1.invoices: print ("Invoice no : {}, Amount : {}".format(x.invno, x.amount)) The output of the above program is as follows − Govind Pant Gulmandi Aurangabad gpant@gmail.com Invoice no : 3, Amount : 10000 Invoice no : 4, Amount : 5000 The other function is called orm.joinedload(). This emits a LEFT OUTER JOIN. Lead object as well as the related object or collection is loaded in one step. from sqlalchemy.orm import joinedload c1 = session.query(Customer).options(joinedload(Customer.invoices)).filter_by(name='Govind Pant').one() This emits following expression giving same output as above − SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email, invoices_1.id AS invoices_1_id, invoices_1.custid AS invoices_1_custid, invoices_1.invno AS invoices_1_invno, invoices_1.amount AS invoices_1_amount FROM customers LEFT OUTER JOIN invoices AS invoices_1 ON customers.id = invoices_1.custid WHERE customers.name = ? ORDER BY invoices_1.id ('Govind Pant',) The OUTER JOIN resulted in two rows, but it gives one instance of Customer back. This is because Query applies a “uniquing” strategy, based on object identity, to the returned entities. Joined eager loading can be applied without affecting the query results. The subqueryload() is more appropriate for loading related collections while joinedload() is better suited for many-to-one relationship. It is easy to perform delete operation on a single table. All you have to do is to delete an object of the mapped class from a session and commit the action. However, delete operation on multiple related tables is little tricky. In our sales.db database, Customer and Invoice classes are mapped to customer and invoice table with one to many type of relationship. We will try to delete Customer object and see the result. As a quick reference, below are the definitions of Customer and Invoice classes − from sqlalchemy import create_engine, ForeignKey, Column, Integer, String engine = create_engine('sqlite:///sales.db', echo = True) from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() from sqlalchemy.orm import relationship class Customer(Base): __tablename__ = 'customers' id = Column(Integer, primary_key = True) name = Column(String) address = Column(String) email = Column(String) class Invoice(Base): __tablename__ = 'invoices' id = Column(Integer, primary_key = True) custid = Column(Integer, ForeignKey('customers.id')) invno = Column(Integer) amount = Column(Integer) customer = relationship("Customer", back_populates = "invoices") Customer.invoices = relationship("Invoice", order_by = Invoice.id, back_populates = "customer") We setup a session and obtain a Customer object by querying it with primary ID using the below program − from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind=engine) session = Session() x = session.query(Customer).get(2) In our sample table, x.name happens to be 'Gopal Krishna'. Let us delete this x from the session and count the occurrence of this name. session.delete(x) session.query(Customer).filter_by(name = 'Gopal Krishna').count() The resulting SQL expression will return 0. SELECT count(*) AS count_1 FROM ( SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers WHERE customers.name = ?) AS anon_1('Gopal Krishna',) 0 However, the related Invoice objects of x are still there. It can be verified by the following code − session.query(Invoice).filter(Invoice.invno.in_([10,14])).count() Here, 10 and 14 are invoice numbers belonging to customer Gopal Krishna. Result of the above query is 2, which means the related objects have not been deleted. SELECT count(*) AS count_1 FROM ( SELECT invoices.id AS invoices_id, invoices.custid AS invoices_custid, invoices.invno AS invoices_invno, invoices.amount AS invoices_amount FROM invoices WHERE invoices.invno IN (?, ?)) AS anon_1(10, 14) 2 This is because SQLAlchemy doesn’t assume the deletion of cascade; we have to give a command to delete it. To change the behavior, we configure cascade options on the User.addresses relationship. Let us close the ongoing session, use new declarative_base() and redeclare the User class, adding in the addresses relationship including the cascade configuration. The cascade attribute in relationship function is a comma-separated list of cascade rules which determines how Session operations should be “cascaded” from parent to child. By default, it is False, which means that it is "save-update, merge". The available cascades are as follows − save-update merge expunge delete delete-orphan refresh-expire Often used option is "all, delete-orphan" to indicate that related objects should follow along with the parent object in all cases, and be deleted when de-associated. Hence redeclared Customer class is shown below − class Customer(Base): __tablename__ = 'customers' id = Column(Integer, primary_key = True) name = Column(String) address = Column(String) email = Column(String) invoices = relationship( "Invoice", order_by = Invoice.id, back_populates = "customer", cascade = "all, delete, delete-orphan" ) Let us delete the Customer with Gopal Krishna name using the below program and see the count of its related Invoice objects − from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind = engine) session = Session() x = session.query(Customer).get(2) session.delete(x) session.query(Customer).filter_by(name = 'Gopal Krishna').count() session.query(Invoice).filter(Invoice.invno.in_([10,14])).count() The count is now 0 with following SQL emitted by above script − SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers WHERE customers.id = ? (2,) SELECT invoices.id AS invoices_id, invoices.custid AS invoices_custid, invoices.invno AS invoices_invno, invoices.amount AS invoices_amount FROM invoices WHERE ? = invoices.custid ORDER BY invoices.id (2,) DELETE FROM invoices WHERE invoices.id = ? ((1,), (2,)) DELETE FROM customers WHERE customers.id = ? (2,) SELECT count(*) AS count_1 FROM ( SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers WHERE customers.name = ?) AS anon_1('Gopal Krishna',) SELECT count(*) AS count_1 FROM ( SELECT invoices.id AS invoices_id, invoices.custid AS invoices_custid, invoices.invno AS invoices_invno, invoices.amount AS invoices_amount FROM invoices WHERE invoices.invno IN (?, ?)) AS anon_1(10, 14) 0 Many to Many relationship between two tables is achieved by adding an association table such that it has two foreign keys - one from each table’s primary key. Moreover, classes mapping to the two tables have an attribute with a collection of objects of other association tables assigned as secondary attribute of relationship() function. For this purpose, we shall create a SQLite database (mycollege.db) with two tables - department and employee. Here, we assume that an employee is a part of more than one department, and a department has more than one employee. This constitutes many-to-many relationship. Definition of Employee and Department classes mapped to department and employee table is as follows − from sqlalchemy import create_engine, ForeignKey, Column, Integer, String engine = create_engine('sqlite:///mycollege.db', echo = True) from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() from sqlalchemy.orm import relationship class Department(Base): __tablename__ = 'department' id = Column(Integer, primary_key = True) name = Column(String) employees = relationship('Employee', secondary = 'link') class Employee(Base): __tablename__ = 'employee' id = Column(Integer, primary_key = True) name = Column(String) departments = relationship(Department,secondary='link') We now define a Link class. It is linked to link table and contains department_id and employee_id attributes respectively referencing to primary keys of department and employee table. class Link(Base): __tablename__ = 'link' department_id = Column( Integer, ForeignKey('department.id'), primary_key = True) employee_id = Column( Integer, ForeignKey('employee.id'), primary_key = True) Here, we have to make a note that Department class has employees attribute related to Employee class. The relationship function’s secondary attribute is assigned a link as its value. Similarly, Employee class has departments attribute related to Department class. The relationship function’s secondary attribute is assigned a link as its value. All these three tables are created when the following statement is executed − Base.metadata.create_all(engine) The Python console emits following CREATE TABLE queries − CREATE TABLE department ( id INTEGER NOT NULL, name VARCHAR, PRIMARY KEY (id) ) CREATE TABLE employee ( id INTEGER NOT NULL, name VARCHAR, PRIMARY KEY (id) ) CREATE TABLE link ( department_id INTEGER NOT NULL, employee_id INTEGER NOT NULL, PRIMARY KEY (department_id, employee_id), FOREIGN KEY(department_id) REFERENCES department (id), FOREIGN KEY(employee_id) REFERENCES employee (id) ) We can check this by opening mycollege.db using SQLiteStudio as shown in the screenshots given below − Next we create three objects of Department class and three objects of Employee class as shown below − d1 = Department(name = "Accounts") d2 = Department(name = "Sales") d3 = Department(name = "Marketing") e1 = Employee(name = "John") e2 = Employee(name = "Tony") e3 = Employee(name = "Graham") Each table has a collection attribute having append() method. We can add Employee objects to Employees collection of Department object. Similarly, we can add Department objects to departments collection attribute of Employee objects. e1.departments.append(d1) e2.departments.append(d3) d1.employees.append(e3) d2.employees.append(e2) d3.employees.append(e1) e3.departments.append(d2) All we have to do now is to set up a session object, add all objects to it and commit the changes as shown below − from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind = engine) session = Session() session.add(e1) session.add(e2) session.add(d1) session.add(d2) session.add(d3) session.add(e3) session.commit() Following SQL statements will be emitted on Python console − INSERT INTO department (name) VALUES (?) ('Accounts',) INSERT INTO department (name) VALUES (?) ('Sales',) INSERT INTO department (name) VALUES (?) ('Marketing',) INSERT INTO employee (name) VALUES (?) ('John',) INSERT INTO employee (name) VALUES (?) ('Graham',) INSERT INTO employee (name) VALUES (?) ('Tony',) INSERT INTO link (department_id, employee_id) VALUES (?, ?) ((1, 2), (3, 1), (2, 3)) INSERT INTO link (department_id, employee_id) VALUES (?, ?) ((1, 1), (2, 2), (3, 3)) To check the effect of above operations, use SQLiteStudio and view data in department, employee and link tables − To display the data, run the following query statement − from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind = engine) session = Session() for x in session.query( Department, Employee).filter(Link.department_id == Department.id, Link.employee_id == Employee.id).order_by(Link.department_id).all(): print ("Department: {} Name: {}".format(x.Department.name, x.Employee.name)) As per the data populated in our example, output will be displayed as below − Department: Accounts Name: John Department: Accounts Name: Graham Department: Sales Name: Graham Department: Sales Name: Tony Department: Marketing Name: John Department: Marketing Name: Tony SQLAlchemy uses system of dialects to communicate with various types of databases. Each database has a corresponding DBAPI wrapper. All dialects require that an appropriate DBAPI driver is installed. Following dialects are included in SQLAlchemy API − Firebird Microsoft SQL Server MySQL Oracle PostgreSQL SQL Sybase An Engine object based on a URL is produced by create_engine() function. These URLs can include username, password, hostname, and database name. There may be optional keyword arguments for additional configuration. In some cases, a file path is accepted, and in others, a “data source name” replaces the “host” and “database” portions. The typical form of a database URL is as follows − dialect+driver://username:password@host:port/database The PostgreSQL dialect uses psycopg2 as the default DBAPI. pg8000 is also available as a pure-Python substitute as shown below: # default engine = create_engine('postgresql://scott:tiger@localhost/mydatabase') # psycopg2 engine = create_engine('postgresql+psycopg2://scott:tiger@localhost/mydatabase') # pg8000 engine = create_engine('postgresql+pg8000://scott:tiger@localhost/mydatabase') The MySQL dialect uses mysql-python as the default DBAPI. There are many MySQL DBAPIs available, such as MySQL-connector-python as follows − # default engine = create_engine('mysql://scott:tiger@localhost/foo') # mysql-python engine = create_engine('mysql+mysqldb://scott:tiger@localhost/foo') # MySQL-connector-python engine = create_engine('mysql+mysqlconnector://scott:tiger@localhost/foo') The Oracle dialect uses cx_oracle as the default DBAPI as follows − engine = create_engine('oracle://scott:tiger@127.0.0.1:1521/sidname') engine = create_engine('oracle+cx_oracle://scott:tiger@tnsname') The SQL Server dialect uses pyodbc as the default DBAPI. pymssql is also available. # pyodbc engine = create_engine('mssql+pyodbc://scott:tiger@mydsn') # pymssql engine = create_engine('mssql+pymssql://scott:tiger@hostname:port/dbname') SQLite connects to file-based databases, using the Python built-in module sqlite3 by default. As SQLite connects to local files, the URL format is slightly different. The “file” portion of the URL is the filename of the database. For a relative file path, this requires three slashes as shown below − engine = create_engine('sqlite:///foo.db') And for an absolute file path, the three slashes are followed by the absolute path as given below − engine = create_engine('sqlite:///C:\\path\\to\\foo.db') To use a SQLite:memory:database, specify an empty URL as given below − engine = create_engine('sqlite://') In the first part of this tutorial, we have learnt how to use the Expression Language to execute SQL statements. Expression language embeds SQL constructs in Python code. In the second part, we have discussed object relation mapping capability of SQLAlchemy. The ORM API maps the SQL tables with Python classes. 21 Lectures 1.5 hours Jack Chan Print Add Notes Bookmark this page
[ { "code": null, "e": 2580, "s": 2340, "text": "SQLAlchemy is a popular SQL toolkit and Object Relational Mapper. It is written in Python and gives full power and flexibility of SQL to an application developer. It is an open source and cross-platform software released under MIT license." }, { "code": null, "e": 2805, "s": 2580, "text": "SQLAlchemy is famous for its object-relational mapper (ORM), using which, classes can be mapped to the database, thereby allowing the object model and database schema to develop in a cleanly decoupled way from the beginning." }, { "code": null, "e": 3075, "s": 2805, "text": "As size and performance of SQL databases start to matter, they behave less like object collections. On the other hand, as abstraction in object collections starts to matter, they behave less like tables and rows. SQLAlchemy aims to accommodate both of these principles." }, { "code": null, "e": 3296, "s": 3075, "text": "For this reason, it has adopted the data mapper pattern (like Hibernate) rather than the active record pattern used by a number of other ORMs. Databases and SQL will be viewed in a different perspective using SQLAlchemy." }, { "code": null, "e": 3475, "s": 3296, "text": "Michael Bayer is the original author of SQLAlchemy. Its initial version was released in February 2006. Latest version is numbered as 1.2.7, released as recently as in April 2018." }, { "code": null, "e": 4003, "s": 3475, "text": "ORM (Object Relational Mapping) is a programming technique for converting data between incompatible type systems in object-oriented programming languages. Usually, the type system used in an Object Oriented (OO) language like Python contains non-scalar types. These cannot be expressed as primitive types such as integers and strings. Hence, the OO programmer has to convert objects in scalar data to interact with backend database. However, data types in most of the database products such as Oracle, MySQL, etc., are primary." }, { "code": null, "e": 4242, "s": 4003, "text": "In an ORM system, each class maps to a table in the underlying database. Instead of writing tedious database interfacing code yourself, an ORM takes care of these issues for you while you can focus on programming the logics of the system." }, { "code": null, "e": 4309, "s": 4242, "text": "Let us discuss the environmental setup required to use SQLAlchemy." }, { "code": null, "e": 4513, "s": 4309, "text": "Any version of Python higher than 2.7 is necessary to install SQLAlchemy. The easiest way to install is by using Python Package Manager, pip. This utility is bundled with standard distribution of Python." }, { "code": null, "e": 4537, "s": 4513, "text": "pip install sqlalchemy\n" }, { "code": null, "e": 4667, "s": 4537, "text": "Using the above command, we can download the latest released version of SQLAlchemy from python.org and install it to your system." }, { "code": null, "e": 4785, "s": 4667, "text": "In case of anaconda distribution of Python, SQLAlchemy can be installed from conda terminal using the below command −" }, { "code": null, "e": 4823, "s": 4785, "text": "conda install -c anaconda sqlalchemy\n" }, { "code": null, "e": 4890, "s": 4823, "text": "It is also possible to install SQLAlchemy from below source code −" }, { "code": null, "e": 4915, "s": 4890, "text": "python setup.py install\n" }, { "code": null, "e": 5175, "s": 4915, "text": "SQLAlchemy is designed to operate with a DBAPI implementation built for a particular database. It uses dialect system to communicate with various types of DBAPI implementations and databases. All dialects require that an appropriate DBAPI driver is installed." }, { "code": null, "e": 5217, "s": 5175, "text": "The following are the dialects included −" }, { "code": null, "e": 5226, "s": 5217, "text": "Firebird" }, { "code": null, "e": 5247, "s": 5226, "text": "Microsoft SQL Server" }, { "code": null, "e": 5253, "s": 5247, "text": "MySQL" }, { "code": null, "e": 5260, "s": 5253, "text": "Oracle" }, { "code": null, "e": 5271, "s": 5260, "text": "PostgreSQL" }, { "code": null, "e": 5278, "s": 5271, "text": "SQLite" }, { "code": null, "e": 5285, "s": 5278, "text": "Sybase" }, { "code": null, "e": 5406, "s": 5285, "text": "To check if SQLAlchemy is properly installed and to know its version, enter the following command in the Python prompt −" }, { "code": null, "e": 5463, "s": 5406, "text": ">>> import sqlalchemy\n>>>sqlalchemy.__version__\n'1.2.7'\n" }, { "code": null, "e": 5736, "s": 5463, "text": "SQLAlchemy core includes SQL rendering engine, DBAPI integration, transaction integration, and schema description services. SQLAlchemy core uses SQL Expression Language that provides a schema-centric usage paradigm whereas SQLAlchemy ORM is a domain-centric mode of usage." }, { "code": null, "e": 6145, "s": 5736, "text": "The SQL Expression Language presents a system of representing relational database structures and expressions using Python constructs. It presents a system of representing the primitive constructs of the relational database directly without opinion, which is in contrast to ORM that presents a high level and abstracted pattern of usage, which itself is an example of applied usage of the Expression Language." }, { "code": null, "e": 6483, "s": 6145, "text": "Expression Language is one of the core components of SQLAlchemy. It allows the programmer to specify SQL statements in Python code and use it directly in more complex queries. Expression language is independent of backend and comprehensively covers every aspect of raw SQL. It is closer to raw SQL than any other component in SQLAlchemy." }, { "code": null, "e": 6863, "s": 6483, "text": "Expression Language represents the primitive constructs of the relational database directly. Because the ORM is based on top of Expression language, a typical Python database application may have overlapped use of both. The application may use expression language alone, though it has to define its own system of translating application concepts into individual database queries." }, { "code": null, "e": 7064, "s": 6863, "text": "Statements of Expression language will be translated into corresponding raw SQL queries by SQLAlchemy engine. We shall now learn how to create the engine and execute various SQL queries with its help." }, { "code": null, "e": 7223, "s": 7064, "text": "In the previous chapter, we have discussed about expression Language in SQLAlchemy. Now let us proceed towards the steps involved in connecting to a database." }, { "code": null, "e": 7410, "s": 7223, "text": "Engine class connects a Pool and Dialect together to provide a source of database connectivity and behavior. An object of Engine class is instantiated using the create_engine() function." }, { "code": null, "e": 7735, "s": 7410, "text": "The create_engine() function takes the database as one argument. The database is not needed to be defined anywhere. The standard calling form has to send the URL as the first positional argument, usually a string that indicates database dialect and connection arguments. Using the code given below, we can create a database." }, { "code": null, "e": 7840, "s": 7735, "text": ">>> from sqlalchemy import create_engine\n>>> engine = create_engine('sqlite:///college.db', echo = True)" }, { "code": null, "e": 7886, "s": 7840, "text": "For a MySQL database, use the below command −" }, { "code": null, "e": 7959, "s": 7886, "text": "engine = create_engine(\"mysql://user:pwd@localhost/college\",echo = True)" }, { "code": null, "e": 8060, "s": 7959, "text": "To specifically mention DB-API to be used for connection, the URL string takes the form as follows −" }, { "code": null, "e": 8105, "s": 8060, "text": "dialect[+driver]://user:password@host/dbname" }, { "code": null, "e": 8190, "s": 8105, "text": "For example, if you are using PyMySQL driver with MySQL, use the following command −" }, { "code": null, "e": 8244, "s": 8190, "text": "mysql+pymysql://<username>:<password>@<host>/<dbname>" }, { "code": null, "e": 8553, "s": 8244, "text": "The echo flag is a shortcut to set up SQLAlchemy logging, which is accomplished via Python’s standard logging module. In the subsequent chapters, we will learn all the generated SQLs. To hide the verbose output, set echo attribute to None. Other arguments to create_engine() function may be dialect specific." }, { "code": null, "e": 8653, "s": 8553, "text": "The create_engine() function returns an Engine object. Some important methods of Engine class are −" }, { "code": null, "e": 8663, "s": 8653, "text": "connect()" }, { "code": null, "e": 8689, "s": 8663, "text": "Returns connection object" }, { "code": null, "e": 8699, "s": 8689, "text": "execute()" }, { "code": null, "e": 8734, "s": 8699, "text": "Executes a SQL statement construct" }, { "code": null, "e": 8742, "s": 8734, "text": "begin()" }, { "code": null, "e": 8904, "s": 8742, "text": "Returns a context manager delivering a Connection with a Transaction established. Upon successful operation, the Transaction is committed, else it is rolled back" }, { "code": null, "e": 8914, "s": 8904, "text": "dispose()" }, { "code": null, "e": 8965, "s": 8914, "text": "Disposes of the connection pool used by the Engine" }, { "code": null, "e": 8974, "s": 8965, "text": "driver()" }, { "code": null, "e": 9022, "s": 8974, "text": "Driver name of the Dialect in use by the Engine" }, { "code": null, "e": 9036, "s": 9022, "text": "table_names()" }, { "code": null, "e": 9096, "s": 9036, "text": "Returns a list of all table names available in the database" }, { "code": null, "e": 9110, "s": 9096, "text": "transaction()" }, { "code": null, "e": 9168, "s": 9110, "text": "Executes the given function within a transaction boundary" }, { "code": null, "e": 9225, "s": 9168, "text": "Let us now discuss how to use the create table function." }, { "code": null, "e": 9514, "s": 9225, "text": "The SQL Expression Language constructs its expressions against table columns. SQLAlchemy Column object represents a column in a database table which is in turn represented by a Tableobject. Metadata contains definitions of tables and associated objects such as index, view, triggers, etc." }, { "code": null, "e": 9744, "s": 9514, "text": "Hence an object of MetaData class from SQLAlchemy Metadata is a collection of Table objects and their associated schema constructs. It holds a collection of Table objects as well as an optional binding to an Engine or Connection." }, { "code": null, "e": 9794, "s": 9744, "text": "from sqlalchemy import MetaData\nmeta = MetaData()" }, { "code": null, "e": 9887, "s": 9794, "text": "Constructor of MetaData class can have bind and schema parameters which are by default None." }, { "code": null, "e": 10028, "s": 9887, "text": "Next, we define our tables all within above metadata catalog, using the Table construct, which resembles regular SQL CREATE TABLE statement." }, { "code": null, "e": 10148, "s": 10028, "text": "An object of Table class represents corresponding table in a database. The constructor takes the following parameters −" }, { "code": null, "e": 10311, "s": 10148, "text": "Column object represents a column in a database table. Constructor takes name, type and other parameters such as primary_key, autoincrement and other constraints." }, { "code": null, "e": 10441, "s": 10311, "text": "SQLAlchemy matches Python data to the best possible generic column data types defined in it. Some of the generic data types are −" }, { "code": null, "e": 10452, "s": 10441, "text": "BigInteger" }, { "code": null, "e": 10460, "s": 10452, "text": "Boolean" }, { "code": null, "e": 10465, "s": 10460, "text": "Date" }, { "code": null, "e": 10474, "s": 10465, "text": "DateTime" }, { "code": null, "e": 10480, "s": 10474, "text": "Float" }, { "code": null, "e": 10488, "s": 10480, "text": "Integer" }, { "code": null, "e": 10496, "s": 10488, "text": "Numeric" }, { "code": null, "e": 10509, "s": 10496, "text": "SmallInteger" }, { "code": null, "e": 10516, "s": 10509, "text": "String" }, { "code": null, "e": 10521, "s": 10516, "text": "Text" }, { "code": null, "e": 10526, "s": 10521, "text": "Time" }, { "code": null, "e": 10602, "s": 10526, "text": "To create a students table in college database, use the following snippet −" }, { "code": null, "e": 10834, "s": 10602, "text": "from sqlalchemy import Table, Column, Integer, String, MetaData\nmeta = MetaData()\n\nstudents = Table(\n 'students', meta, \n Column('id', Integer, primary_key = True), \n Column('name', String), \n Column('lastname', String), \n)" }, { "code": null, "e": 10963, "s": 10834, "text": "The create_all() function uses the engine object to create all the defined table objects and stores the information in metadata." }, { "code": null, "e": 10988, "s": 10963, "text": "meta.create_all(engine)\n" }, { "code": null, "e": 11093, "s": 10988, "text": "Complete code is given below which will create a SQLite database college.db with a students table in it." }, { "code": null, "e": 11423, "s": 11093, "text": "from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String\nengine = create_engine('sqlite:///college.db', echo = True)\nmeta = MetaData()\n\nstudents = Table(\n 'students', meta, \n Column('id', Integer, primary_key = True), \n Column('name', String), \n Column('lastname', String),\n)\nmeta.create_all(engine)" }, { "code": null, "e": 11568, "s": 11423, "text": "Because echo attribute of create_engine() function is set to True, the console will display the actual SQL query for table creation as follows −" }, { "code": null, "e": 11676, "s": 11568, "text": "CREATE TABLE students (\n id INTEGER NOT NULL,\n name VARCHAR,\n lastname VARCHAR,\n PRIMARY KEY (id)\n)" }, { "code": null, "e": 11854, "s": 11676, "text": "The college.db will be created in current working directory. To check if the students table is created, you can open the database using any SQLite GUI tool such as SQLiteStudio." }, { "code": null, "e": 11929, "s": 11854, "text": "The below image shows the students table that is created in the database −" }, { "code": null, "e": 12012, "s": 11929, "text": "In this chapter, we will briefly focus on the SQL Expressions and their functions." }, { "code": null, "e": 12192, "s": 12012, "text": "SQL expressions are constructed using corresponding methods relative to target table object. For example, the INSERT statement is created by executing insert() method as follows −" }, { "code": null, "e": 12216, "s": 12192, "text": "ins = students.insert()" }, { "code": null, "e": 12373, "s": 12216, "text": "The result of above method is an insert object that can be verified by using str() function. The below code inserts details like student id, name, lastname." }, { "code": null, "e": 12448, "s": 12373, "text": "'INSERT INTO students (id, name, lastname) VALUES (:id, :name, :lastname)'" }, { "code": null, "e": 12575, "s": 12448, "text": "It is possible to insert value in a specific field by values() method to insert object. The code for the same is given below −" }, { "code": null, "e": 12678, "s": 12575, "text": ">>> ins = users.insert().values(name = 'Karan')\n>>> str(ins)\n'INSERT INTO users (name) VALUES (:name)'" }, { "code": null, "e": 12864, "s": 12678, "text": "The SQL echoed on Python console doesn’t show the actual value (‘Karan’ in this case). Instead, SQLALchemy generates a bind parameter which is visible in compiled form of the statement." }, { "code": null, "e": 12903, "s": 12864, "text": "ins.compile().params\n{'name': 'Karan'}" }, { "code": null, "e": 13063, "s": 12903, "text": "Similarly, methods like update(), delete() and select() create UPDATE, DELETE and SELECT expressions respectively. We shall learn about them in later chapters." }, { "code": null, "e": 13192, "s": 13063, "text": "In the previous chapter, we have learnt SQL Expressions. In this chapter, we shall look into the execution of these expressions." }, { "code": null, "e": 13408, "s": 13192, "text": "In order to execute the resulting SQL expressions, we have to obtain a connection object representing an actively checked out DBAPI connection resource and then feed the expression object as shown in the code below." }, { "code": null, "e": 13432, "s": 13408, "text": "conn = engine.connect()" }, { "code": null, "e": 13497, "s": 13432, "text": "The following insert() object can be used for execute() method −" }, { "code": null, "e": 13591, "s": 13497, "text": "ins = students.insert().values(name = 'Ravi', lastname = 'Kapoor')\nresult = conn.execute(ins)" }, { "code": null, "e": 13662, "s": 13591, "text": "The console shows the result of execution of SQL expression as below −" }, { "code": null, "e": 13740, "s": 13662, "text": "INSERT INTO students (name, lastname) VALUES (?, ?)\n('Ravi', 'Kapoor')\nCOMMIT" }, { "code": null, "e": 13849, "s": 13740, "text": "Following is the entire snippet that shows the execution of INSERT query using SQLAlchemy’s core technique −" }, { "code": null, "e": 14299, "s": 13849, "text": "from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String\nengine = create_engine('sqlite:///college.db', echo = True)\nmeta = MetaData()\n\nstudents = Table(\n 'students', meta, \n Column('id', Integer, primary_key = True), \n Column('name', String), \n Column('lastname', String), \n)\n\nins = students.insert()\nins = students.insert().values(name = 'Ravi', lastname = 'Kapoor')\nconn = engine.connect()\nresult = conn.execute(ins)" }, { "code": null, "e": 14405, "s": 14299, "text": "The result can be verified by opening the database using SQLite Studio as shown in the below screenshot −" }, { "code": null, "e": 14655, "s": 14405, "text": "The result variable is known as a ResultProxy object. It is analogous to the DBAPI cursor object. We can acquire information about the primary key values which were generated from our statement using ResultProxy.inserted_primary_key as shown below −" }, { "code": null, "e": 14687, "s": 14655, "text": "result.inserted_primary_key\n[1]" }, { "code": null, "e": 14845, "s": 14687, "text": "To issue many inserts using DBAPI’s execute many() method, we can send in a list of dictionaries each containing a distinct set of parameters to be inserted." }, { "code": null, "e": 15059, "s": 14845, "text": "conn.execute(students.insert(), [\n {'name':'Rajiv', 'lastname' : 'Khanna'},\n {'name':'Komal','lastname' : 'Bhandari'},\n {'name':'Abdul','lastname' : 'Sattar'},\n {'name':'Priya','lastname' : 'Rajhans'},\n])\n" }, { "code": null, "e": 15142, "s": 15059, "text": "This is reflected in the data view of the table as shown in the following figure −" }, { "code": null, "e": 15232, "s": 15142, "text": "In this chapter, we will discuss about the concept of selecting rows in the table object." }, { "code": null, "e": 15311, "s": 15232, "text": "The select() method of table object enables us to construct SELECT expression." }, { "code": null, "e": 15333, "s": 15311, "text": "s = students.select()" }, { "code": null, "e": 15414, "s": 15333, "text": "The select object translates to SELECT query by str(s) function as shown below −" }, { "code": null, "e": 15483, "s": 15414, "text": "'SELECT students.id, students.name, students.lastname FROM students'" }, { "code": null, "e": 15598, "s": 15483, "text": "We can use this select object as a parameter to execute() method of connection object as shown in the code below −" }, { "code": null, "e": 15623, "s": 15598, "text": "result = conn.execute(s)" }, { "code": null, "e": 15719, "s": 15623, "text": "When the above statement is executed, Python shell echoes following equivalent SQL expression −" }, { "code": null, "e": 15786, "s": 15719, "text": "SELECT students.id, students.name, students.lastname\nFROM students" }, { "code": null, "e": 15896, "s": 15786, "text": "The resultant variable is an equivalent of cursor in DBAPI. We can now fetch records using fetchone() method." }, { "code": null, "e": 15920, "s": 15896, "text": "row = result.fetchone()" }, { "code": null, "e": 15997, "s": 15920, "text": "All selected rows in the table can be printed by a for loop as given below −" }, { "code": null, "e": 16031, "s": 15997, "text": "for row in result:\n print (row)" }, { "code": null, "e": 16104, "s": 16031, "text": "The complete code to print all rows from students table is shown below −" }, { "code": null, "e": 16518, "s": 16104, "text": "from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String\nengine = create_engine('sqlite:///college.db', echo = True)\nmeta = MetaData()\n\nstudents = Table(\n 'students', meta, \n Column('id', Integer, primary_key = True), \n Column('name', String), \n Column('lastname', String), \n)\n\ns = students.select()\nconn = engine.connect()\nresult = conn.execute(s)\n\nfor row in result:\n print (row)" }, { "code": null, "e": 16567, "s": 16518, "text": "The output shown in Python shell is as follows −" }, { "code": null, "e": 16685, "s": 16567, "text": "(1, 'Ravi', 'Kapoor')\n(2, 'Rajiv', 'Khanna')\n(3, 'Komal', 'Bhandari')\n(4, 'Abdul', 'Sattar')\n(5, 'Priya', 'Rajhans')\n" }, { "code": null, "e": 16809, "s": 16685, "text": "The WHERE clause of SELECT query can be applied by using Select.where(). For example, if we want to display rows with id >2" }, { "code": null, "e": 16914, "s": 16809, "text": "s = students.select().where(students.c.id>2)\nresult = conn.execute(s)\n\nfor row in result:\n print (row)" }, { "code": null, "e": 17005, "s": 16914, "text": "Here c attribute is an alias for column. Following output will be displayed on the shell −" }, { "code": null, "e": 17078, "s": 17005, "text": "(3, 'Komal', 'Bhandari')\n(4, 'Abdul', 'Sattar')\n(5, 'Priya', 'Rajhans')\n" }, { "code": null, "e": 17248, "s": 17078, "text": "Here, we have to note that select object can also be obtained by select() function in sqlalchemy.sql module. The select() function requires the table object as argument." }, { "code": null, "e": 17327, "s": 17248, "text": "from sqlalchemy.sql import select\ns = select([users])\nresult = conn.execute(s)" }, { "code": null, "e": 17597, "s": 17327, "text": "SQLAlchemy lets you just use strings, for those cases when the SQL is already known and there isn’t a strong need for the statement to support dynamic features. The text() construct is used to compose a textual statement that is passed to the database mostly unchanged." }, { "code": null, "e": 17701, "s": 17597, "text": "It constructs a new TextClause, representing a textual SQL string directly as shown in the below code −" }, { "code": null, "e": 17795, "s": 17701, "text": "from sqlalchemy import text\nt = text(\"SELECT * FROM students\")\nresult = connection.execute(t)" }, { "code": null, "e": 17852, "s": 17795, "text": "The advantages text() provides over a plain string are −" }, { "code": null, "e": 17896, "s": 17852, "text": "backend-neutral support for bind parameters" }, { "code": null, "e": 17928, "s": 17896, "text": "per-statement execution options" }, { "code": null, "e": 17959, "s": 17928, "text": "result-column typing behaviour" }, { "code": null, "e": 18185, "s": 17959, "text": "The text()function requires Bound parameters in the named colon format. They are consistent regardless of database backend. To send values in for the parameters, we pass them into the execute() method as additional arguments." }, { "code": null, "e": 18246, "s": 18185, "text": "The following example uses bound parameters in textual SQL −" }, { "code": null, "e": 18427, "s": 18246, "text": "from sqlalchemy.sql import text\ns = text(\"select students.name, students.lastname from students where students.name between :x and :y\")\nconn.execute(s, x = 'A', y = 'L').fetchall()" }, { "code": null, "e": 18486, "s": 18427, "text": "The text() function constructs SQL expression as follows −" }, { "code": null, "e": 18576, "s": 18486, "text": "select students.name, students.lastname from students where students.name between ? and ?" }, { "code": null, "e": 18694, "s": 18576, "text": "The values of x = ’A’ and y = ’L’ are passed as parameters. Result is a list of rows with names between ‘A’ and ‘L’ −" }, { "code": null, "e": 18739, "s": 18694, "text": "[('Komal', 'Bhandari'), ('Abdul', 'Sattar')]" }, { "code": null, "e": 18897, "s": 18739, "text": "The text() construct supports pre-established bound values using the TextClause.bindparams() method. The parameters can also be explicitly typed as follows −" }, { "code": null, "e": 19647, "s": 18897, "text": "stmt = text(\"SELECT * FROM students WHERE students.name BETWEEN :x AND :y\")\n\nstmt = stmt.bindparams(\n bindparam(\"x\", type_= String), \n bindparam(\"y\", type_= String)\n)\n\nresult = conn.execute(stmt, {\"x\": \"A\", \"y\": \"L\"})\n\nThe text() function also be produces fragments of SQL within a select() object that \naccepts text() objects as an arguments. The “geometry” of the statement is provided by \nselect() construct , and the textual content by text() construct. We can build a statement \nwithout the need to refer to any pre-established Table metadata. \n\nfrom sqlalchemy.sql import select\ns = select([text(\"students.name, students.lastname from students\")]).where(text(\"students.name between :x and :y\"))\nconn.execute(s, x = 'A', y = 'L').fetchall()" }, { "code": null, "e": 19769, "s": 19647, "text": "You can also use and_() function to combine multiple conditions in WHERE clause created with the help of text() function." }, { "code": null, "e": 20015, "s": 19769, "text": "from sqlalchemy import and_\nfrom sqlalchemy.sql import select\ns = select([text(\"* from students\")]) \\\n.where(\n and_(\n text(\"students.name between :x and :y\"),\n text(\"students.id>2\")\n )\n)\nconn.execute(s, x = 'A', y = 'L').fetchall()" }, { "code": null, "e": 20134, "s": 20015, "text": "Above code fetches rows with names between “A” and “L” with id greater than 2. The output of the code is given below −" }, { "code": null, "e": 20186, "s": 20134, "text": "[(3, 'Komal', 'Bhandari'), (4, 'Abdul', 'Sattar')]\n" }, { "code": null, "e": 20440, "s": 20186, "text": "The alias in SQL corresponds to a “renamed” version of a table or SELECT statement, which occurs anytime you say “SELECT * FROM table1 AS a”. The AS creates a new name for the table. Aliases allow any table or subquery to be referenced by a unique name." }, { "code": null, "e": 20660, "s": 20440, "text": "In case of a table, this allows the same table to be named in the FROM clause multiple times. It provides a parent name for the columns represented by the statement, allowing them to be referenced relative to this name." }, { "code": null, "e": 20994, "s": 20660, "text": "In SQLAlchemy, any Table, select() construct, or other selectable object can be turned into an alias using the From Clause.alias() method, which produces an Alias construct. The alias() function in sqlalchemy.sql module represents an alias, as typically applied to any table or sub-select within a SQL statement using the AS keyword." }, { "code": null, "e": 21052, "s": 20994, "text": "from sqlalchemy.sql import alias\nst = students.alias(\"a\")" }, { "code": null, "e": 21130, "s": 21052, "text": "This alias can now be used in select() construct to refer to students table −" }, { "code": null, "e": 21164, "s": 21130, "text": "s = select([st]).where(st.c.id>2)" }, { "code": null, "e": 21211, "s": 21164, "text": "This translates to SQL expression as follows −" }, { "code": null, "e": 21277, "s": 21211, "text": "SELECT a.id, a.name, a.lastname FROM students AS a WHERE a.id > 2" }, { "code": null, "e": 21393, "s": 21277, "text": "We can now execute this SQL query with the execute() method of connection object. The complete code is as follows −" }, { "code": null, "e": 21522, "s": 21393, "text": "from sqlalchemy.sql import alias, select\nst = students.alias(\"a\")\ns = select([st]).where(st.c.id > 2)\nconn.execute(s).fetchall()" }, { "code": null, "e": 21595, "s": 21522, "text": "When above line of code is executed, it generates the following output −" }, { "code": null, "e": 21672, "s": 21595, "text": "[(3, 'Komal', 'Bhandari'), (4, 'Abdul', 'Sattar'), (5, 'Priya', 'Rajhans')]\n" }, { "code": null, "e": 21760, "s": 21672, "text": "The update() method on target table object constructs equivalent UPDATE SQL expression." }, { "code": null, "e": 21817, "s": 21760, "text": "table.update().where(conditions).values(SET expressions)" }, { "code": null, "e": 22076, "s": 21817, "text": "The values() method on the resultant update object is used to specify the SET conditions of the UPDATE. If left as None, the SET conditions are determined from those parameters passed to the statement during the execution and/or compilation of the statement." }, { "code": null, "e": 22175, "s": 22076, "text": "The where clause is an Optional expression describing the WHERE condition of the UPDATE statement." }, { "code": null, "e": 22279, "s": 22175, "text": "Following code snippet changes value of ‘lastname’ column from ‘Khanna’ to ‘Kapoor’ in students table −" }, { "code": null, "e": 22371, "s": 22279, "text": "stmt = students.update().where(students.c.lastname == 'Khanna').values(lastname = 'Kapoor')" }, { "code": null, "e": 22428, "s": 22371, "text": "The stmt object is an update object that translates to −" }, { "code": null, "e": 22509, "s": 22428, "text": "'UPDATE students SET lastname = :lastname WHERE students.lastname = :lastname_1'" }, { "code": null, "e": 22636, "s": 22509, "text": "The bound parameter lastname_1 will be substituted when execute() method is invoked. The complete update code is given below −" }, { "code": null, "e": 23126, "s": 22636, "text": "from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String\nengine = create_engine('sqlite:///college.db', echo = True)\nmeta = MetaData()\n\nstudents = Table(\n 'students', \n meta, \n Column('id', Integer, primary_key = True), \n Column('name', String), \n Column('lastname', String), \n)\n\nconn = engine.connect()\nstmt=students.update().where(students.c.lastname=='Khanna').values(lastname='Kapoor')\nconn.execute(stmt)\ns = students.select()\nconn.execute(s).fetchall()" }, { "code": null, "e": 23247, "s": 23126, "text": "The above code displays following output with second row showing effect of update operation as in the screenshot given −" }, { "code": null, "e": 23388, "s": 23247, "text": "[\n (1, 'Ravi', 'Kapoor'),\n (2, 'Rajiv', 'Kapoor'),\n (3, 'Komal', 'Bhandari'),\n (4, 'Abdul', 'Sattar'),\n (5, 'Priya', 'Rajhans')\n]\n" }, { "code": null, "e": 23521, "s": 23388, "text": "Note that similar functionality can also be achieved by using update() function in sqlalchemy.sql.expression module as shown below −" }, { "code": null, "e": 23657, "s": 23521, "text": "from sqlalchemy.sql.expression import update\nstmt = update(students).where(students.c.lastname == 'Khanna').values(lastname = 'Kapoor')" }, { "code": null, "e": 23791, "s": 23657, "text": "In the previous chapter, we have understood what an Update expression does. The next expression that we are going to learn is Delete." }, { "code": null, "e": 23916, "s": 23791, "text": "The delete operation can be achieved by running delete() method on target table object as given in the following statement −" }, { "code": null, "e": 23941, "s": 23916, "text": "stmt = students.delete()" }, { "code": null, "e": 24034, "s": 23941, "text": "In case of students table, the above line of code constructs a SQL expression as following −" }, { "code": null, "e": 24057, "s": 24034, "text": "'DELETE FROM students'" }, { "code": null, "e": 24247, "s": 24057, "text": "However, this will delete all rows in students table. Usually DELETE query is associated with a logical expression specified by WHERE clause. The following statement shows where parameter −" }, { "code": null, "e": 24297, "s": 24247, "text": "stmt = students.delete().where(students.c.id > 2)" }, { "code": null, "e": 24423, "s": 24297, "text": "The resultant SQL expression will have a bound parameter which will be substituted at runtime when the statement is executed." }, { "code": null, "e": 24472, "s": 24423, "text": "'DELETE FROM students WHERE students.id > :id_1'" }, { "code": null, "e": 24568, "s": 24472, "text": "Following code example will delete those rows from students table having lastname as ‘Khanna’ −" }, { "code": null, "e": 25078, "s": 24568, "text": "from sqlalchemy.sql.expression import update\nfrom sqlalchemy import create_engine, MetaData, Table, Column, Integer, String\nengine = create_engine('sqlite:///college.db', echo = True)\n\nmeta = MetaData()\n\nstudents = Table(\n 'students', meta, \n Column('id', Integer, primary_key = True), \n Column('name', String), \n Column('lastname', String), \n)\n\nconn = engine.connect()\nstmt = students.delete().where(students.c.lastname == 'Khanna')\nconn.execute(stmt)\ns = students.select()\nconn.execute(s).fetchall()" }, { "code": null, "e": 25157, "s": 25078, "text": "To verify the result, refresh the data view of students table in SQLiteStudio." }, { "code": null, "e": 25377, "s": 25157, "text": "One of the important features of RDBMS is establishing relation between tables. SQL operations like SELECT, UPDATE and DELETE can be performed on related tables. This section describes these operations using SQLAlchemy." }, { "code": null, "e": 25653, "s": 25377, "text": "For this purpose, two tables are created in our SQLite database (college.db). The students table has the same structure as given in the previous section; whereas the addresses table has st_id column which is mapped to id column in students table using foreign key constraint." }, { "code": null, "e": 25711, "s": 25653, "text": "The following code will create two tables in college.db −" }, { "code": null, "e": 26266, "s": 25711, "text": "from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, ForeignKey\nengine = create_engine('sqlite:///college.db', echo=True)\nmeta = MetaData()\n\nstudents = Table(\n 'students', meta, \n Column('id', Integer, primary_key = True), \n Column('name', String), \n Column('lastname', String), \n)\n\naddresses = Table(\n 'addresses', meta, \n Column('id', Integer, primary_key = True), \n Column('st_id', Integer, ForeignKey('students.id')), \n Column('postal_add', String), \n Column('email_add', String))\n\nmeta.create_all(engine)" }, { "code": null, "e": 26360, "s": 26266, "text": "Above code will translate to CREATE TABLE queries for students and addresses table as below −" }, { "code": null, "e": 26651, "s": 26360, "text": "CREATE TABLE students (\n id INTEGER NOT NULL,\n name VARCHAR,\n lastname VARCHAR,\n PRIMARY KEY (id)\n)\n\nCREATE TABLE addresses (\n id INTEGER NOT NULL,\n st_id INTEGER,\n postal_add VARCHAR,\n email_add VARCHAR,\n PRIMARY KEY (id),\n FOREIGN KEY(st_id) REFERENCES students (id)\n)" }, { "code": null, "e": 26715, "s": 26651, "text": "The following screenshots present the above code very clearly −" }, { "code": null, "e": 26870, "s": 26715, "text": "These tables are populated with data by executing insert() method of table objects. To insert 5 rows in students table, you can use the code given below −" }, { "code": null, "e": 27456, "s": 26870, "text": "from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String\nengine = create_engine('sqlite:///college.db', echo = True)\nmeta = MetaData()\n\nconn = engine.connect()\nstudents = Table(\n 'students', meta, \n Column('id', Integer, primary_key = True), \n Column('name', String), \n Column('lastname', String), \n)\n\nconn.execute(students.insert(), [\n {'name':'Ravi', 'lastname':'Kapoor'},\n {'name':'Rajiv', 'lastname' : 'Khanna'},\n {'name':'Komal','lastname' : 'Bhandari'},\n {'name':'Abdul','lastname' : 'Sattar'},\n {'name':'Priya','lastname' : 'Rajhans'},\n])" }, { "code": null, "e": 27528, "s": 27456, "text": "Rows are added in addresses table with the help of the following code −" }, { "code": null, "e": 28352, "s": 27528, "text": "from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String\nengine = create_engine('sqlite:///college.db', echo = True)\nmeta = MetaData()\nconn = engine.connect()\n\naddresses = Table(\n 'addresses', meta, \n Column('id', Integer, primary_key = True), \n Column('st_id', Integer), \n Column('postal_add', String), \n Column('email_add', String)\n)\n\nconn.execute(addresses.insert(), [\n {'st_id':1, 'postal_add':'Shivajinagar Pune', 'email_add':'ravi@gmail.com'},\n {'st_id':1, 'postal_add':'ChurchGate Mumbai', 'email_add':'kapoor@gmail.com'},\n {'st_id':3, 'postal_add':'Jubilee Hills Hyderabad', 'email_add':'komal@gmail.com'},\n {'st_id':5, 'postal_add':'MG Road Bangaluru', 'email_add':'as@yahoo.com'},\n {'st_id':2, 'postal_add':'Cannought Place new Delhi', 'email_add':'admin@khanna.com'},\n])" }, { "code": null, "e": 28604, "s": 28352, "text": "Note that the st_id column in addresses table refers to id column in students table. We can now use this relation to fetch data from both the tables. We want to fetch name and lastname from students table corresponding to st_id in the addresses table." }, { "code": null, "e": 28774, "s": 28604, "text": "from sqlalchemy.sql import select\ns = select([students, addresses]).where(students.c.id == addresses.c.st_id)\nresult = conn.execute(s)\n\nfor row in result:\n print (row)" }, { "code": null, "e": 28890, "s": 28774, "text": "The select objects will effectively translate into following SQL expression joining two tables on common relation −" }, { "code": null, "e": 29102, "s": 28890, "text": "SELECT students.id, \n students.name, \n students.lastname, \n addresses.id, \n addresses.st_id, \n addresses.postal_add, \n addresses.email_add\nFROM students, addresses\nWHERE students.id = addresses.st_id" }, { "code": null, "e": 29187, "s": 29102, "text": "This will produce output extracting corresponding data from both tables as follows −" }, { "code": null, "e": 29546, "s": 29187, "text": "(1, 'Ravi', 'Kapoor', 1, 1, 'Shivajinagar Pune', 'ravi@gmail.com')\n(1, 'Ravi', 'Kapoor', 2, 1, 'ChurchGate Mumbai', 'kapoor@gmail.com')\n(3, 'Komal', 'Bhandari', 3, 3, 'Jubilee Hills Hyderabad', 'komal@gmail.com')\n(5, 'Priya', 'Rajhans', 4, 5, 'MG Road Bangaluru', 'as@yahoo.com')\n(2, 'Rajiv', 'Khanna', 5, 2, 'Cannought Place new Delhi', 'admin@khanna.com')\n" }, { "code": null, "e": 29702, "s": 29546, "text": "In the previous chapter, we have discussed about how to use multiple tables. So we proceed a step further and learn multiple table updates in this chapter." }, { "code": null, "e": 30168, "s": 29702, "text": "Using SQLAlchemy’s table object, more than one table can be specified in WHERE clause of update() method. The PostgreSQL and Microsoft SQL Server support UPDATE statements that refer to multiple tables. This implements “UPDATE FROM” syntax, which updates one table at a time. However, additional tables can be referenced in an additional “FROM” clause in the WHERE clause directly. The following lines of codes explain the concept of multiple table updates clearly." }, { "code": null, "e": 30313, "s": 30168, "text": "stmt = students.update().\\\nvalues({\n students.c.name:'xyz',\n addresses.c.email_add:'abc@xyz.com'\n}).\\\nwhere(students.c.id == addresses.c.id)" }, { "code": null, "e": 30377, "s": 30313, "text": "The update object is equivalent to the following UPDATE query −" }, { "code": null, "e": 30495, "s": 30377, "text": "UPDATE students \nSET email_add = :addresses_email_add, name = :name \nFROM addresses \nWHERE students.id = addresses.id" }, { "code": null, "e": 30634, "s": 30495, "text": "As far as MySQL dialect is concerned, multiple tables can be embedded into a single UPDATE statement separated by a comma as given below −" }, { "code": null, "e": 30729, "s": 30634, "text": "stmt = students.update().\\\n values(name = 'xyz').\\\n where(students.c.id == addresses.c.id)" }, { "code": null, "e": 30785, "s": 30729, "text": "The following code depicts the resulting UPDATE query −" }, { "code": null, "e": 30870, "s": 30785, "text": "'UPDATE students SET name = :name \nFROM addresses \nWHERE students.id = addresses.id'" }, { "code": null, "e": 30975, "s": 30870, "text": "SQLite dialect however doesn’t support multiple-table criteria within UPDATE and shows following error −" }, { "code": null, "e": 31065, "s": 30975, "text": "NotImplementedError: This backend does not support multiple-table criteria within UPDATE\n" }, { "code": null, "e": 31461, "s": 31065, "text": "The UPDATE query of raw SQL has SET clause. It is rendered by the update() construct using the column ordering given in the originating Table object. Therefore, a particular UPDATE statement with particular columns will be rendered the same each time. Since the parameters themselves are passed to the Update.values() method as Python dictionary keys, there is no other fixed ordering available." }, { "code": null, "e": 31630, "s": 31461, "text": "In some cases, the order of parameters rendered in the SET clause are significant. In MySQL, providing updates to column values is based on that of other column values." }, { "code": null, "e": 31661, "s": 31630, "text": "Following statement’s result −" }, { "code": null, "e": 31698, "s": 31661, "text": "UPDATE table1 SET x = y + 10, y = 20" }, { "code": null, "e": 31734, "s": 31698, "text": "will have a different result than −" }, { "code": null, "e": 31771, "s": 31734, "text": "UPDATE table1 SET y = 20, x = y + 10" }, { "code": null, "e": 31984, "s": 31771, "text": "SET clause in MySQL is evaluated on a per-value basis and not on per-row basis. For this purpose, the preserve_parameter_order is used. Python list of 2-tuples is given as argument to the Update.values() method −" }, { "code": null, "e": 32101, "s": 31984, "text": "stmt = table1.update(preserve_parameter_order = True).\\\n values([(table1.c.y, 20), (table1.c.x, table1.c.y + 10)])" }, { "code": null, "e": 32268, "s": 32101, "text": "The List object is similar to dictionary except that it is ordered. This ensures that the “y” column’s SET clause will render first, then the “x” column’s SET clause." }, { "code": null, "e": 32400, "s": 32268, "text": "In this chapter, we will look into the Multiple Table Deletes expression which is similar to using Multiple Table Updates function." }, { "code": null, "e": 32764, "s": 32400, "text": "More than one table can be referred in WHERE clause of DELETE statement in many DBMS dialects. For PG and MySQL, “DELETE USING” syntax is used; and for SQL Server, using “DELETE FROM” expression refers to more than one table. The SQLAlchemy delete() construct supports both of these modes implicitly, by specifying multiple tables in the WHERE clause as follows −" }, { "code": null, "e": 32903, "s": 32764, "text": "stmt = users.delete().\\\n where(users.c.id == addresses.c.id).\\\n where(addresses.c.email_address.startswith('xyz%'))\nconn.execute(stmt)" }, { "code": null, "e": 32989, "s": 32903, "text": "On a PostgreSQL backend, the resulting SQL from the above statement would render as −" }, { "code": null, "e": 33116, "s": 32989, "text": "DELETE FROM users USING addresses\nWHERE users.id = addresses.id\nAND (addresses.email_address LIKE %(email_address_1)s || '%%')" }, { "code": null, "e": 33237, "s": 33116, "text": "If this method is used with a database that doesn’t support this behaviour, the compiler will raise NotImplementedError." }, { "code": null, "e": 33300, "s": 33237, "text": "In this chapter, we will learn how to use Joins in SQLAlchemy." }, { "code": null, "e": 33480, "s": 33300, "text": "Effect of joining is achieved by just placing two tables in either the columns clause or the where clause of the select() construct. Now we use the join() and outerjoin() methods." }, { "code": null, "e": 33554, "s": 33480, "text": "The join() method returns a join object from one table object to another." }, { "code": null, "e": 33614, "s": 33554, "text": "join(right, onclause = None, isouter = False, full = False)" }, { "code": null, "e": 33691, "s": 33614, "text": "The functions of the parameters mentioned in the above code are as follows −" }, { "code": null, "e": 33752, "s": 33691, "text": "right − the right side of the join; this is any Table object" }, { "code": null, "e": 33813, "s": 33752, "text": "right − the right side of the join; this is any Table object" }, { "code": null, "e": 33969, "s": 33813, "text": "onclause − a SQL expression representing the ON clause of the join. If left at None, it attempts to join the two tables based on a foreign key relationship" }, { "code": null, "e": 34125, "s": 33969, "text": "onclause − a SQL expression representing the ON clause of the join. If left at None, it attempts to join the two tables based on a foreign key relationship" }, { "code": null, "e": 34187, "s": 34125, "text": "isouter − if True, renders a LEFT OUTER JOIN, instead of JOIN" }, { "code": null, "e": 34249, "s": 34187, "text": "isouter − if True, renders a LEFT OUTER JOIN, instead of JOIN" }, { "code": null, "e": 34319, "s": 34249, "text": "full − if True, renders a FULL OUTER JOIN, instead of LEFT OUTER JOIN" }, { "code": null, "e": 34389, "s": 34319, "text": "full − if True, renders a FULL OUTER JOIN, instead of LEFT OUTER JOIN" }, { "code": null, "e": 34493, "s": 34389, "text": "For example, following use of join() method will automatically result in join based on the foreign key." }, { "code": null, "e": 34529, "s": 34493, "text": ">>> print(students.join(addresses))" }, { "code": null, "e": 34578, "s": 34529, "text": "This is equivalent to following SQL expression −" }, { "code": null, "e": 34635, "s": 34578, "text": "students JOIN addresses ON students.id = addresses.st_id" }, { "code": null, "e": 34692, "s": 34635, "text": "You can explicitly mention joining criteria as follows −" }, { "code": null, "e": 34757, "s": 34692, "text": "j = students.join(addresses, students.c.id == addresses.c.st_id)" }, { "code": null, "e": 34821, "s": 34757, "text": "If we now build the below select construct using this join as −" }, { "code": null, "e": 34862, "s": 34821, "text": "stmt = select([students]).select_from(j)" }, { "code": null, "e": 34909, "s": 34862, "text": "This will result in following SQL expression −" }, { "code": null, "e": 35024, "s": 34909, "text": "SELECT students.id, students.name, students.lastname\nFROM students JOIN addresses ON students.id = addresses.st_id" }, { "code": null, "e": 35184, "s": 35024, "text": "If this statement is executed using the connection representing engine, data belonging to selected columns will be displayed. The complete code is as follows −" }, { "code": null, "e": 35955, "s": 35184, "text": "from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, ForeignKey\nengine = create_engine('sqlite:///college.db', echo = True)\n\nmeta = MetaData()\nconn = engine.connect()\nstudents = Table(\n 'students', meta, \n Column('id', Integer, primary_key = True), \n Column('name', String), \n Column('lastname', String), \n)\n\naddresses = Table(\n 'addresses', meta, \n Column('id', Integer, primary_key = True), \n Column('st_id', Integer,ForeignKey('students.id')), \n Column('postal_add', String), \n Column('email_add', String)\n)\n\nfrom sqlalchemy import join\nfrom sqlalchemy.sql import select\nj = students.join(addresses, students.c.id == addresses.c.st_id)\nstmt = select([students]).select_from(j)\nresult = conn.execute(stmt)\nresult.fetchall()" }, { "code": null, "e": 36003, "s": 35955, "text": "The following is the output of the above code −" }, { "code": null, "e": 36143, "s": 36003, "text": "[\n (1, 'Ravi', 'Kapoor'),\n (1, 'Ravi', 'Kapoor'),\n (3, 'Komal', 'Bhandari'),\n (5, 'Priya', 'Rajhans'),\n (2, 'Rajiv', 'Khanna')\n]\n" }, { "code": null, "e": 36453, "s": 36143, "text": "Conjunctions are functions in SQLAlchemy module that implement relational operators used in WHERE clause of SQL expressions. The operators AND, OR, NOT, etc., are used to form a compound expression combining two individual logical expressions. A simple example of using AND in SELECT statement is as follows −" }, { "code": null, "e": 36506, "s": 36453, "text": "SELECT * from EMPLOYEE WHERE salary>10000 AND age>30" }, { "code": null, "e": 36602, "s": 36506, "text": "SQLAlchemy functions and_(), or_() and not_() respectively implement AND, OR and NOT operators." }, { "code": null, "e": 36711, "s": 36602, "text": "It produces a conjunction of expressions joined by AND. An example is given below for better understanding −" }, { "code": null, "e": 36819, "s": 36711, "text": "from sqlalchemy import and_\n\nprint(\n and_(\n students.c.name == 'Ravi',\n students.c.id <3\n )\n)" }, { "code": null, "e": 36840, "s": 36819, "text": "This translates to −" }, { "code": null, "e": 36888, "s": 36840, "text": "students.name = :name_1 AND students.id < :id_1" }, { "code": null, "e": 36980, "s": 36888, "text": "To use and_() in a select() construct on a students table, use the following line of code −" }, { "code": null, "e": 37063, "s": 36980, "text": "stmt = select([students]).where(and_(students.c.name == 'Ravi', students.c.id <3))" }, { "code": null, "e": 37126, "s": 37063, "text": "SELECT statement of the following nature will be constructed −" }, { "code": null, "e": 37255, "s": 37126, "text": "SELECT students.id, \n students.name, \n students.lastname\nFROM students\nWHERE students.name = :name_1 AND students.id < :id_1" }, { "code": null, "e": 37336, "s": 37255, "text": "The complete code that displays output of the above SELECT query is as follows −" }, { "code": null, "e": 37858, "s": 37336, "text": "from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, ForeignKey, select\nengine = create_engine('sqlite:///college.db', echo = True)\nmeta = MetaData()\nconn = engine.connect()\n\nstudents = Table(\n 'students', meta, \n Column('id', Integer, primary_key = True), \n Column('name', String), \n Column('lastname', String), \n)\n\nfrom sqlalchemy import and_, or_\nstmt = select([students]).where(and_(students.c.name == 'Ravi', students.c.id <3))\nresult = conn.execute(stmt)\nprint (result.fetchall())" }, { "code": null, "e": 37968, "s": 37858, "text": "Following row will be selected assuming that students table is populated with data used in previous example −" }, { "code": null, "e": 37993, "s": 37968, "text": "[(1, 'Ravi', 'Kapoor')]\n" }, { "code": null, "e": 38135, "s": 37993, "text": "It produces conjunction of expressions joined by OR. We shall replace the stmt object in the above example with the following one using or_()" }, { "code": null, "e": 38217, "s": 38135, "text": "stmt = select([students]).where(or_(students.c.name == 'Ravi', students.c.id <3))" }, { "code": null, "e": 38282, "s": 38217, "text": "Which will be effectively equivalent to following SELECT query −" }, { "code": null, "e": 38411, "s": 38282, "text": "SELECT students.id, \n students.name, \n students.lastname\nFROM students\nWHERE students.name = :name_1 \nOR students.id < :id_1" }, { "code": null, "e": 38524, "s": 38411, "text": "Once you make the substitution and run the above code, the result will be two rows falling in the OR condition −" }, { "code": null, "e": 38573, "s": 38524, "text": "[(1, 'Ravi', 'Kapoor'),\n(2, 'Rajiv', 'Khanna')]\n" }, { "code": null, "e": 38683, "s": 38573, "text": "It produces an ascending ORDER BY clause. The function takes the column to apply the function as a parameter." }, { "code": null, "e": 38767, "s": 38683, "text": "from sqlalchemy import asc\nstmt = select([students]).order_by(asc(students.c.name))" }, { "code": null, "e": 38819, "s": 38767, "text": "The statement implements following SQL expression −" }, { "code": null, "e": 38922, "s": 38819, "text": "SELECT students.id, \n students.name, \n students.lastname\nFROM students \nORDER BY students.name ASC" }, { "code": null, "e": 39013, "s": 38922, "text": "Following code lists out all records in students table in ascending order of name column −" }, { "code": null, "e": 39512, "s": 39013, "text": "from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, ForeignKey, select\nengine = create_engine('sqlite:///college.db', echo = True)\nmeta = MetaData()\nconn = engine.connect()\n\nstudents = Table(\n 'students', meta, \n Column('id', Integer, primary_key = True), \n Column('name', String), \n Column('lastname', String), \n)\n\nfrom sqlalchemy import asc\nstmt = select([students]).order_by(asc(students.c.name))\nresult = conn.execute(stmt)\n\nfor row in result:\n print (row)" }, { "code": null, "e": 39551, "s": 39512, "text": "Above code produces following output −" }, { "code": null, "e": 39669, "s": 39551, "text": "(4, 'Abdul', 'Sattar')\n(3, 'Komal', 'Bhandari')\n(5, 'Priya', 'Rajhans')\n(2, 'Rajiv', 'Khanna')\n(1, 'Ravi', 'Kapoor')\n" }, { "code": null, "e": 39744, "s": 39669, "text": "Similarly desc() function produces descending ORDER BY clause as follows −" }, { "code": null, "e": 39834, "s": 39744, "text": "from sqlalchemy import desc\nstmt = select([students]).order_by(desc(students.c.lastname))" }, { "code": null, "e": 39869, "s": 39834, "text": "The equivalent SQL expression is −" }, { "code": null, "e": 39977, "s": 39869, "text": "SELECT students.id, \n students.name, \n students.lastname\nFROM students \nORDER BY students.lastname DESC" }, { "code": null, "e": 40025, "s": 39977, "text": "And the output for the above lines of code is −" }, { "code": null, "e": 40143, "s": 40025, "text": "(4, 'Abdul', 'Sattar')\n(5, 'Priya', 'Rajhans')\n(2, 'Rajiv', 'Khanna')\n(1, 'Ravi', 'Kapoor')\n(3, 'Komal', 'Bhandari')\n" }, { "code": null, "e": 40352, "s": 40143, "text": "It produces a BETWEEN predicate clause. This is generally used to validate if value of a certain column falls between a range. For example, following code selects rows for which id column is between 2 and 4 −" }, { "code": null, "e": 40456, "s": 40352, "text": "from sqlalchemy import between\nstmt = select([students]).where(between(students.c.id,2,4))\nprint (stmt)" }, { "code": null, "e": 40497, "s": 40456, "text": "The resulting SQL expression resembles −" }, { "code": null, "e": 40615, "s": 40497, "text": "SELECT students.id, \n students.name, \n students.lastname\nFROM students\nWHERE students.id \nBETWEEN :id_1 AND :id_2" }, { "code": null, "e": 40646, "s": 40615, "text": "and the result is as follows −" }, { "code": null, "e": 40718, "s": 40646, "text": "(2, 'Rajiv', 'Khanna')\n(3, 'Komal', 'Bhandari')\n(4, 'Abdul', 'Sattar')\n" }, { "code": null, "e": 40800, "s": 40718, "text": "Some of the important functions used in SQLAlchemy are discussed in this chapter." }, { "code": null, "e": 41090, "s": 40800, "text": "Standard SQL has recommended many functions which are implemented by most dialects. They return a single value based on the arguments passed to it. Some SQL functions take columns as arguments whereas some are generic. Thefunc keyword in SQLAlchemy API is used to generate these functions." }, { "code": null, "e": 41188, "s": 41090, "text": "In SQL, now() is a generic function. Following statements renders the now() function using func −" }, { "code": null, "e": 41290, "s": 41188, "text": "from sqlalchemy.sql import func\nresult = conn.execute(select([func.now()]))\nprint (result.fetchone())" }, { "code": null, "e": 41342, "s": 41290, "text": "Sample result of above code may be as shown below −" }, { "code": null, "e": 41387, "s": 41342, "text": "(datetime.datetime(2018, 6, 16, 6, 4, 40),)\n" }, { "code": null, "e": 41516, "s": 41387, "text": "On the other hand, count() function which returns number of rows selected from a table, is rendered by following usage of func −" }, { "code": null, "e": 41633, "s": 41516, "text": "from sqlalchemy.sql import func\nresult = conn.execute(select([func.count(students.c.id)]))\nprint (result.fetchone())" }, { "code": null, "e": 41713, "s": 41633, "text": "From the above code, count of number of rows in students table will be fetched." }, { "code": null, "e": 41801, "s": 41713, "text": "Some built-in SQL functions are demonstrated using Employee table with following data −" }, { "code": null, "e": 41938, "s": 41801, "text": "The max() function is implemented by following usage of func from SQLAlchemy which will result in 85, the total maximum marks obtained −" }, { "code": null, "e": 42056, "s": 41938, "text": "from sqlalchemy.sql import func\nresult = conn.execute(select([func.max(employee.c.marks)]))\nprint (result.fetchone())" }, { "code": null, "e": 42155, "s": 42056, "text": "Similarly, min() function that will return 56, minimum marks, will be rendered by following code −" }, { "code": null, "e": 42273, "s": 42155, "text": "from sqlalchemy.sql import func\nresult = conn.execute(select([func.min(employee.c.marks)]))\nprint (result.fetchone())" }, { "code": null, "e": 42346, "s": 42273, "text": "So, the AVG() function can also be implemented by using the below code −" }, { "code": null, "e": 42887, "s": 42346, "text": "from sqlalchemy.sql import func\nresult = conn.execute(select([func.avg(employee.c.marks)]))\nprint (result.fetchone())\n\nFunctions are normally used in the columns clause of a select statement. \nThey can also be given label as well as a type. A label to function allows the result \nto be targeted in a result row based on a string name, and a type is required when \nyou need result-set processing to occur.from sqlalchemy.sql import func\n\nresult = conn.execute(select([func.max(students.c.lastname).label('Name')]))\n\nprint (result.fetchone())" }, { "code": null, "e": 43041, "s": 42887, "text": "In the last chapter, we have learnt about various functions such as max(), min(), count(), etc., here, we will learn about set operations and their uses." }, { "code": null, "e": 43205, "s": 43041, "text": "Set operations such as UNION and INTERSECT are supported by standard SQL and most of its dialect. SQLAlchemy implements them with the help of following functions −" }, { "code": null, "e": 43379, "s": 43205, "text": "While combining results of two or more SELECT statements, UNION eliminates duplicates from the resultset. The number of columns and datatype must be same in both the tables." }, { "code": null, "e": 43495, "s": 43379, "text": "The union() function returns a CompoundSelect object from multiple tables. Following example demonstrates its use −" }, { "code": null, "e": 44060, "s": 43495, "text": "from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, union\nengine = create_engine('sqlite:///college.db', echo = True)\n\nmeta = MetaData()\nconn = engine.connect()\naddresses = Table(\n 'addresses', meta, \n Column('id', Integer, primary_key = True), \n Column('st_id', Integer), \n Column('postal_add', String), \n Column('email_add', String)\n)\n\nu = union(addresses.select().where(addresses.c.email_add.like('%@gmail.com addresses.select().where(addresses.c.email_add.like('%@yahoo.com'))))\n\nresult = conn.execute(u)\nresult.fetchall()" }, { "code": null, "e": 44121, "s": 44060, "text": "The union construct translates to following SQL expression −" }, { "code": null, "e": 44407, "s": 44121, "text": "SELECT addresses.id, \n addresses.st_id, \n addresses.postal_add, \n addresses.email_add\nFROM addresses\nWHERE addresses.email_add LIKE ? UNION SELECT addresses.id, \n addresses.st_id, \n addresses.postal_add, \n addresses.email_add\nFROM addresses\nWHERE addresses.email_add LIKE ?" }, { "code": null, "e": 44480, "s": 44407, "text": "From our addresses table, following rows represent the union operation −" }, { "code": null, "e": 44691, "s": 44480, "text": "[\n (1, 1, 'Shivajinagar Pune', 'ravi@gmail.com'),\n (2, 1, 'ChurchGate Mumbai', 'kapoor@gmail.com'),\n (3, 3, 'Jubilee Hills Hyderabad', 'komal@gmail.com'),\n (4, 5, 'MG Road Bangaluru', 'as@yahoo.com')\n]\n" }, { "code": null, "e": 44862, "s": 44691, "text": "UNION ALL operation cannot remove the duplicates and cannot sort the data in the resultset. For example, in above query, UNION is replaced by UNION ALL to see the effect." }, { "code": null, "e": 45014, "s": 44862, "text": "u = union_all(addresses.select().where(addresses.c.email_add.like('%@gmail.com')), addresses.select().where(addresses.c.email_add.like('%@yahoo.com')))" }, { "code": null, "e": 45063, "s": 45014, "text": "The corresponding SQL expression is as follows −" }, { "code": null, "e": 45353, "s": 45063, "text": "SELECT addresses.id, \n addresses.st_id, \n addresses.postal_add, \n addresses.email_add\nFROM addresses\nWHERE addresses.email_add LIKE ? UNION ALL SELECT addresses.id, \n addresses.st_id, \n addresses.postal_add, \n addresses.email_add\nFROM addresses\nWHERE addresses.email_add LIKE ?" }, { "code": null, "e": 45600, "s": 45353, "text": "The SQL EXCEPT clause/operator is used to combine two SELECT statements and return rows from the first SELECT statement that are not returned by the second SELECT statement. The except_() function generates a SELECT expression with EXCEPT clause." }, { "code": null, "e": 45804, "s": 45600, "text": "In the following example, the except_() function returns only those records from addresses table that have ‘gmail.com’ in email_add field but excludes those which have ‘Pune’ as part of postal_add field." }, { "code": null, "e": 45949, "s": 45804, "text": "u = except_(addresses.select().where(addresses.c.email_add.like('%@gmail.com')), addresses.select().where(addresses.c.postal_add.like('%Pune')))" }, { "code": null, "e": 46008, "s": 45949, "text": "Result of the above code is the following SQL expression −" }, { "code": null, "e": 46296, "s": 46008, "text": "SELECT addresses.id, \n addresses.st_id, \n addresses.postal_add, \n addresses.email_add\nFROM addresses\nWHERE addresses.email_add LIKE ? EXCEPT SELECT addresses.id, \n addresses.st_id, \n addresses.postal_add, \n addresses.email_add\nFROM addresses\nWHERE addresses.postal_add LIKE ?" }, { "code": null, "e": 46401, "s": 46296, "text": "Assuming that addresses table contains data used in earlier examples, it will display following output −" }, { "code": null, "e": 46509, "s": 46401, "text": "[(2, 1, 'ChurchGate Mumbai', 'kapoor@gmail.com'),\n (3, 3, 'Jubilee Hills Hyderabad', 'komal@gmail.com')]\n" }, { "code": null, "e": 46645, "s": 46509, "text": "Using INTERSECT operator, SQL displays common rows from both the SELECT statements. The intersect() function implements this behaviour." }, { "code": null, "e": 46919, "s": 46645, "text": "In following examples, two SELECT constructs are parameters to intersect() function. One returns rows containing ‘gmail.com’ as part of email_add column, and other returns rows having ‘Pune’ as part of postal_add column. The result will be common rows from both resultsets." }, { "code": null, "e": 47066, "s": 46919, "text": "u = intersect(addresses.select().where(addresses.c.email_add.like('%@gmail.com')), addresses.select().where(addresses.c.postal_add.like('%Pune')))" }, { "code": null, "e": 47125, "s": 47066, "text": "In effect, this is equivalent to following SQL statement −" }, { "code": null, "e": 47416, "s": 47125, "text": "SELECT addresses.id, \n addresses.st_id, \n addresses.postal_add, \n addresses.email_add\nFROM addresses\nWHERE addresses.email_add LIKE ? INTERSECT SELECT addresses.id, \n addresses.st_id, \n addresses.postal_add, \n addresses.email_add\nFROM addresses\nWHERE addresses.postal_add LIKE ?" }, { "code": null, "e": 47543, "s": 47416, "text": "The two bound parameters ‘%gmail.com’ and ‘%Pune’ generate a single row from original data in addresses table as shown below −" }, { "code": null, "e": 47592, "s": 47543, "text": "[(1, 1, 'Shivajinagar Pune', 'ravi@gmail.com')]\n" }, { "code": null, "e": 48004, "s": 47592, "text": "The main objective of the Object Relational Mapper API of SQLAlchemy is to facilitate associating user-defined Python classes with database tables, and objects of those classes with rows in their corresponding tables. Changes in states of objects and rows are synchronously matched with each other. SQLAlchemy enables expressing database queries in terms of user defined classes and their defined relationships." }, { "code": null, "e": 48179, "s": 48004, "text": "The ORM is constructed on top of the SQL Expression Language. It is a high level and abstracted pattern of usage. In fact, ORM is an applied usage of the Expression Language." }, { "code": null, "e": 48422, "s": 48179, "text": "Although a successful application may be constructed using the Object Relational Mapper exclusively, sometimes an application constructed with the ORM may use the Expression Language directly where specific database interactions are required." }, { "code": null, "e": 48799, "s": 48422, "text": "First of all, create_engine() function is called to set up an engine object which is subsequently used to perform SQL operations. The function has two arguments, one is the name of database and other is an echo parameter when set to True will generate the activity log. If it doesn’t exist, the database will be created. In the following example, a SQLite database is created." }, { "code": null, "e": 48894, "s": 48799, "text": "from sqlalchemy import create_engine\nengine = create_engine('sqlite:///sales.db', echo = True)" }, { "code": null, "e": 49149, "s": 48894, "text": "The Engine establishes a real DBAPI connection to the database when a method like Engine.execute() or Engine.connect() is called. It is then used to emit the SQLORM which does not use the Engine directly; instead, it is used behind the scenes by the ORM." }, { "code": null, "e": 49495, "s": 49149, "text": "In case of ORM, the configurational process starts by describing the database tables and then by defining classes which will be mapped to those tables. In SQLAlchemy, these two tasks are performed together. This is done by using Declarative system; the classes created include directives to describe the actual database table they are mapped to." }, { "code": null, "e": 49835, "s": 49495, "text": "A base class stores a catlog of classes and mapped tables in the Declarative system. This is called as the declarative base class. There will be usually just one instance of this base in a commonly imported module. The declarative_base() function is used to create base class. This function is defined in sqlalchemy.ext.declarative module." }, { "code": null, "e": 49917, "s": 49835, "text": "from sqlalchemy.ext.declarative import declarative_base\nBase = declarative_base()" }, { "code": null, "e": 50129, "s": 49917, "text": "Once base classis declared, any number of mapped classes can be defined in terms of it. Following code defines a Customer’s class. It contains the table to be mapped to, and names and datatypes of columns in it." }, { "code": null, "e": 50310, "s": 50129, "text": "class Customers(Base):\n __tablename__ = 'customers'\n \n id = Column(Integer, primary_key = True)\n name = Column(String)\n address = Column(String)\n email = Column(String)" }, { "code": null, "e": 50703, "s": 50310, "text": "A class in Declarative must have a __tablename__ attribute, and at least one Column which is part of a primary key. Declarative replaces all the Column objects with special Python accessors known as descriptors. This process is known as instrumentation which provides the means to refer to the table in a SQL context and enables persisting and loading the values of columns from the database." }, { "code": null, "e": 50799, "s": 50703, "text": "This mapped class like a normal Python class has attributes and methods as per the requirement." }, { "code": null, "e": 51218, "s": 50799, "text": "The information about class in Declarative system, is called as table metadata. SQLAlchemy uses Table object to represent this information for a specific table created by Declarative. The Table object is created according to the specifications, and is associated with the class by constructing a Mapper object. This mapper object is not directly used but is used internally as interface between mapped class and table." }, { "code": null, "e": 51567, "s": 51218, "text": "Each Table object is a member of larger collection known as MetaData and this object is available using the .metadata attribute of declarative base class. The MetaData.create_all() method is, passing in our Engine as a source of database connectivity. For all tables that haven’t been created yet, it issues CREATE TABLE statements to the database." }, { "code": null, "e": 51600, "s": 51567, "text": "Base.metadata.create_all(engine)" }, { "code": null, "e": 51695, "s": 51600, "text": "The complete script to create a database and a table, and to map Python class is given below −" }, { "code": null, "e": 52129, "s": 51695, "text": "from sqlalchemy import Column, Integer, String\nfrom sqlalchemy import create_engine\nengine = create_engine('sqlite:///sales.db', echo = True)\nfrom sqlalchemy.ext.declarative import declarative_base\nBase = declarative_base()\n\nclass Customers(Base):\n __tablename__ = 'customers'\n id = Column(Integer, primary_key=True)\n\n name = Column(String)\n address = Column(String)\n email = Column(String)\nBase.metadata.create_all(engine)" }, { "code": null, "e": 52211, "s": 52129, "text": "When executed, Python console will echo following SQL expression being executed −" }, { "code": null, "e": 52338, "s": 52211, "text": "CREATE TABLE customers (\n id INTEGER NOT NULL,\n name VARCHAR,\n address VARCHAR,\n email VARCHAR,\n PRIMARY KEY (id)\n)\n" }, { "code": null, "e": 52462, "s": 52338, "text": "If we open the Sales.db using SQLiteStudio graphic tool, it shows customers table inside it with above mentioned structure." }, { "code": null, "e": 52715, "s": 52462, "text": "In order to interact with the database, we need to obtain its handle. A session object is the handle to database. Session class is defined using sessionmaker() – a configurable session factory method which is bound to the engine object created earlier." }, { "code": null, "e": 52793, "s": 52715, "text": "from sqlalchemy.orm import sessionmaker\nSession = sessionmaker(bind = engine)" }, { "code": null, "e": 52870, "s": 52793, "text": "The session object is then set up using its default constructor as follows −" }, { "code": null, "e": 52890, "s": 52870, "text": "session = Session()" }, { "code": null, "e": 52966, "s": 52890, "text": "Some of the frequently required methods of session class are listed below −" }, { "code": null, "e": 52974, "s": 52966, "text": "begin()" }, { "code": null, "e": 53011, "s": 52974, "text": "begins a transaction on this session" }, { "code": null, "e": 53017, "s": 53011, "text": "add()" }, { "code": null, "e": 53113, "s": 53017, "text": "places an object in the session. Its state is persisted in the database on next flush operation" }, { "code": null, "e": 53123, "s": 53113, "text": "add_all()" }, { "code": null, "e": 53167, "s": 53123, "text": "adds a collection of objects to the session" }, { "code": null, "e": 53176, "s": 53167, "text": "commit()" }, { "code": null, "e": 53226, "s": 53176, "text": "flushes all items and any transaction in progress" }, { "code": null, "e": 53235, "s": 53226, "text": "delete()" }, { "code": null, "e": 53266, "s": 53235, "text": "marks a transaction as deleted" }, { "code": null, "e": 53276, "s": 53266, "text": "execute()" }, { "code": null, "e": 53302, "s": 53276, "text": "executes a SQL expression" }, { "code": null, "e": 53311, "s": 53302, "text": "expire()" }, { "code": null, "e": 53358, "s": 53311, "text": "marks attributes of an instance as out of date" }, { "code": null, "e": 53366, "s": 53358, "text": "flush()" }, { "code": null, "e": 53409, "s": 53366, "text": "flushes all object changes to the database" }, { "code": null, "e": 53422, "s": 53409, "text": "invalidate()" }, { "code": null, "e": 53471, "s": 53422, "text": "closes the session using connection invalidation" }, { "code": null, "e": 53482, "s": 53471, "text": "rollback()" }, { "code": null, "e": 53529, "s": 53482, "text": "rolls back the current transaction in progress" }, { "code": null, "e": 53537, "s": 53529, "text": "close()" }, { "code": null, "e": 53621, "s": 53537, "text": "Closes current session by clearing all items and ending any transaction in progress" }, { "code": null, "e": 53788, "s": 53621, "text": "In the previous chapters of SQLAlchemy ORM, we have learnt how to declare mapping and create sessions. In this chapter, we will learn how to add objects to the table." }, { "code": null, "e": 53976, "s": 53788, "text": "We have declared Customer class that has been mapped to customers table. We have to declare an object of this class and persistently add it to the table by add() method of session object." }, { "code": null, "e": 54083, "s": 53976, "text": "c1 = Sales(name = 'Ravi Kumar', address = 'Station Road Nanded', email = 'ravi@gmail.com')\nsession.add(c1)" }, { "code": null, "e": 54170, "s": 54083, "text": "Note that this transaction is pending until the same is flushed using commit() method." }, { "code": null, "e": 54187, "s": 54170, "text": "session.commit()" }, { "code": null, "e": 54257, "s": 54187, "text": "Following is the complete script to add a record in customers table −" }, { "code": null, "e": 54893, "s": 54257, "text": "from sqlalchemy import Column, Integer, String\nfrom sqlalchemy import create_engine\nengine = create_engine('sqlite:///sales.db', echo = True)\nfrom sqlalchemy.ext.declarative import declarative_base\nBase = declarative_base()\n\nclass Customers(Base):\n __tablename__ = 'customers'\n \n id = Column(Integer, primary_key=True)\n name = Column(String)\n address = Column(String)\n email = Column(String)\n \nfrom sqlalchemy.orm import sessionmaker\nSession = sessionmaker(bind = engine)\nsession = Session()\n\nc1 = Customers(name = 'Ravi Kumar', address = 'Station Road Nanded', email = 'ravi@gmail.com')\n\nsession.add(c1)\nsession.commit()" }, { "code": null, "e": 54968, "s": 54893, "text": "To add multiple records, we can use add_all() method of the session class." }, { "code": null, "e": 55289, "s": 54968, "text": "session.add_all([\n Customers(name = 'Komal Pande', address = 'Koti, Hyderabad', email = 'komal@gmail.com'), \n Customers(name = 'Rajender Nath', address = 'Sector 40, Gurgaon', email = 'nath@gmail.com'), \n Customers(name = 'S.M.Krishna', address = 'Budhwar Peth, Pune', email = 'smk@gmail.com')]\n)\n\nsession.commit()" }, { "code": null, "e": 55421, "s": 55289, "text": "Table view of SQLiteStudio shows that the records are persistently added in customers table. The following image shows the result −" }, { "code": null, "e": 55668, "s": 55421, "text": "All SELECT statements generated by SQLAlchemy ORM are constructed by Query object. It provides a generative interface, hence successive calls return a new Query object, a copy of the former with additional criteria and options associated with it." }, { "code": null, "e": 55759, "s": 55668, "text": "Query objects are initially generated using the query() method of the Session as follows −" }, { "code": null, "e": 55791, "s": 55759, "text": "q = session.query(mapped class)" }, { "code": null, "e": 55861, "s": 55791, "text": "Following statement is also equivalent to the above given statement −" }, { "code": null, "e": 55893, "s": 55861, "text": "q = Query(mappedClass, session)" }, { "code": null, "e": 56027, "s": 55893, "text": "The query object has all() method which returns a resultset in the form of list of objects. If we execute it on our customers table −" }, { "code": null, "e": 56067, "s": 56027, "text": "result = session.query(Customers).all()" }, { "code": null, "e": 56138, "s": 56067, "text": "This statement is effectively equivalent to following SQL expression −" }, { "code": null, "e": 56303, "s": 56138, "text": "SELECT customers.id \nAS customers_id, customers.name \nAS customers_name, customers.address \nAS customers_address, customers.email \nAS customers_email\nFROM customers" }, { "code": null, "e": 56485, "s": 56303, "text": "The result object can be traversed using For loop as below to obtain all records in underlying customers table. Here is the complete code to display all records in Customers table −" }, { "code": null, "e": 57121, "s": 56485, "text": "from sqlalchemy import Column, Integer, String\nfrom sqlalchemy import create_engine\nengine = create_engine('sqlite:///sales.db', echo = True)\nfrom sqlalchemy.ext.declarative import declarative_base\nBase = declarative_base()\n\nclass Customers(Base):\n __tablename__ = 'customers'\n id = Column(Integer, primary_key = True)\n name = Column(String)\n\n address = Column(String)\n email = Column(String)\n\nfrom sqlalchemy.orm import sessionmaker\nSession = sessionmaker(bind = engine)\nsession = Session()\nresult = session.query(Customers).all()\n\nfor row in result:\n print (\"Name: \",row.name, \"Address:\",row.address, \"Email:\",row.email)" }, { "code": null, "e": 57169, "s": 57121, "text": "Python console shows list of records as below −" }, { "code": null, "e": 57441, "s": 57169, "text": "Name: Ravi Kumar Address: Station Road Nanded Email: ravi@gmail.com\nName: Komal Pande Address: Koti, Hyderabad Email: komal@gmail.com\nName: Rajender Nath Address: Sector 40, Gurgaon Email: nath@gmail.com\nName: S.M.Krishna Address: Budhwar Peth, Pune Email: smk@gmail.com\n" }, { "code": null, "e": 57494, "s": 57441, "text": "The Query object also has following useful methods −" }, { "code": null, "e": 57508, "s": 57494, "text": "add_columns()" }, { "code": null, "e": 57593, "s": 57508, "text": "It adds one or more column expressions to the list of result columns to be returned." }, { "code": null, "e": 57606, "s": 57593, "text": "add_entity()" }, { "code": null, "e": 57676, "s": 57606, "text": "It adds a mapped entity to the list of result columns to be returned." }, { "code": null, "e": 57684, "s": 57676, "text": "count()" }, { "code": null, "e": 57736, "s": 57684, "text": "It returns a count of rows this Query would return." }, { "code": null, "e": 57745, "s": 57736, "text": "delete()" }, { "code": null, "e": 57832, "s": 57745, "text": "It performs a bulk delete query. Deletes rows matched by this query from the database." }, { "code": null, "e": 57843, "s": 57832, "text": "distinct()" }, { "code": null, "e": 57923, "s": 57843, "text": "It applies a DISTINCT clause to the query and return the newly resulting Query." }, { "code": null, "e": 57932, "s": 57923, "text": "filter()" }, { "code": null, "e": 58021, "s": 57932, "text": "It applies the given filtering criterion to a copy of this Query, using SQL expressions." }, { "code": null, "e": 58029, "s": 58021, "text": "first()" }, { "code": null, "e": 58118, "s": 58029, "text": "It returns the first result of this Query or None if the result doesn’t contain any row." }, { "code": null, "e": 58124, "s": 58118, "text": "get()" }, { "code": null, "e": 58256, "s": 58124, "text": "It returns an instance based on the given primary key identifier providing direct access to the identity map of the owning Session." }, { "code": null, "e": 58267, "s": 58256, "text": "group_by()" }, { "code": null, "e": 58359, "s": 58267, "text": "It applies one or more GROUP BY criterion to the query and return the newly resulting Query" }, { "code": null, "e": 58366, "s": 58359, "text": "join()" }, { "code": null, "e": 58487, "s": 58366, "text": "It creates a SQL JOIN against this Query object’s criterion and apply generatively, returning the newly resulting Query." }, { "code": null, "e": 58493, "s": 58487, "text": "one()" }, { "code": null, "e": 58546, "s": 58493, "text": "It returns exactly one result or raise an exception." }, { "code": null, "e": 58557, "s": 58546, "text": "order_by()" }, { "code": null, "e": 58651, "s": 58557, "text": "It applies one or more ORDER BY criterion to the query and returns the newly resulting Query." }, { "code": null, "e": 58660, "s": 58651, "text": "update()" }, { "code": null, "e": 58748, "s": 58660, "text": "It performs a bulk update query and updates rows matched by this query in the database." }, { "code": null, "e": 58832, "s": 58748, "text": "In this chapter, we will see how to modify or update the table with desired values." }, { "code": null, "e": 58973, "s": 58832, "text": "To modify data of a certain attribute of any object, we have to assign new value to it and commit the changes to make the change persistent." }, { "code": null, "e": 59123, "s": 58973, "text": "Let us fetch an object from the table whose primary key identifier, in our Customers table with ID=2. We can use get() method of session as follows −" }, { "code": null, "e": 59159, "s": 59123, "text": "x = session.query(Customers).get(2)" }, { "code": null, "e": 59234, "s": 59159, "text": "We can display contents of the selected object with the below given code −" }, { "code": null, "e": 59301, "s": 59234, "text": "print (\"Name: \", x.name, \"Address:\", x.address, \"Email:\", x.email)" }, { "code": null, "e": 59366, "s": 59301, "text": "From our customers table, following output should be displayed −" }, { "code": null, "e": 59433, "s": 59366, "text": "Name: Komal Pande Address: Koti, Hyderabad Email: komal@gmail.com\n" }, { "code": null, "e": 59513, "s": 59433, "text": "Now we need to update the Address field by assigning new value as given below −" }, { "code": null, "e": 59571, "s": 59513, "text": "x.address = 'Banjara Hills Secunderabad'\nsession.commit()" }, { "code": null, "e": 59727, "s": 59571, "text": "The change will be persistently reflected in the database. Now we fetch object corresponding to first row in the table by using first() method as follows −" }, { "code": null, "e": 59764, "s": 59727, "text": "x = session.query(Customers).first()" }, { "code": null, "e": 59809, "s": 59764, "text": "This will execute following SQL expression −" }, { "code": null, "e": 59991, "s": 59809, "text": "SELECT customers.id \nAS customers_id, customers.name \nAS customers_name, customers.address \nAS customers_address, customers.email \nAS customers_email\nFROM customers\nLIMIT ? OFFSET ?" }, { "code": null, "e": 60098, "s": 59991, "text": "The bound parameters will be LIMIT = 1 and OFFSET = 0 respectively which means first row will be selected." }, { "code": null, "e": 60165, "s": 60098, "text": "print (\"Name: \", x.name, \"Address:\", x.address, \"Email:\", x.email)" }, { "code": null, "e": 60241, "s": 60165, "text": "Now, the output for the above code displaying the first row is as follows −" }, { "code": null, "e": 60310, "s": 60241, "text": "Name: Ravi Kumar Address: Station Road Nanded Email: ravi@gmail.com\n" }, { "code": null, "e": 60384, "s": 60310, "text": "Now change name attribute and display the contents using the below code −" }, { "code": null, "e": 60480, "s": 60384, "text": "x.name = 'Ravi Shrivastava'\nprint (\"Name: \", x.name, \"Address:\", x.address, \"Email:\", x.email)\n" }, { "code": null, "e": 60514, "s": 60480, "text": "The output of the above code is −" }, { "code": null, "e": 60589, "s": 60514, "text": "Name: Ravi Shrivastava Address: Station Road Nanded Email: ravi@gmail.com\n" }, { "code": null, "e": 60742, "s": 60589, "text": "Even though the change is displayed, it is not committed. You can retain the earlier persistent position by using rollback() method with the code below." }, { "code": null, "e": 60829, "s": 60742, "text": "session.rollback()\n\nprint (\"Name: \", x.name, \"Address:\", x.address, \"Email:\", x.email)" }, { "code": null, "e": 60882, "s": 60829, "text": "Original contents of first record will be displayed." }, { "code": null, "e": 61076, "s": 60882, "text": "For bulk updates, we shall use update() method of the Query object. Let us try and give a prefix, ‘Mr.’ to name in each row (except ID = 2). The corresponding update() statement is as follows −" }, { "code": null, "e": 61203, "s": 61076, "text": "session.query(Customers).filter(Customers.id! = 2).\nupdate({Customers.name:\"Mr.\"+Customers.name}, synchronize_session = False)" }, { "code": null, "e": 61260, "s": 61203, "text": "The update() method requires two parameters as follows −" }, { "code": null, "e": 61378, "s": 61260, "text": "A dictionary of key-values with key being the attribute to be updated, and value being the new contents of attribute." }, { "code": null, "e": 61496, "s": 61378, "text": "A dictionary of key-values with key being the attribute to be updated, and value being the new contents of attribute." }, { "code": null, "e": 61808, "s": 61496, "text": "synchronize_session attribute mentioning the strategy to update attributes in the session. Valid values are false: for not synchronizing the session, fetch: performs a select query before the update to find objects that are matched by the update query; and evaluate: evaluate criteria on objects in the session." }, { "code": null, "e": 62120, "s": 61808, "text": "synchronize_session attribute mentioning the strategy to update attributes in the session. Valid values are false: for not synchronizing the session, fetch: performs a select query before the update to find objects that are matched by the update query; and evaluate: evaluate criteria on objects in the session." }, { "code": null, "e": 62348, "s": 62120, "text": "Three out of 4 rows in the table will have name prefixed with ‘Mr.’ However, the changes are not committed and hence will not be reflected in the table view of SQLiteStudio. It will be refreshed only when we commit the session." }, { "code": null, "e": 62460, "s": 62348, "text": "In this chapter, we will discuss how to apply filter and also certain filter operations along with their codes." }, { "code": null, "e": 62612, "s": 62460, "text": "Resultset represented by Query object can be subjected to certain criteria by using filter() method. The general usage of filter method is as follows −" }, { "code": null, "e": 62650, "s": 62612, "text": "session.query(class).filter(criteria)" }, { "code": null, "e": 62767, "s": 62650, "text": "In the following example, resultset obtained by SELECT query on Customers table is filtered by a condition, (ID>2) −" }, { "code": null, "e": 62824, "s": 62767, "text": "result = session.query(Customers).filter(Customers.id>2)" }, { "code": null, "e": 62886, "s": 62824, "text": "This statement will translate into following SQL expression −" }, { "code": null, "e": 63074, "s": 62886, "text": "SELECT customers.id \nAS customers_id, customers.name \nAS customers_name, customers.address \nAS customers_address, customers.email \nAS customers_email\nFROM customers\nWHERE customers.id > ?" }, { "code": null, "e": 63206, "s": 63074, "text": "Since the bound parameter (?) is given as 2, only those rows with ID column>2 will be displayed. The complete code is given below −" }, { "code": null, "e": 63877, "s": 63206, "text": "from sqlalchemy import Column, Integer, String\nfrom sqlalchemy import create_engine\nengine = create_engine('sqlite:///sales.db', echo = True)\nfrom sqlalchemy.ext.declarative import declarative_base\nBase = declarative_base()\n\nclass Customers(Base):\n __tablename__ = 'customers'\n \n id = Column(Integer, primary_key = True)\n name = Column(String)\n\n address = Column(String)\n email = Column(String)\n\nfrom sqlalchemy.orm import sessionmaker\nSession = sessionmaker(bind = engine)\nsession = Session()\nresult = session.query(Customers).filter(Customers.id>2)\n\nfor row in result:\n print (\"ID:\", row.id, \"Name: \",row.name, \"Address:\",row.address, \"Email:\",row.email)" }, { "code": null, "e": 63936, "s": 63877, "text": "The output displayed in the Python console is as follows −" }, { "code": null, "e": 64086, "s": 63936, "text": "ID: 3 Name: Rajender Nath Address: Sector 40, Gurgaon Email: nath@gmail.com\nID: 4 Name: S.M.Krishna Address: Budhwar Peth, Pune Email: smk@gmail.com\n" }, { "code": null, "e": 64167, "s": 64086, "text": "Now, we will learn the filter operations with their respective codes and output." }, { "code": null, "e": 64244, "s": 64167, "text": "The usual operator used is == and it applies the criteria to check equality." }, { "code": null, "e": 64412, "s": 64244, "text": "result = session.query(Customers).filter(Customers.id == 2)\n\nfor row in result:\n print (\"ID:\", row.id, \"Name: \",row.name, \"Address:\",row.address, \"Email:\",row.email)" }, { "code": null, "e": 64460, "s": 64412, "text": "SQLAlchemy will send following SQL expression −" }, { "code": null, "e": 64648, "s": 64460, "text": "SELECT customers.id \nAS customers_id, customers.name \nAS customers_name, customers.address \nAS customers_address, customers.email \nAS customers_email\nFROM customers\nWHERE customers.id = ?" }, { "code": null, "e": 64694, "s": 64648, "text": "The output for the above code is as follows −" }, { "code": null, "e": 64778, "s": 64694, "text": "ID: 2 Name: Komal Pande Address: Banjara Hills Secunderabad Email: komal@gmail.com\n" }, { "code": null, "e": 64854, "s": 64778, "text": "The operator used for not equals is != and it provides not equals criteria." }, { "code": null, "e": 65022, "s": 64854, "text": "result = session.query(Customers).filter(Customers.id! = 2)\n\nfor row in result:\n print (\"ID:\", row.id, \"Name: \",row.name, \"Address:\",row.address, \"Email:\",row.email)" }, { "code": null, "e": 65056, "s": 65022, "text": "The resulting SQL expression is −" }, { "code": null, "e": 65245, "s": 65056, "text": "SELECT customers.id \nAS customers_id, customers.name \nAS customers_name, customers.address \nAS customers_address, customers.email \nAS customers_email\nFROM customers\nWHERE customers.id != ?" }, { "code": null, "e": 65300, "s": 65245, "text": "The output for the above lines of code is as follows −" }, { "code": null, "e": 65524, "s": 65300, "text": "ID: 1 Name: Ravi Kumar Address: Station Road Nanded Email: ravi@gmail.com\nID: 3 Name: Rajender Nath Address: Sector 40, Gurgaon Email: nath@gmail.com\nID: 4 Name: S.M.Krishna Address: Budhwar Peth, Pune Email: smk@gmail.com\n" }, { "code": null, "e": 65615, "s": 65524, "text": "like() method itself produces the LIKE criteria for WHERE clause in the SELECT expression." }, { "code": null, "e": 65791, "s": 65615, "text": "result = session.query(Customers).filter(Customers.name.like('Ra%'))\nfor row in result:\n print (\"ID:\", row.id, \"Name: \",row.name, \"Address:\",row.address, \"Email:\",row.email)" }, { "code": null, "e": 65857, "s": 65791, "text": "Above SQLAlchemy code is equivalent to following SQL expression −" }, { "code": null, "e": 66050, "s": 65857, "text": "SELECT customers.id \nAS customers_id, customers.name \nAS customers_name, customers.address \nAS customers_address, customers.email \nAS customers_email\nFROM customers\nWHERE customers.name LIKE ?" }, { "code": null, "e": 66089, "s": 66050, "text": "And the output for the above code is −" }, { "code": null, "e": 66240, "s": 66089, "text": "ID: 1 Name: Ravi Kumar Address: Station Road Nanded Email: ravi@gmail.com\nID: 3 Name: Rajender Nath Address: Sector 40, Gurgaon Email: nath@gmail.com\n" }, { "code": null, "e": 66362, "s": 66240, "text": "This operator checks whether the column value belongs to a collection of items in a list. It is provided by in_() method." }, { "code": null, "e": 66535, "s": 66362, "text": "result = session.query(Customers).filter(Customers.id.in_([1,3]))\nfor row in result:\n print (\"ID:\", row.id, \"Name: \",row.name, \"Address:\",row.address, \"Email:\",row.email)" }, { "code": null, "e": 66608, "s": 66535, "text": "Here, the SQL expression evaluated by SQLite engine will be as follows −" }, { "code": null, "e": 66802, "s": 66608, "text": "SELECT customers.id \nAS customers_id, customers.name \nAS customers_name, customers.address \nAS customers_address, customers.email \nAS customers_email\nFROM customers\nWHERE customers.id IN (?, ?)" }, { "code": null, "e": 66848, "s": 66802, "text": "The output for the above code is as follows −" }, { "code": null, "e": 66999, "s": 66848, "text": "ID: 1 Name: Ravi Kumar Address: Station Road Nanded Email: ravi@gmail.com\nID: 3 Name: Rajender Nath Address: Sector 40, Gurgaon Email: nath@gmail.com\n" }, { "code": null, "e": 67136, "s": 66999, "text": "This conjunction is generated by either putting multiple commas separated criteria in the filter or using and_() method as given below −" }, { "code": null, "e": 67328, "s": 67136, "text": "result = session.query(Customers).filter(Customers.id>2, Customers.name.like('Ra%'))\nfor row in result:\n print (\"ID:\", row.id, \"Name: \",row.name, \"Address:\",row.address, \"Email:\",row.email)" }, { "code": null, "e": 67555, "s": 67328, "text": "from sqlalchemy import and_\nresult = session.query(Customers).filter(and_(Customers.id>2, Customers.name.like('Ra%')))\n\nfor row in result:\n print (\"ID:\", row.id, \"Name: \",row.name, \"Address:\",row.address, \"Email:\",row.email)" }, { "code": null, "e": 67616, "s": 67555, "text": "Both the above approaches result in similar SQL expression −" }, { "code": null, "e": 67830, "s": 67616, "text": "SELECT customers.id \nAS customers_id, customers.name \nAS customers_name, customers.address \nAS customers_address, customers.email \nAS customers_email\nFROM customers\nWHERE customers.id > ? AND customers.name LIKE ?" }, { "code": null, "e": 67874, "s": 67830, "text": "The output for the above lines of code is −" }, { "code": null, "e": 67951, "s": 67874, "text": "ID: 3 Name: Rajender Nath Address: Sector 40, Gurgaon Email: nath@gmail.com\n" }, { "code": null, "e": 68000, "s": 67951, "text": "This conjunction is implemented by or_() method." }, { "code": null, "e": 68225, "s": 68000, "text": "from sqlalchemy import or_\nresult = session.query(Customers).filter(or_(Customers.id>2, Customers.name.like('Ra%')))\n\nfor row in result:\n print (\"ID:\", row.id, \"Name: \",row.name, \"Address:\",row.address, \"Email:\",row.email)" }, { "code": null, "e": 68295, "s": 68225, "text": "As a result, SQLite engine gets following equivalent SQL expression −" }, { "code": null, "e": 68508, "s": 68295, "text": "SELECT customers.id \nAS customers_id, customers.name \nAS customers_name, customers.address \nAS customers_address, customers.email \nAS customers_email\nFROM customers\nWHERE customers.id > ? OR customers.name LIKE ?" }, { "code": null, "e": 68554, "s": 68508, "text": "The output for the above code is as follows −" }, { "code": null, "e": 68778, "s": 68554, "text": "ID: 1 Name: Ravi Kumar Address: Station Road Nanded Email: ravi@gmail.com\nID: 3 Name: Rajender Nath Address: Sector 40, Gurgaon Email: nath@gmail.com\nID: 4 Name: S.M.Krishna Address: Budhwar Peth, Pune Email: smk@gmail.com\n" }, { "code": null, "e": 68906, "s": 68778, "text": "There are a number of methods of Query object that immediately issue SQL and return a value containing loaded database results." }, { "code": null, "e": 68961, "s": 68906, "text": "Here’s a brief rundown of returning list and scalars −" }, { "code": null, "e": 69032, "s": 68961, "text": "It returns a list. Given below is the line of code for all() function." }, { "code": null, "e": 69063, "s": 69032, "text": "session.query(Customers).all()" }, { "code": null, "e": 69122, "s": 69063, "text": "Python console displays following SQL expression emitted −" }, { "code": null, "e": 69287, "s": 69122, "text": "SELECT customers.id \nAS customers_id, customers.name \nAS customers_name, customers.address \nAS customers_address, customers.email \nAS customers_email\nFROM customers" }, { "code": null, "e": 69355, "s": 69287, "text": "It applies a limit of one and returns the first result as a scalar." }, { "code": null, "e": 69537, "s": 69355, "text": "SELECT customers.id \nAS customers_id, customers.name \nAS customers_name, customers.address \nAS customers_address, customers.email \nAS customers_email\nFROM customers\nLIMIT ? OFFSET ?" }, { "code": null, "e": 69594, "s": 69537, "text": "The bound parameters for LIMIT is 1 and for OFFSET is 0." }, { "code": null, "e": 69739, "s": 69594, "text": "This command fully fetches all rows, and if there is not exactly one object identity or composite row present in the result, it raises an error." }, { "code": null, "e": 69770, "s": 69739, "text": "session.query(Customers).one()" }, { "code": null, "e": 69797, "s": 69770, "text": "With multiple rows found −" }, { "code": null, "e": 69854, "s": 69797, "text": "MultipleResultsFound: Multiple rows were found for one()" }, { "code": null, "e": 69875, "s": 69854, "text": "With no rows found −" }, { "code": null, "e": 69918, "s": 69875, "text": "NoResultFound: No row was found for one()\n" }, { "code": null, "e": 70039, "s": 69918, "text": "The one() method is useful for systems that expect to handle “no items found” versus “multiple items found” differently." }, { "code": null, "e": 70134, "s": 70039, "text": "It invokes the one() method, and upon success returns the first column of the row as follows −" }, { "code": null, "e": 70194, "s": 70134, "text": "session.query(Customers).filter(Customers.id == 3).scalar()" }, { "code": null, "e": 70235, "s": 70194, "text": "This generates following SQL statement −" }, { "code": null, "e": 70423, "s": 70235, "text": "SELECT customers.id \nAS customers_id, customers.name \nAS customers_name, customers.address \nAS customers_address, customers.email \nAS customers_email\nFROM customers\nWHERE customers.id = ?" }, { "code": null, "e": 70597, "s": 70423, "text": "Earlier, textual SQL using text() function has been explained from the perspective of core expression language of SQLAlchemy. Now we shall discuss it from ORM point of view." }, { "code": null, "e": 70776, "s": 70597, "text": "Literal strings can be used flexibly with Query object by specifying their use with the text() construct. Most applicable methods accept it. For example, filter() and order_by()." }, { "code": null, "e": 70871, "s": 70776, "text": "In the example given below, the filter() method translates the string “id<3” to the WHERE id<3" }, { "code": null, "e": 70978, "s": 70871, "text": "from sqlalchemy import text\nfor cust in session.query(Customers).filter(text(\"id<3\")):\n print(cust.name)" }, { "code": null, "e": 71088, "s": 70978, "text": "The raw SQL expression generated shows conversion of filter to WHERE clause with the code illustrated below −" }, { "code": null, "e": 71264, "s": 71088, "text": "SELECT customers.id \nAS customers_id, customers.name \nAS customers_name, customers.address \nAS customers_address, customers.email \nAS customers_email\nFROM customers\nWHERE id<3" }, { "code": null, "e": 71376, "s": 71264, "text": "From our sample data in Customers table, two rows will be selected and name column will be printed as follows −" }, { "code": null, "e": 71400, "s": 71376, "text": "Ravi Kumar\nKomal Pande\n" }, { "code": null, "e": 71514, "s": 71400, "text": "To specify bind parameters with string-based SQL, use a colon,and to specify the values, use the params() method." }, { "code": null, "e": 71598, "s": 71514, "text": "cust = session.query(Customers).filter(text(\"id = :value\")).params(value = 1).one()" }, { "code": null, "e": 71669, "s": 71598, "text": "The effective SQL displayed on Python console will be as given below −" }, { "code": null, "e": 71847, "s": 71669, "text": "SELECT customers.id \nAS customers_id, customers.name \nAS customers_name, customers.address \nAS customers_address, customers.email \nAS customers_email\nFROM customers\nWHERE id = ?" }, { "code": null, "e": 71978, "s": 71847, "text": "To use an entirely string-based statement, a text() construct representing a complete statement can be passed to from_statement()." }, { "code": null, "e": 72057, "s": 71978, "text": "session.query(Customers).from_statement(text(\"SELECT * FROM customers\")).all()" }, { "code": null, "e": 72132, "s": 72057, "text": "The result of above code will be a basic SELECT statement as given below −" }, { "code": null, "e": 72156, "s": 72132, "text": "SELECT * FROM customers" }, { "code": null, "e": 72216, "s": 72156, "text": "Obviously, all records in customers table will be selected." }, { "code": null, "e": 72436, "s": 72216, "text": "The text() construct allows us to link its textual SQL to Core or ORM-mapped column expressions positionally. We can achieve this by passing column expressions as positional arguments to the TextClause.columns() method." }, { "code": null, "e": 72625, "s": 72436, "text": "stmt = text(\"SELECT name, id, name, address, email FROM customers\")\nstmt = stmt.columns(Customers.id, Customers.name)\nsession.query(Customers.id, Customers.name).from_statement(stmt).all()" }, { "code": null, "e": 72799, "s": 72625, "text": "The id and name columns of all rows will be selected even though the SQLite engine executes following expression generated by above code shows all columns in text() method −" }, { "code": null, "e": 72852, "s": 72799, "text": "SELECT name, id, name, address, email FROM customers" }, { "code": null, "e": 73159, "s": 72852, "text": "This session describes creation of another table which is related to already existing one in our database. The customers table contains master data of customers. We now need to create invoices table which may have any number of invoices belonging to a customer. This is a case of one to many relationships." }, { "code": null, "e": 73254, "s": 73159, "text": "Using declarative, we define this table along with its mapped class, Invoices as given below −" }, { "code": null, "e": 74095, "s": 73254, "text": "from sqlalchemy import create_engine, ForeignKey, Column, Integer, String\nengine = create_engine('sqlite:///sales.db', echo = True)\nfrom sqlalchemy.ext.declarative import declarative_base\nBase = declarative_base()\nfrom sqlalchemy.orm import relationship\n\nclass Customer(Base):\n __tablename__ = 'customers'\n\n id = Column(Integer, primary_key = True)\n name = Column(String)\n address = Column(String)\n email = Column(String)\n\nclass Invoice(Base):\n __tablename__ = 'invoices'\n \n id = Column(Integer, primary_key = True)\n custid = Column(Integer, ForeignKey('customers.id'))\n invno = Column(Integer)\n amount = Column(Integer)\n customer = relationship(\"Customer\", back_populates = \"invoices\")\n\nCustomer.invoices = relationship(\"Invoice\", order_by = Invoice.id, back_populates = \"customer\")\nBase.metadata.create_all(engine)" }, { "code": null, "e": 74159, "s": 74095, "text": "This will send a CREATE TABLE query to SQLite engine as below −" }, { "code": null, "e": 74335, "s": 74159, "text": "CREATE TABLE invoices (\n id INTEGER NOT NULL,\n custid INTEGER,\n invno INTEGER,\n amount INTEGER,\n PRIMARY KEY (id),\n FOREIGN KEY(custid) REFERENCES customers (id)\n)" }, { "code": null, "e": 74422, "s": 74335, "text": "We can check that new table is created in sales.db with the help of SQLiteStudio tool." }, { "code": null, "e": 74770, "s": 74422, "text": "Invoices class applies ForeignKey construct on custid attribute. This directive indicates that values in this column should be constrained to be values present in id column in customers table. This is a core feature of relational databases, and is the “glue” that transforms unconnected collection of tables to have rich overlapping relationships." }, { "code": null, "e": 75083, "s": 74770, "text": "A second directive, known as relationship(), tells the ORM that the Invoice class should be linked to the Customer class using the attribute Invoice.customer. The relationship() uses the foreign key relationships between the two tables to determine the nature of this linkage, determining that it is many to one." }, { "code": null, "e": 75554, "s": 75083, "text": "An additional relationship() directive is placed on the Customer mapped class under the attribute Customer.invoices. The parameter relationship.back_populates is assigned to refer to the complementary attribute names, so that each relationship() can make intelligent decision about the same relationship as expressed in reverse. On one side, Invoices.customer refers to Invoices instance, and on the other side, Customer.invoices refers to a list of Customers instances." }, { "code": null, "e": 75762, "s": 75554, "text": "The relationship function is a part of Relationship API of SQLAlchemy ORM package. It provides a relationship between two mapped classes. This corresponds to a parent-child or associative table relationship." }, { "code": null, "e": 75816, "s": 75762, "text": "Following are the basic Relationship Patterns found −" }, { "code": null, "e": 76173, "s": 75816, "text": "A One to Many relationship refers to parent with the help of a foreign key on the child table. relationship() is then specified on the parent, as referencing a collection of items represented by the child. The relationship.back_populates parameter is used to establish a bidirectional relationship in one-to-many, where the “reverse” side is a many to one." }, { "code": null, "e": 76466, "s": 76173, "text": "On the other hand, Many to One relationship places a foreign key in the parent table to refer to the child. relationship() is declared on the parent, where a new scalar-holding attribute will be created. Here again the relationship.back_populates parameter is used for Bidirectionalbehaviour." }, { "code": null, "e": 76761, "s": 76466, "text": "One To One relationship is essentially a bidirectional relationship in nature. The uselist flag indicates the placement of a scalar attribute instead of a collection on the “many” side of the relationship. To convert one-to-many into one-to-one type of relation, set uselist parameter to false." }, { "code": null, "e": 77297, "s": 76761, "text": "Many to Many relationship is established by adding an association table related to two classes by defining attributes with their foreign keys. It is indicated by the secondary argument to relationship(). Usually, the Table uses the MetaData object associated with the declarative base class, so that the ForeignKey directives can locate the remote tables with which to link. The relationship.back_populates parameter for each relationship() establishes a bidirectional relationship. Both sides of the relationship contain a collection." }, { "code": null, "e": 77370, "s": 77297, "text": "In this chapter, we will focus on the related objects in SQLAlchemy ORM." }, { "code": null, "e": 77479, "s": 77370, "text": "Now when we create a Customer object, a blank invoice collection will be present in the form of Python List." }, { "code": null, "e": 77576, "s": 77479, "text": "c1 = Customer(name = \"Gopal Krishna\", address = \"Bank Street Hydarebad\", email = \"gk@gmail.com\")" }, { "code": null, "e": 77674, "s": 77576, "text": "The invoices attribute of c1.invoices will be an empty list. We can assign items in the list as −" }, { "code": null, "e": 77762, "s": 77674, "text": "c1.invoices = [Invoice(invno = 10, amount = 15000), Invoice(invno = 14, amount = 3850)]" }, { "code": null, "e": 77838, "s": 77762, "text": "Let us commit this object to the database using Session object as follows −" }, { "code": null, "e": 77969, "s": 77838, "text": "from sqlalchemy.orm import sessionmaker\nSession = sessionmaker(bind = engine)\nsession = Session()\nsession.add(c1)\nsession.commit()" }, { "code": null, "e": 78053, "s": 77969, "text": "This will automatically generate INSERT queries for customers and invoices tables −" }, { "code": null, "e": 78329, "s": 78053, "text": "INSERT INTO customers (name, address, email) VALUES (?, ?, ?) \n('Gopal Krishna', 'Bank Street Hydarebad', 'gk@gmail.com')\nINSERT INTO invoices (custid, invno, amount) VALUES (?, ?, ?)\n(2, 10, 15000)\nINSERT INTO invoices (custid, invno, amount) VALUES (?, ?, ?)\n(2, 14, 3850)\n" }, { "code": null, "e": 78431, "s": 78329, "text": "Let us now look at contents of customers table and invoices table in the table view of SQLiteStudio −" }, { "code": null, "e": 78562, "s": 78431, "text": "You can construct Customer object by providing mapped attribute of invoices in the constructor itself by using the below command −" }, { "code": null, "e": 78786, "s": 78562, "text": "c2 = [\n Customer(\n name = \"Govind Pant\", \n address = \"Gulmandi Aurangabad\",\n email = \"gpant@gmail.com\",\n invoices = [Invoice(invno = 3, amount = 10000), \n Invoice(invno = 4, amount = 5000)]\n )\n]" }, { "code": null, "e": 78879, "s": 78786, "text": "Or a list of objects to be added using add_all() function of session object as shown below −" }, { "code": null, "e": 79344, "s": 78879, "text": "rows = [\n Customer(\n name = \"Govind Kala\", \n address = \"Gulmandi Aurangabad\", \n email = \"kala@gmail.com\", \n invoices = [Invoice(invno = 7, amount = 12000), Invoice(invno = 8, amount = 18500)]),\n\n Customer(\n name = \"Abdul Rahman\", \n address = \"Rohtak\", \n email = \"abdulr@gmail.com\",\n invoices = [Invoice(invno = 9, amount = 15000), \n Invoice(invno = 11, amount = 6000)\n ])\n]\n\nsession.add_all(rows)\nsession.commit()" }, { "code": null, "e": 79651, "s": 79344, "text": "Now that we have two tables, we will see how to create queries on both tables at the same time. To construct a simple implicit join between Customer and Invoice, we can use Query.filter() to equate their related columns together. Below, we load the Customer and Invoice entities at once using this method −" }, { "code": null, "e": 79934, "s": 79651, "text": "from sqlalchemy.orm import sessionmaker\nSession = sessionmaker(bind = engine)\nsession = Session()\n\nfor c, i in session.query(Customer, Invoice).filter(Customer.id == Invoice.custid).all():\n print (\"ID: {} Name: {} Invoice No: {} Amount: {}\".format(c.id,c.name, i.invno, i.amount))" }, { "code": null, "e": 79991, "s": 79934, "text": "The SQL expression emitted by SQLAlchemy is as follows −" }, { "code": null, "e": 80341, "s": 79991, "text": "SELECT customers.id \nAS customers_id, customers.name \nAS customers_name, customers.address \nAS customers_address, customers.email \nAS customers_email, invoices.id \nAS invoices_id, invoices.custid \nAS invoices_custid, invoices.invno \nAS invoices_invno, invoices.amount \nAS invoices_amount\nFROM customers, invoices\nWHERE customers.id = invoices.custid" }, { "code": null, "e": 80399, "s": 80341, "text": "And the result of the above lines of code is as follows −" }, { "code": null, "e": 80821, "s": 80399, "text": "ID: 2 Name: Gopal Krishna Invoice No: 10 Amount: 15000\nID: 2 Name: Gopal Krishna Invoice No: 14 Amount: 3850\nID: 3 Name: Govind Pant Invoice No: 3 Amount: 10000\nID: 3 Name: Govind Pant Invoice No: 4 Amount: 5000\nID: 4 Name: Govind Kala Invoice No: 7 Amount: 12000\nID: 4 Name: Govind Kala Invoice No: 8 Amount: 8500\nID: 5 Name: Abdul Rahman Invoice No: 9 Amount: 15000\nID: 5 Name: Abdul Rahman Invoice No: 11 Amount: 6000\n" }, { "code": null, "e": 80910, "s": 80821, "text": "The actual SQL JOIN syntax is easily achieved using the Query.join() method as follows −" }, { "code": null, "e": 80985, "s": 80910, "text": "session.query(Customer).join(Invoice).filter(Invoice.amount == 8500).all()" }, { "code": null, "e": 81048, "s": 80985, "text": "The SQL expression for join will be displayed on the console −" }, { "code": null, "e": 81287, "s": 81048, "text": "SELECT customers.id \nAS customers_id, customers.name \nAS customers_name, customers.address \nAS customers_address, customers.email \nAS customers_email\nFROM customers JOIN invoices ON customers.id = invoices.custid\nWHERE invoices.amount = ?" }, { "code": null, "e": 81338, "s": 81287, "text": "We can iterate through the result using for loop −" }, { "code": null, "e": 81517, "s": 81338, "text": "result = session.query(Customer).join(Invoice).filter(Invoice.amount == 8500)\nfor row in result:\n for inv in row.invoices:\n print (row.id, row.name, inv.invno, inv.amount)" }, { "code": null, "e": 81582, "s": 81517, "text": "With 8500 as the bind parameter, following output is displayed −" }, { "code": null, "e": 81606, "s": 81582, "text": "4 Govind Kala 8 8500 \n" }, { "code": null, "e": 81831, "s": 81606, "text": "Query.join() knows how to join between these tables because there’s only one foreign key between them. If there were no foreign keys, or more foreign keys, Query.join() works better when one of the following forms are used −" }, { "code": null, "e": 81903, "s": 81831, "text": "Similarly outerjoin() function is available to achieve left outer join." }, { "code": null, "e": 81938, "s": 81903, "text": "query.outerjoin(Customer.invoices)" }, { "code": null, "e": 82042, "s": 81938, "text": "The subquery() method produces a SQL expression representing SELECT statement embedded within an alias." }, { "code": null, "e": 82193, "s": 82042, "text": "from sqlalchemy.sql import func\n\nstmt = session.query(\n Invoice.custid, func.count('*').label('invoice_count')\n).group_by(Invoice.custid).subquery()" }, { "code": null, "e": 82249, "s": 82193, "text": "The stmt object will contain a SQL statement as below −" }, { "code": null, "e": 82345, "s": 82249, "text": "SELECT invoices.custid, count(:count_1) AS invoice_count FROM invoices GROUP BY invoices.custid" }, { "code": null, "e": 82511, "s": 82345, "text": "Once we have our statement, it behaves like a Table construct. The columns on the statement are accessible through an attribute called c as shown in the below code −" }, { "code": null, "e": 82666, "s": 82511, "text": "for u, count in session.query(Customer, stmt.c.invoice_count).outerjoin(stmt, Customer.id == stmt.c.custid).order_by(Customer.id):\n print(u.name, count)" }, { "code": null, "e": 82735, "s": 82666, "text": "The above for loop displays name-wise count of invoices as follows −" }, { "code": null, "e": 82813, "s": 82735, "text": "Arjun Pandit None\nGopal Krishna 2\nGovind Pant 2\nGovind Kala 2\nAbdul Rahman 2\n" }, { "code": null, "e": 82896, "s": 82813, "text": "In this chapter, we will discuss about the operators which build on relationships." }, { "code": null, "e": 83008, "s": 82896, "text": "The above operator is a many-to-one “equals” comparison. The line of code for this operator is as shown below −" }, { "code": null, "e": 83069, "s": 83008, "text": "s = session.query(Customer).filter(Invoice.invno.__eq__(12))" }, { "code": null, "e": 83126, "s": 83069, "text": "The equivalent SQL query for the above line of code is −" }, { "code": null, "e": 83326, "s": 83126, "text": "SELECT customers.id \nAS customers_id, customers.name \nAS customers_name, customers.address \nAS customers_address, customers.email \nAS customers_email\nFROM customers, invoices\nWHERE invoices.invno = ?" }, { "code": null, "e": 83437, "s": 83326, "text": "This operator is a many-to-one “not equals” comparison. The line of code for this operator is as shown below −" }, { "code": null, "e": 83498, "s": 83437, "text": "s = session.query(Customer).filter(Invoice.custid.__ne__(2))" }, { "code": null, "e": 83567, "s": 83498, "text": "The equivalent SQL query for the above line of code is given below −" }, { "code": null, "e": 83769, "s": 83567, "text": "SELECT customers.id \nAS customers_id, customers.name \nAS customers_name, customers.address \nAS customers_address, customers.email \nAS customers_email\nFROM customers, invoices\nWHERE invoices.custid != ?" }, { "code": null, "e": 83864, "s": 83769, "text": "This operator is used for one-to-many collections and given below is the code for contains() −" }, { "code": null, "e": 83931, "s": 83864, "text": "s = session.query(Invoice).filter(Invoice.invno.contains([3,4,5]))" }, { "code": null, "e": 83988, "s": 83931, "text": "The equivalent SQL query for the above line of code is −" }, { "code": null, "e": 84189, "s": 83988, "text": "SELECT invoices.id \nAS invoices_id, invoices.custid \nAS invoices_custid, invoices.invno \nAS invoices_invno, invoices.amount \nAS invoices_amount\nFROM invoices\nWHERE (invoices.invno LIKE '%' + ? || '%')" }, { "code": null, "e": 84245, "s": 84189, "text": "any() operator is used for collections as shown below −" }, { "code": null, "e": 84322, "s": 84245, "text": "s = session.query(Customer).filter(Customer.invoices.any(Invoice.invno==11))" }, { "code": null, "e": 84391, "s": 84322, "text": "The equivalent SQL query for the above line of code is shown below −" }, { "code": null, "e": 84668, "s": 84391, "text": "SELECT customers.id \nAS customers_id, customers.name \nAS customers_name, customers.address \nAS customers_address, customers.email \nAS customers_email\nFROM customers\nWHERE EXISTS (\n SELECT 1\n FROM invoices\n WHERE customers.id = invoices.custid \n AND invoices.invno = ?)" }, { "code": null, "e": 84725, "s": 84668, "text": "This operator is used for scalar references as follows −" }, { "code": null, "e": 84804, "s": 84725, "text": "s = session.query(Invoice).filter(Invoice.customer.has(name = 'Arjun Pandit'))" }, { "code": null, "e": 84861, "s": 84804, "text": "The equivalent SQL query for the above line of code is −" }, { "code": null, "e": 85132, "s": 84861, "text": "SELECT invoices.id \nAS invoices_id, invoices.custid \nAS invoices_custid, invoices.invno \nAS invoices_invno, invoices.amount \nAS invoices_amount\nFROM invoices\nWHERE EXISTS (\n SELECT 1\n FROM customers\n WHERE customers.id = invoices.custid \n AND customers.name = ?)" }, { "code": null, "e": 85378, "s": 85132, "text": "Eager load reduces the number of queries. SQLAlchemy offers eager loading functions invoked via query options which give additional instructions to the Query. These options determine how to load various attributes via the Query.options() method." }, { "code": null, "e": 85731, "s": 85378, "text": "We want that Customer.invoices should load eagerly. The orm.subqueryload() option gives a second SELECT statement that fully loads the collections associated with the results just loaded. The name “subquery” causes the SELECT statement to be constructed directly via the Query re-used and embedded as a subquery into a SELECT against the related table." }, { "code": null, "e": 85879, "s": 85731, "text": "from sqlalchemy.orm import subqueryload\nc1 = session.query(Customer).options(subqueryload(Customer.invoices)).filter_by(name = 'Govind Pant').one()" }, { "code": null, "e": 85931, "s": 85879, "text": "This results in the following two SQL expressions −" }, { "code": null, "e": 86617, "s": 85931, "text": "SELECT customers.id \nAS customers_id, customers.name \nAS customers_name, customers.address \nAS customers_address, customers.email \nAS customers_email\nFROM customers\nWHERE customers.name = ?\n('Govind Pant',)\n\nSELECT invoices.id \nAS invoices_id, invoices.custid \nAS invoices_custid, invoices.invno \nAS invoices_invno, invoices.amount \nAS invoices_amount, anon_1.customers_id \nAS anon_1_customers_id\nFROM (\n SELECT customers.id \n AS customers_id\n FROM customers\n WHERE customers.name = ?) \n \nAS anon_1 \nJOIN invoices \nON anon_1.customers_id = invoices.custid \nORDER BY anon_1.customers_id, invoices.id 2018-06-25 18:24:47,479 \nINFO sqlalchemy.engine.base.Engine ('Govind Pant',)" }, { "code": null, "e": 86684, "s": 86617, "text": "To access the data from two tables, we can use the below program −" }, { "code": null, "e": 86813, "s": 86684, "text": "print (c1.name, c1.address, c1.email)\n\nfor x in c1.invoices:\n print (\"Invoice no : {}, Amount : {}\".format(x.invno, x.amount))" }, { "code": null, "e": 86861, "s": 86813, "text": "The output of the above program is as follows −" }, { "code": null, "e": 86971, "s": 86861, "text": "Govind Pant Gulmandi Aurangabad gpant@gmail.com\nInvoice no : 3, Amount : 10000\nInvoice no : 4, Amount : 5000\n" }, { "code": null, "e": 87127, "s": 86971, "text": "The other function is called orm.joinedload(). This emits a LEFT OUTER JOIN. Lead object as well as the related object or collection is loaded in one step." }, { "code": null, "e": 87269, "s": 87127, "text": "from sqlalchemy.orm import joinedload\nc1 = session.query(Customer).options(joinedload(Customer.invoices)).filter_by(name='Govind Pant').one()" }, { "code": null, "e": 87331, "s": 87269, "text": "This emits following expression giving same output as above −" }, { "code": null, "e": 87795, "s": 87331, "text": "SELECT customers.id \nAS customers_id, customers.name \nAS customers_name, customers.address \nAS customers_address, customers.email \nAS customers_email, invoices_1.id \nAS invoices_1_id, invoices_1.custid \nAS invoices_1_custid, invoices_1.invno \nAS invoices_1_invno, invoices_1.amount \nAS invoices_1_amount\n\nFROM customers \nLEFT OUTER JOIN invoices \nAS invoices_1 \nON customers.id = invoices_1.custid\n\nWHERE customers.name = ? ORDER BY invoices_1.id\n('Govind Pant',)" }, { "code": null, "e": 88054, "s": 87795, "text": "The OUTER JOIN resulted in two rows, but it gives one instance of Customer back. This is because Query applies a “uniquing” strategy, based on object identity, to the returned entities. Joined eager loading can be applied without affecting the query results." }, { "code": null, "e": 88191, "s": 88054, "text": "The subqueryload() is more appropriate for loading related collections while joinedload() is better suited for many-to-one relationship." }, { "code": null, "e": 88420, "s": 88191, "text": "It is easy to perform delete operation on a single table. All you have to do is to delete an object of the mapped class from a session and commit the action. However, delete operation on multiple related tables is little tricky." }, { "code": null, "e": 88613, "s": 88420, "text": "In our sales.db database, Customer and Invoice classes are mapped to customer and invoice table with one to many type of relationship. We will try to delete Customer object and see the result." }, { "code": null, "e": 88695, "s": 88613, "text": "As a quick reference, below are the definitions of Customer and Invoice classes −" }, { "code": null, "e": 89505, "s": 88695, "text": "from sqlalchemy import create_engine, ForeignKey, Column, Integer, String\nengine = create_engine('sqlite:///sales.db', echo = True)\nfrom sqlalchemy.ext.declarative import declarative_base\nBase = declarative_base()\nfrom sqlalchemy.orm import relationship\nclass Customer(Base):\n __tablename__ = 'customers'\n\n id = Column(Integer, primary_key = True)\n name = Column(String)\n address = Column(String)\n email = Column(String)\n \nclass Invoice(Base):\n __tablename__ = 'invoices'\n\n id = Column(Integer, primary_key = True)\n custid = Column(Integer, ForeignKey('customers.id'))\n invno = Column(Integer)\n amount = Column(Integer)\n customer = relationship(\"Customer\", back_populates = \"invoices\")\n \nCustomer.invoices = relationship(\"Invoice\", order_by = Invoice.id, back_populates = \"customer\")" }, { "code": null, "e": 89610, "s": 89505, "text": "We setup a session and obtain a Customer object by querying it with primary ID using the below program −" }, { "code": null, "e": 89741, "s": 89610, "text": "from sqlalchemy.orm import sessionmaker\nSession = sessionmaker(bind=engine)\nsession = Session()\nx = session.query(Customer).get(2)" }, { "code": null, "e": 89877, "s": 89741, "text": "In our sample table, x.name happens to be 'Gopal Krishna'. Let us delete this x from the session and count the occurrence of this name." }, { "code": null, "e": 89961, "s": 89877, "text": "session.delete(x)\nsession.query(Customer).filter_by(name = 'Gopal Krishna').count()" }, { "code": null, "e": 90005, "s": 89961, "text": "The resulting SQL expression will return 0." }, { "code": null, "e": 90283, "s": 90005, "text": "SELECT count(*) \nAS count_1\nFROM (\n SELECT customers.id \n AS customers_id, customers.name \n AS customers_name, customers.address \n AS customers_address, customers.email \n AS customers_email\n FROM customers\n WHERE customers.name = ?) \nAS anon_1('Gopal Krishna',) 0" }, { "code": null, "e": 90385, "s": 90283, "text": "However, the related Invoice objects of x are still there. It can be verified by the following code −" }, { "code": null, "e": 90451, "s": 90385, "text": "session.query(Invoice).filter(Invoice.invno.in_([10,14])).count()" }, { "code": null, "e": 90611, "s": 90451, "text": "Here, 10 and 14 are invoice numbers belonging to customer Gopal Krishna. Result of the above query is 2, which means the related objects have not been deleted." }, { "code": null, "e": 90878, "s": 90611, "text": "SELECT count(*) \nAS count_1\nFROM (\n SELECT invoices.id \n AS invoices_id, invoices.custid \n AS invoices_custid, invoices.invno \n AS invoices_invno, invoices.amount \n AS invoices_amount\n FROM invoices\n WHERE invoices.invno IN (?, ?)) \nAS anon_1(10, 14) 2" }, { "code": null, "e": 90985, "s": 90878, "text": "This is because SQLAlchemy doesn’t assume the deletion of cascade; we have to give a command to delete it." }, { "code": null, "e": 91239, "s": 90985, "text": "To change the behavior, we configure cascade options on the User.addresses relationship. Let us close the ongoing session, use new declarative_base() and redeclare the User class, adding in the addresses relationship including the cascade configuration." }, { "code": null, "e": 91482, "s": 91239, "text": "The cascade attribute in relationship function is a comma-separated list of cascade rules which determines how Session operations should be “cascaded” from parent to child. By default, it is False, which means that it is \"save-update, merge\"." }, { "code": null, "e": 91522, "s": 91482, "text": "The available cascades are as follows −" }, { "code": null, "e": 91534, "s": 91522, "text": "save-update" }, { "code": null, "e": 91540, "s": 91534, "text": "merge" }, { "code": null, "e": 91548, "s": 91540, "text": "expunge" }, { "code": null, "e": 91555, "s": 91548, "text": "delete" }, { "code": null, "e": 91569, "s": 91555, "text": "delete-orphan" }, { "code": null, "e": 91584, "s": 91569, "text": "refresh-expire" }, { "code": null, "e": 91751, "s": 91584, "text": "Often used option is \"all, delete-orphan\" to indicate that related objects should follow along with the parent object in all cases, and be deleted when de-associated." }, { "code": null, "e": 91800, "s": 91751, "text": "Hence redeclared Customer class is shown below −" }, { "code": null, "e": 92154, "s": 91800, "text": "class Customer(Base): \n __tablename__ = 'customers'\n \n id = Column(Integer, primary_key = True) \n name = Column(String) \n address = Column(String) \n email = Column(String) \n invoices = relationship(\n \"Invoice\", \n order_by = Invoice.id, \n back_populates = \"customer\",\n cascade = \"all, \n delete, delete-orphan\" \n )" }, { "code": null, "e": 92280, "s": 92154, "text": "Let us delete the Customer with Gopal Krishna name using the below program and see the count of its related Invoice objects −" }, { "code": null, "e": 92563, "s": 92280, "text": "from sqlalchemy.orm import sessionmaker\nSession = sessionmaker(bind = engine)\nsession = Session()\nx = session.query(Customer).get(2)\nsession.delete(x)\nsession.query(Customer).filter_by(name = 'Gopal Krishna').count()\nsession.query(Invoice).filter(Invoice.invno.in_([10,14])).count()" }, { "code": null, "e": 92627, "s": 92563, "text": "The count is now 0 with following SQL emitted by above script −" }, { "code": null, "e": 93681, "s": 92627, "text": "SELECT customers.id \nAS customers_id, customers.name \nAS customers_name, customers.address \nAS customers_address, customers.email \nAS customers_email\nFROM customers\nWHERE customers.id = ?\n(2,)\nSELECT invoices.id \nAS invoices_id, invoices.custid \nAS invoices_custid, invoices.invno \nAS invoices_invno, invoices.amount\nAS invoices_amount\nFROM invoices\nWHERE ? = invoices.custid \nORDER BY invoices.id (2,)\nDELETE FROM invoices \nWHERE invoices.id = ? ((1,), (2,))\nDELETE FROM customers \nWHERE customers.id = ? (2,)\nSELECT count(*) \nAS count_1\nFROM (\n SELECT customers.id \n AS customers_id, customers.name \n AS customers_name, customers.address \n AS customers_address, customers.email \n AS customers_email\n FROM customers\n WHERE customers.name = ?) \nAS anon_1('Gopal Krishna',)\nSELECT count(*) \nAS count_1\nFROM (\n SELECT invoices.id \n AS invoices_id, invoices.custid \n AS invoices_custid, invoices.invno \n AS invoices_invno, invoices.amount \n AS invoices_amount\n FROM invoices\n WHERE invoices.invno IN (?, ?)) \nAS anon_1(10, 14)\n0" }, { "code": null, "e": 94019, "s": 93681, "text": "Many to Many relationship between two tables is achieved by adding an association table such that it has two foreign keys - one from each table’s primary key. Moreover, classes mapping to the two tables have an attribute with a collection of objects of other association tables assigned as secondary attribute of relationship() function." }, { "code": null, "e": 94290, "s": 94019, "text": "For this purpose, we shall create a SQLite database (mycollege.db) with two tables - department and employee. Here, we assume that an employee is a part of more than one department, and a department has more than one employee. This constitutes many-to-many relationship." }, { "code": null, "e": 94392, "s": 94290, "text": "Definition of Employee and Department classes mapped to department and employee table is as follows −" }, { "code": null, "e": 95020, "s": 94392, "text": "from sqlalchemy import create_engine, ForeignKey, Column, Integer, String\nengine = create_engine('sqlite:///mycollege.db', echo = True)\nfrom sqlalchemy.ext.declarative import declarative_base\nBase = declarative_base()\nfrom sqlalchemy.orm import relationship\n\nclass Department(Base):\n __tablename__ = 'department'\n id = Column(Integer, primary_key = True)\n name = Column(String)\n employees = relationship('Employee', secondary = 'link')\n \nclass Employee(Base):\n __tablename__ = 'employee'\n id = Column(Integer, primary_key = True)\n name = Column(String)\n departments = relationship(Department,secondary='link')" }, { "code": null, "e": 95204, "s": 95020, "text": "We now define a Link class. It is linked to link table and contains department_id and employee_id attributes respectively referencing to primary keys of department and employee table." }, { "code": null, "e": 95443, "s": 95204, "text": "class Link(Base):\n __tablename__ = 'link'\n department_id = Column(\n Integer, \n ForeignKey('department.id'), \n primary_key = True)\n\nemployee_id = Column(\n Integer, \n ForeignKey('employee.id'), \n primary_key = True)" }, { "code": null, "e": 95626, "s": 95443, "text": "Here, we have to make a note that Department class has employees attribute related to Employee class. The relationship function’s secondary attribute is assigned a link as its value." }, { "code": null, "e": 95788, "s": 95626, "text": "Similarly, Employee class has departments attribute related to Department class. The relationship function’s secondary attribute is assigned a link as its value." }, { "code": null, "e": 95866, "s": 95788, "text": "All these three tables are created when the following statement is executed −" }, { "code": null, "e": 95899, "s": 95866, "text": "Base.metadata.create_all(engine)" }, { "code": null, "e": 95957, "s": 95899, "text": "The Python console emits following CREATE TABLE queries −" }, { "code": null, "e": 96381, "s": 95957, "text": "CREATE TABLE department (\n id INTEGER NOT NULL,\n name VARCHAR,\n PRIMARY KEY (id)\n)\n\nCREATE TABLE employee (\n id INTEGER NOT NULL,\n name VARCHAR,\n PRIMARY KEY (id)\n)\n\nCREATE TABLE link (\n department_id INTEGER NOT NULL,\n employee_id INTEGER NOT NULL,\n PRIMARY KEY (department_id, employee_id),\n FOREIGN KEY(department_id) REFERENCES department (id),\n FOREIGN KEY(employee_id) REFERENCES employee (id)\n)" }, { "code": null, "e": 96484, "s": 96381, "text": "We can check this by opening mycollege.db using SQLiteStudio as shown in the screenshots given below −" }, { "code": null, "e": 96586, "s": 96484, "text": "Next we create three objects of Department class and three objects of Employee class as shown below −" }, { "code": null, "e": 96779, "s": 96586, "text": "d1 = Department(name = \"Accounts\")\nd2 = Department(name = \"Sales\")\nd3 = Department(name = \"Marketing\")\n\ne1 = Employee(name = \"John\")\ne2 = Employee(name = \"Tony\")\ne3 = Employee(name = \"Graham\")" }, { "code": null, "e": 97013, "s": 96779, "text": "Each table has a collection attribute having append() method. We can add Employee objects to Employees collection of Department object. Similarly, we can add Department objects to departments collection attribute of Employee objects." }, { "code": null, "e": 97163, "s": 97013, "text": "e1.departments.append(d1)\ne2.departments.append(d3)\nd1.employees.append(e3)\nd2.employees.append(e2)\nd3.employees.append(e1)\ne3.departments.append(d2)" }, { "code": null, "e": 97278, "s": 97163, "text": "All we have to do now is to set up a session object, add all objects to it and commit the changes as shown below −" }, { "code": null, "e": 97489, "s": 97278, "text": "from sqlalchemy.orm import sessionmaker\nSession = sessionmaker(bind = engine)\nsession = Session()\nsession.add(e1)\nsession.add(e2)\nsession.add(d1)\nsession.add(d2)\nsession.add(d3)\nsession.add(e3)\nsession.commit()" }, { "code": null, "e": 97550, "s": 97489, "text": "Following SQL statements will be emitted on Python console −" }, { "code": null, "e": 98032, "s": 97550, "text": "INSERT INTO department (name) VALUES (?) ('Accounts',)\nINSERT INTO department (name) VALUES (?) ('Sales',)\nINSERT INTO department (name) VALUES (?) ('Marketing',)\nINSERT INTO employee (name) VALUES (?) ('John',)\nINSERT INTO employee (name) VALUES (?) ('Graham',)\nINSERT INTO employee (name) VALUES (?) ('Tony',)\nINSERT INTO link (department_id, employee_id) VALUES (?, ?) ((1, 2), (3, 1), (2, 3))\nINSERT INTO link (department_id, employee_id) VALUES (?, ?) ((1, 1), (2, 2), (3, 3))" }, { "code": null, "e": 98146, "s": 98032, "text": "To check the effect of above operations, use SQLiteStudio and view data in department, employee and link tables −" }, { "code": null, "e": 98203, "s": 98146, "text": "To display the data, run the following query statement −" }, { "code": null, "e": 98545, "s": 98203, "text": "from sqlalchemy.orm import sessionmaker\nSession = sessionmaker(bind = engine)\nsession = Session()\n\nfor x in session.query( Department, Employee).filter(Link.department_id == Department.id, \n Link.employee_id == Employee.id).order_by(Link.department_id).all():\n print (\"Department: {} Name: {}\".format(x.Department.name, x.Employee.name))" }, { "code": null, "e": 98623, "s": 98545, "text": "As per the data populated in our example, output will be displayed as below −" }, { "code": null, "e": 98816, "s": 98623, "text": "Department: Accounts Name: John\nDepartment: Accounts Name: Graham\nDepartment: Sales Name: Graham\nDepartment: Sales Name: Tony\nDepartment: Marketing Name: John\nDepartment: Marketing Name: Tony\n" }, { "code": null, "e": 99016, "s": 98816, "text": "SQLAlchemy uses system of dialects to communicate with various types of databases. Each database has a corresponding DBAPI wrapper. All dialects require that an appropriate DBAPI driver is installed." }, { "code": null, "e": 99068, "s": 99016, "text": "Following dialects are included in SQLAlchemy API −" }, { "code": null, "e": 99077, "s": 99068, "text": "Firebird" }, { "code": null, "e": 99098, "s": 99077, "text": "Microsoft SQL Server" }, { "code": null, "e": 99104, "s": 99098, "text": "MySQL" }, { "code": null, "e": 99111, "s": 99104, "text": "Oracle" }, { "code": null, "e": 99122, "s": 99111, "text": "PostgreSQL" }, { "code": null, "e": 99126, "s": 99122, "text": "SQL" }, { "code": null, "e": 99133, "s": 99126, "text": "Sybase" }, { "code": null, "e": 99520, "s": 99133, "text": "An Engine object based on a URL is produced by create_engine() function. These URLs can include username, password, hostname, and database name. There may be optional keyword arguments for additional configuration. In some cases, a file path is accepted, and in others, a “data source name” replaces the “host” and “database” portions. The typical form of a database URL is as follows −" }, { "code": null, "e": 99575, "s": 99520, "text": "dialect+driver://username:password@host:port/database\n" }, { "code": null, "e": 99703, "s": 99575, "text": "The PostgreSQL dialect uses psycopg2 as the default DBAPI. pg8000 is also available as a pure-Python substitute as shown below:" }, { "code": null, "e": 99967, "s": 99703, "text": "# default\nengine = create_engine('postgresql://scott:tiger@localhost/mydatabase')\n\n# psycopg2\nengine = create_engine('postgresql+psycopg2://scott:tiger@localhost/mydatabase')\n\n# pg8000\nengine = create_engine('postgresql+pg8000://scott:tiger@localhost/mydatabase')" }, { "code": null, "e": 100108, "s": 99967, "text": "The MySQL dialect uses mysql-python as the default DBAPI. There are many MySQL DBAPIs available, such as MySQL-connector-python as follows −" }, { "code": null, "e": 100363, "s": 100108, "text": "# default\nengine = create_engine('mysql://scott:tiger@localhost/foo')\n\n# mysql-python\nengine = create_engine('mysql+mysqldb://scott:tiger@localhost/foo')\n\n# MySQL-connector-python\nengine = create_engine('mysql+mysqlconnector://scott:tiger@localhost/foo')" }, { "code": null, "e": 100431, "s": 100363, "text": "The Oracle dialect uses cx_oracle as the default DBAPI as follows −" }, { "code": null, "e": 100566, "s": 100431, "text": "engine = create_engine('oracle://scott:tiger@127.0.0.1:1521/sidname')\nengine = create_engine('oracle+cx_oracle://scott:tiger@tnsname')" }, { "code": null, "e": 100650, "s": 100566, "text": "The SQL Server dialect uses pyodbc as the default DBAPI. pymssql is also available." }, { "code": null, "e": 100804, "s": 100650, "text": "# pyodbc\nengine = create_engine('mssql+pyodbc://scott:tiger@mydsn')\n\n# pymssql\nengine = create_engine('mssql+pymssql://scott:tiger@hostname:port/dbname')" }, { "code": null, "e": 101105, "s": 100804, "text": "SQLite connects to file-based databases, using the Python built-in module sqlite3 by default. As SQLite connects to local files, the URL format is slightly different. The “file” portion of the URL is the filename of the database. For a relative file path, this requires three slashes as shown below −" }, { "code": null, "e": 101148, "s": 101105, "text": "engine = create_engine('sqlite:///foo.db')" }, { "code": null, "e": 101248, "s": 101148, "text": "And for an absolute file path, the three slashes are followed by the absolute path as given below −" }, { "code": null, "e": 101305, "s": 101248, "text": "engine = create_engine('sqlite:///C:\\\\path\\\\to\\\\foo.db')" }, { "code": null, "e": 101376, "s": 101305, "text": "To use a SQLite:memory:database, specify an empty URL as given below −" }, { "code": null, "e": 101412, "s": 101376, "text": "engine = create_engine('sqlite://')" }, { "code": null, "e": 101724, "s": 101412, "text": "In the first part of this tutorial, we have learnt how to use the Expression Language to execute SQL statements. Expression language embeds SQL constructs in Python code. In the second part, we have discussed object relation mapping capability of SQLAlchemy. The ORM API maps the SQL tables with Python classes." }, { "code": null, "e": 101759, "s": 101724, "text": "\n 21 Lectures \n 1.5 hours \n" }, { "code": null, "e": 101770, "s": 101759, "text": " Jack Chan" }, { "code": null, "e": 101777, "s": 101770, "text": " Print" }, { "code": null, "e": 101788, "s": 101777, "text": " Add Notes" } ]
Accenture Interview Experience (On-Campus) - GeeksforGeeks
27 Nov, 2020 I recently appeared for the Accenture recruitment process. They were offering 2 profile roles: Associate Software Engineer.Software Engineer/Full Stack Engineer. Associate Software Engineer. Software Engineer/Full Stack Engineer. This was a Pool Campus Recruitment process. Additional Requirements along with academic eligibility: PAN Card – all students must submit a PAN card that has their photo as the only identity proof mandatorily during the registration process. No minor PAN cards will be entertained. If provided, candidate will be rejected from the process Due to the lockdown and the slow movement of the PAN Card application process, Accenture even allowed those students who didn’t have a PAN Card. Either of driver’s license, Aadhaar card, minor PAN card, or a voter ID was required for such students. 1st round: Cognitive and Technical Assessment Round: This round was an elimination round. In this round, there were some sections Cognitive: Quantitative Aptitude, Reasoning and Verbal ability Technical: MS Office and Common applications, Pseudocode outputs, and Fundamentals of Cloud and Network security. This round contained 90 questions that have to be solved in 90 minutes. To qualify for the next round, marks above the overall cutoff should be obtained. A sectional cutoff was also there which was required to be cleared. After clearing this round, there was a coding round, which was a non-elimination round and it was a compulsory round. 2nd round: Coding Assessment: This round was compulsory and no student could back off from here. This round was a non-elimination round. And 2 coding questions were given which have to be solved in 45 minutes. Function accepts an array of size m and integer n. Implement the function to create a n*n matrix (n*n=m) and fill the matrix in spiral order starting from matrix[0][0] in a clockwise direction. Visit https://www.geeksforgeeks.org/form-a-spiral-matrix-from-the-given-array/ to check the solution.The function accepts 2 positive integers ‘a’ and ‘n’ as input. ‘a’ is the first element of the collatz sequence. Implement the function to find the nth term of the sequence and return it. First-term P1=a, and each successive term Pk+1 was calculated as:If Pk is even , Pk+1 = Pk / 2 If Pk is odd, Pk+1=( 3 * Pk )+1 Function accepts an array of size m and integer n. Implement the function to create a n*n matrix (n*n=m) and fill the matrix in spiral order starting from matrix[0][0] in a clockwise direction. Visit https://www.geeksforgeeks.org/form-a-spiral-matrix-from-the-given-array/ to check the solution. The function accepts 2 positive integers ‘a’ and ‘n’ as input. ‘a’ is the first element of the collatz sequence. Implement the function to find the nth term of the sequence and return it. First-term P1=a, and each successive term Pk+1 was calculated as:If Pk is even , Pk+1 = Pk / 2 If Pk is odd, Pk+1=( 3 * Pk )+1 If Pk is even , Pk+1 = Pk / 2 If Pk is odd, Pk+1=( 3 * Pk )+1 After this round, everyone was called for a communication test. 3rd round: Communication Assessment: Again this round was a non-elimination round. And this test consists of some sections and was of around 17 minutes. Tests included sections like reading, listening and repeating it, arranging jumbled words in a proper sequence, etc. Just be sure that you don’t talk too fast. 4th round: Virtual Interview: This round was an elimination round, had 2-panel members. One was an HR and the other was a guy from a technical background who was asking tech-related questions. HR guy asked me to introduce myself and how I feel about working in a team, the pros and cons of working in a team and I had done any courses or projects related to tech background. The tech guy was asking project-related questions stated on the resume; so make sure you’ve covered everything on the resume properly. After a few days, I got a mail from Accenture that I was selected for the Software Engineer role. Thanks to GFG for providing archives and helping me! Accenture Marketing On-Campus Interview Experiences Accenture Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE-1 (On-Campus) Microsoft Interview Experience for Internship (Via Engage) Amazon Interview Experience Zoho Interview | Set 3 (Off-Campus) Amazon Interview Experience for SDE-1 Difference between ANN, CNN and RNN Amazon Interview Experience (Off-Campus) 2022 Amazon Interview Experience for SDE-1(Off-Campus) Amazon Interview Experience for SDE-1 Amazon Interview Experience for SDE1 (8 Months Experienced) 2022
[ { "code": null, "e": 25214, "s": 25186, "text": "\n27 Nov, 2020" }, { "code": null, "e": 25309, "s": 25214, "text": "I recently appeared for the Accenture recruitment process. They were offering 2 profile roles:" }, { "code": null, "e": 25376, "s": 25309, "text": "Associate Software Engineer.Software Engineer/Full Stack Engineer." }, { "code": null, "e": 25405, "s": 25376, "text": "Associate Software Engineer." }, { "code": null, "e": 25444, "s": 25405, "text": "Software Engineer/Full Stack Engineer." }, { "code": null, "e": 25488, "s": 25444, "text": "This was a Pool Campus Recruitment process." }, { "code": null, "e": 25545, "s": 25488, "text": "Additional Requirements along with academic eligibility:" }, { "code": null, "e": 25685, "s": 25545, "text": "PAN Card – all students must submit a PAN card that has their photo as the only identity proof mandatorily during the registration process." }, { "code": null, "e": 25782, "s": 25685, "text": "No minor PAN cards will be entertained. If provided, candidate will be rejected from the process" }, { "code": null, "e": 26031, "s": 25782, "text": "Due to the lockdown and the slow movement of the PAN Card application process, Accenture even allowed those students who didn’t have a PAN Card. Either of driver’s license, Aadhaar card, minor PAN card, or a voter ID was required for such students." }, { "code": null, "e": 26161, "s": 26031, "text": "1st round: Cognitive and Technical Assessment Round: This round was an elimination round. In this round, there were some sections" }, { "code": null, "e": 26226, "s": 26161, "text": "Cognitive: Quantitative Aptitude, Reasoning and Verbal ability " }, { "code": null, "e": 26340, "s": 26226, "text": "Technical: MS Office and Common applications, Pseudocode outputs, and Fundamentals of Cloud and Network security." }, { "code": null, "e": 26413, "s": 26340, "text": "This round contained 90 questions that have to be solved in 90 minutes. " }, { "code": null, "e": 26563, "s": 26413, "text": "To qualify for the next round, marks above the overall cutoff should be obtained. A sectional cutoff was also there which was required to be cleared." }, { "code": null, "e": 26681, "s": 26563, "text": "After clearing this round, there was a coding round, which was a non-elimination round and it was a compulsory round." }, { "code": null, "e": 26893, "s": 26681, "text": "2nd round: Coding Assessment: This round was compulsory and no student could back off from here. This round was a non-elimination round. And 2 coding questions were given which have to be solved in 45 minutes. " }, { "code": null, "e": 27503, "s": 26893, "text": "Function accepts an array of size m and integer n. Implement the function to create a n*n matrix (n*n=m) and fill the matrix in spiral order starting from matrix[0][0] in a clockwise direction. Visit https://www.geeksforgeeks.org/form-a-spiral-matrix-from-the-given-array/ to check the solution.The function accepts 2 positive integers ‘a’ and ‘n’ as input. ‘a’ is the first element of the collatz sequence. Implement the function to find the nth term of the sequence and return it. First-term P1=a, and each successive term Pk+1 was calculated as:If Pk is even , Pk+1 = Pk / 2\nIf Pk is odd, Pk+1=( 3 * Pk )+1" }, { "code": null, "e": 27799, "s": 27503, "text": "Function accepts an array of size m and integer n. Implement the function to create a n*n matrix (n*n=m) and fill the matrix in spiral order starting from matrix[0][0] in a clockwise direction. Visit https://www.geeksforgeeks.org/form-a-spiral-matrix-from-the-given-array/ to check the solution." }, { "code": null, "e": 28114, "s": 27799, "text": "The function accepts 2 positive integers ‘a’ and ‘n’ as input. ‘a’ is the first element of the collatz sequence. Implement the function to find the nth term of the sequence and return it. First-term P1=a, and each successive term Pk+1 was calculated as:If Pk is even , Pk+1 = Pk / 2\nIf Pk is odd, Pk+1=( 3 * Pk )+1" }, { "code": null, "e": 28176, "s": 28114, "text": "If Pk is even , Pk+1 = Pk / 2\nIf Pk is odd, Pk+1=( 3 * Pk )+1" }, { "code": null, "e": 28240, "s": 28176, "text": "After this round, everyone was called for a communication test." }, { "code": null, "e": 28510, "s": 28240, "text": "3rd round: Communication Assessment: Again this round was a non-elimination round. And this test consists of some sections and was of around 17 minutes. Tests included sections like reading, listening and repeating it, arranging jumbled words in a proper sequence, etc." }, { "code": null, "e": 28553, "s": 28510, "text": "Just be sure that you don’t talk too fast." }, { "code": null, "e": 28747, "s": 28553, "text": "4th round: Virtual Interview: This round was an elimination round, had 2-panel members. One was an HR and the other was a guy from a technical background who was asking tech-related questions. " }, { "code": null, "e": 28929, "s": 28747, "text": "HR guy asked me to introduce myself and how I feel about working in a team, the pros and cons of working in a team and I had done any courses or projects related to tech background." }, { "code": null, "e": 29064, "s": 28929, "text": "The tech guy was asking project-related questions stated on the resume; so make sure you’ve covered everything on the resume properly." }, { "code": null, "e": 29215, "s": 29064, "text": "After a few days, I got a mail from Accenture that I was selected for the Software Engineer role. Thanks to GFG for providing archives and helping me!" }, { "code": null, "e": 29225, "s": 29215, "text": "Accenture" }, { "code": null, "e": 29235, "s": 29225, "text": "Marketing" }, { "code": null, "e": 29245, "s": 29235, "text": "On-Campus" }, { "code": null, "e": 29267, "s": 29245, "text": "Interview Experiences" }, { "code": null, "e": 29277, "s": 29267, "text": "Accenture" }, { "code": null, "e": 29375, "s": 29277, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29425, "s": 29375, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" }, { "code": null, "e": 29484, "s": 29425, "text": "Microsoft Interview Experience for Internship (Via Engage)" }, { "code": null, "e": 29512, "s": 29484, "text": "Amazon Interview Experience" }, { "code": null, "e": 29548, "s": 29512, "text": "Zoho Interview | Set 3 (Off-Campus)" }, { "code": null, "e": 29586, "s": 29548, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 29622, "s": 29586, "text": "Difference between ANN, CNN and RNN" }, { "code": null, "e": 29668, "s": 29622, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 29718, "s": 29668, "text": "Amazon Interview Experience for SDE-1(Off-Campus)" }, { "code": null, "e": 29756, "s": 29718, "text": "Amazon Interview Experience for SDE-1" } ]
How can we use a MySQL subquery with FROM clause?
Subqueries can work well in a SELECT statement FROM clause. Following is the syntax for the same − SELECT ... FROM(subquery) [AS] name ... To make it understand we are using the following data from table ‘cars’ − mysql> Select * from Cars; +------+--------------+---------+ | ID | Name | Price | +------+--------------+---------+ | 1 | Nexa | 750000 | | 2 | Maruti Swift | 450000 | | 3 | BMW | 4450000 | | 4 | VOLVO | 2250000 | | 5 | Alto | 250000 | | 6 | Skoda | 1250000 | | 7 | Toyota | 2400000 | | 8 | Ford | 1100000 | +------+--------------+---------+ 8 rows in set (0.02 sec) Now in the following query, we are using the subquery with FROM clause − mysql> Select Id_New, Name_New, Price_New FROM (SELECT Id as Id_New, Name as Name_New, Price as Price_New FROM Cars) as c Where Price_New > 500000; +--------+----------+-----------+ | Id_New | Name_New | Price_New | +--------+----------+-----------+ | 1 | Nexa | 750000 | | 3 | BMW | 4450000 | | 4 | VOLVO | 2250000 | | 6 | Skoda | 1250000 | | 7 | Toyota | 2400000 | | 8 | Ford | 1100000 | +--------+----------+-----------+ 6 rows in set (0.00 sec)
[ { "code": null, "e": 1161, "s": 1062, "text": "Subqueries can work well in a SELECT statement FROM clause. Following is the syntax for the same −" }, { "code": null, "e": 1201, "s": 1161, "text": "SELECT ... FROM(subquery) [AS] name ..." }, { "code": null, "e": 1275, "s": 1201, "text": "To make it understand we are using the following data from table ‘cars’ −" }, { "code": null, "e": 1735, "s": 1275, "text": "mysql> Select * from Cars;\n+------+--------------+---------+\n| ID | Name | Price |\n+------+--------------+---------+\n| 1 | Nexa | 750000 |\n| 2 | Maruti Swift | 450000 |\n| 3 | BMW | 4450000 |\n| 4 | VOLVO | 2250000 |\n| 5 | Alto | 250000 |\n| 6 | Skoda | 1250000 |\n| 7 | Toyota | 2400000 |\n| 8 | Ford | 1100000 |\n+------+--------------+---------+\n8 rows in set (0.02 sec)" }, { "code": null, "e": 1808, "s": 1735, "text": "Now in the following query, we are using the subquery with FROM clause −" }, { "code": null, "e": 2321, "s": 1808, "text": "mysql> Select Id_New, Name_New, Price_New FROM (SELECT Id as Id_New, Name as Name_New, Price as Price_New FROM Cars) as c Where Price_New > 500000;\n+--------+----------+-----------+\n| Id_New | Name_New | Price_New |\n+--------+----------+-----------+\n| 1 | Nexa | 750000 |\n| 3 | BMW | 4450000 |\n| 4 | VOLVO | 2250000 |\n| 6 | Skoda | 1250000 |\n| 7 | Toyota | 2400000 |\n| 8 | Ford | 1100000 |\n+--------+----------+-----------+\n6 rows in set (0.00 sec)" } ]
Productivity Tips for Jupyter Users | by Shinichi Okada | Towards Data Science
Table of ContentsIntroduction1. Startup files2. Auto reload3. Multi-cursor4. Exit confirmation5. Update you python packages6. Copying cells from another file To be an efficient Jupyter user, there are few things you need to know. In this article, I am going through six tips that will improve your productivity. These tips work both in Jupyter Notebook and Jupyter Lab. For more information on Jupyter hacks and version control, please read these articles. If you are typing the same things again and again, startup files are your solution. Jupyter Notebook will access files within the start-up folder automatically. Generally, the default location is /Users/<your_profile>/.ipython/profile_default/startup in Mac. You can find your startup directory by running this in a Jypyter Notebook cell. get_ipython().profile_dir.startup_dir Output can be like this. '/Users/<your_profile>/.ipython/profile_default/startup' You can create a file or files that you want to run in this directory when you start Jupyter Notebook. For example, you create a file called 00-startup.py and add the following codes. import pandas as pdimport numpy as npimport matplotlib.pyplot as pltget_ipython().magic('matplotlib inline') When you are using magic %, you need to use get_ipython().magic() as seen above. Restart your Jupyter Notebook. You can use Pandas or Numpy without importing them. You can add more libraries depending on your needs. Example towardsdatascience.com When you modify an imported file, you have to restart the kernel. But autoreload reloads modules automatically before entering the execution of your cell. You can add this to one of the cells and execute it. %load_ext autoreload%autoreload 2 By saving the modified file, it enables auto-reload in another file. If you want to always enable this setting, you can add it to ~/.ipython/profile_default/ipython_config.py. If you don’t have the file, you can call ipython profile create first. ipython profile create[ProfileCreate] Generating default config file: '/Users/yourname/.ipython/profile_default/ipython_config.py'[ProfileCreate] Generating default config file: '/Users/yourname/.ipython/profile_default/ipython_kernel_config.py' Around line 31: # ~/.ipython/profile_default/ipython_config.pyc.InteractiveShellApp.exec_lines = ['%autoreload 2']c.InteractiveShellApp.extensions = ['autoreload'] Auto-reload in action. You can select multiple positions with your cursor. Click where you want to start, press Option, drag the cursor, start typing. You can use the Cmd+right arrow to jump to the far right of every line. How many times have you typed y and pressed return after the Ctrl+C to shutdown? You can skip it by pressing the Ctrl+C twice. Are you updating python packages regularly? Check which packages you need to update. This will list outdated packages. pip list -o# orpip list --outdated You can run install -U to update a package. pip install -U package If you want to update all packages at once, run this in your terminal. pip list --outdated --format=freeze | grep -v '^\-e' | cut -d = -f 1 | xargs -n1 pip install -U pip check verifies which installed packages have compatible dependencies. If you find a problem, you need to install the proper version using, pip install 'packagename==0.14.1'. Other useful commands are: pip reference In Jupyter Notebook, you can copy-paste from another file by pressing cmd+v twice. If you press only once you get the warning below. In JupyterLab, you need to use c to copy a cell or cells and v to paste it into another file. I hope these tips will help your productivity. What is your favorite tip? Get full access to every story on Medium by becoming a member.
[ { "code": null, "e": 205, "s": 47, "text": "Table of ContentsIntroduction1. Startup files2. Auto reload3. Multi-cursor4. Exit confirmation5. Update you python packages6. Copying cells from another file" }, { "code": null, "e": 417, "s": 205, "text": "To be an efficient Jupyter user, there are few things you need to know. In this article, I am going through six tips that will improve your productivity. These tips work both in Jupyter Notebook and Jupyter Lab." }, { "code": null, "e": 504, "s": 417, "text": "For more information on Jupyter hacks and version control, please read these articles." }, { "code": null, "e": 763, "s": 504, "text": "If you are typing the same things again and again, startup files are your solution. Jupyter Notebook will access files within the start-up folder automatically. Generally, the default location is /Users/<your_profile>/.ipython/profile_default/startup in Mac." }, { "code": null, "e": 843, "s": 763, "text": "You can find your startup directory by running this in a Jypyter Notebook cell." }, { "code": null, "e": 881, "s": 843, "text": "get_ipython().profile_dir.startup_dir" }, { "code": null, "e": 906, "s": 881, "text": "Output can be like this." }, { "code": null, "e": 963, "s": 906, "text": "'/Users/<your_profile>/.ipython/profile_default/startup'" }, { "code": null, "e": 1066, "s": 963, "text": "You can create a file or files that you want to run in this directory when you start Jupyter Notebook." }, { "code": null, "e": 1147, "s": 1066, "text": "For example, you create a file called 00-startup.py and add the following codes." }, { "code": null, "e": 1256, "s": 1147, "text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltget_ipython().magic('matplotlib inline')" }, { "code": null, "e": 1337, "s": 1256, "text": "When you are using magic %, you need to use get_ipython().magic() as seen above." }, { "code": null, "e": 1420, "s": 1337, "text": "Restart your Jupyter Notebook. You can use Pandas or Numpy without importing them." }, { "code": null, "e": 1480, "s": 1420, "text": "You can add more libraries depending on your needs. Example" }, { "code": null, "e": 1503, "s": 1480, "text": "towardsdatascience.com" }, { "code": null, "e": 1658, "s": 1503, "text": "When you modify an imported file, you have to restart the kernel. But autoreload reloads modules automatically before entering the execution of your cell." }, { "code": null, "e": 1711, "s": 1658, "text": "You can add this to one of the cells and execute it." }, { "code": null, "e": 1745, "s": 1711, "text": "%load_ext autoreload%autoreload 2" }, { "code": null, "e": 1814, "s": 1745, "text": "By saving the modified file, it enables auto-reload in another file." }, { "code": null, "e": 1921, "s": 1814, "text": "If you want to always enable this setting, you can add it to ~/.ipython/profile_default/ipython_config.py." }, { "code": null, "e": 1992, "s": 1921, "text": "If you don’t have the file, you can call ipython profile create first." }, { "code": null, "e": 2238, "s": 1992, "text": "ipython profile create[ProfileCreate] Generating default config file: '/Users/yourname/.ipython/profile_default/ipython_config.py'[ProfileCreate] Generating default config file: '/Users/yourname/.ipython/profile_default/ipython_kernel_config.py'" }, { "code": null, "e": 2254, "s": 2238, "text": "Around line 31:" }, { "code": null, "e": 2402, "s": 2254, "text": "# ~/.ipython/profile_default/ipython_config.pyc.InteractiveShellApp.exec_lines = ['%autoreload 2']c.InteractiveShellApp.extensions = ['autoreload']" }, { "code": null, "e": 2425, "s": 2402, "text": "Auto-reload in action." }, { "code": null, "e": 2625, "s": 2425, "text": "You can select multiple positions with your cursor. Click where you want to start, press Option, drag the cursor, start typing. You can use the Cmd+right arrow to jump to the far right of every line." }, { "code": null, "e": 2752, "s": 2625, "text": "How many times have you typed y and pressed return after the Ctrl+C to shutdown? You can skip it by pressing the Ctrl+C twice." }, { "code": null, "e": 2796, "s": 2752, "text": "Are you updating python packages regularly?" }, { "code": null, "e": 2871, "s": 2796, "text": "Check which packages you need to update. This will list outdated packages." }, { "code": null, "e": 2906, "s": 2871, "text": "pip list -o# orpip list --outdated" }, { "code": null, "e": 2950, "s": 2906, "text": "You can run install -U to update a package." }, { "code": null, "e": 2973, "s": 2950, "text": "pip install -U package" }, { "code": null, "e": 3044, "s": 2973, "text": "If you want to update all packages at once, run this in your terminal." }, { "code": null, "e": 3141, "s": 3044, "text": "pip list --outdated --format=freeze | grep -v '^\\-e' | cut -d = -f 1 | xargs -n1 pip install -U" }, { "code": null, "e": 3319, "s": 3141, "text": "pip check verifies which installed packages have compatible dependencies. If you find a problem, you need to install the proper version using, pip install 'packagename==0.14.1'." }, { "code": null, "e": 3346, "s": 3319, "text": "Other useful commands are:" }, { "code": null, "e": 3360, "s": 3346, "text": "pip reference" }, { "code": null, "e": 3587, "s": 3360, "text": "In Jupyter Notebook, you can copy-paste from another file by pressing cmd+v twice. If you press only once you get the warning below. In JupyterLab, you need to use c to copy a cell or cells and v to paste it into another file." }, { "code": null, "e": 3661, "s": 3587, "text": "I hope these tips will help your productivity. What is your favorite tip?" } ]
Commonly Asked C Programming Interview Questions | Set 2 - GeeksforGeeks
28 Jun, 2021 This post is second set of Commonly Asked C Programming Interview Questions | Set 1What are main characteristics of C language? C is a procedural language. The main features of C language include low-level access to memory, simple set of keywords, and clean style. These features make it suitable for system programming like operating system or compiler development. What is difference between i++ and ++i? 1) The expression ‘i++’ returns the old value and then increments i. The expression ++i increments the value and returns new value. 2) Precedence of postfix ++ is higher than that of prefix ++. 3) Associativity of postfix ++ is left to right and associativity of prefix ++ is right to left. 4) In C++, ++i can be used as l-value, but i++ cannot be. In C, they both cannot be used as l-value. See Difference between ++*p, *p++ and *++p for more details.What is l-value? l-value or location value refers to an expression that can be used on left side of assignment operator. For example in expression “a = 3”, a is l-value and 3 is r-value. l-values are of two types: “nonmodifiable l-value” represent a l-value that can not be modified. const variables are “nonmodifiable l-value”. “modifiable l-value” represent a l-value that can be modified.Refer lvalue and rvalue in C language for details.What is the difference between array and pointer? See Array vs PointerHow to write your own sizeof operator? c #define my_sizeof(type) (char *)(&type+1)-(char*)(&type) See Implement your own sizeof for more details.How will you print numbers from 1 to 100 without using loop? We can use recursion for this purpose. C /* Prints numbers from 1 to n */void printNos(unsigned int n){ if(n > 0) { printNos(n-1); printf("%d ", n); }} What is volatile keyword? The volatile keyword is intended to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler. Objects declared as volatile are omitted from optimization because their values can be changed by code outside the scope of current code at any time. See Understanding “volatile” qualifier in C for more details.Can a variable be both const and volatile? yes, the const means that the variable cannot be assigned a new value. The value can be changed by other code or pointer. For example the following program works fine. C #include <stdio.h>int main(void){ const volatile int local = 10; int* ptr = (int*)&local; printf("Initial value of local : %d \n", local); *ptr = 100; printf("Modified value of local: %d \n", local); return 0;} Practices Quizzes on C C articles We will soon be publishing more sets of commonly asked C programming questions.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. idvivekgfg interview-preparation placement preparation C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in C / C++ rand() and srand() in C/C++ Left Shift and Right Shift Operators in C/C++ Substring in C++ Command line arguments in C/C++ fork() in C Function Pointer in C Different methods to reverse a string in C/C++ Structures in C TCP Server-Client implementation in C
[ { "code": null, "e": 24552, "s": 24524, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24920, "s": 24552, "text": "This post is second set of Commonly Asked C Programming Interview Questions | Set 1What are main characteristics of C language? C is a procedural language. The main features of C language include low-level access to memory, simple set of keywords, and clean style. These features make it suitable for system programming like operating system or compiler development. " }, { "code": null, "e": 25963, "s": 24920, "text": "What is difference between i++ and ++i? 1) The expression ‘i++’ returns the old value and then increments i. The expression ++i increments the value and returns new value. 2) Precedence of postfix ++ is higher than that of prefix ++. 3) Associativity of postfix ++ is left to right and associativity of prefix ++ is right to left. 4) In C++, ++i can be used as l-value, but i++ cannot be. In C, they both cannot be used as l-value. See Difference between ++*p, *p++ and *++p for more details.What is l-value? l-value or location value refers to an expression that can be used on left side of assignment operator. For example in expression “a = 3”, a is l-value and 3 is r-value. l-values are of two types: “nonmodifiable l-value” represent a l-value that can not be modified. const variables are “nonmodifiable l-value”. “modifiable l-value” represent a l-value that can be modified.Refer lvalue and rvalue in C language for details.What is the difference between array and pointer? See Array vs PointerHow to write your own sizeof operator? " }, { "code": null, "e": 25965, "s": 25963, "text": "c" }, { "code": "#define my_sizeof(type) (char *)(&type+1)-(char*)(&type)", "e": 26022, "s": 25965, "text": null }, { "code": null, "e": 26169, "s": 26022, "text": "See Implement your own sizeof for more details.How will you print numbers from 1 to 100 without using loop? We can use recursion for this purpose." }, { "code": null, "e": 26171, "s": 26169, "text": "C" }, { "code": "/* Prints numbers from 1 to n */void printNos(unsigned int n){ if(n > 0) { printNos(n-1); printf(\"%d \", n); }}", "e": 26292, "s": 26171, "text": null }, { "code": null, "e": 26908, "s": 26292, "text": "What is volatile keyword? The volatile keyword is intended to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler. Objects declared as volatile are omitted from optimization because their values can be changed by code outside the scope of current code at any time. See Understanding “volatile” qualifier in C for more details.Can a variable be both const and volatile? yes, the const means that the variable cannot be assigned a new value. The value can be changed by other code or pointer. For example the following program works fine. " }, { "code": null, "e": 26910, "s": 26908, "text": "C" }, { "code": "#include <stdio.h>int main(void){ const volatile int local = 10; int* ptr = (int*)&local; printf(\"Initial value of local : %d \\n\", local); *ptr = 100; printf(\"Modified value of local: %d \\n\", local); return 0;}", "e": 27139, "s": 26910, "text": null }, { "code": null, "e": 27162, "s": 27139, "text": "Practices Quizzes on C" }, { "code": null, "e": 27173, "s": 27162, "text": "C articles" }, { "code": null, "e": 27377, "s": 27173, "text": "We will soon be publishing more sets of commonly asked C programming questions.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 27388, "s": 27377, "text": "idvivekgfg" }, { "code": null, "e": 27410, "s": 27388, "text": "interview-preparation" }, { "code": null, "e": 27432, "s": 27410, "text": "placement preparation" }, { "code": null, "e": 27443, "s": 27432, "text": "C Language" }, { "code": null, "e": 27541, "s": 27443, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27576, "s": 27541, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 27604, "s": 27576, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 27650, "s": 27604, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 27667, "s": 27650, "text": "Substring in C++" }, { "code": null, "e": 27699, "s": 27667, "text": "Command line arguments in C/C++" }, { "code": null, "e": 27711, "s": 27699, "text": "fork() in C" }, { "code": null, "e": 27733, "s": 27711, "text": "Function Pointer in C" }, { "code": null, "e": 27780, "s": 27733, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 27796, "s": 27780, "text": "Structures in C" } ]
DAX Aggregation SELECTCOLUMNS function
Adds calculated columns to the given table or table expression. DAX SELECTCOLUMNS function is new in Excel 2016. SELECTCOLUMNS (<table>, <name>, <scalar_expression>, [<name>, <scalar_expression>] ...) table Table or a DAX expression that returns a table. name The name given to the column, enclosed in double quotes. scalar_expression DAX expression that returns a scalar value like a column reference, integer or string value. A table with the same number of rows as the table specified as the first parameter. The returned table has one column for each pair of name and scalar_expression parameters. Each scalar_expression is evaluated in the context of a row from the specified table parameter. SELECTCOLUMNS is similar to ADDCOLUMNS, and has the same behavior except that instead of starting with the table specified, SELECTCOLUMNS start with an empty table before adding columns. = SELECTCOLUMNS ( Products,"Product-NoOfUnits",Products[Product]&" - "&Products[Units Sold]) 53 Lectures 5.5 hours Abhay Gadiya 24 Lectures 2 hours Randy Minder 26 Lectures 4.5 hours Randy Minder Print Add Notes Bookmark this page
[ { "code": null, "e": 2114, "s": 2001, "text": "Adds calculated columns to the given table or table expression. DAX SELECTCOLUMNS function is new in Excel 2016." }, { "code": null, "e": 2204, "s": 2114, "text": "SELECTCOLUMNS (<table>, <name>, <scalar_expression>, [<name>, <scalar_expression>] ...) \n" }, { "code": null, "e": 2210, "s": 2204, "text": "table" }, { "code": null, "e": 2258, "s": 2210, "text": "Table or a DAX expression that returns a table." }, { "code": null, "e": 2263, "s": 2258, "text": "name" }, { "code": null, "e": 2320, "s": 2263, "text": "The name given to the column, enclosed in double quotes." }, { "code": null, "e": 2338, "s": 2320, "text": "scalar_expression" }, { "code": null, "e": 2431, "s": 2338, "text": "DAX expression that returns a scalar value like a column reference, integer or string value." }, { "code": null, "e": 2701, "s": 2431, "text": "A table with the same number of rows as the table specified as the first parameter. The returned table has one column for each pair of name and scalar_expression parameters. Each scalar_expression is evaluated in the context of a row from the specified table parameter." }, { "code": null, "e": 2888, "s": 2701, "text": "SELECTCOLUMNS is similar to ADDCOLUMNS, and has the same behavior except that instead of starting with the table specified, SELECTCOLUMNS start with an empty table before adding columns." }, { "code": null, "e": 2985, "s": 2888, "text": "= SELECTCOLUMNS ( \n Products,\"Product-NoOfUnits\",Products[Product]&\" - \"&Products[Units Sold])" }, { "code": null, "e": 3020, "s": 2985, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3034, "s": 3020, "text": " Abhay Gadiya" }, { "code": null, "e": 3067, "s": 3034, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3081, "s": 3067, "text": " Randy Minder" }, { "code": null, "e": 3116, "s": 3081, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3130, "s": 3116, "text": " Randy Minder" }, { "code": null, "e": 3137, "s": 3130, "text": " Print" }, { "code": null, "e": 3148, "s": 3137, "text": " Add Notes" } ]
shutdown - Unix, Linux Command
If shutdown is called with a delay, it creates the advisory file /etc/nologin which causes programs such as login(1) to not allow new user logins. Shutdown removes this file if it is stopped before it can signal init (i.e. it is cancelled or something goes wrong). It also removes it before calling init to change the runlevel. The -f flag means ‘reboot fast’. This only creates an advisory file /fastboot which can be tested by the system when it comes up again. The boot rc file can test if this file is present, and decide not to run fsck(1) since the system has been shut down in the proper way. After that, the boot process should remove /fastboot. The -F flag means ‘force fsck’. This only creates an advisory file /forcefsck which can be tested by the system when it comes up again. The boot rc file can test if this file is present, and decide to run fsck(1) with a special ‘force’ flag so that even properly unmounted filesystems get checked. After that, the boot process should remove /forcefsck. The -n flag causes shutdown not to call init, but to kill all running processes itself. shutdown will then turn off quota, accounting, and swapping and unmount all filesystems. shutdown: no authorized users logged in to the (physical) system console. The format of /etc/shutdown.allow is one user name per line. Empty lines and comment lines (prefixed by a #) are allowed. Currently there is a limit of 32 users in this file. Note that if /etc/shutdown.allow is not present, the -a argument is ignored. /fastboot /etc/inittab /etc/init.d/halt /etc/init.d/reboot /etc/shutdown.allow Init can only capture CTRL-ALT-DEL and start shutdown in console mode. If the system is running the X window System, the X server processes all key strokes. Some X11 environments make it possible to capture CTRL-ALT-DEL, but what exactly is done with that event depends on that environment. Shutdown wasn’t designed to be run setuid. /etc/shutdown.allow is not used to find out who is executing shutdown, it ONLY checks who is currently logged in on (one of the) console(s). fsck (8) fsck (8) init (8) init (8) halt (8) halt (8) poweroff (8) poweroff (8) reboot (8) reboot (8) Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10907, "s": 10577, "text": "\nIf shutdown is called with a delay, it creates the advisory file\n/etc/nologin which causes programs such as login(1) to not allow new user\nlogins. Shutdown removes this file if it is stopped before it\ncan signal init (i.e. it is cancelled or something goes wrong).\nIt also removes it before calling init to change the runlevel.\n" }, { "code": null, "e": 11238, "s": 10907, "text": "\nThe -f flag means ‘reboot fast’. This only creates an advisory\nfile /fastboot which can be tested by the system when it comes\nup again. The boot rc file can test if this file is present, and decide not\nto run fsck(1) since the system has been shut down in the proper way. \nAfter that, the boot process should remove /fastboot.\n" }, { "code": null, "e": 11595, "s": 11238, "text": "\nThe -F flag means ‘force fsck’. This only creates an advisory\nfile /forcefsck which can be tested by the system when it comes\nup again. The boot rc file can test if this file is present, and decide\nto run fsck(1) with a special ‘force’ flag so that even properly\nunmounted filesystems get checked.\nAfter that, the boot process should remove /forcefsck.\n" }, { "code": null, "e": 11774, "s": 11595, "text": "\nThe -n flag causes shutdown not to call init,\nbut to kill all running processes itself.\nshutdown will then turn off quota, accounting, and swapping\nand unmount all filesystems.\n" }, { "code": null, "e": 11817, "s": 11776, "text": "shutdown: no authorized users logged in\n" }, { "code": null, "e": 12028, "s": 11817, "text": "\nto the (physical) system console. The format of /etc/shutdown.allow\nis one user name per line. Empty lines and comment lines (prefixed by a\n#) are allowed. Currently there is a limit of 32 users in this file.\n" }, { "code": null, "e": 12107, "s": 12028, "text": "\nNote that if /etc/shutdown.allow is not present, the -a\nargument is ignored.\n" }, { "code": null, "e": 12187, "s": 12107, "text": "/fastboot\n/etc/inittab\n/etc/init.d/halt\n/etc/init.d/reboot\n/etc/shutdown.allow\n" }, { "code": null, "e": 12480, "s": 12187, "text": "\nInit can only capture CTRL-ALT-DEL and start shutdown in console mode.\nIf the system is running the X window System, the X server processes\nall key strokes. Some X11 environments make it possible to capture\nCTRL-ALT-DEL, but what exactly is done with that event depends on\nthat environment.\n" }, { "code": null, "e": 12666, "s": 12480, "text": "\nShutdown wasn’t designed to be run setuid. /etc/shutdown.allow is\nnot used to find out who is executing shutdown, it ONLY checks who\nis currently logged in on (one of the) console(s).\n" }, { "code": null, "e": 12675, "s": 12666, "text": "fsck (8)" }, { "code": null, "e": 12684, "s": 12675, "text": "fsck (8)" }, { "code": null, "e": 12693, "s": 12684, "text": "init (8)" }, { "code": null, "e": 12702, "s": 12693, "text": "init (8)" }, { "code": null, "e": 12711, "s": 12702, "text": "halt (8)" }, { "code": null, "e": 12720, "s": 12711, "text": "halt (8)" }, { "code": null, "e": 12733, "s": 12720, "text": "poweroff (8)" }, { "code": null, "e": 12746, "s": 12733, "text": "poweroff (8)" }, { "code": null, "e": 12757, "s": 12746, "text": "reboot (8)" }, { "code": null, "e": 12768, "s": 12757, "text": "reboot (8)" }, { "code": null, "e": 12785, "s": 12768, "text": "\nAdvertisements\n" }, { "code": null, "e": 12820, "s": 12785, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 12848, "s": 12820, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 12882, "s": 12848, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 12899, "s": 12882, "text": " Frahaan Hussain" }, { "code": null, "e": 12932, "s": 12899, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 12943, "s": 12932, "text": " Pradeep D" }, { "code": null, "e": 12978, "s": 12943, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 12994, "s": 12978, "text": " Musab Zayadneh" }, { "code": null, "e": 13027, "s": 12994, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 13039, "s": 13027, "text": " GUHARAJANM" }, { "code": null, "e": 13071, "s": 13039, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 13079, "s": 13071, "text": " Uplatz" }, { "code": null, "e": 13086, "s": 13079, "text": " Print" }, { "code": null, "e": 13097, "s": 13086, "text": " Add Notes" } ]
Java 9 - REPL (JShell)
REPL stands for Read-Eval-Print Loop. With JShell, java has REPL capability. Using REPL, we can code and test java based logic without compiling using javac and see the result of calculations directly. Open command prompt and type jshell. $ jshell | Welcome to JShell -- Version 9-ea | For an introduction type: /help intro jshell> Type /help once jshell command starts running. jshell> /help | Type a Java language expression, statement, or declaration. | Or type one of the following commands: | /list [<name or id>|-all|-start] | list the source you have typed | /edit <name or id> | edit a source entry referenced by name or id | /drop <name or id> | delete a source entry referenced by name or id | /save [-all|-history|-start] <file> | Save snippet source to a file. | /open <file> | open a file as source input | /vars [<name or id>|-all|-start] | list the declared variables and their values | /methods [<name or id>|-all|-start] | list the declared methods and their signatures | /types [<name or id>|-all|-start] | list the declared types | /imports | list the imported items Type /imports once jshell command starts running and see the used imports. jshell> /imports | import java.io.* | import java.math.* | import java.net.* | import java.nio.file.* | import java.util.* | import java.util.concurrent.* | import java.util.function.* | import java.util.prefs.* | import java.util.regex.* | import java.util.stream.* jshell> Try running simple calculations in JShell. jshell> 3+1 $1 ==> 4 jshell> 13%7 $2 ==> 6 jshell> $2 $2 ==> 6 jshell> Create a function doubled() to take int and return its doubled value. jshell> int doubled(int i){ return i*2;} | created method doubled(int) jshell> doubled(6) $3 ==> 12 jshell> Type /exit. jshell> /exit | Goodbye 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2311, "s": 2109, "text": "REPL stands for Read-Eval-Print Loop. With JShell, java has REPL capability. Using REPL, we can code and test java based logic without compiling using javac and see the result of calculations directly." }, { "code": null, "e": 2348, "s": 2311, "text": "Open command prompt and type jshell." }, { "code": null, "e": 2444, "s": 2348, "text": "$ jshell\n| Welcome to JShell -- Version 9-ea\n| For an introduction type: /help intro\njshell>\n" }, { "code": null, "e": 2491, "s": 2444, "text": "Type /help once jshell command starts running." }, { "code": null, "e": 3220, "s": 2491, "text": "jshell> /help\n| Type a Java language expression, statement, or declaration.\n| Or type one of the following commands:\n| /list [<name or id>|-all|-start]\n| list the source you have typed\n| /edit <name or id>\n| edit a source entry referenced by name or id\n| /drop <name or id>\n| delete a source entry referenced by name or id\n| /save [-all|-history|-start] <file>\n| Save snippet source to a file.\n| /open <file>\n| open a file as source input\n| /vars [<name or id>|-all|-start]\n| list the declared variables and their values\n| /methods [<name or id>|-all|-start]\n| list the declared methods and their signatures\n| /types [<name or id>|-all|-start]\n| list the declared types\n| /imports \n| list the imported items\n" }, { "code": null, "e": 3295, "s": 3220, "text": "Type /imports once jshell command starts running and see the used imports." }, { "code": null, "e": 3601, "s": 3295, "text": "jshell> /imports\n| import java.io.*\n| import java.math.*\n| import java.net.*\n| import java.nio.file.*\n| import java.util.*\n| import java.util.concurrent.*\n| import java.util.function.*\n| import java.util.prefs.*\n| import java.util.regex.*\n| import java.util.stream.*\njshell>\n" }, { "code": null, "e": 3644, "s": 3601, "text": "Try running simple calculations in JShell." }, { "code": null, "e": 3716, "s": 3644, "text": "jshell> 3+1\n$1 ==> 4\njshell> 13%7\n$2 ==> 6\njshell> $2\n$2 ==> 6\njshell>\n" }, { "code": null, "e": 3786, "s": 3716, "text": "Create a function doubled() to take int and return its doubled value." }, { "code": null, "e": 3896, "s": 3786, "text": "jshell> int doubled(int i){ return i*2;}\n| created method doubled(int)\njshell> doubled(6)\n$3 ==> 12\njshell>\n" }, { "code": null, "e": 3908, "s": 3896, "text": "Type /exit." }, { "code": null, "e": 3933, "s": 3908, "text": "jshell> /exit\n| Goodbye\n" }, { "code": null, "e": 3966, "s": 3933, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 3982, "s": 3966, "text": " Malhar Lathkar" }, { "code": null, "e": 4015, "s": 3982, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 4031, "s": 4015, "text": " Malhar Lathkar" }, { "code": null, "e": 4066, "s": 4031, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4080, "s": 4066, "text": " Anadi Sharma" }, { "code": null, "e": 4114, "s": 4080, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 4128, "s": 4114, "text": " Tushar Kale" }, { "code": null, "e": 4165, "s": 4128, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4180, "s": 4165, "text": " Monica Mittal" }, { "code": null, "e": 4213, "s": 4180, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 4232, "s": 4213, "text": " Arnab Chakraborty" }, { "code": null, "e": 4239, "s": 4232, "text": " Print" }, { "code": null, "e": 4250, "s": 4239, "text": " Add Notes" } ]
C program to calculate distance between three points in 3D
Given with the 3-D plane and hence three coordinates and the task is to find the distance between the given points and display the result. In a three dimension plane there are three axis that are x-axis with its coordinates as (x1, y1, z1), y-axis with its coordinates as (x2, y2, z2) and z-axis with its coordinates as (x3, y3, z). To calculate the distance between them there is a direct formula which is given below ⟮x2−x1⟯2+⟮y2−y1⟯2+⟮z2−z1⟯2 Given below is the diagram representing three different axis and their coordinates Approach used below is as follows − Input the coordinates as (x1, y1, z1), (x2, y2, z2) and (x3, y3, z3) Apply the formula to compute the difference between these points Print the distance Start Step 1-> declare function to calculate distance between three point void three_dis(float x1, float y1, float z1, float x2, float y2, float z2) set float dis = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2) + pow(z2 - z1, 2) * 1.0) print dis step 2-> In main() Set float x1 = 4 Set float y1 = 9 Set float z1 = -3 Set float x2 = 5 Set float y2 = 10 Set float z2 = 9 Call three_dis(x1, y1, z1, x2, y2, z2) Stop #include <stdio.h> #include<math.h> //function to find distance bewteen 3 point void three_dis(float x1, float y1, float z1, float x2, float y2, float z2) { float dis = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2) + pow(z2 - z1, 2) * 1.0); printf("Distance between 3 points are : %f", dis); return; } int main() { float x1 = 4; float y1 = 9; float z1 = -3; float x2 = 5; float y2 = 10; float z2 = 9; three_dis(x1, y1, z1, x2, y2, z2); return 0; } IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT Distance between 3 points are : 12.083046
[ { "code": null, "e": 1201, "s": 1062, "text": "Given with the 3-D plane and hence three coordinates and the task is to find the distance between the given points and display the result." }, { "code": null, "e": 1481, "s": 1201, "text": "In a three dimension plane there are three axis that are x-axis with its coordinates as (x1, y1, z1), y-axis with its coordinates as (x2, y2, z2) and z-axis with its coordinates as (x3, y3, z). To calculate the distance between them there is a direct formula which is given below" }, { "code": null, "e": 1508, "s": 1481, "text": "⟮x2−x1⟯2+⟮y2−y1⟯2+⟮z2−z1⟯2" }, { "code": null, "e": 1591, "s": 1508, "text": "Given below is the diagram representing three different axis and their coordinates" }, { "code": null, "e": 1627, "s": 1591, "text": "Approach used below is as follows −" }, { "code": null, "e": 1696, "s": 1627, "text": "Input the coordinates as (x1, y1, z1), (x2, y2, z2) and (x3, y3, z3)" }, { "code": null, "e": 1761, "s": 1696, "text": "Apply the formula to compute the difference between these points" }, { "code": null, "e": 1780, "s": 1761, "text": "Print the distance" }, { "code": null, "e": 2222, "s": 1780, "text": "Start\nStep 1-> declare function to calculate distance between three point\n void three_dis(float x1, float y1, float z1, float x2, float y2, float z2)\n set float dis = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2) + pow(z2 - z1, 2) * 1.0)\n print dis\nstep 2-> In main()\n Set float x1 = 4\n Set float y1 = 9\n Set float z1 = -3\n Set float x2 = 5\n Set float y2 = 10\n Set float z2 = 9\n Call three_dis(x1, y1, z1, x2, y2, z2)\nStop" }, { "code": null, "e": 2696, "s": 2222, "text": "#include <stdio.h>\n#include<math.h>\n//function to find distance bewteen 3 point\nvoid three_dis(float x1, float y1, float z1, float x2, float y2, float z2) {\n float dis = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2) + pow(z2 - z1, 2) * 1.0);\n printf(\"Distance between 3 points are : %f\", dis);\n return;\n}\nint main() {\n float x1 = 4;\n float y1 = 9;\n float z1 = -3;\n float x2 = 5;\n float y2 = 10;\n float z2 = 9;\n three_dis(x1, y1, z1, x2, y2, z2);\n return 0;\n}" }, { "code": null, "e": 2755, "s": 2696, "text": "IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT" }, { "code": null, "e": 2797, "s": 2755, "text": "Distance between 3 points are : 12.083046" } ]
How to use useState in arrow function instead of hook ? - GeeksforGeeks
24 Mar, 2021 The useState hook is used to update the state in a React component. It is a hook that takes the initial state as an argument and returns an array of two entries. It can be used in a React class based component as well as a functional component (declared using the function or const keyword). The functional component loads before any code are executed while const component loads only when the interpreter reaches that line of code. Always remember that rendering a functional component created using function syntax can be done before it is defined in the code while if it’s defined using const then it needs to be declared before using it. The const functional components are also called arrow functions. By using these functions, we can get rid of annoying method of binding every time and can access hooks very easily. Creating React Application: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Project Structure: It will look like the following. Project Structure Example 1: We create an arrow function App in which we set up an initial state count with the value of 10 and a function setCount for updating the state value. We pass an onClick event to our button component which updates the state value when we click on it. When the state variable needs to be updated, it is done by updating the state variable directly inside setCount (like we have done here in the button component). We will learn how to do the same with an update function in our next example. App.js import React, { useState } from 'react' const App = () => { const [count, setCount] = useState(10); return ( <div> <h1>Countdown Information</h1> <p>You have clicked me {10 - count} times</p> <button onClick={() => setCount(count - 1)}> Please click me {count} more times. </button> </div> )} export default App Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Example 2: We create two functions increaseCount and decreaseCount which increment and decrement the state value by 1 respectively. Both functions get triggered by onClick event and the state value gets updated. Note that we created two update functions and passed them as event handlers in our button components which just signifies how we can use useState in an arrow function in different ways. App.js import React, { useState } from 'react' const App = () => { const [count, setCount] = useState(0); const increaseCount = () => { setCount(count + 1); } const decreaseCount = () => { setCount(count - 1); } return ( <div> <h1>Countdown Information</h1> <p>Value is {count}</p> <button onClick={increaseCount}> Increment </button> <button onClick={decreaseCount}> Decrement </button> </div> )} export default App Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Picked ReactJS-Basics ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ReactJS useNavigate() Hook How to set background images in ReactJS ? Axios in React: A Guide for Beginners How to create a table in ReactJS ? How to navigate on path by button click in react router ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26097, "s": 26069, "text": "\n24 Mar, 2021" }, { "code": null, "e": 26740, "s": 26097, "text": "The useState hook is used to update the state in a React component. It is a hook that takes the initial state as an argument and returns an array of two entries. It can be used in a React class based component as well as a functional component (declared using the function or const keyword). The functional component loads before any code are executed while const component loads only when the interpreter reaches that line of code. Always remember that rendering a functional component created using function syntax can be done before it is defined in the code while if it’s defined using const then it needs to be declared before using it. " }, { "code": null, "e": 26922, "s": 26740, "text": "The const functional components are also called arrow functions. By using these functions, we can get rid of annoying method of binding every time and can access hooks very easily. " }, { "code": null, "e": 26950, "s": 26922, "text": "Creating React Application:" }, { "code": null, "e": 27045, "s": 26950, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 27109, "s": 27045, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 27141, "s": 27109, "text": "npx create-react-app foldername" }, { "code": null, "e": 27254, "s": 27141, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 27354, "s": 27254, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 27368, "s": 27354, "text": "cd foldername" }, { "code": null, "e": 27420, "s": 27368, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 27438, "s": 27420, "text": "Project Structure" }, { "code": null, "e": 27938, "s": 27438, "text": "Example 1: We create an arrow function App in which we set up an initial state count with the value of 10 and a function setCount for updating the state value. We pass an onClick event to our button component which updates the state value when we click on it. When the state variable needs to be updated, it is done by updating the state variable directly inside setCount (like we have done here in the button component). We will learn how to do the same with an update function in our next example." }, { "code": null, "e": 27945, "s": 27938, "text": "App.js" }, { "code": "import React, { useState } from 'react' const App = () => { const [count, setCount] = useState(10); return ( <div> <h1>Countdown Information</h1> <p>You have clicked me {10 - count} times</p> <button onClick={() => setCount(count - 1)}> Please click me {count} more times. </button> </div> )} export default App", "e": 28305, "s": 27945, "text": null }, { "code": null, "e": 28418, "s": 28305, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 28428, "s": 28418, "text": "npm start" }, { "code": null, "e": 28527, "s": 28428, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 28925, "s": 28527, "text": "Example 2: We create two functions increaseCount and decreaseCount which increment and decrement the state value by 1 respectively. Both functions get triggered by onClick event and the state value gets updated. Note that we created two update functions and passed them as event handlers in our button components which just signifies how we can use useState in an arrow function in different ways." }, { "code": null, "e": 28932, "s": 28925, "text": "App.js" }, { "code": "import React, { useState } from 'react' const App = () => { const [count, setCount] = useState(0); const increaseCount = () => { setCount(count + 1); } const decreaseCount = () => { setCount(count - 1); } return ( <div> <h1>Countdown Information</h1> <p>Value is {count}</p> <button onClick={increaseCount}> Increment </button> <button onClick={decreaseCount}> Decrement </button> </div> )} export default App", "e": 29425, "s": 28932, "text": null }, { "code": null, "e": 29538, "s": 29425, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 29548, "s": 29538, "text": "npm start" }, { "code": null, "e": 29647, "s": 29548, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 29654, "s": 29647, "text": "Picked" }, { "code": null, "e": 29669, "s": 29654, "text": "ReactJS-Basics" }, { "code": null, "e": 29677, "s": 29669, "text": "ReactJS" }, { "code": null, "e": 29694, "s": 29677, "text": "Web Technologies" }, { "code": null, "e": 29792, "s": 29694, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29819, "s": 29792, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 29861, "s": 29819, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 29899, "s": 29861, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 29934, "s": 29899, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 29992, "s": 29934, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 30032, "s": 29992, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30065, "s": 30032, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30110, "s": 30065, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30160, "s": 30110, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Create a balanced BST using vector in C++ STL - GeeksforGeeks
29 Dec, 2021 Given an unsorted vector arr, the task is to create a balanced binary search tree using the elements of the array. Note: There can be more than one balanced BST. Forming any is acceptable Examples: Input: arr[] = { 2, 1, 3}Output: 2 1 3Explanation: The tree formed is show below. The preorder traversal is 2 1 3 2 / \ 1 3 Input: arr[] = {4, 3, 1, 2}Output: 2 1 3 4Explanation: The tree formed is 2 / \ 1 3 \ 4Another possible option can provide preorder traversal is 3 2 1 4 Approach: To solve this problem, follow the below steps: Firstly, we will sort the vector using the sort function.Now, get the Middle of the vector and make it root.Recursively do the same for the left half and the right half.Get the middle of the left half and make it the left child of the root created in step 2.Get the middle of the right half and make it the right child of the root created in step 2. Firstly, we will sort the vector using the sort function. Now, get the Middle of the vector and make it root. Recursively do the same for the left half and the right half.Get the middle of the left half and make it the left child of the root created in step 2.Get the middle of the right half and make it the right child of the root created in step 2. Get the middle of the left half and make it the left child of the root created in step 2.Get the middle of the right half and make it the right child of the root created in step 2. Get the middle of the left half and make it the left child of the root created in step 2. Get the middle of the right half and make it the right child of the root created in step 2. Below is the implementation of the above approach: C++ // C++ program to print BST in given range#include <bits/stdc++.h>using namespace std; // Node of Binary Search Treeclass Node {public: Node* left; int data; Node* right; Node(int d) { data = d; left = right = NULL; }}; // A function that constructs Balanced// Binary Search Tree from a vectorNode* createBST(vector<int> v, int start, int end){ sort(v.begin(), v.end()); // Base Case if (start > end) return NULL; // Get the middle element and make it root int mid = (start + end) / 2; Node* root = new Node(v[mid]); // Recursively construct the left subtree // and make it left child of root root->left = createBST(v, start, mid - 1); // Recursively construct the right subtree // and make it right child of root root->right = createBST(v, mid + 1, end); return root;} vector<int> preNode, vec; // A utility function to print// preorder traversal of BSTvector<int> preOrder(Node* node){ // Root Left Right if (node == NULL) { return vec; } preNode.push_back(node->data); preOrder(node->left); preOrder(node->right); return preNode;} // Driver Codeint main(){ vector<int> v = { 4, 3, 1, 2 }; Node* root = createBST(v, 0, v.size() - 1); vector<int> ans = preOrder(root); for (auto i : ans) { cout << i << " "; } return 0;} PreOrder Traversal of constructed BST 4 2 1 3 6 5 7 Time Complexity: O(N * logN)Auxiliary Space: O(N) to create the tree Algo-Geek 2021 BST cpp-vector STL Algo Geek Binary Search Tree C++ Tree Binary Search Tree Tree STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Lexicographically smallest string formed by concatenating any prefix and its mirrored form Check if the given string is valid English word or not Check if an edge is a part of any Minimum Spanning Tree Divide given number into two even parts Find One’s Complement of an Integer | Set 2 Binary Search Tree | Set 1 (Search and Insertion) Binary Search Tree | Set 2 (Delete) AVL Tree | Set 1 (Insertion) A program to check if a binary tree is BST or not Sorted Array to Balanced BST
[ { "code": null, "e": 26236, "s": 26208, "text": "\n29 Dec, 2021" }, { "code": null, "e": 26351, "s": 26236, "text": "Given an unsorted vector arr, the task is to create a balanced binary search tree using the elements of the array." }, { "code": null, "e": 26424, "s": 26351, "text": "Note: There can be more than one balanced BST. Forming any is acceptable" }, { "code": null, "e": 26436, "s": 26424, "text": "Examples: " }, { "code": null, "e": 26572, "s": 26436, "text": "Input: arr[] = { 2, 1, 3}Output: 2 1 3Explanation: The tree formed is show below. The preorder traversal is 2 1 3 2 / \\ 1 3 " }, { "code": null, "e": 26765, "s": 26572, "text": "Input: arr[] = {4, 3, 1, 2}Output: 2 1 3 4Explanation: The tree formed is 2 / \\ 1 3 \\ 4Another possible option can provide preorder traversal is 3 2 1 4" }, { "code": null, "e": 26822, "s": 26765, "text": "Approach: To solve this problem, follow the below steps:" }, { "code": null, "e": 27172, "s": 26822, "text": "Firstly, we will sort the vector using the sort function.Now, get the Middle of the vector and make it root.Recursively do the same for the left half and the right half.Get the middle of the left half and make it the left child of the root created in step 2.Get the middle of the right half and make it the right child of the root created in step 2." }, { "code": null, "e": 27230, "s": 27172, "text": "Firstly, we will sort the vector using the sort function." }, { "code": null, "e": 27282, "s": 27230, "text": "Now, get the Middle of the vector and make it root." }, { "code": null, "e": 27524, "s": 27282, "text": "Recursively do the same for the left half and the right half.Get the middle of the left half and make it the left child of the root created in step 2.Get the middle of the right half and make it the right child of the root created in step 2." }, { "code": null, "e": 27705, "s": 27524, "text": "Get the middle of the left half and make it the left child of the root created in step 2.Get the middle of the right half and make it the right child of the root created in step 2." }, { "code": null, "e": 27795, "s": 27705, "text": "Get the middle of the left half and make it the left child of the root created in step 2." }, { "code": null, "e": 27887, "s": 27795, "text": "Get the middle of the right half and make it the right child of the root created in step 2." }, { "code": null, "e": 27938, "s": 27887, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27942, "s": 27938, "text": "C++" }, { "code": "// C++ program to print BST in given range#include <bits/stdc++.h>using namespace std; // Node of Binary Search Treeclass Node {public: Node* left; int data; Node* right; Node(int d) { data = d; left = right = NULL; }}; // A function that constructs Balanced// Binary Search Tree from a vectorNode* createBST(vector<int> v, int start, int end){ sort(v.begin(), v.end()); // Base Case if (start > end) return NULL; // Get the middle element and make it root int mid = (start + end) / 2; Node* root = new Node(v[mid]); // Recursively construct the left subtree // and make it left child of root root->left = createBST(v, start, mid - 1); // Recursively construct the right subtree // and make it right child of root root->right = createBST(v, mid + 1, end); return root;} vector<int> preNode, vec; // A utility function to print// preorder traversal of BSTvector<int> preOrder(Node* node){ // Root Left Right if (node == NULL) { return vec; } preNode.push_back(node->data); preOrder(node->left); preOrder(node->right); return preNode;} // Driver Codeint main(){ vector<int> v = { 4, 3, 1, 2 }; Node* root = createBST(v, 0, v.size() - 1); vector<int> ans = preOrder(root); for (auto i : ans) { cout << i << \" \"; } return 0;}", "e": 29330, "s": 27942, "text": null }, { "code": null, "e": 29384, "s": 29330, "text": "PreOrder Traversal of constructed BST \n4 2 1 3 6 5 7 " }, { "code": null, "e": 29453, "s": 29384, "text": "Time Complexity: O(N * logN)Auxiliary Space: O(N) to create the tree" }, { "code": null, "e": 29468, "s": 29453, "text": "Algo-Geek 2021" }, { "code": null, "e": 29472, "s": 29468, "text": "BST" }, { "code": null, "e": 29483, "s": 29472, "text": "cpp-vector" }, { "code": null, "e": 29487, "s": 29483, "text": "STL" }, { "code": null, "e": 29497, "s": 29487, "text": "Algo Geek" }, { "code": null, "e": 29516, "s": 29497, "text": "Binary Search Tree" }, { "code": null, "e": 29520, "s": 29516, "text": "C++" }, { "code": null, "e": 29525, "s": 29520, "text": "Tree" }, { "code": null, "e": 29544, "s": 29525, "text": "Binary Search Tree" }, { "code": null, "e": 29549, "s": 29544, "text": "Tree" }, { "code": null, "e": 29553, "s": 29549, "text": "STL" }, { "code": null, "e": 29557, "s": 29553, "text": "CPP" }, { "code": null, "e": 29655, "s": 29557, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29664, "s": 29655, "text": "Comments" }, { "code": null, "e": 29677, "s": 29664, "text": "Old Comments" }, { "code": null, "e": 29768, "s": 29677, "text": "Lexicographically smallest string formed by concatenating any prefix and its mirrored form" }, { "code": null, "e": 29823, "s": 29768, "text": "Check if the given string is valid English word or not" }, { "code": null, "e": 29879, "s": 29823, "text": "Check if an edge is a part of any Minimum Spanning Tree" }, { "code": null, "e": 29919, "s": 29879, "text": "Divide given number into two even parts" }, { "code": null, "e": 29963, "s": 29919, "text": "Find One’s Complement of an Integer | Set 2" }, { "code": null, "e": 30013, "s": 29963, "text": "Binary Search Tree | Set 1 (Search and Insertion)" }, { "code": null, "e": 30049, "s": 30013, "text": "Binary Search Tree | Set 2 (Delete)" }, { "code": null, "e": 30078, "s": 30049, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 30128, "s": 30078, "text": "A program to check if a binary tree is BST or not" } ]
VB.Net - Arithmetic Operators
Following table shows all the arithmetic operators supported by VB.Net. Assume variable A holds 2 and variable B holds 7, then − Try the following example to understand all the arithmetic operators available in VB.Net − Module operators Sub Main() Dim a As Integer = 21 Dim b As Integer = 10 Dim p As Integer = 2 Dim c As Integer Dim d As Single c = a + b Console.WriteLine("Line 1 - Value of c is {0}", c) c = a - b Console.WriteLine("Line 2 - Value of c is {0}", c) c = a * b Console.WriteLine("Line 3 - Value of c is {0}", c) d = a / b Console.WriteLine("Line 4 - Value of d is {0}", d) c = a \ b Console.WriteLine("Line 5 - Value of c is {0}", c) c = a Mod b Console.WriteLine("Line 6 - Value of c is {0}", c) c = b ^ p Console.WriteLine("Line 7 - Value of c is {0}", c) Console.ReadLine() End Sub End Module When the above code is compiled and executed, it produces the following result − Line 1 - Value of c is 31 Line 2 - Value of c is 11 Line 3 - Value of c is 210 Line 4 - Value of d is 2.1 Line 5 - Value of c is 2 Line 6 - Value of c is 1 Line 7 - Value of c is 100 63 Lectures 4 hours Frahaan Hussain 103 Lectures 12 hours Arnold Higuit 60 Lectures 9.5 hours Arnold Higuit 97 Lectures 9 hours Arnold Higuit Print Add Notes Bookmark this page
[ { "code": null, "e": 2429, "s": 2300, "text": "Following table shows all the arithmetic operators supported by VB.Net. Assume variable A holds 2 and variable B holds 7, then −" }, { "code": null, "e": 2520, "s": 2429, "text": "Try the following example to understand all the arithmetic operators available in VB.Net −" }, { "code": null, "e": 3288, "s": 2520, "text": "Module operators\n Sub Main()\n Dim a As Integer = 21\n Dim b As Integer = 10\n Dim p As Integer = 2\n Dim c As Integer\n Dim d As Single\n \n c = a + b\n Console.WriteLine(\"Line 1 - Value of c is {0}\", c)\n \n c = a - b\n Console.WriteLine(\"Line 2 - Value of c is {0}\", c)\n \n c = a * b\n Console.WriteLine(\"Line 3 - Value of c is {0}\", c)\n \n d = a / b\n Console.WriteLine(\"Line 4 - Value of d is {0}\", d)\n \n c = a \\ b\n Console.WriteLine(\"Line 5 - Value of c is {0}\", c)\n \n c = a Mod b\n Console.WriteLine(\"Line 6 - Value of c is {0}\", c)\n \n c = b ^ p\n Console.WriteLine(\"Line 7 - Value of c is {0}\", c)\n Console.ReadLine()\n End Sub\nEnd Module" }, { "code": null, "e": 3369, "s": 3288, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3553, "s": 3369, "text": "Line 1 - Value of c is 31\nLine 2 - Value of c is 11\nLine 3 - Value of c is 210\nLine 4 - Value of d is 2.1\nLine 5 - Value of c is 2\nLine 6 - Value of c is 1\nLine 7 - Value of c is 100\n" }, { "code": null, "e": 3586, "s": 3553, "text": "\n 63 Lectures \n 4 hours \n" }, { "code": null, "e": 3603, "s": 3586, "text": " Frahaan Hussain" }, { "code": null, "e": 3638, "s": 3603, "text": "\n 103 Lectures \n 12 hours \n" }, { "code": null, "e": 3653, "s": 3638, "text": " Arnold Higuit" }, { "code": null, "e": 3688, "s": 3653, "text": "\n 60 Lectures \n 9.5 hours \n" }, { "code": null, "e": 3703, "s": 3688, "text": " Arnold Higuit" }, { "code": null, "e": 3736, "s": 3703, "text": "\n 97 Lectures \n 9 hours \n" }, { "code": null, "e": 3751, "s": 3736, "text": " Arnold Higuit" }, { "code": null, "e": 3758, "s": 3751, "text": " Print" }, { "code": null, "e": 3769, "s": 3758, "text": " Add Notes" } ]
Pair Class in JavaTuples - GeeksforGeeks
05 Aug, 2021 A Pair is a Tuple from JavaTuples library that deals with 2 elements. Since this Pair is a generic class, it can hold any type of value in it.Since Pair is a Tuple, hence it also has all the characteristics of JavaTuples: They are Typesafe They are Immutable They are Iterable They are Serializable They are Comparable (implements Comparable<Tuple>) They implement equals() and hashCode() They also implement toString() public final class Pair<A, B> extends Tuple implements IValue0<A>, IValue1<B> Object ↳ org.javatuples.Tuple ↳ org.javatuples.Pair<A, B> From Constructor:Syntax: Pair<A, B> pair = new Pair<A, B>(value1, value2); Example: Java // Below is a Java program to create// a Pair tuple from Constructor import java.util.*;import org.javatuples.Pair; class GfG { public static void main(String[] args) { Pair<Integer, String> pair = new Pair<Integer, String>(Integer.valueOf(1), "GeeksforGeeks"); System.out.println(pair); }} Output: [1, GeeksforGeeks] Using with() method: The with() method is a function provided by the JavaTuples library, to instantiate the object with such values.Syntax: Pair<type1, type2> pair = Pair.with(value1, value2); Example: Java // Below is a Java program to create// a Pair tuple from with() method import java.util.*;import org.javatuples.Pair; class GfG { public static void main(String[] args) { Pair<Integer, String> pair = Pair.with(Integer.valueOf(1), "GeeksforGeeks"); System.out.println(pair); }} Output: [1, GeeksforGeeks] From other collections: The fromCollection() method is used to create a Tuple from a collection, and fromArray() method is used to create from an array. The collection/array must have the same type as of the Tuple and the number of values in the collection/array must match the Tuple class.Syntax: Pair<type1, type2> pair = Pair.fromCollection(collectionWith_2_value); Pair<type1, type2> pair = Pair.fromArray(arrayWith_2_value); Example: Java // Below is a Java program to create// a Pair tuple from Collection import java.util.*;import org.javatuples.Pair; class GfG { public static void main(String[] args) { // Creating Pair from List List<String> list = new ArrayList<String>(); list.add("GeeksforGeeks"); list.add("A computer portal"); Pair<Strin, String> pair = Pair.fromCollection(list); // Creating Pair from Array String[] arr = { "GeeksforGeeks", "A computer portal" }; Pair<String, String> otherPair = Pair.fromArray(arr); System.out.println(pair); System.out.println(otherPair); }} Output: [GeeksforGeeks, A computer portal] [GeeksforGeeks, A computer portal] The getValueX() method can be used to fetch the value in a Tuple at index X. The indexing in Tuples start with 0. Hence the value at index X represents the value at position X+1. Syntax: Pair<type1, type2> pair = new Pair<type1, type2>(value1, value2); type1 val1 = pair.getValue0(); Example: Java // Below is a Java program to get// a Pair value import java.util.*;import org.javatuples.Pair; class GfG { public static void main(String[] args) { Pair<Integer, String> pair = Pair.with(Integer.valueOf(1), "GeeksforGeeks"); System.out.println(pair.getValue0()); }} Output: 1 Since the Tuples are immutable, it means that modifying a value at an index is not possible. Hence, JavaTuples offer setAtX(value) which creates a copy of the Tuple with a new value at index X, and returns that Tuple. Syntax: Pair<type1, type2> pair = new Pair<type1, type2>(value1, value2); type1 val1 = pair.getValue0(); Example: Java // Below is a Java program to set// a Pair value import java.util.*;import org.javatuples.Pair; class GfG { public static void main(String[] args) { Pair<Integer, String> pair = Pair.with(Integer.valueOf(1), "GeeksforGeeks"); Pair<Integer, String> otherPair = pair.setAt1("A computer portal"); System.out.println(otherPair); }} Output: [1, A computer portal] Adding a value can be done with the help of addAtX() method, where X represents the index at which the value is to be added. This method returns a Tuple of element one more than the called Tuple. Syntax: Pair<type1, type2> pair = new Pair<type1, type2>(value1, value2); Triplet<type 1, type 2, type 3> pair = pair.addAt2(value 2); Example: Java // Below is a Java program to add// a value import java.util.*;import org.javatuples.Pair;import org.javatuples.Triplet; class GfG { public static void main(String[] args) { Pair<Integer, String> pair = Pair.with(Integer.valueOf(1), "GeeksforGeeks"); Triplet<Integer, String, String> triplet = pair.addAt2("A computer portal"); System.out.println(triplet); }} Output: [1, GeeksforGeeks, A computer portal] An element can be searched in a tuple with the pre-defined method contains(). It returns a boolean value whether the value is present or not. Syntax: Pair<type1, type2> pair = new Pair<type1, type2>(value1, value2); boolean res = pair.contains(value2); Example: Java // Below is a Java program to search// a value import java.util.*;import org.javatuples.Pair; class GfG { public static void main(String[] args) { Pair<Integer, String> pair = Pair.with(Integer.valueOf(1), "GeeksforGeeks"); boolean exist = pair.contains("GeeksforGeeks"); boolean exist1 = pair.contains(4); System.out.println(exist); System.out.println(exist1); }} Output: true false Since Pair implement the Iterable<Object> interface. It means that they can be iterated in the same way as collections or arrays. Syntax: Pair<type1, type2> pair = new Pair<type1, type2>(value1, value2); for (Object item : pair) { ... } Example: Java // Below is a Java program to iterate// a Pair import java.util.*;import org.javatuples.Pair; class GfG { public static void main(String[] args) { Pair<Integer, String> pair = Pair.with(Integer.valueOf(1), "GeeksforGeeks"); for (Object item : pair) System.out.println(item); }} Output: 1 GeeksforGeeks kk9826225 JavaTuples Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples For-each loop in Java Stream In Java Object Oriented Programming (OOPs) Concept in Java Reverse a string in Java HashMap in Java with Examples Arrays.sort() in Java with examples Interfaces in Java How to iterate any Map in Java
[ { "code": null, "e": 24284, "s": 24256, "text": "\n05 Aug, 2021" }, { "code": null, "e": 24507, "s": 24284, "text": "A Pair is a Tuple from JavaTuples library that deals with 2 elements. Since this Pair is a generic class, it can hold any type of value in it.Since Pair is a Tuple, hence it also has all the characteristics of JavaTuples: " }, { "code": null, "e": 24525, "s": 24507, "text": "They are Typesafe" }, { "code": null, "e": 24544, "s": 24525, "text": "They are Immutable" }, { "code": null, "e": 24562, "s": 24544, "text": "They are Iterable" }, { "code": null, "e": 24584, "s": 24562, "text": "They are Serializable" }, { "code": null, "e": 24635, "s": 24584, "text": "They are Comparable (implements Comparable<Tuple>)" }, { "code": null, "e": 24674, "s": 24635, "text": "They implement equals() and hashCode()" }, { "code": null, "e": 24705, "s": 24674, "text": "They also implement toString()" }, { "code": null, "e": 24796, "s": 24705, "text": "public final class Pair<A, B> extends Tuple \n implements IValue0<A>, IValue1<B> " }, { "code": null, "e": 24863, "s": 24796, "text": "Object\n ↳ org.javatuples.Tuple\n ↳ org.javatuples.Pair<A, B> " }, { "code": null, "e": 24889, "s": 24863, "text": "From Constructor:Syntax: " }, { "code": null, "e": 24939, "s": 24889, "text": "Pair<A, B> pair = new Pair<A, B>(value1, value2);" }, { "code": null, "e": 24949, "s": 24939, "text": "Example: " }, { "code": null, "e": 24954, "s": 24949, "text": "Java" }, { "code": "// Below is a Java program to create// a Pair tuple from Constructor import java.util.*;import org.javatuples.Pair; class GfG { public static void main(String[] args) { Pair<Integer, String> pair = new Pair<Integer, String>(Integer.valueOf(1), \"GeeksforGeeks\"); System.out.println(pair); }}", "e": 25280, "s": 24954, "text": null }, { "code": null, "e": 25289, "s": 25280, "text": "Output: " }, { "code": null, "e": 25308, "s": 25289, "text": "[1, GeeksforGeeks]" }, { "code": null, "e": 25449, "s": 25308, "text": "Using with() method: The with() method is a function provided by the JavaTuples library, to instantiate the object with such values.Syntax: " }, { "code": null, "e": 25502, "s": 25449, "text": "Pair<type1, type2> pair = Pair.with(value1, value2);" }, { "code": null, "e": 25512, "s": 25502, "text": "Example: " }, { "code": null, "e": 25517, "s": 25512, "text": "Java" }, { "code": "// Below is a Java program to create// a Pair tuple from with() method import java.util.*;import org.javatuples.Pair; class GfG { public static void main(String[] args) { Pair<Integer, String> pair = Pair.with(Integer.valueOf(1), \"GeeksforGeeks\"); System.out.println(pair); }}", "e": 25829, "s": 25517, "text": null }, { "code": null, "e": 25838, "s": 25829, "text": "Output: " }, { "code": null, "e": 25857, "s": 25838, "text": "[1, GeeksforGeeks]" }, { "code": null, "e": 26156, "s": 25857, "text": "From other collections: The fromCollection() method is used to create a Tuple from a collection, and fromArray() method is used to create from an array. The collection/array must have the same type as of the Tuple and the number of values in the collection/array must match the Tuple class.Syntax: " }, { "code": null, "e": 26288, "s": 26156, "text": "Pair<type1, type2> pair = Pair.fromCollection(collectionWith_2_value);\nPair<type1, type2> pair = Pair.fromArray(arrayWith_2_value);" }, { "code": null, "e": 26298, "s": 26288, "text": "Example: " }, { "code": null, "e": 26303, "s": 26298, "text": "Java" }, { "code": "// Below is a Java program to create// a Pair tuple from Collection import java.util.*;import org.javatuples.Pair; class GfG { public static void main(String[] args) { // Creating Pair from List List<String> list = new ArrayList<String>(); list.add(\"GeeksforGeeks\"); list.add(\"A computer portal\"); Pair<Strin, String> pair = Pair.fromCollection(list); // Creating Pair from Array String[] arr = { \"GeeksforGeeks\", \"A computer portal\" }; Pair<String, String> otherPair = Pair.fromArray(arr); System.out.println(pair); System.out.println(otherPair); }}", "e": 26957, "s": 26303, "text": null }, { "code": null, "e": 26966, "s": 26957, "text": "Output: " }, { "code": null, "e": 27037, "s": 26966, "text": "[GeeksforGeeks, A computer portal]\n[GeeksforGeeks, A computer portal] " }, { "code": null, "e": 27216, "s": 27037, "text": "The getValueX() method can be used to fetch the value in a Tuple at index X. The indexing in Tuples start with 0. Hence the value at index X represents the value at position X+1." }, { "code": null, "e": 27226, "s": 27216, "text": "Syntax: " }, { "code": null, "e": 27329, "s": 27226, "text": "Pair<type1, type2> pair = \n new Pair<type1, type2>(value1, value2);\n\ntype1 val1 = pair.getValue0();" }, { "code": null, "e": 27340, "s": 27329, "text": "Example: " }, { "code": null, "e": 27345, "s": 27340, "text": "Java" }, { "code": "// Below is a Java program to get// a Pair value import java.util.*;import org.javatuples.Pair; class GfG { public static void main(String[] args) { Pair<Integer, String> pair = Pair.with(Integer.valueOf(1), \"GeeksforGeeks\"); System.out.println(pair.getValue0()); }}", "e": 27647, "s": 27345, "text": null }, { "code": null, "e": 27656, "s": 27647, "text": "Output: " }, { "code": null, "e": 27659, "s": 27656, "text": "1 " }, { "code": null, "e": 27877, "s": 27659, "text": "Since the Tuples are immutable, it means that modifying a value at an index is not possible. Hence, JavaTuples offer setAtX(value) which creates a copy of the Tuple with a new value at index X, and returns that Tuple." }, { "code": null, "e": 27887, "s": 27877, "text": "Syntax: " }, { "code": null, "e": 27990, "s": 27887, "text": "Pair<type1, type2> pair = \n new Pair<type1, type2>(value1, value2);\n\ntype1 val1 = pair.getValue0();" }, { "code": null, "e": 28001, "s": 27990, "text": "Example: " }, { "code": null, "e": 28006, "s": 28001, "text": "Java" }, { "code": "// Below is a Java program to set// a Pair value import java.util.*;import org.javatuples.Pair; class GfG { public static void main(String[] args) { Pair<Integer, String> pair = Pair.with(Integer.valueOf(1), \"GeeksforGeeks\"); Pair<Integer, String> otherPair = pair.setAt1(\"A computer portal\"); System.out.println(otherPair); }}", "e": 28388, "s": 28006, "text": null }, { "code": null, "e": 28397, "s": 28388, "text": "Output: " }, { "code": null, "e": 28421, "s": 28397, "text": "[1, A computer portal] " }, { "code": null, "e": 28617, "s": 28421, "text": "Adding a value can be done with the help of addAtX() method, where X represents the index at which the value is to be added. This method returns a Tuple of element one more than the called Tuple." }, { "code": null, "e": 28627, "s": 28617, "text": "Syntax: " }, { "code": null, "e": 28765, "s": 28627, "text": "Pair<type1, type2> pair = \n new Pair<type1, type2>(value1, value2);\n\nTriplet<type 1, type 2, type 3> pair = \n pair.addAt2(value 2);" }, { "code": null, "e": 28776, "s": 28765, "text": "Example: " }, { "code": null, "e": 28781, "s": 28776, "text": "Java" }, { "code": "// Below is a Java program to add// a value import java.util.*;import org.javatuples.Pair;import org.javatuples.Triplet; class GfG { public static void main(String[] args) { Pair<Integer, String> pair = Pair.with(Integer.valueOf(1), \"GeeksforGeeks\"); Triplet<Integer, String, String> triplet = pair.addAt2(\"A computer portal\"); System.out.println(triplet); }}", "e": 29195, "s": 28781, "text": null }, { "code": null, "e": 29204, "s": 29195, "text": "Output: " }, { "code": null, "e": 29243, "s": 29204, "text": "[1, GeeksforGeeks, A computer portal] " }, { "code": null, "e": 29385, "s": 29243, "text": "An element can be searched in a tuple with the pre-defined method contains(). It returns a boolean value whether the value is present or not." }, { "code": null, "e": 29395, "s": 29385, "text": "Syntax: " }, { "code": null, "e": 29504, "s": 29395, "text": "Pair<type1, type2> pair = \n new Pair<type1, type2>(value1, value2);\n\nboolean res = pair.contains(value2);" }, { "code": null, "e": 29515, "s": 29504, "text": "Example: " }, { "code": null, "e": 29520, "s": 29515, "text": "Java" }, { "code": "// Below is a Java program to search// a value import java.util.*;import org.javatuples.Pair; class GfG { public static void main(String[] args) { Pair<Integer, String> pair = Pair.with(Integer.valueOf(1), \"GeeksforGeeks\"); boolean exist = pair.contains(\"GeeksforGeeks\"); boolean exist1 = pair.contains(4); System.out.println(exist); System.out.println(exist1); }}", "e": 29942, "s": 29520, "text": null }, { "code": null, "e": 29951, "s": 29942, "text": "Output: " }, { "code": null, "e": 29963, "s": 29951, "text": "true\nfalse " }, { "code": null, "e": 30093, "s": 29963, "text": "Since Pair implement the Iterable<Object> interface. It means that they can be iterated in the same way as collections or arrays." }, { "code": null, "e": 30103, "s": 30093, "text": "Syntax: " }, { "code": null, "e": 30216, "s": 30103, "text": "Pair<type1, type2> pair = \n new Pair<type1, type2>(value1, value2);\n\nfor (Object item : pair) {\n ...\n}" }, { "code": null, "e": 30226, "s": 30216, "text": "Example: " }, { "code": null, "e": 30231, "s": 30226, "text": "Java" }, { "code": "// Below is a Java program to iterate// a Pair import java.util.*;import org.javatuples.Pair; class GfG { public static void main(String[] args) { Pair<Integer, String> pair = Pair.with(Integer.valueOf(1), \"GeeksforGeeks\"); for (Object item : pair) System.out.println(item); }}", "e": 30555, "s": 30231, "text": null }, { "code": null, "e": 30564, "s": 30555, "text": "Output: " }, { "code": null, "e": 30580, "s": 30564, "text": "1\nGeeksforGeeks" }, { "code": null, "e": 30592, "s": 30582, "text": "kk9826225" }, { "code": null, "e": 30603, "s": 30592, "text": "JavaTuples" }, { "code": null, "e": 30608, "s": 30603, "text": "Java" }, { "code": null, "e": 30613, "s": 30608, "text": "Java" }, { "code": null, "e": 30711, "s": 30613, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30726, "s": 30711, "text": "Arrays in Java" }, { "code": null, "e": 30770, "s": 30726, "text": "Split() String method in Java with examples" }, { "code": null, "e": 30792, "s": 30770, "text": "For-each loop in Java" }, { "code": null, "e": 30807, "s": 30792, "text": "Stream In Java" }, { "code": null, "e": 30858, "s": 30807, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 30883, "s": 30858, "text": "Reverse a string in Java" }, { "code": null, "e": 30913, "s": 30883, "text": "HashMap in Java with Examples" }, { "code": null, "e": 30949, "s": 30913, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 30968, "s": 30949, "text": "Interfaces in Java" } ]
Find the fractional (or n/k - th) node in linked list - GeeksforGeeks
07 Feb, 2022 Given a singly linked list and a number k, write a function to find the (n/k)-th element, where n is the number of elements in the list. We need to consider ceil value in case of decimals.Examples: Input : list = 1->2->3->4->5->6 k = 2 Output : 3 Since n = 6 and k = 2, we print (6/2)-th node which is 3. Input : list = 2->7->9->3->5 k = 3 Output : 7 Since n is 5 and k is 3, we print ceil(5/3)-th node which is 2nd node, i.e., 7. Take two pointers temp and fractionalNode and initialize them with null and head respectively.For every k jumps of the temp pointer, make one jump of the fractionalNode pointer. Take two pointers temp and fractionalNode and initialize them with null and head respectively. For every k jumps of the temp pointer, make one jump of the fractionalNode pointer. C++ Java Python3 C# Javascript // C++ program to find fractional node in a linked list#include <bits/stdc++.h> /* Linked list node */struct Node { int data; Node* next;}; /* Function to create a new node with given data */Node* newNode(int data){ Node* new_node = new Node; new_node->data = data; new_node->next = NULL; return new_node;} /* Function to find fractional node in the linked list */Node* fractionalNodes(Node* head, int k){ // Corner cases if (k <= 0 || head == NULL) return NULL; Node* fractionalNode = NULL; // Traverse the given list int i = 0; for (Node* temp = head; temp != NULL; temp = temp->next) { // For every k nodes, we move fractionalNode one // step ahead. if (i % k == 0) { // First time we see a multiple of k if (fractionalNode == NULL) fractionalNode = head; else fractionalNode = fractionalNode->next; } i++; } return fractionalNode;} // A utility function to print a linked listvoid printList(Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; } printf("\n");} /* Driver program to test above function */int main(void){ Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); int k = 2; printf("List is "); printList(head); Node* answer = fractionalNodes(head, k); printf("\nFractional node is "); printf("%d\n", answer->data); return 0;} // Java program to find fractional node in// a linked listpublic class FractionalNodell{ /* Linked list node */ static class Node{ int data; Node next; //Constructor Node (int data){ this.data = data; } } /* Function to find fractional node in the linked list */ static Node fractionalNodes(Node head, int k) { // Corner cases if (k <= 0 || head == null) return null; Node fractionalNode = null; // Traverse the given list int i = 0; for (Node temp = head; temp != null; temp = temp.next){ // For every k nodes, we move // fractionalNode one step ahead. if (i % k == 0){ // First time we see a multiple of k if (fractionalNode == null) fractionalNode = head; else fractionalNode = fractionalNode.next; } i++; } return fractionalNode; } // A utility function to print a linked list static void printList(Node node) { while (node != null) { System.out.print(node.data+" "); node = node.next; } System.out.println(); } /* Driver program to test above function */ public static void main(String[] args) { Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); int k =2; System.out.print("List is "); printList(head); Node answer = fractionalNodes(head, k); System.out.println("Fractional node is "+ answer.data); }}// This code is contributed by Sumit Ghosh # Python3 program to find fractional node# in a linked listimport math # Linked list nodeclass Node: def __init__(self, data): self.data = data self.next = None # Function to create a new node# with given datadef newNode(data): new_node = Node(data) new_node.data = data new_node.next = None return new_node # Function to find fractional node# in the linked listdef fractionalNodes(head, k): # Corner cases if (k <= 0 or head == None): return None fractionalNode = None # Traverse the given list i = 0 temp = head while (temp != None): # For every k nodes, we move # fractionalNode one step ahead. if (i % k == 0): # First time we see a multiple of k if (fractionalNode == None): fractionalNode = head else: fractionalNode = fractionalNode.next i = i + 1 temp = temp.next return fractionalNode # A utility function to print a linked listdef printList(node): while (node != None): print(node.data, end = ' ') node = node.next # Driver Codeif __name__ == '__main__': head = newNode(1) head.next = newNode(2) head.next.next = newNode(3) head.next.next.next = newNode(4) head.next.next.next.next = newNode(5) k = 2 print("List is", end = ' ') printList(head) answer = fractionalNodes(head, k) print("\nFractional node is", end = ' ') print(answer.data) # This code is contributed by Srathore // C# program to find fractional node in// a linked listusing System; public class FractionalNodell{ /* Linked list node */ public class Node { public int data; public Node next; //Constructor public Node (int data) { this.data = data; } } /* Function to find fractional node in the linked list */ static Node fractionalNodes(Node head, int k) { // Corner cases if (k <= 0 || head == null) return null; Node fractionalNode = null; // Traverse the given list int i = 0; for (Node temp = head; temp != null; temp = temp.next) { // For every k nodes, we move // fractionalNode one step ahead. if (i % k == 0) { // First time we see a multiple of k if (fractionalNode == null) fractionalNode = head; else fractionalNode = fractionalNode.next; } i++; } return fractionalNode; } // A utility function to print a linked list static void printList(Node node) { while (node != null) { Console.Write(node.data+" "); node = node.next; } Console.WriteLine(); } /* Driver code */ public static void Main(String[] args) { Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); int k =2; Console.Write("List is "); printList(head); Node answer = fractionalNodes(head, k); Console.WriteLine("Fractional node is "+ answer.data); }} // This code is contributed by Rajput-Ji <script> // JavaScript program to find fractional node in// a linked list /* Linked list node */ class Node { constructor(val) { this.data = val; this.next = null; } } /* * Function to find fractional node in the linked list */ function fractionalNodes(head , k) { // Corner cases if (k <= 0 || head == null) return null; var fractionalNode = null; // Traverse the given list var i = 0; for (temp = head; temp != null; temp = temp.next) { // For every k nodes, we move // fractionalNode one step ahead. if (i % k == 0) { // First time we see a multiple of k if (fractionalNode == null) fractionalNode = head; else fractionalNode = fractionalNode.next; } i++; } return fractionalNode; } // A utility function to print a linked list function printList(node) { while (node != null) { document.write(node.data + " "); node = node.next; } document.write(); } /* Driver program to test above function */ var head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); var k = 2; document.write("List is "); printList(head); var answer = fractionalNodes(head, k); document.write("<br/>Fractional node is " + answer.data); // This code contributed by Rajput-Ji </script> Output: List is 1 2 3 4 5 Fractional node is 3 This article is contributed by Prakriti 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 contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Rajput-Ji sapnasingh4991 Akanksha_Rai arorakashish0911 surinderdawra388 Fraction Hike SAP Labs Linked List Hike SAP Labs Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Linked List | Set 1 (Introduction) Linked List | Set 2 (Inserting a node) Stack Data Structure (Introduction and Program) Linked List | Set 3 (Deleting a node) LinkedList in Java Linked List vs Array Detect loop in a linked list Merge two sorted linked lists Find the middle of a given linked list Delete a Linked List node at a given position
[ { "code": null, "e": 32806, "s": 32778, "text": "\n07 Feb, 2022" }, { "code": null, "e": 33006, "s": 32806, "text": "Given a singly linked list and a number k, write a function to find the (n/k)-th element, where n is the number of elements in the list. We need to consider ceil value in case of decimals.Examples: " }, { "code": null, "e": 33260, "s": 33006, "text": "Input : list = 1->2->3->4->5->6 \n k = 2\nOutput : 3\nSince n = 6 and k = 2, we print (6/2)-th node \nwhich is 3.\n\nInput : list = 2->7->9->3->5\n k = 3\nOutput : 7 \nSince n is 5 and k is 3, we print ceil(5/3)-th \nnode which is 2nd node, i.e., 7." }, { "code": null, "e": 33442, "s": 33264, "text": "Take two pointers temp and fractionalNode and initialize them with null and head respectively.For every k jumps of the temp pointer, make one jump of the fractionalNode pointer." }, { "code": null, "e": 33537, "s": 33442, "text": "Take two pointers temp and fractionalNode and initialize them with null and head respectively." }, { "code": null, "e": 33621, "s": 33537, "text": "For every k jumps of the temp pointer, make one jump of the fractionalNode pointer." }, { "code": null, "e": 33627, "s": 33623, "text": "C++" }, { "code": null, "e": 33632, "s": 33627, "text": "Java" }, { "code": null, "e": 33640, "s": 33632, "text": "Python3" }, { "code": null, "e": 33643, "s": 33640, "text": "C#" }, { "code": null, "e": 33654, "s": 33643, "text": "Javascript" }, { "code": "// C++ program to find fractional node in a linked list#include <bits/stdc++.h> /* Linked list node */struct Node { int data; Node* next;}; /* Function to create a new node with given data */Node* newNode(int data){ Node* new_node = new Node; new_node->data = data; new_node->next = NULL; return new_node;} /* Function to find fractional node in the linked list */Node* fractionalNodes(Node* head, int k){ // Corner cases if (k <= 0 || head == NULL) return NULL; Node* fractionalNode = NULL; // Traverse the given list int i = 0; for (Node* temp = head; temp != NULL; temp = temp->next) { // For every k nodes, we move fractionalNode one // step ahead. if (i % k == 0) { // First time we see a multiple of k if (fractionalNode == NULL) fractionalNode = head; else fractionalNode = fractionalNode->next; } i++; } return fractionalNode;} // A utility function to print a linked listvoid printList(Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; } printf(\"\\n\");} /* Driver program to test above function */int main(void){ Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); int k = 2; printf(\"List is \"); printList(head); Node* answer = fractionalNodes(head, k); printf(\"\\nFractional node is \"); printf(\"%d\\n\", answer->data); return 0;}", "e": 35249, "s": 33654, "text": null }, { "code": "// Java program to find fractional node in// a linked listpublic class FractionalNodell{ /* Linked list node */ static class Node{ int data; Node next; //Constructor Node (int data){ this.data = data; } } /* Function to find fractional node in the linked list */ static Node fractionalNodes(Node head, int k) { // Corner cases if (k <= 0 || head == null) return null; Node fractionalNode = null; // Traverse the given list int i = 0; for (Node temp = head; temp != null; temp = temp.next){ // For every k nodes, we move // fractionalNode one step ahead. if (i % k == 0){ // First time we see a multiple of k if (fractionalNode == null) fractionalNode = head; else fractionalNode = fractionalNode.next; } i++; } return fractionalNode; } // A utility function to print a linked list static void printList(Node node) { while (node != null) { System.out.print(node.data+\" \"); node = node.next; } System.out.println(); } /* Driver program to test above function */ public static void main(String[] args) { Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); int k =2; System.out.print(\"List is \"); printList(head); Node answer = fractionalNodes(head, k); System.out.println(\"Fractional node is \"+ answer.data); }}// This code is contributed by Sumit Ghosh", "e": 37094, "s": 35249, "text": null }, { "code": "# Python3 program to find fractional node# in a linked listimport math # Linked list nodeclass Node: def __init__(self, data): self.data = data self.next = None # Function to create a new node# with given datadef newNode(data): new_node = Node(data) new_node.data = data new_node.next = None return new_node # Function to find fractional node# in the linked listdef fractionalNodes(head, k): # Corner cases if (k <= 0 or head == None): return None fractionalNode = None # Traverse the given list i = 0 temp = head while (temp != None): # For every k nodes, we move # fractionalNode one step ahead. if (i % k == 0): # First time we see a multiple of k if (fractionalNode == None): fractionalNode = head else: fractionalNode = fractionalNode.next i = i + 1 temp = temp.next return fractionalNode # A utility function to print a linked listdef printList(node): while (node != None): print(node.data, end = ' ') node = node.next # Driver Codeif __name__ == '__main__': head = newNode(1) head.next = newNode(2) head.next.next = newNode(3) head.next.next.next = newNode(4) head.next.next.next.next = newNode(5) k = 2 print(\"List is\", end = ' ') printList(head) answer = fractionalNodes(head, k) print(\"\\nFractional node is\", end = ' ') print(answer.data) # This code is contributed by Srathore", "e": 38612, "s": 37094, "text": null }, { "code": "// C# program to find fractional node in// a linked listusing System; public class FractionalNodell{ /* Linked list node */ public class Node { public int data; public Node next; //Constructor public Node (int data) { this.data = data; } } /* Function to find fractional node in the linked list */ static Node fractionalNodes(Node head, int k) { // Corner cases if (k <= 0 || head == null) return null; Node fractionalNode = null; // Traverse the given list int i = 0; for (Node temp = head; temp != null; temp = temp.next) { // For every k nodes, we move // fractionalNode one step ahead. if (i % k == 0) { // First time we see a multiple of k if (fractionalNode == null) fractionalNode = head; else fractionalNode = fractionalNode.next; } i++; } return fractionalNode; } // A utility function to print a linked list static void printList(Node node) { while (node != null) { Console.Write(node.data+\" \"); node = node.next; } Console.WriteLine(); } /* Driver code */ public static void Main(String[] args) { Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); int k =2; Console.Write(\"List is \"); printList(head); Node answer = fractionalNodes(head, k); Console.WriteLine(\"Fractional node is \"+ answer.data); }} // This code is contributed by Rajput-Ji", "e": 40483, "s": 38612, "text": null }, { "code": "<script> // JavaScript program to find fractional node in// a linked list /* Linked list node */ class Node { constructor(val) { this.data = val; this.next = null; } } /* * Function to find fractional node in the linked list */ function fractionalNodes(head , k) { // Corner cases if (k <= 0 || head == null) return null; var fractionalNode = null; // Traverse the given list var i = 0; for (temp = head; temp != null; temp = temp.next) { // For every k nodes, we move // fractionalNode one step ahead. if (i % k == 0) { // First time we see a multiple of k if (fractionalNode == null) fractionalNode = head; else fractionalNode = fractionalNode.next; } i++; } return fractionalNode; } // A utility function to print a linked list function printList(node) { while (node != null) { document.write(node.data + \" \"); node = node.next; } document.write(); } /* Driver program to test above function */ var head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); var k = 2; document.write(\"List is \"); printList(head); var answer = fractionalNodes(head, k); document.write(\"<br/>Fractional node is \" + answer.data); // This code contributed by Rajput-Ji </script>", "e": 42164, "s": 40483, "text": null }, { "code": null, "e": 42174, "s": 42164, "text": "Output: " }, { "code": null, "e": 42214, "s": 42174, "text": "List is 1 2 3 4 5 \nFractional node is 3" }, { "code": null, "e": 42636, "s": 42214, "text": "This article is contributed by Prakriti 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 contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 42646, "s": 42636, "text": "Rajput-Ji" }, { "code": null, "e": 42661, "s": 42646, "text": "sapnasingh4991" }, { "code": null, "e": 42674, "s": 42661, "text": "Akanksha_Rai" }, { "code": null, "e": 42691, "s": 42674, "text": "arorakashish0911" }, { "code": null, "e": 42708, "s": 42691, "text": "surinderdawra388" }, { "code": null, "e": 42717, "s": 42708, "text": "Fraction" }, { "code": null, "e": 42722, "s": 42717, "text": "Hike" }, { "code": null, "e": 42731, "s": 42722, "text": "SAP Labs" }, { "code": null, "e": 42743, "s": 42731, "text": "Linked List" }, { "code": null, "e": 42748, "s": 42743, "text": "Hike" }, { "code": null, "e": 42757, "s": 42748, "text": "SAP Labs" }, { "code": null, "e": 42769, "s": 42757, "text": "Linked List" }, { "code": null, "e": 42867, "s": 42769, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42902, "s": 42867, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 42941, "s": 42902, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 42989, "s": 42941, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 43027, "s": 42989, "text": "Linked List | Set 3 (Deleting a node)" }, { "code": null, "e": 43046, "s": 43027, "text": "LinkedList in Java" }, { "code": null, "e": 43067, "s": 43046, "text": "Linked List vs Array" }, { "code": null, "e": 43096, "s": 43067, "text": "Detect loop in a linked list" }, { "code": null, "e": 43126, "s": 43096, "text": "Merge two sorted linked lists" }, { "code": null, "e": 43165, "s": 43126, "text": "Find the middle of a given linked list" } ]
Convert Adjacency List to Adjacency Matrix representation of a Graph - GeeksforGeeks
30 Jun, 2021 Given an adjacency list representation of a Graph, the task is to convert the given Adjacency List to Adjacency Matrix representation. Examples: Input: adjList[] = {{0 –> 1 –> 3}, {1 –> 2}, {2 –> 3}} Output: 0 1 0 10 0 1 00 0 0 10 0 0 0 Input: adjList[] = {{0 –> 1 –> 4}, {1 –> 0 –> 2 –> 3 –> 4}, {2 –> 1 –> 3}, {3 –> 1 –> 2 –> 4}, {4 –> 0 –> 1 –> 3}} Output: 0 1 0 0 11 0 1 1 10 1 0 1 00 1 1 0 11 1 0 1 0 Adjacency List: An array of lists is used. The size of the array is equal to the number of vertices. Let the array be an array[]. An entry array[i] represents the list of vertices adjacent to the ith Vertex. Adjacency Matrix: Adjacency Matrix is a 2D array of size V x V where V is the number of vertices in a graph. Let the 2D array be adj[][], a slot adj[i][j] = 1 indicates that there is an edge from vertex i to vertex j. Follow the steps below to convert an adjacency list to an adjacency matrix: Initialize a matrix with 0s. Iterate over the vertices in the adjacency list For every jth vertex in the adjacency list, traverse its edges. For each vertex i with which the jth vertex has an edge, set mat[i][j] = 1. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to insert vertices to adjacency listvoid insert(vector<int> adj[], int u, int v){ // Insert a vertex v to vertex u adj[u].push_back(v); return;} // Function to display adjacency listvoid printList(vector<int> adj[], int V){ for (int i = 0; i < V; i++) { cout << i; for (auto j : adj[i]) cout << " --> " << j; cout << endl; } cout << endl;} // Function to convert adjacency// list to adjacency matrixvector<vector<int> > convert(vector<int> adj[], int V){ // Initialize a matrix vector<vector<int> > matrix(V, vector<int>(V, 0)); for (int i = 0; i < V; i++) { for (auto j : adj[i]) matrix[i][j] = 1; } return matrix;} // Function to display adjacency matrixvoid printMatrix(vector<vector<int> > adj, int V){ for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { cout << adj[i][j] << " "; } cout << endl; } cout << endl;} // Driver codeint main(){ int V = 5; vector<int> adjList[V]; // Inserting edges insert(adjList, 0, 1); insert(adjList, 0, 4); insert(adjList, 1, 0); insert(adjList, 1, 2); insert(adjList, 1, 3); insert(adjList, 1, 4); insert(adjList, 2, 1); insert(adjList, 2, 3); insert(adjList, 3, 1); insert(adjList, 3, 2); insert(adjList, 3, 4); insert(adjList, 4, 0); insert(adjList, 4, 1); insert(adjList, 4, 3); // Display adjacency list cout << "Adjacency List: \n"; printList(adjList, V); // Function call which returns // adjacency matrix after conversion vector<vector<int> > adjMatrix = convert(adjList, V); // Display adjacency matrix cout << "Adjacency Matrix: \n"; printMatrix(adjMatrix, V); return 0;} // Java program to implement// the above approachimport java.util.*; class GFG{ // Function to insert vertices to adjacency liststatic void insert(Vector<Integer> adj[], int u, int v){ // Insert a vertex v to vertex u adj[u].add(v); return;} // Function to display adjacency liststatic void printList(Vector<Integer> adj[], int V){ for(int i = 0; i < V; i++) { System.out.print(i); for(int j : adj[i]) System.out.print(" --> " + j); System.out.println(); } System.out.println();} // Function to convert adjacency// list to adjacency matrixstatic int[][] convert(Vector<Integer> adj[], int V){ // Initialize a matrix int [][]matrix = new int[V][V]; for(int i = 0; i < V; i++) { for(int j : adj[i]) matrix[i][j] = 1; } return matrix;} // Function to display adjacency matrixstatic void printMatrix(int[][] adj, int V){ for(int i = 0; i < V; i++) { for(int j = 0; j < V; j++) { System.out.print(adj[i][j] + " "); } System.out.println(); } System.out.println();} // Driver codepublic static void main(String[] args){ int V = 5; @SuppressWarnings("unchecked") Vector<Integer> []adjList = new Vector[V]; for(int i = 0; i < adjList.length; i++) adjList[i] = new Vector<Integer>(); // Inserting edges insert(adjList, 0, 1); insert(adjList, 0, 4); insert(adjList, 1, 0); insert(adjList, 1, 2); insert(adjList, 1, 3); insert(adjList, 1, 4); insert(adjList, 2, 1); insert(adjList, 2, 3); insert(adjList, 3, 1); insert(adjList, 3, 2); insert(adjList, 3, 4); insert(adjList, 4, 0); insert(adjList, 4, 1); insert(adjList, 4, 3); // Display adjacency list System.out.print("Adjacency List: \n"); printList(adjList, V); // Function call which returns // adjacency matrix after conversion int[][] adjMatrix = convert(adjList, V); // Display adjacency matrix System.out.print("Adjacency Matrix: \n"); printMatrix(adjMatrix, V);}} // This code is contributed by amal kumar choubey # Python3 program to implement# the above approach # Function to insert vertices# to adjacency listdef insert(adj, u, v): # Insert a vertex v to vertex u adj[u].append(v) return # Function to display adjacency listdef printList(adj, V): for i in range(V): print(i, end = '') for j in adj[i]: print(' --> ' + str(j), end = '') print() print() # Function to convert adjacency# list to adjacency matrixdef convert(adj, V): # Initialize a matrix matrix = [[0 for j in range(V)] for i in range(V)] for i in range(V): for j in adj[i]: matrix[i][j] = 1 return matrix # Function to display adjacency matrixdef printMatrix(adj, V): for i in range(V): for j in range(V): print(adj[i][j], end = ' ') print() print() # Driver codeif __name__=='__main__': V = 5 adjList = [[] for i in range(V)] # Inserting edges insert(adjList, 0, 1) insert(adjList, 0, 4) insert(adjList, 1, 0) insert(adjList, 1, 2) insert(adjList, 1, 3) insert(adjList, 1, 4) insert(adjList, 2, 1) insert(adjList, 2, 3) insert(adjList, 3, 1) insert(adjList, 3, 2) insert(adjList, 3, 4) insert(adjList, 4, 0) insert(adjList, 4, 1) insert(adjList, 4, 3) # Display adjacency list print("Adjacency List: ") printList(adjList, V) # Function call which returns # adjacency matrix after conversion adjMatrix = convert(adjList, V) # Display adjacency matrix print("Adjacency Matrix: ") printMatrix(adjMatrix, V) # This code is contributed by rutvik_56 // C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG{ // Function to insert vertices to adjacency liststatic void insert(List<int> []adj, int u, int v){ // Insert a vertex v to vertex u adj[u].Add(v); return;} // Function to display adjacency liststatic void printList(List<int> []adj, int V){ for(int i = 0; i < V; i++) { Console.Write(i); foreach(int j in adj[i]) Console.Write(" --> " + j); Console.WriteLine(); } Console.WriteLine();} // Function to convert adjacency// list to adjacency matrixstatic int[,] convert(List<int> []adj, int V){ // Initialize a matrix int [,]matrix = new int[V, V]; for(int i = 0; i < V; i++) { foreach(int j in adj[i]) matrix[i, j] = 1; } return matrix;} // Function to display adjacency matrixstatic void printMatrix(int[,] adj, int V){ for(int i = 0; i < V; i++) { for(int j = 0; j < V; j++) { Console.Write(adj[i, j] + " "); } Console.WriteLine(); } Console.WriteLine();} // Driver codepublic static void Main(String[] args){ int V = 5; List<int> []adjList = new List<int>[V]; for(int i = 0; i < adjList.Length; i++) adjList[i] = new List<int>(); // Inserting edges insert(adjList, 0, 1); insert(adjList, 0, 4); insert(adjList, 1, 0); insert(adjList, 1, 2); insert(adjList, 1, 3); insert(adjList, 1, 4); insert(adjList, 2, 1); insert(adjList, 2, 3); insert(adjList, 3, 1); insert(adjList, 3, 2); insert(adjList, 3, 4); insert(adjList, 4, 0); insert(adjList, 4, 1); insert(adjList, 4, 3); // Display adjacency list Console.Write("Adjacency List: \n"); printList(adjList, V); // Function call which returns // adjacency matrix after conversion int[,] adjMatrix = convert(adjList, V); // Display adjacency matrix Console.Write("Adjacency Matrix: \n"); printMatrix(adjMatrix, V);}} // This code is contributed by amal kumar choubey <script> // Javascript program to implement// the above approach // Function to insert vertices to adjacency listfunction insert(adj, u, v){ // Insert a vertex v to vertex u adj[u].push(v); return;} // Function to display adjacency listfunction printList(adj, V){ for(var i = 0; i < V; i++) { document.write(i); for(var j of adj[i]) document.write(" --> " + j); document.write("<br>"); } document.write("<br>");} // Function to convert adjacency// list to adjacency matrixfunction convert(adj, V){ // Initialize a matrix var matrix = Array.from(Array(V), ()=>Array(V).fill(0)); for (var i = 0; i < V; i++) { for (var j of adj[i]) matrix[i][j] = 1; } return matrix;} // Function to display adjacency matrixfunction printMatrix(adj, V){ for(var i = 0; i < V; i++) { for(var j = 0; j < V; j++) { document.write(adj[i][j] + " "); } document.write("<br>"); } document.write("<br>");} // Driver codevar V = 5;var adjList = Array.from(Array(V), ()=>Array().fill(0)); // Inserting edgesinsert(adjList, 0, 1);insert(adjList, 0, 4);insert(adjList, 1, 0);insert(adjList, 1, 2);insert(adjList, 1, 3);insert(adjList, 1, 4);insert(adjList, 2, 1);insert(adjList, 2, 3);insert(adjList, 3, 1);insert(adjList, 3, 2);insert(adjList, 3, 4);insert(adjList, 4, 0);insert(adjList, 4, 1);insert(adjList, 4, 3);// Display adjacency listdocument.write("Adjacency List: <br>");printList(adjList, V);// Function call which returns// adjacency matrix after conversionvar adjMatrix = convert(adjList, V);// Display adjacency matrixdocument.write("Adjacency Matrix: <br>");printMatrix(adjMatrix, V); </script> Adjacency List: 0 --> 1 --> 4 1 --> 0 --> 2 --> 3 --> 4 2 --> 1 --> 3 3 --> 1 --> 2 --> 4 4 --> 0 --> 1 --> 3 Adjacency Matrix: 0 1 0 0 1 1 0 1 1 1 0 1 0 1 0 0 1 1 0 1 1 1 0 1 0 Time Complexity: O(N*M) Auxiliary Space: O(N2) Amal Kumar Choubey rutvik_56 rrrtnx Graph Traversals graph-basics Data Structures Graph Data Structures Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar How to Start Learning DSA? Introduction to Algorithms Insertion and Deletion in Heaps Dijkstra's shortest path algorithm | Greedy Algo-7 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Topological Sorting Bellman–Ford Algorithm | DP-23
[ { "code": null, "e": 26743, "s": 26715, "text": "\n30 Jun, 2021" }, { "code": null, "e": 26878, "s": 26743, "text": "Given an adjacency list representation of a Graph, the task is to convert the given Adjacency List to Adjacency Matrix representation." }, { "code": null, "e": 26890, "s": 26878, "text": "Examples: " }, { "code": null, "e": 26982, "s": 26890, "text": "Input: adjList[] = {{0 –> 1 –> 3}, {1 –> 2}, {2 –> 3}} Output: 0 1 0 10 0 1 00 0 0 10 0 0 0" }, { "code": null, "e": 27152, "s": 26982, "text": "Input: adjList[] = {{0 –> 1 –> 4}, {1 –> 0 –> 2 –> 3 –> 4}, {2 –> 1 –> 3}, {3 –> 1 –> 2 –> 4}, {4 –> 0 –> 1 –> 3}} Output: 0 1 0 0 11 0 1 1 10 1 0 1 00 1 1 0 11 1 0 1 0 " }, { "code": null, "e": 27360, "s": 27152, "text": "Adjacency List: An array of lists is used. The size of the array is equal to the number of vertices. Let the array be an array[]. An entry array[i] represents the list of vertices adjacent to the ith Vertex." }, { "code": null, "e": 27578, "s": 27360, "text": "Adjacency Matrix: Adjacency Matrix is a 2D array of size V x V where V is the number of vertices in a graph. Let the 2D array be adj[][], a slot adj[i][j] = 1 indicates that there is an edge from vertex i to vertex j." }, { "code": null, "e": 27655, "s": 27578, "text": "Follow the steps below to convert an adjacency list to an adjacency matrix: " }, { "code": null, "e": 27684, "s": 27655, "text": "Initialize a matrix with 0s." }, { "code": null, "e": 27732, "s": 27684, "text": "Iterate over the vertices in the adjacency list" }, { "code": null, "e": 27796, "s": 27732, "text": "For every jth vertex in the adjacency list, traverse its edges." }, { "code": null, "e": 27872, "s": 27796, "text": "For each vertex i with which the jth vertex has an edge, set mat[i][j] = 1." }, { "code": null, "e": 27923, "s": 27872, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27927, "s": 27923, "text": "C++" }, { "code": null, "e": 27932, "s": 27927, "text": "Java" }, { "code": null, "e": 27940, "s": 27932, "text": "Python3" }, { "code": null, "e": 27943, "s": 27940, "text": "C#" }, { "code": null, "e": 27954, "s": 27943, "text": "Javascript" }, { "code": "// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to insert vertices to adjacency listvoid insert(vector<int> adj[], int u, int v){ // Insert a vertex v to vertex u adj[u].push_back(v); return;} // Function to display adjacency listvoid printList(vector<int> adj[], int V){ for (int i = 0; i < V; i++) { cout << i; for (auto j : adj[i]) cout << \" --> \" << j; cout << endl; } cout << endl;} // Function to convert adjacency// list to adjacency matrixvector<vector<int> > convert(vector<int> adj[], int V){ // Initialize a matrix vector<vector<int> > matrix(V, vector<int>(V, 0)); for (int i = 0; i < V; i++) { for (auto j : adj[i]) matrix[i][j] = 1; } return matrix;} // Function to display adjacency matrixvoid printMatrix(vector<vector<int> > adj, int V){ for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { cout << adj[i][j] << \" \"; } cout << endl; } cout << endl;} // Driver codeint main(){ int V = 5; vector<int> adjList[V]; // Inserting edges insert(adjList, 0, 1); insert(adjList, 0, 4); insert(adjList, 1, 0); insert(adjList, 1, 2); insert(adjList, 1, 3); insert(adjList, 1, 4); insert(adjList, 2, 1); insert(adjList, 2, 3); insert(adjList, 3, 1); insert(adjList, 3, 2); insert(adjList, 3, 4); insert(adjList, 4, 0); insert(adjList, 4, 1); insert(adjList, 4, 3); // Display adjacency list cout << \"Adjacency List: \\n\"; printList(adjList, V); // Function call which returns // adjacency matrix after conversion vector<vector<int> > adjMatrix = convert(adjList, V); // Display adjacency matrix cout << \"Adjacency Matrix: \\n\"; printMatrix(adjMatrix, V); return 0;}", "e": 29866, "s": 27954, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to insert vertices to adjacency liststatic void insert(Vector<Integer> adj[], int u, int v){ // Insert a vertex v to vertex u adj[u].add(v); return;} // Function to display adjacency liststatic void printList(Vector<Integer> adj[], int V){ for(int i = 0; i < V; i++) { System.out.print(i); for(int j : adj[i]) System.out.print(\" --> \" + j); System.out.println(); } System.out.println();} // Function to convert adjacency// list to adjacency matrixstatic int[][] convert(Vector<Integer> adj[], int V){ // Initialize a matrix int [][]matrix = new int[V][V]; for(int i = 0; i < V; i++) { for(int j : adj[i]) matrix[i][j] = 1; } return matrix;} // Function to display adjacency matrixstatic void printMatrix(int[][] adj, int V){ for(int i = 0; i < V; i++) { for(int j = 0; j < V; j++) { System.out.print(adj[i][j] + \" \"); } System.out.println(); } System.out.println();} // Driver codepublic static void main(String[] args){ int V = 5; @SuppressWarnings(\"unchecked\") Vector<Integer> []adjList = new Vector[V]; for(int i = 0; i < adjList.length; i++) adjList[i] = new Vector<Integer>(); // Inserting edges insert(adjList, 0, 1); insert(adjList, 0, 4); insert(adjList, 1, 0); insert(adjList, 1, 2); insert(adjList, 1, 3); insert(adjList, 1, 4); insert(adjList, 2, 1); insert(adjList, 2, 3); insert(adjList, 3, 1); insert(adjList, 3, 2); insert(adjList, 3, 4); insert(adjList, 4, 0); insert(adjList, 4, 1); insert(adjList, 4, 3); // Display adjacency list System.out.print(\"Adjacency List: \\n\"); printList(adjList, V); // Function call which returns // adjacency matrix after conversion int[][] adjMatrix = convert(adjList, V); // Display adjacency matrix System.out.print(\"Adjacency Matrix: \\n\"); printMatrix(adjMatrix, V);}} // This code is contributed by amal kumar choubey", "e": 32058, "s": 29866, "text": null }, { "code": "# Python3 program to implement# the above approach # Function to insert vertices# to adjacency listdef insert(adj, u, v): # Insert a vertex v to vertex u adj[u].append(v) return # Function to display adjacency listdef printList(adj, V): for i in range(V): print(i, end = '') for j in adj[i]: print(' --> ' + str(j), end = '') print() print() # Function to convert adjacency# list to adjacency matrixdef convert(adj, V): # Initialize a matrix matrix = [[0 for j in range(V)] for i in range(V)] for i in range(V): for j in adj[i]: matrix[i][j] = 1 return matrix # Function to display adjacency matrixdef printMatrix(adj, V): for i in range(V): for j in range(V): print(adj[i][j], end = ' ') print() print() # Driver codeif __name__=='__main__': V = 5 adjList = [[] for i in range(V)] # Inserting edges insert(adjList, 0, 1) insert(adjList, 0, 4) insert(adjList, 1, 0) insert(adjList, 1, 2) insert(adjList, 1, 3) insert(adjList, 1, 4) insert(adjList, 2, 1) insert(adjList, 2, 3) insert(adjList, 3, 1) insert(adjList, 3, 2) insert(adjList, 3, 4) insert(adjList, 4, 0) insert(adjList, 4, 1) insert(adjList, 4, 3) # Display adjacency list print(\"Adjacency List: \") printList(adjList, V) # Function call which returns # adjacency matrix after conversion adjMatrix = convert(adjList, V) # Display adjacency matrix print(\"Adjacency Matrix: \") printMatrix(adjMatrix, V) # This code is contributed by rutvik_56", "e": 33765, "s": 32058, "text": null }, { "code": "// C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG{ // Function to insert vertices to adjacency liststatic void insert(List<int> []adj, int u, int v){ // Insert a vertex v to vertex u adj[u].Add(v); return;} // Function to display adjacency liststatic void printList(List<int> []adj, int V){ for(int i = 0; i < V; i++) { Console.Write(i); foreach(int j in adj[i]) Console.Write(\" --> \" + j); Console.WriteLine(); } Console.WriteLine();} // Function to convert adjacency// list to adjacency matrixstatic int[,] convert(List<int> []adj, int V){ // Initialize a matrix int [,]matrix = new int[V, V]; for(int i = 0; i < V; i++) { foreach(int j in adj[i]) matrix[i, j] = 1; } return matrix;} // Function to display adjacency matrixstatic void printMatrix(int[,] adj, int V){ for(int i = 0; i < V; i++) { for(int j = 0; j < V; j++) { Console.Write(adj[i, j] + \" \"); } Console.WriteLine(); } Console.WriteLine();} // Driver codepublic static void Main(String[] args){ int V = 5; List<int> []adjList = new List<int>[V]; for(int i = 0; i < adjList.Length; i++) adjList[i] = new List<int>(); // Inserting edges insert(adjList, 0, 1); insert(adjList, 0, 4); insert(adjList, 1, 0); insert(adjList, 1, 2); insert(adjList, 1, 3); insert(adjList, 1, 4); insert(adjList, 2, 1); insert(adjList, 2, 3); insert(adjList, 3, 1); insert(adjList, 3, 2); insert(adjList, 3, 4); insert(adjList, 4, 0); insert(adjList, 4, 1); insert(adjList, 4, 3); // Display adjacency list Console.Write(\"Adjacency List: \\n\"); printList(adjList, V); // Function call which returns // adjacency matrix after conversion int[,] adjMatrix = convert(adjList, V); // Display adjacency matrix Console.Write(\"Adjacency Matrix: \\n\"); printMatrix(adjMatrix, V);}} // This code is contributed by amal kumar choubey", "e": 35922, "s": 33765, "text": null }, { "code": "<script> // Javascript program to implement// the above approach // Function to insert vertices to adjacency listfunction insert(adj, u, v){ // Insert a vertex v to vertex u adj[u].push(v); return;} // Function to display adjacency listfunction printList(adj, V){ for(var i = 0; i < V; i++) { document.write(i); for(var j of adj[i]) document.write(\" --> \" + j); document.write(\"<br>\"); } document.write(\"<br>\");} // Function to convert adjacency// list to adjacency matrixfunction convert(adj, V){ // Initialize a matrix var matrix = Array.from(Array(V), ()=>Array(V).fill(0)); for (var i = 0; i < V; i++) { for (var j of adj[i]) matrix[i][j] = 1; } return matrix;} // Function to display adjacency matrixfunction printMatrix(adj, V){ for(var i = 0; i < V; i++) { for(var j = 0; j < V; j++) { document.write(adj[i][j] + \" \"); } document.write(\"<br>\"); } document.write(\"<br>\");} // Driver codevar V = 5;var adjList = Array.from(Array(V), ()=>Array().fill(0)); // Inserting edgesinsert(adjList, 0, 1);insert(adjList, 0, 4);insert(adjList, 1, 0);insert(adjList, 1, 2);insert(adjList, 1, 3);insert(adjList, 1, 4);insert(adjList, 2, 1);insert(adjList, 2, 3);insert(adjList, 3, 1);insert(adjList, 3, 2);insert(adjList, 3, 4);insert(adjList, 4, 0);insert(adjList, 4, 1);insert(adjList, 4, 3);// Display adjacency listdocument.write(\"Adjacency List: <br>\");printList(adjList, V);// Function call which returns// adjacency matrix after conversionvar adjMatrix = convert(adjList, V);// Display adjacency matrixdocument.write(\"Adjacency Matrix: <br>\");printMatrix(adjMatrix, V); </script>", "e": 37668, "s": 35922, "text": null }, { "code": null, "e": 37901, "s": 37668, "text": "Adjacency List: \n0 --> 1 --> 4\n1 --> 0 --> 2 --> 3 --> 4\n2 --> 1 --> 3\n3 --> 1 --> 2 --> 4\n4 --> 0 --> 1 --> 3\n\nAdjacency Matrix: \n0 1 0 0 1 \n1 0 1 1 1 \n0 1 0 1 0 \n0 1 1 0 1 \n1 1 0 1 0" }, { "code": null, "e": 37951, "s": 37903, "text": "Time Complexity: O(N*M) Auxiliary Space: O(N2) " }, { "code": null, "e": 37970, "s": 37951, "text": "Amal Kumar Choubey" }, { "code": null, "e": 37980, "s": 37970, "text": "rutvik_56" }, { "code": null, "e": 37987, "s": 37980, "text": "rrrtnx" }, { "code": null, "e": 38004, "s": 37987, "text": "Graph Traversals" }, { "code": null, "e": 38017, "s": 38004, "text": "graph-basics" }, { "code": null, "e": 38033, "s": 38017, "text": "Data Structures" }, { "code": null, "e": 38039, "s": 38033, "text": "Graph" }, { "code": null, "e": 38055, "s": 38039, "text": "Data Structures" }, { "code": null, "e": 38061, "s": 38055, "text": "Graph" }, { "code": null, "e": 38159, "s": 38061, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38208, "s": 38159, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 38233, "s": 38208, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 38260, "s": 38233, "text": "How to Start Learning DSA?" }, { "code": null, "e": 38287, "s": 38260, "text": "Introduction to Algorithms" }, { "code": null, "e": 38319, "s": 38287, "text": "Insertion and Deletion in Heaps" }, { "code": null, "e": 38370, "s": 38319, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 38428, "s": 38370, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 38479, "s": 38428, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 38499, "s": 38479, "text": "Topological Sorting" } ]
Using Machine Learning to Predict if a F1 Driver Will Score | by Caio Santos Pedroso | Towards Data Science
I’m a huge fan of Formula One, all the technology, the mechanics, how fast everything evolves, the amount of investment in research, all these characteristics make me being fascinated about this world, and recently surfing the web I’ve found this dataset in kaggle with compiled data from 1950 to 2020, so I decide to play around with it and see if I was able to find some insights and in the end create a simple model to predict something related to podium, position, or if a driver will or not score. A lot of people say these days that Formula One is decided by the car features more than the driver itself, and it is partially true, the car is really important to the race result, but the driver skills and the strategy that the team and the driver create before the race given the circumstances, which kind of tire, how many pit stops, if it’s warm or cold, if it’s gonna rain, all of these characteristics matter in the end, and the driver is a really important piece of this equation to feel and use his experience to determine the better strategy to the race, and to improve even more the efficacy of this decision, we see a lot of Machine Learning involved and we probably gonna see more and more as data being collected by the teams is increasing. “Races are won at the track. Championships are won at the factory.” — Mercedes-AMG Petronas Motorsport The dataset was distributed in different files, one for drivers, one for the constructor, one for race results, and so on, to get more information about all the available data and fields, please check the kaggle page, the link is above. The first thing I did was to merge all these datasets to create one with all the necessary information I needed. The only dataset that required some transformation was the pit stops one, every pit stop was a row in the dataset, and I wanted to know how many pit stops one pilot did at a race, so I had to group by racerId using count aggregation. df_pitstops_gb = df_pitstops.groupby([“driverId”, “raceId”]).count().reset_index() Then I was able to merge the pit stops with the other datasets. With the base dataset ready, I started to verify the fields and how the data was distributed in then. The first thing I did was to check how driver’s positions in the race were distributed, the result was the chart below. The two things that gave me a warning flag were the “\N”, which means that the driver did not finish the race, and, besides today’s grid have only 20 cars, there were times where more cars were allowed, at least 24 as per our data. With that information, I was ready to start the Data Preparation part. By curiosity, I tried to identify what causes most drivers to not finish the race and where, and the result was quite predictable, the problems were related to one of the most important parts of the car, the engine, and the circuit, the well-known of every F1 fan, Monaco. Knowing a lot about the data, this part was kinda easy. The first thing I did was to decide what to do with the drivers that did not finish a race, the “\N”, as we don’t have enough information about the specifics of the strategy that could cause an engine failure, the most assertive thing to do was to remove this rows. df_base = df_base[df_base.position == ‘\\N’] As already explained, in recent years, there were more than 20 cars in the grid, but now there are only 20 cars, to set the “bounds” of the prediction and to be fair with the data, I’ve subtracted the driver position by the difference between the position and 20. df_base['position'] = df_base['position'].apply(lambda x: x if x <= 20 else x-(x-20)) One of the most critical things was that the data was not that well balanced, in the “original” data we had a lot of drivers in the first positions of the grid and a few in the end, mostly because of the ones who did not finish the race. Having that in mind in combination with, what I judged fewer data to predict the position of the race, I realized that I was only able to predict if the driver would score in the race or not, i.e. the drive would finish in the first 10 positions, so one more column was created, our target, 1 if the driver will score and 0 if not. df_base['score'] = df_base['position'].apply(lambda x: 1 if x in range(1,11) else 0) This new way to see the target, made the dataset to be fairly distributed, 40% in class 1 and 60% in class 0. Then I separated the columns I found useful for the prediction circuitname: The name of the circuit where the race will happen grid: The start position in the grid stop: The number of pist stops the team is planning to do constructorname: The name of the constructor of the car The fields with “name” were text ones, to apply a Machine Learning algorithm, I used the “get_dummies” function from pandas, the idea was to apply the one-hot encoding technique and having them as a number. X = df_base[["circuitname", "grid", "stop", "constructorname"]]y = df_base["podium"]X = pd.get_dummies(X) To predict our class I decided to test two different models, the Random Forest and XGBoost, the first one was because this problem looks like one that would fit a Decision Tree problem. I went directly to Random Forest as overkill to solve the problem, and the XGBoost was a very similar decision to the first one, besides the fact that is the algorithm that I use the most. With the data already splited I decided to use the GridSearchCV for both algorithms to try different params and look for the best one, you can check the params and the result below. params = { 'n_estimators':[100, 300, 500, 800, 1200], 'max_depth': [5, 8, 15, 25, 30], 'min_samples_split': [2, 5, 10, 15, 100], 'min_samples_leaf': [1, 2, 5, 10] }clf = GridSearchCV(estimator=RandomForestClassifier(), param_grid=params)clf.fit(X_train, y_train)print(clf.best_params_) max_depth=25, min_samples_leaf=1, min_samples_split=15, n_estimators=1200 params = { 'min_child_weight': [1, 3, 5, 7], 'gamma': [0.3, 0.4, 0.5, 0.7, 1, 1.5, 2, 5], 'subsample': [0.6, 0.8, 1.0], 'colsample_bytree': [0.3, 0.4, 0.5, 0.6, 0.8, 1.0], 'max_depth': [5, 8, 15, 25, 30], 'eval_metric': ['error'] }clf = GridSearchCV(estimator=XGBClassifier(), param_grid=params)clf.fit(X_train, y_train)print(clf.best_params_) colsample_bytree=1.0,gamma=2, max_depth=5, min_child_weight=1, subsample=1.0 The results of both algorithms at their “state of the art” for this problem were very similar as you check below. As I don’t want my driver to be misguided by the algorithm saying that he will score, but his team strategy was not that good, I decided to use Precision as the main metric, penalizing the False Positives, and the weighted version of the metric, as I don’t have a big imbalanced dataset. so the chosen one was Random Forest, but as you can see, the difference is just 0.01. If you have any questions regarding the article’s content, please feel free to reach out to me. You can find me on Linkedin.
[ { "code": null, "e": 674, "s": 171, "text": "I’m a huge fan of Formula One, all the technology, the mechanics, how fast everything evolves, the amount of investment in research, all these characteristics make me being fascinated about this world, and recently surfing the web I’ve found this dataset in kaggle with compiled data from 1950 to 2020, so I decide to play around with it and see if I was able to find some insights and in the end create a simple model to predict something related to podium, position, or if a driver will or not score." }, { "code": null, "e": 1429, "s": 674, "text": "A lot of people say these days that Formula One is decided by the car features more than the driver itself, and it is partially true, the car is really important to the race result, but the driver skills and the strategy that the team and the driver create before the race given the circumstances, which kind of tire, how many pit stops, if it’s warm or cold, if it’s gonna rain, all of these characteristics matter in the end, and the driver is a really important piece of this equation to feel and use his experience to determine the better strategy to the race, and to improve even more the efficacy of this decision, we see a lot of Machine Learning involved and we probably gonna see more and more as data being collected by the teams is increasing." }, { "code": null, "e": 1532, "s": 1429, "text": "“Races are won at the track. Championships are won at the factory.” — Mercedes-AMG Petronas Motorsport" }, { "code": null, "e": 2116, "s": 1532, "text": "The dataset was distributed in different files, one for drivers, one for the constructor, one for race results, and so on, to get more information about all the available data and fields, please check the kaggle page, the link is above. The first thing I did was to merge all these datasets to create one with all the necessary information I needed. The only dataset that required some transformation was the pit stops one, every pit stop was a row in the dataset, and I wanted to know how many pit stops one pilot did at a race, so I had to group by racerId using count aggregation." }, { "code": null, "e": 2199, "s": 2116, "text": "df_pitstops_gb = df_pitstops.groupby([“driverId”, “raceId”]).count().reset_index()" }, { "code": null, "e": 2263, "s": 2199, "text": "Then I was able to merge the pit stops with the other datasets." }, { "code": null, "e": 2485, "s": 2263, "text": "With the base dataset ready, I started to verify the fields and how the data was distributed in then. The first thing I did was to check how driver’s positions in the race were distributed, the result was the chart below." }, { "code": null, "e": 2788, "s": 2485, "text": "The two things that gave me a warning flag were the “\\N”, which means that the driver did not finish the race, and, besides today’s grid have only 20 cars, there were times where more cars were allowed, at least 24 as per our data. With that information, I was ready to start the Data Preparation part." }, { "code": null, "e": 3061, "s": 2788, "text": "By curiosity, I tried to identify what causes most drivers to not finish the race and where, and the result was quite predictable, the problems were related to one of the most important parts of the car, the engine, and the circuit, the well-known of every F1 fan, Monaco." }, { "code": null, "e": 3383, "s": 3061, "text": "Knowing a lot about the data, this part was kinda easy. The first thing I did was to decide what to do with the drivers that did not finish a race, the “\\N”, as we don’t have enough information about the specifics of the strategy that could cause an engine failure, the most assertive thing to do was to remove this rows." }, { "code": null, "e": 3428, "s": 3383, "text": "df_base = df_base[df_base.position == ‘\\\\N’]" }, { "code": null, "e": 3692, "s": 3428, "text": "As already explained, in recent years, there were more than 20 cars in the grid, but now there are only 20 cars, to set the “bounds” of the prediction and to be fair with the data, I’ve subtracted the driver position by the difference between the position and 20." }, { "code": null, "e": 3778, "s": 3692, "text": "df_base['position'] = df_base['position'].apply(lambda x: x if x <= 20 else x-(x-20))" }, { "code": null, "e": 4348, "s": 3778, "text": "One of the most critical things was that the data was not that well balanced, in the “original” data we had a lot of drivers in the first positions of the grid and a few in the end, mostly because of the ones who did not finish the race. Having that in mind in combination with, what I judged fewer data to predict the position of the race, I realized that I was only able to predict if the driver would score in the race or not, i.e. the drive would finish in the first 10 positions, so one more column was created, our target, 1 if the driver will score and 0 if not." }, { "code": null, "e": 4433, "s": 4348, "text": "df_base['score'] = df_base['position'].apply(lambda x: 1 if x in range(1,11) else 0)" }, { "code": null, "e": 4543, "s": 4433, "text": "This new way to see the target, made the dataset to be fairly distributed, 40% in class 1 and 60% in class 0." }, { "code": null, "e": 4606, "s": 4543, "text": "Then I separated the columns I found useful for the prediction" }, { "code": null, "e": 4670, "s": 4606, "text": "circuitname: The name of the circuit where the race will happen" }, { "code": null, "e": 4707, "s": 4670, "text": "grid: The start position in the grid" }, { "code": null, "e": 4765, "s": 4707, "text": "stop: The number of pist stops the team is planning to do" }, { "code": null, "e": 4821, "s": 4765, "text": "constructorname: The name of the constructor of the car" }, { "code": null, "e": 5028, "s": 4821, "text": "The fields with “name” were text ones, to apply a Machine Learning algorithm, I used the “get_dummies” function from pandas, the idea was to apply the one-hot encoding technique and having them as a number." }, { "code": null, "e": 5134, "s": 5028, "text": "X = df_base[[\"circuitname\", \"grid\", \"stop\", \"constructorname\"]]y = df_base[\"podium\"]X = pd.get_dummies(X)" }, { "code": null, "e": 5509, "s": 5134, "text": "To predict our class I decided to test two different models, the Random Forest and XGBoost, the first one was because this problem looks like one that would fit a Decision Tree problem. I went directly to Random Forest as overkill to solve the problem, and the XGBoost was a very similar decision to the first one, besides the fact that is the algorithm that I use the most." }, { "code": null, "e": 5691, "s": 5509, "text": "With the data already splited I decided to use the GridSearchCV for both algorithms to try different params and look for the best one, you can check the params and the result below." }, { "code": null, "e": 6029, "s": 5691, "text": "params = { 'n_estimators':[100, 300, 500, 800, 1200], 'max_depth': [5, 8, 15, 25, 30], 'min_samples_split': [2, 5, 10, 15, 100], 'min_samples_leaf': [1, 2, 5, 10] }clf = GridSearchCV(estimator=RandomForestClassifier(), param_grid=params)clf.fit(X_train, y_train)print(clf.best_params_)" }, { "code": null, "e": 6103, "s": 6029, "text": "max_depth=25, min_samples_leaf=1, min_samples_split=15, n_estimators=1200" }, { "code": null, "e": 6520, "s": 6103, "text": "params = { 'min_child_weight': [1, 3, 5, 7], 'gamma': [0.3, 0.4, 0.5, 0.7, 1, 1.5, 2, 5], 'subsample': [0.6, 0.8, 1.0], 'colsample_bytree': [0.3, 0.4, 0.5, 0.6, 0.8, 1.0], 'max_depth': [5, 8, 15, 25, 30], 'eval_metric': ['error'] }clf = GridSearchCV(estimator=XGBClassifier(), param_grid=params)clf.fit(X_train, y_train)print(clf.best_params_)" }, { "code": null, "e": 6597, "s": 6520, "text": "colsample_bytree=1.0,gamma=2, max_depth=5, min_child_weight=1, subsample=1.0" }, { "code": null, "e": 6711, "s": 6597, "text": "The results of both algorithms at their “state of the art” for this problem were very similar as you check below." }, { "code": null, "e": 7085, "s": 6711, "text": "As I don’t want my driver to be misguided by the algorithm saying that he will score, but his team strategy was not that good, I decided to use Precision as the main metric, penalizing the False Positives, and the weighted version of the metric, as I don’t have a big imbalanced dataset. so the chosen one was Random Forest, but as you can see, the difference is just 0.01." } ]
Pair with given sum in a sorted array | Practice | GeeksforGeeks
You are given an array Arr of size N. You need to find all pairs in the array that sum to a number K. If no such pair exists then output will be -1. The elements of the array are distinct and are in sorted order. Note: (a,b) and (b,a) are considered same. Also, an element cannot pair with itself, i.e., (a,a) is invalid. Example 1: ​Input: n = 7 arr[] = {1, 2, 3, 4, 5, 6, 7} K = 8 Output: 3 Explanation: We find 3 such pairs that sum to 8 (1,7) (2,6) (3,5) ​Example 2: Input: n = 7 arr[] = {1, 2, 3, 4, 5, 6, 7} K = 98 Output: -1 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 Countpair() that takes an array (arr), sizeOfArray (n), an integer K and return the count of the pairs which add up to the sum K. The driver code takes care of the printing. Expected Time Complexity: O(N). Expected Auxiliary Space: O(1). Constraints: 0 <= Ai <=107 2 <= N <= 107 0 <= K <= 107 +1 harendraseervi1234567892 weeks ago Easy C++ solution int Countpair(int arr[], int n, int k){ unordered_map<int,int>mp; for(int i=0;i<n;i++){ mp[arr[i]]++; } int ct=0; for(int i=0;i<n;i++){ if(mp[k-arr[i]]) ct++; } if(ct/2==0) return -1; return ct/2; } 0 harshpandeyalfa23 weeks ago C++ (0.03sec) int Countpair(int arr[], int n, int sum){ unordered_set<int> s; int count=0; for (int i=0;i<n;i++) { if(s.find(sum-arr[i]) != s.end() ) count++; s.insert(arr[i]); } if(count==0) return -1; return count; } +1 dangrio1 month ago int count=0; int left=0,right=n-1; while(left<right){ if(arr[left]+arr[right]==sum){ count++; left++,right--; } else if(arr[left]+arr[right]<sum) left++; else right--; } return count==0?-1:count; 0 skjha919992 months ago int Countpair(int a[], int n, int sum) { Arrays.sort(a); int l=0; int r=n-1; int count=0; while(r>l) { if(a[l]+a[r]==sum) { count++; l++; r--; } else if(a[l]+a[r]>sum) r--; else l++; } if(count==0) return -1; return count; } 0 mayank20212 months ago C++int Countpair(int arr[], int n, int sum){ int l=0, r=n-1, count=0; while(l<r) { if(arr[l]+arr[r]==sum) { count++; l++; r--; } else if(arr[l]+arr[r] < sum) l++; else r--; } return count==0?-1:count; } +2 badgujarsachin832 months ago int Countpair(int arr[], int n, int sum){ int c=0; // Complete the function for(int i=0;i<n-1;i++){ for(int j=i+1;j<n;j++){ if(arr[i]+arr[j]==sum){ c++; } } } if(c!=0){ return c; }else{ return -1; } } -1 rajnish243 months ago int Countpair(int a[], int n, int sum) { // Complete the function int x=0; for(int i=0; i<n-1; i++) { for(int j=i+1; j<n; j++) { if(a[i]+a[j]==sum) { x++; } } } if(x!=0) { return x; } else { return -1; } } 0 akashkhurana283 months ago EASY HASHSET SOLUTION int Countpair(int a[], int n, int sum) { // Complete the function int count=0; HashSet<Integer>hs=new HashSet<Integer>(); for(int i=0;i<n;i++){ if(hs.contains(sum-a[i])) count++; hs.add(a[i]); } if(count==0) return -1; else return count; } 0 tanishkaashi5673 months ago class Solution: def Countpair (self, arr, n, sum) : #Complete the function l = 0 h = n-1 count = 0 while l < h: if arr[l] + arr[h] == K: count +=1 l += 1 h -=1 elif arr[l] + arr[h] < K: l += 1 elif arr[l] + arr[h] > K: h -= 1 if count == 0: return -1 return count 0 sagrikasoni3 months ago class Solution{ int Countpair(int a[], int n, int sum) { int i =0, j= a.length-1, count=0; while(i<j){ if(a[i]+a[j]>sum) j--; else if(a[i]+a[j]<sum) i++; else{ count++; i++; j--; } } return count==0?-1:count; } } 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": 548, "s": 226, "text": "You are given an array Arr of size N. You need to find all pairs in the array that sum to a number K. If no such pair exists then output will be -1. The elements of the array are distinct and are in sorted order.\nNote: (a,b) and (b,a) are considered same. Also, an element cannot pair with itself, i.e., (a,a) is invalid." }, { "code": null, "e": 559, "s": 548, "text": "Example 1:" }, { "code": null, "e": 689, "s": 559, "text": "​Input:\nn = 7\narr[] = {1, 2, 3, 4, 5, 6, 7}\nK = 8\nOutput:\n3\nExplanation:\nWe find 3 such pairs that\nsum to 8 (1,7) (2,6) (3,5)\n" }, { "code": null, "e": 705, "s": 689, "text": "\n​Example 2:" }, { "code": null, "e": 768, "s": 705, "text": "Input:\nn = 7\narr[] = {1, 2, 3, 4, 5, 6, 7}\nK = 98 \nOutput:\n-1 " }, { "code": null, "e": 1077, "s": 770, "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 Countpair() that takes an array (arr), sizeOfArray (n), an integer K and return the count of the pairs which add up to the sum K. The driver code takes care of the printing." }, { "code": null, "e": 1142, "s": 1077, "text": "\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 1199, "s": 1144, "text": "Constraints:\n0 <= Ai <=107\n2 <= N <= 107\n0 <= K <= 107" }, { "code": null, "e": 1202, "s": 1199, "text": "+1" }, { "code": null, "e": 1237, "s": 1202, "text": "harendraseervi1234567892 weeks ago" }, { "code": null, "e": 1255, "s": 1237, "text": "Easy C++ solution" }, { "code": null, "e": 1535, "s": 1255, "text": "int Countpair(int arr[], int n, int k){\n unordered_map<int,int>mp;\n for(int i=0;i<n;i++){\n mp[arr[i]]++;\n }\n int ct=0;\n for(int i=0;i<n;i++){\n if(mp[k-arr[i]]) ct++;\n }\n if(ct/2==0) return -1;\n return ct/2;\n }" }, { "code": null, "e": 1537, "s": 1535, "text": "0" }, { "code": null, "e": 1565, "s": 1537, "text": "harshpandeyalfa23 weeks ago" }, { "code": null, "e": 1569, "s": 1565, "text": "C++" }, { "code": null, "e": 1579, "s": 1569, "text": "(0.03sec)" }, { "code": null, "e": 1866, "s": 1579, "text": "int Countpair(int arr[], int n, int sum){ unordered_set<int> s; int count=0; for (int i=0;i<n;i++) { if(s.find(sum-arr[i]) != s.end() ) count++; s.insert(arr[i]); } if(count==0) return -1; return count; }" }, { "code": null, "e": 1869, "s": 1866, "text": "+1" }, { "code": null, "e": 1888, "s": 1869, "text": "dangrio1 month ago" }, { "code": null, "e": 2176, "s": 1888, "text": "int count=0; int left=0,right=n-1; while(left<right){ if(arr[left]+arr[right]==sum){ count++; left++,right--; } else if(arr[left]+arr[right]<sum) left++; else right--; } return count==0?-1:count;" }, { "code": null, "e": 2178, "s": 2176, "text": "0" }, { "code": null, "e": 2201, "s": 2178, "text": "skjha919992 months ago" }, { "code": null, "e": 2578, "s": 2201, "text": " int Countpair(int a[], int n, int sum) { Arrays.sort(a); int l=0; int r=n-1; int count=0; while(r>l) { if(a[l]+a[r]==sum) { count++; l++; r--; } else if(a[l]+a[r]>sum) r--; else l++; } if(count==0) return -1; return count; }" }, { "code": null, "e": 2580, "s": 2578, "text": "0" }, { "code": null, "e": 2603, "s": 2580, "text": "mayank20212 months ago" }, { "code": null, "e": 2982, "s": 2603, "text": "C++int Countpair(int arr[], int n, int sum){ int l=0, r=n-1, count=0; while(l<r) { if(arr[l]+arr[r]==sum) { count++; l++; r--; } else if(arr[l]+arr[r] < sum) l++; else r--; } return count==0?-1:count; }" }, { "code": null, "e": 2985, "s": 2982, "text": "+2" }, { "code": null, "e": 3014, "s": 2985, "text": "badgujarsachin832 months ago" }, { "code": null, "e": 3377, "s": 3014, "text": " int Countpair(int arr[], int n, int sum){\n int c=0;\n // Complete the function\n for(int i=0;i<n-1;i++){\n for(int j=i+1;j<n;j++){\n if(arr[i]+arr[j]==sum){\n c++;\n }\n }\n }\n if(c!=0){\n return c;\n }else{\n return -1;\n }\n }" }, { "code": null, "e": 3380, "s": 3377, "text": "-1" }, { "code": null, "e": 3402, "s": 3380, "text": "rajnish243 months ago" }, { "code": null, "e": 3789, "s": 3402, "text": " int Countpair(int a[], int n, int sum) { // Complete the function int x=0; for(int i=0; i<n-1; i++) { for(int j=i+1; j<n; j++) { if(a[i]+a[j]==sum) { x++; } } } if(x!=0) { return x; } else { return -1; } }" }, { "code": null, "e": 3791, "s": 3789, "text": "0" }, { "code": null, "e": 3818, "s": 3791, "text": "akashkhurana283 months ago" }, { "code": null, "e": 3840, "s": 3818, "text": "EASY HASHSET SOLUTION" }, { "code": null, "e": 4217, "s": 3840, "text": "int Countpair(int a[], int n, int sum) { // Complete the function int count=0; HashSet<Integer>hs=new HashSet<Integer>(); for(int i=0;i<n;i++){ if(hs.contains(sum-a[i])) count++; hs.add(a[i]); } if(count==0) return -1; else return count;" }, { "code": null, "e": 4219, "s": 4217, "text": "}" }, { "code": null, "e": 4221, "s": 4219, "text": "0" }, { "code": null, "e": 4249, "s": 4221, "text": "tanishkaashi5673 months ago" }, { "code": null, "e": 4736, "s": 4249, "text": "class Solution:\n def Countpair (self, arr, n, sum) : \n #Complete the function \n l = 0 \n h = n-1 \n count = 0\n while l < h:\n \n if arr[l] + arr[h] == K:\n count +=1 \n l += 1 \n h -=1 \n elif arr[l] + arr[h] < K:\n l += 1 \n elif arr[l] + arr[h] > K:\n h -= 1 \n \n if count == 0:\n return -1\n return count" }, { "code": null, "e": 4738, "s": 4736, "text": "0" }, { "code": null, "e": 4762, "s": 4738, "text": "sagrikasoni3 months ago" }, { "code": null, "e": 5159, "s": 4762, "text": "class Solution{\n \n \n int Countpair(int a[], int n, int sum)\n { \n int i =0, j= a.length-1, count=0;\n while(i<j){\n if(a[i]+a[j]>sum)\n j--;\n else if(a[i]+a[j]<sum)\n i++;\n else{\n count++;\n i++;\n j--;\n }\n }\n return count==0?-1:count;\n }\n \n \n}\n" }, { "code": null, "e": 5305, "s": 5159, "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": 5341, "s": 5305, "text": " Login to access your submissions. " }, { "code": null, "e": 5351, "s": 5341, "text": "\nProblem\n" }, { "code": null, "e": 5361, "s": 5351, "text": "\nContest\n" }, { "code": null, "e": 5424, "s": 5361, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5572, "s": 5424, "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": 5780, "s": 5572, "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": 5886, "s": 5780, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to find out which character key is pressed using JavaScript?
06 Sep, 2019 Here, the task is to get the character key, which is pressed. In the code written below, an event triggered when any key is pressed and it calls a function then that function identifies it. Approach: Attach an event to the input box. like onkeypress event. Call a function when that event happens and pass the event parameter in it. In the called function, identify the key pressed. Example 1: This example using the approach defined above. <!DOCTYPE HTML><html> <head> <title> How to find out which character key is pressed using JavaScript? </title></head> <body id="body" style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <form> Type Here: <input type="text" onkeypress="return GFG_Fun(event)" /> </form> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); up.innerHTML = "Type in the Input box to see functioning."; var down = document.getElementById('GFG_DOWN'); function GFG_Fun(e) { var key; if (window.event) { key = e.keyCode; } else if (e.which) { key = e.which; } var str = down.innerHTML; str += String.fromCharCode(key); down.innerHTML = str; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This example using the approach defined above. <!DOCTYPE HTML><html> <head> <title> How to find out which character key is pressed using JavaScript? </title></head> <body id="body" style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <form> Type Here: <input type="text" onkeypress="return GFG_Fun(event)" /> </form> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); up.innerHTML = "Type in the Input box to see functioning."; var down = document.getElementById('GFG_DOWN'); function GFG_Fun(e) { var str = down.innerHTML; str += e.key down.innerHTML = str; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript-Misc JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request How to append HTML code to a div using JavaScript ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Sep, 2019" }, { "code": null, "e": 218, "s": 28, "text": "Here, the task is to get the character key, which is pressed. In the code written below, an event triggered when any key is pressed and it calls a function then that function identifies it." }, { "code": null, "e": 228, "s": 218, "text": "Approach:" }, { "code": null, "e": 285, "s": 228, "text": "Attach an event to the input box. like onkeypress event." }, { "code": null, "e": 361, "s": 285, "text": "Call a function when that event happens and pass the event parameter in it." }, { "code": null, "e": 411, "s": 361, "text": "In the called function, identify the key pressed." }, { "code": null, "e": 469, "s": 411, "text": "Example 1: This example using the approach defined above." }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to find out which character key is pressed using JavaScript? </title></head> <body id=\"body\" style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <form> Type Here: <input type=\"text\" onkeypress=\"return GFG_Fun(event)\" /> </form> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); up.innerHTML = \"Type in the Input box to see functioning.\"; var down = document.getElementById('GFG_DOWN'); function GFG_Fun(e) { var key; if (window.event) { key = e.keyCode; } else if (e.which) { key = e.which; } var str = down.innerHTML; str += String.fromCharCode(key); down.innerHTML = str; } </script></body> </html>", "e": 1580, "s": 469, "text": null }, { "code": null, "e": 1588, "s": 1580, "text": "Output:" }, { "code": null, "e": 1619, "s": 1588, "text": "Before clicking on the button:" }, { "code": null, "e": 1649, "s": 1619, "text": "After clicking on the button:" }, { "code": null, "e": 1707, "s": 1649, "text": "Example 2: This example using the approach defined above." }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to find out which character key is pressed using JavaScript? </title></head> <body id=\"body\" style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <form> Type Here: <input type=\"text\" onkeypress=\"return GFG_Fun(event)\" /> </form> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); up.innerHTML = \"Type in the Input box to see functioning.\"; var down = document.getElementById('GFG_DOWN'); function GFG_Fun(e) { var str = down.innerHTML; str += e.key down.innerHTML = str; } </script></body> </html>", "e": 2637, "s": 1707, "text": null }, { "code": null, "e": 2645, "s": 2637, "text": "Output:" }, { "code": null, "e": 2676, "s": 2645, "text": "Before clicking on the button:" }, { "code": null, "e": 2706, "s": 2676, "text": "After clicking on the button:" }, { "code": null, "e": 2722, "s": 2706, "text": "JavaScript-Misc" }, { "code": null, "e": 2733, "s": 2722, "text": "JavaScript" }, { "code": null, "e": 2750, "s": 2733, "text": "Web Technologies" }, { "code": null, "e": 2777, "s": 2750, "text": "Web technologies Questions" }, { "code": null, "e": 2875, "s": 2777, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2936, "s": 2875, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3008, "s": 2936, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3048, "s": 3008, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3089, "s": 3048, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3141, "s": 3089, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 3174, "s": 3141, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3236, "s": 3174, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3297, "s": 3236, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3347, "s": 3297, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to use hide() method on button click using jQuery ?
10 Aug, 2021 jQuery has a lot of handy methods to get the work done easily. In this article, we will discuss one of them which is the hide() method. We can use this method for various purposes on our webpage and get an efficient result. The very first step will be creating an HTML file and link the jQuery library file via CDN. jQuery CDN Link: <script src=”https://code.jquery.com/jquery-3.6.0.min.js” integrity=”sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=” crossorigin=”anonymous”></script> jQuery hide() method: This method is used for hiding the web elements. Example 1: Create an HTML file and add the following code to it. HTML <!DOCTYPE html><html lang="en"> <head> <!-- jQuery CDN link. --> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"> </script> </head> <body> <button id="btn">Hide</button> <p><b>GeeksforGeeks</b></p> <!-- Using hide() method to hide <p/> element. --> <script> $(document).ready(function () { $("#btn").click(function () { $("p").hide(); }); }); </script> </body></html> Output: Hide p element Example 2: We can use the hide() method to hide an image. HTML <!DOCTYPE html><html lang="en"> <head> <!-- jQuery CDN link. --> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"> </script> </head> <body> <img id="image" src="https://media.geeksforgeeks.org/wp-content/uploads/20210805112556/gfgImage.png" alt=""/> <button id="btn" style="padding-left: 10px; margin-left: 30px"> Hide </button> <!-- Using hide() method to hide an image.--> <script> $(document).ready(function () { $("#btn").click(function () { $("#image").hide(); }); }); </script> </body></html> Output: Hide Image Example 3: The hide() method can also be used to hide any geometrical shape. HTML <!DOCTYPE html><html lang="en"> <head> <!-- jQuery CDN link. --> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"> </script> </head> <body> <div id="shape" style="height:100px; width:100px; background-color:green; border-radius:00%;margin:10px;"> </div> <button id="btn" style="margin:10px;">Hide Shape</button> <!-- Using hide() method to hide a shape. --> <script> $(document).ready(function () { $("#btn").click(function () { $("#shape").hide(); }); }); </script> </body></html> Output: Hide shape jQuery-Methods jQuery-Questions Picked HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Aug, 2021" }, { "code": null, "e": 278, "s": 54, "text": "jQuery has a lot of handy methods to get the work done easily. In this article, we will discuss one of them which is the hide() method. We can use this method for various purposes on our webpage and get an efficient result." }, { "code": null, "e": 370, "s": 278, "text": "The very first step will be creating an HTML file and link the jQuery library file via CDN." }, { "code": null, "e": 388, "s": 370, "text": "jQuery CDN Link: " }, { "code": null, "e": 544, "s": 388, "text": "<script src=”https://code.jquery.com/jquery-3.6.0.min.js” integrity=”sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=” crossorigin=”anonymous”></script>" }, { "code": null, "e": 617, "s": 546, "text": "jQuery hide() method: This method is used for hiding the web elements." }, { "code": null, "e": 682, "s": 617, "text": "Example 1: Create an HTML file and add the following code to it." }, { "code": null, "e": 687, "s": 682, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- jQuery CDN link. --> <script src=\"https://code.jquery.com/jquery-3.6.0.min.js\" integrity=\"sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=\" crossorigin=\"anonymous\"> </script> </head> <body> <button id=\"btn\">Hide</button> <p><b>GeeksforGeeks</b></p> <!-- Using hide() method to hide <p/> element. --> <script> $(document).ready(function () { $(\"#btn\").click(function () { $(\"p\").hide(); }); }); </script> </body></html>", "e": 1235, "s": 687, "text": null }, { "code": null, "e": 1243, "s": 1235, "text": "Output:" }, { "code": null, "e": 1258, "s": 1243, "text": "Hide p element" }, { "code": null, "e": 1316, "s": 1258, "text": "Example 2: We can use the hide() method to hide an image." }, { "code": null, "e": 1321, "s": 1316, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- jQuery CDN link. --> <script src=\"https://code.jquery.com/jquery-3.6.0.min.js\" integrity=\"sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=\" crossorigin=\"anonymous\"> </script> </head> <body> <img id=\"image\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210805112556/gfgImage.png\" alt=\"\"/> <button id=\"btn\" style=\"padding-left: 10px; margin-left: 30px\"> Hide </button> <!-- Using hide() method to hide an image.--> <script> $(document).ready(function () { $(\"#btn\").click(function () { $(\"#image\").hide(); }); }); </script> </body></html>", "e": 2043, "s": 1321, "text": null }, { "code": null, "e": 2051, "s": 2043, "text": "Output:" }, { "code": null, "e": 2062, "s": 2051, "text": "Hide Image" }, { "code": null, "e": 2140, "s": 2062, "text": "Example 3: The hide() method can also be used to hide any geometrical shape. " }, { "code": null, "e": 2145, "s": 2140, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- jQuery CDN link. --> <script src=\"https://code.jquery.com/jquery-3.6.0.min.js\" integrity=\"sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=\" crossorigin=\"anonymous\"> </script> </head> <body> <div id=\"shape\" style=\"height:100px; width:100px; background-color:green; border-radius:00%;margin:10px;\"> </div> <button id=\"btn\" style=\"margin:10px;\">Hide Shape</button> <!-- Using hide() method to hide a shape. --> <script> $(document).ready(function () { $(\"#btn\").click(function () { $(\"#shape\").hide(); }); }); </script> </body></html>", "e": 2860, "s": 2145, "text": null }, { "code": null, "e": 2868, "s": 2860, "text": "Output:" }, { "code": null, "e": 2879, "s": 2868, "text": "Hide shape" }, { "code": null, "e": 2894, "s": 2879, "text": "jQuery-Methods" }, { "code": null, "e": 2911, "s": 2894, "text": "jQuery-Questions" }, { "code": null, "e": 2918, "s": 2911, "text": "Picked" }, { "code": null, "e": 2923, "s": 2918, "text": "HTML" }, { "code": null, "e": 2930, "s": 2923, "text": "JQuery" }, { "code": null, "e": 2947, "s": 2930, "text": "Web Technologies" }, { "code": null, "e": 2952, "s": 2947, "text": "HTML" } ]
LRU Cache implementation using Double Linked Lists
01 Sep, 2021 Given a pre define size of a list N and an array Arr. The task is to implement Least Recently Used(LRU) algorithm using Double Linked Lists. The program takes two sets of inputs. First, The size of the linked list. Second, The element to search in the linked list.Examples: Input: N = 3, Arr = { 1, 2, 3 } Output: [0]->[0]->[0]->NULL [1]->[0]->[0]->NULL [2]->[1]->[0]->NULL [3]->[2]->[1]->NULL Input: N = 5, Arr = { 1, 2, 3, 4, 3, 8 } Output: [0]->[0]->[0]->[0]->[0]->NULL [1]->[0]->[0]->[0]->[0]->NULL [2]->[1]->[0]->[0]->[0]->NULL [3]->[2]->[1]->[0]->[0]->NULL [4]->[3]->[2]->[1]->[0]->NULL [2]->[4]->[3]->[1]->[0]->NULL [8]->[2]->[4]->[3]->[1]->NULL Approach: The idea is very basic that keep inserting the elements at the head if the element is not present in the list the add it to the head of the list if the element is present in the list then move the element to the head and shift the remaining element of the list Below is the implementation of the above approach: C++ C // C++ implementation of the approach#include <iostream>using namespace std; // Creating the structure// for linkedliststruct doublelinkedlist { int val; struct doublelinkedlist* next; struct doublelinkedlist* prev;}; // Creating three list for having// head, a temporarily list and// a list for tailstruct doublelinkedlist* head;struct doublelinkedlist* tail;struct doublelinkedlist* temp; int status; // Function to add new node// in the listint AddNode(int value){ // if head is NULL creating // the new node and assigning // to head if (head == NULL) { head = (struct doublelinkedlist*) malloc(sizeof(struct doublelinkedlist)); if (head == NULL) { cout <<"Unable to allocate space\n"; return -2; } head->val = value; tail = head; head->prev = NULL; } else { temp = tail; tail->next = (struct doublelinkedlist*) malloc(sizeof(struct doublelinkedlist)); if (tail->next == NULL) { cout <<"Unable to allocate space\n"; return -2; } tail->next->val = value; tail = tail->next; tail->prev = temp; } tail->next = NULL; return 0;} // Function to print// the linked listint Display(void){ if (head == NULL) { cout <<"Add a node first\n"; return -2; } else { temp = head; while (temp != NULL) { cout <<"[ ]->"<< temp->val; temp = temp->next; } cout <<"NULL\n"; } return 0;} // Function to search the// elements is already present// in the list or notint SearchCache(int value){ if (head == NULL) { cout <<"Add a node first\n"; return -1; } // Store head temporarily. temp = head; // Traverse Double Linked List. while (temp != NULL) { // If value in list // matches with given value. if (temp->val == value) { // Shift all values before // the found value to the right. while (temp != head) { temp->val = temp->prev->val; temp = temp->prev; } // Place the found // value at the head. head->val = value; return 0; } // Keep iterating the loop. temp = temp->next; } // For new elements. temp = tail->prev; // Shift all value to the // right and over-write // the last value. while (temp != NULL) { temp->next->val = temp->val; temp = temp->prev; } // Place new value at head. head->val = value; return 0;} // Initializing function// that will create the// list with values 0 in it.int NumberOfNodes(int number){ static int i = 0; for (i = 0; i < number; i += 1) { status = AddNode(0); // if status is 0 then // it will return if (status < 0) { cout <<"Could not assign node\n"; return status; } } return 0;} // This function will// remove the linked// list from the memory.int FreeCache(int number){ struct doublelinkedlist** freeing_ptr = &head; static int i = 0; for (i = 0; i < number; i += 1) { free(*freeing_ptr); *freeing_ptr = NULL; freeing_ptr += 1; } return 0;} // Function to perform LRU// operationsvoid LRUOp(int arr[], int n){ // Iterating through the // elements so that LRU // operation can take place for (int i = 0; i < n; ++i) { SearchCache(arr[i]); // If the status is -ve // then return if (status < 0) { exit(1); } // Printing it every time status = Display(); }} // Driver Codeint main(void){ // Pre defining the // size of the cache int MEMSIZE = 5; status = NumberOfNodes(MEMSIZE); // Number of elements // to be added in LRU List. int n = 10; // The Numbers to be // added in LRU List. int arr[] = { 1, 2, 3, 4, 5, 2, 10, 7, 11, 1 }; LRUOp(arr, n); // Removing the linked // list from the memory. FreeCache(MEMSIZE); return 0;} // this code is contributed by shivanisinghss2110 // C implementation of the approach#include <stdint.h>#include <stdio.h>#include <stdlib.h> // Creating the structure// for linkedliststruct doublelinkedlist { int val; struct doublelinkedlist* next; struct doublelinkedlist* prev;}; // Creating three list for having// head, a temporarily list and// a list for tailstruct doublelinkedlist* head;struct doublelinkedlist* tail;struct doublelinkedlist* temp; int status; // Function to add new node// in the listint AddNode(int value){ // if head is NULL creating // the new node and assigning // to head if (head == NULL) { head = (struct doublelinkedlist*) malloc(sizeof(struct doublelinkedlist)); if (head == NULL) { printf("Unable to allocate space\n"); return -2; } head->val = value; tail = head; head->prev = NULL; } else { temp = tail; tail->next = (struct doublelinkedlist*) malloc(sizeof(struct doublelinkedlist)); if (tail->next == NULL) { printf("Unable to allocate space\n"); return -2; } tail->next->val = value; tail = tail->next; tail->prev = temp; } tail->next = NULL; return 0;} // Function to print// the linked listint Display(void){ if (head == NULL) { printf("Add a node first\n"); return -2; } else { temp = head; while (temp != NULL) { printf("[%d]->", temp->val); temp = temp->next; } printf("NULL\n"); } return 0;} // Function to search the// elements is already present// in the list or notint SearchCache(int value){ if (head == NULL) { printf("Add a node first\n"); return -1; } // Store head temporarily. temp = head; // Traverse Double Linked List. while (temp != NULL) { // If value in list // matches with given value. if (temp->val == value) { // Shift all values before // the found value to the right. while (temp != head) { temp->val = temp->prev->val; temp = temp->prev; } // Place the found // value at the head. head->val = value; return 0; } // Keep iterating the loop. temp = temp->next; } // For new elements. temp = tail->prev; // Shift all value to the // right and over-write // the last value. while (temp != NULL) { temp->next->val = temp->val; temp = temp->prev; } // Place new value at head. head->val = value; return 0;} // Initializing function// that will create the// list with values 0 in it.int NumberOfNodes(int number){ static int i = 0; for (i = 0; i < number; i += 1) { status = AddNode(0); // if status is 0 then // it will return if (status < 0) { printf("Could not assign node\n"); return status; } } return 0;} // This function will// remove the linked// list from the memory.int FreeCache(int number){ struct doublelinkedlist** freeing_ptr = &head; static int i = 0; for (i = 0; i < number; i += 1) { free(*freeing_ptr); *freeing_ptr = NULL; freeing_ptr += 1; } return 0;} // Function to perform LRU// operationsvoid LRUOp(int arr[], int n){ // Iterating through the // elements so that LRU // operation can take place for (int i = 0; i < n; ++i) { SearchCache(arr[i]); // If the status is -ve // then return if (status < 0) { exit(1); } // Printing it every time status = Display(); }} // Driver Codeint main(void){ // Pre defining the // size of the cache int MEMSIZE = 5; status = NumberOfNodes(MEMSIZE); // Number of elements // to be added in LRU List. int n = 10; // The Numbers to be // added in LRU List. int arr[] = { 1, 2, 3, 4, 5, 2, 10, 7, 11, 1 }; LRUOp(arr, n); // Removing the linked // list from the memory. FreeCache(MEMSIZE); return 0;} [1]->[0]->[0]->[0]->[0]->NULL [2]->[1]->[0]->[0]->[0]->NULL [3]->[2]->[1]->[0]->[0]->NULL [4]->[3]->[2]->[1]->[0]->NULL [5]->[4]->[3]->[2]->[1]->NULL [2]->[5]->[4]->[3]->[1]->NULL [10]->[2]->[5]->[4]->[3]->NULL [7]->[10]->[2]->[5]->[4]->NULL [11]->[7]->[10]->[2]->[5]->NULL [1]->[11]->[7]->[10]->[2]->NULL gulshankumarar231 shivanisinghss2110 surindertarika1234 doubly linked list Algorithms Linked List Operating Systems Linked List Operating Systems Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Sep, 2021" }, { "code": null, "e": 303, "s": 28, "text": "Given a pre define size of a list N and an array Arr. The task is to implement Least Recently Used(LRU) algorithm using Double Linked Lists. The program takes two sets of inputs. First, The size of the linked list. Second, The element to search in the linked list.Examples: " }, { "code": null, "e": 684, "s": 303, "text": "Input: N = 3, Arr = { 1, 2, 3 } Output: [0]->[0]->[0]->NULL [1]->[0]->[0]->NULL [2]->[1]->[0]->NULL [3]->[2]->[1]->NULL Input: N = 5, Arr = { 1, 2, 3, 4, 3, 8 } Output: [0]->[0]->[0]->[0]->[0]->NULL [1]->[0]->[0]->[0]->[0]->NULL [2]->[1]->[0]->[0]->[0]->NULL [3]->[2]->[1]->[0]->[0]->NULL [4]->[3]->[2]->[1]->[0]->NULL [2]->[4]->[3]->[1]->[0]->NULL [8]->[2]->[4]->[3]->[1]->NULL " }, { "code": null, "e": 766, "s": 686, "text": "Approach: The idea is very basic that keep inserting the elements at the head " }, { "code": null, "e": 843, "s": 766, "text": "if the element is not present in the list the add it to the head of the list" }, { "code": null, "e": 959, "s": 843, "text": "if the element is present in the list then move the element to the head and shift the remaining element of the list" }, { "code": null, "e": 1012, "s": 959, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1016, "s": 1012, "text": "C++" }, { "code": null, "e": 1018, "s": 1016, "text": "C" }, { "code": "// C++ implementation of the approach#include <iostream>using namespace std; // Creating the structure// for linkedliststruct doublelinkedlist { int val; struct doublelinkedlist* next; struct doublelinkedlist* prev;}; // Creating three list for having// head, a temporarily list and// a list for tailstruct doublelinkedlist* head;struct doublelinkedlist* tail;struct doublelinkedlist* temp; int status; // Function to add new node// in the listint AddNode(int value){ // if head is NULL creating // the new node and assigning // to head if (head == NULL) { head = (struct doublelinkedlist*) malloc(sizeof(struct doublelinkedlist)); if (head == NULL) { cout <<\"Unable to allocate space\\n\"; return -2; } head->val = value; tail = head; head->prev = NULL; } else { temp = tail; tail->next = (struct doublelinkedlist*) malloc(sizeof(struct doublelinkedlist)); if (tail->next == NULL) { cout <<\"Unable to allocate space\\n\"; return -2; } tail->next->val = value; tail = tail->next; tail->prev = temp; } tail->next = NULL; return 0;} // Function to print// the linked listint Display(void){ if (head == NULL) { cout <<\"Add a node first\\n\"; return -2; } else { temp = head; while (temp != NULL) { cout <<\"[ ]->\"<< temp->val; temp = temp->next; } cout <<\"NULL\\n\"; } return 0;} // Function to search the// elements is already present// in the list or notint SearchCache(int value){ if (head == NULL) { cout <<\"Add a node first\\n\"; return -1; } // Store head temporarily. temp = head; // Traverse Double Linked List. while (temp != NULL) { // If value in list // matches with given value. if (temp->val == value) { // Shift all values before // the found value to the right. while (temp != head) { temp->val = temp->prev->val; temp = temp->prev; } // Place the found // value at the head. head->val = value; return 0; } // Keep iterating the loop. temp = temp->next; } // For new elements. temp = tail->prev; // Shift all value to the // right and over-write // the last value. while (temp != NULL) { temp->next->val = temp->val; temp = temp->prev; } // Place new value at head. head->val = value; return 0;} // Initializing function// that will create the// list with values 0 in it.int NumberOfNodes(int number){ static int i = 0; for (i = 0; i < number; i += 1) { status = AddNode(0); // if status is 0 then // it will return if (status < 0) { cout <<\"Could not assign node\\n\"; return status; } } return 0;} // This function will// remove the linked// list from the memory.int FreeCache(int number){ struct doublelinkedlist** freeing_ptr = &head; static int i = 0; for (i = 0; i < number; i += 1) { free(*freeing_ptr); *freeing_ptr = NULL; freeing_ptr += 1; } return 0;} // Function to perform LRU// operationsvoid LRUOp(int arr[], int n){ // Iterating through the // elements so that LRU // operation can take place for (int i = 0; i < n; ++i) { SearchCache(arr[i]); // If the status is -ve // then return if (status < 0) { exit(1); } // Printing it every time status = Display(); }} // Driver Codeint main(void){ // Pre defining the // size of the cache int MEMSIZE = 5; status = NumberOfNodes(MEMSIZE); // Number of elements // to be added in LRU List. int n = 10; // The Numbers to be // added in LRU List. int arr[] = { 1, 2, 3, 4, 5, 2, 10, 7, 11, 1 }; LRUOp(arr, n); // Removing the linked // list from the memory. FreeCache(MEMSIZE); return 0;} // this code is contributed by shivanisinghss2110", "e": 5208, "s": 1018, "text": null }, { "code": "// C implementation of the approach#include <stdint.h>#include <stdio.h>#include <stdlib.h> // Creating the structure// for linkedliststruct doublelinkedlist { int val; struct doublelinkedlist* next; struct doublelinkedlist* prev;}; // Creating three list for having// head, a temporarily list and// a list for tailstruct doublelinkedlist* head;struct doublelinkedlist* tail;struct doublelinkedlist* temp; int status; // Function to add new node// in the listint AddNode(int value){ // if head is NULL creating // the new node and assigning // to head if (head == NULL) { head = (struct doublelinkedlist*) malloc(sizeof(struct doublelinkedlist)); if (head == NULL) { printf(\"Unable to allocate space\\n\"); return -2; } head->val = value; tail = head; head->prev = NULL; } else { temp = tail; tail->next = (struct doublelinkedlist*) malloc(sizeof(struct doublelinkedlist)); if (tail->next == NULL) { printf(\"Unable to allocate space\\n\"); return -2; } tail->next->val = value; tail = tail->next; tail->prev = temp; } tail->next = NULL; return 0;} // Function to print// the linked listint Display(void){ if (head == NULL) { printf(\"Add a node first\\n\"); return -2; } else { temp = head; while (temp != NULL) { printf(\"[%d]->\", temp->val); temp = temp->next; } printf(\"NULL\\n\"); } return 0;} // Function to search the// elements is already present// in the list or notint SearchCache(int value){ if (head == NULL) { printf(\"Add a node first\\n\"); return -1; } // Store head temporarily. temp = head; // Traverse Double Linked List. while (temp != NULL) { // If value in list // matches with given value. if (temp->val == value) { // Shift all values before // the found value to the right. while (temp != head) { temp->val = temp->prev->val; temp = temp->prev; } // Place the found // value at the head. head->val = value; return 0; } // Keep iterating the loop. temp = temp->next; } // For new elements. temp = tail->prev; // Shift all value to the // right and over-write // the last value. while (temp != NULL) { temp->next->val = temp->val; temp = temp->prev; } // Place new value at head. head->val = value; return 0;} // Initializing function// that will create the// list with values 0 in it.int NumberOfNodes(int number){ static int i = 0; for (i = 0; i < number; i += 1) { status = AddNode(0); // if status is 0 then // it will return if (status < 0) { printf(\"Could not assign node\\n\"); return status; } } return 0;} // This function will// remove the linked// list from the memory.int FreeCache(int number){ struct doublelinkedlist** freeing_ptr = &head; static int i = 0; for (i = 0; i < number; i += 1) { free(*freeing_ptr); *freeing_ptr = NULL; freeing_ptr += 1; } return 0;} // Function to perform LRU// operationsvoid LRUOp(int arr[], int n){ // Iterating through the // elements so that LRU // operation can take place for (int i = 0; i < n; ++i) { SearchCache(arr[i]); // If the status is -ve // then return if (status < 0) { exit(1); } // Printing it every time status = Display(); }} // Driver Codeint main(void){ // Pre defining the // size of the cache int MEMSIZE = 5; status = NumberOfNodes(MEMSIZE); // Number of elements // to be added in LRU List. int n = 10; // The Numbers to be // added in LRU List. int arr[] = { 1, 2, 3, 4, 5, 2, 10, 7, 11, 1 }; LRUOp(arr, n); // Removing the linked // list from the memory. FreeCache(MEMSIZE); return 0;}", "e": 9370, "s": 5208, "text": null }, { "code": null, "e": 9676, "s": 9370, "text": "[1]->[0]->[0]->[0]->[0]->NULL\n[2]->[1]->[0]->[0]->[0]->NULL\n[3]->[2]->[1]->[0]->[0]->NULL\n[4]->[3]->[2]->[1]->[0]->NULL\n[5]->[4]->[3]->[2]->[1]->NULL\n[2]->[5]->[4]->[3]->[1]->NULL\n[10]->[2]->[5]->[4]->[3]->NULL\n[7]->[10]->[2]->[5]->[4]->NULL\n[11]->[7]->[10]->[2]->[5]->NULL\n[1]->[11]->[7]->[10]->[2]->NULL" }, { "code": null, "e": 9696, "s": 9678, "text": "gulshankumarar231" }, { "code": null, "e": 9715, "s": 9696, "text": "shivanisinghss2110" }, { "code": null, "e": 9734, "s": 9715, "text": "surindertarika1234" }, { "code": null, "e": 9753, "s": 9734, "text": "doubly linked list" }, { "code": null, "e": 9764, "s": 9753, "text": "Algorithms" }, { "code": null, "e": 9776, "s": 9764, "text": "Linked List" }, { "code": null, "e": 9794, "s": 9776, "text": "Operating Systems" }, { "code": null, "e": 9806, "s": 9794, "text": "Linked List" }, { "code": null, "e": 9824, "s": 9806, "text": "Operating Systems" }, { "code": null, "e": 9835, "s": 9824, "text": "Algorithms" } ]
FORMAT() Function in SQL Server
04 Oct, 2021 The FORMAT() function is one of the String Functions, which is used to format the specified value in the given format. Syntax : FORMAT(value, format, culture) Parameter: This method accepts three parameters as mentioned above and described below: Value: It is the value to do formatting. It should be in support of the data type format. Format: It is the required format in which we require the output. Culture: It is an optional parameter. By default, SQL Server uses the current session language for a default culture. We can provide a specific culture here, but the .Net framework should support it. We get an error message in case of invalid Culture Returns: It returns a value formatted with the specified format and optional culture. Now if we want to Format a Number. then we use the below query:Query: SELECT FORMAT(25, 'N') Output : Take another example of PERCENTAGE format. Query: SELECT FORMAT(1, 'P', 'en-US')AS [PERCENTAGE IN US FORMAT], FORMAT(1, 'P', 'en-IN') AS [PERCENTAGE IN INDIA FORMAT]; Output : Example of DATE format. Query: DECLARE @d DATETIME = GETDATE(); SELECT FORMAT( @d, 'dd/MM/yyyy', 'en-US' ) AS 'DateTime Result' Output : In this example, we will format the current time with AM or PM. Query: SELECT FORMAT(SYSDATETIME(), N'hh:mm tt'); Output : In this example, we change the CURRENCY format. Query: SELECT FORMAT(1, 'C', 'in-IN') AS 'INDIA', FORMAT(1, 'C', 'ch-CH') AS 'CHINA', FORMAT(1, 'C', 'sw-SW') AS 'SWITZERLAND', FORMAT(1, 'C', 'us-US') AS 'USA'; Output : varshachoudhary DBMS-SQL SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL SQL Trigger | Student Database How to Update Multiple Columns in Single Update Statement in SQL? SQL | Views Difference between DELETE, DROP and TRUNCATE Difference between SQL and NoSQL Window functions in SQL MySQL | Group_CONCAT() Function SQL | GROUP BY Difference between DDL and DML in DBMS
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Oct, 2021" }, { "code": null, "e": 148, "s": 28, "text": "The FORMAT() function is one of the String Functions, which is used to format the specified value in the given format. " }, { "code": null, "e": 158, "s": 148, "text": "Syntax : " }, { "code": null, "e": 191, "s": 158, "text": "FORMAT(value, format, culture) " }, { "code": null, "e": 203, "s": 191, "text": "Parameter: " }, { "code": null, "e": 281, "s": 203, "text": "This method accepts three parameters as mentioned above and described below: " }, { "code": null, "e": 372, "s": 281, "text": "Value: It is the value to do formatting. It should be in support of the data type format. " }, { "code": null, "e": 438, "s": 372, "text": "Format: It is the required format in which we require the output." }, { "code": null, "e": 689, "s": 438, "text": "Culture: It is an optional parameter. By default, SQL Server uses the current session language for a default culture. We can provide a specific culture here, but the .Net framework should support it. We get an error message in case of invalid Culture" }, { "code": null, "e": 777, "s": 689, "text": "Returns: It returns a value formatted with the specified format and optional culture. " }, { "code": null, "e": 847, "s": 777, "text": "Now if we want to Format a Number. then we use the below query:Query:" }, { "code": null, "e": 870, "s": 847, "text": "SELECT FORMAT(25, 'N')" }, { "code": null, "e": 881, "s": 870, "text": "Output : " }, { "code": null, "e": 931, "s": 881, "text": "Take another example of PERCENTAGE format. Query:" }, { "code": null, "e": 1053, "s": 931, "text": "SELECT FORMAT(1, 'P', 'en-US')AS [PERCENTAGE IN US FORMAT], \n FORMAT(1, 'P', 'en-IN') AS [PERCENTAGE IN INDIA FORMAT];" }, { "code": null, "e": 1063, "s": 1053, "text": "Output : " }, { "code": null, "e": 1094, "s": 1063, "text": "Example of DATE format. Query:" }, { "code": null, "e": 1193, "s": 1094, "text": "DECLARE @d DATETIME = GETDATE(); \nSELECT FORMAT( @d, 'dd/MM/yyyy', 'en-US' ) AS 'DateTime Result'" }, { "code": null, "e": 1204, "s": 1193, "text": "Output : " }, { "code": null, "e": 1275, "s": 1204, "text": "In this example, we will format the current time with AM or PM. Query:" }, { "code": null, "e": 1318, "s": 1275, "text": "SELECT FORMAT(SYSDATETIME(), N'hh:mm tt');" }, { "code": null, "e": 1329, "s": 1318, "text": "Output : " }, { "code": null, "e": 1384, "s": 1329, "text": "In this example, we change the CURRENCY format. Query:" }, { "code": null, "e": 1559, "s": 1384, "text": "SELECT \n FORMAT(1, 'C', 'in-IN') AS 'INDIA', \n FORMAT(1, 'C', 'ch-CH') AS 'CHINA', \n FORMAT(1, 'C', 'sw-SW') AS 'SWITZERLAND', \n FORMAT(1, 'C', 'us-US') AS 'USA';" }, { "code": null, "e": 1570, "s": 1559, "text": "Output : " }, { "code": null, "e": 1588, "s": 1572, "text": "varshachoudhary" }, { "code": null, "e": 1597, "s": 1588, "text": "DBMS-SQL" }, { "code": null, "e": 1608, "s": 1597, "text": "SQL-Server" }, { "code": null, "e": 1612, "s": 1608, "text": "SQL" }, { "code": null, "e": 1616, "s": 1612, "text": "SQL" }, { "code": null, "e": 1714, "s": 1616, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1725, "s": 1714, "text": "CTE in SQL" }, { "code": null, "e": 1756, "s": 1725, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 1822, "s": 1756, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 1834, "s": 1822, "text": "SQL | Views" }, { "code": null, "e": 1879, "s": 1834, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 1912, "s": 1879, "text": "Difference between SQL and NoSQL" }, { "code": null, "e": 1936, "s": 1912, "text": "Window functions in SQL" }, { "code": null, "e": 1968, "s": 1936, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 1983, "s": 1968, "text": "SQL | GROUP BY" } ]
Lodash_.shuffle() Method
01 Oct, 2020 The _.shuffle() method shuffles of collection by returning the new array. Syntax: _.shuffle(collection) Parameters: This method accepts a single parameter as mentioned above and described below: collection: This parameter holds the collection to inspect. Return Value: This method returns the new array after shuffling. Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file. Javascript // Requiring the lodash library const _ = require("lodash"); // Original array and use _.shuffle() methodvar gfg = _.shuffle([1, 2, 3,4]); // Printing the output console.log(gfg); Output : [4, 1, 3, 2] Example 2 : Javascript // Requiring the lodash library const _ = require("lodash"); // Original array and use _.shuffle() methodvar gfg = _.shuffle(["g", "e", "e", "k", "s", "f", "o", "r", "g", "e", "e", "k", "s"]); // Printing the output console.log(gfg); Output : ["o", "e", "k", "s", "e", "e", "s", "g", "r", "e", "g", "f", "k"] Note: This code will not work in normal JavaScript because it requires the library lodash to be installed. JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Oct, 2020" }, { "code": null, "e": 102, "s": 28, "text": "The _.shuffle() method shuffles of collection by returning the new array." }, { "code": null, "e": 111, "s": 102, "text": "Syntax: " }, { "code": null, "e": 134, "s": 111, "text": "_.shuffle(collection)\n" }, { "code": null, "e": 225, "s": 134, "text": "Parameters: This method accepts a single parameter as mentioned above and described below:" }, { "code": null, "e": 285, "s": 225, "text": "collection: This parameter holds the collection to inspect." }, { "code": null, "e": 350, "s": 285, "text": "Return Value: This method returns the new array after shuffling." }, { "code": null, "e": 445, "s": 350, "text": "Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file." }, { "code": null, "e": 456, "s": 445, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array and use _.shuffle() methodvar gfg = _.shuffle([1, 2, 3,4]); // Printing the output console.log(gfg);", "e": 644, "s": 456, "text": null }, { "code": null, "e": 653, "s": 644, "text": "Output :" }, { "code": null, "e": 667, "s": 653, "text": "[4, 1, 3, 2]\n" }, { "code": null, "e": 679, "s": 667, "text": "Example 2 :" }, { "code": null, "e": 690, "s": 679, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array and use _.shuffle() methodvar gfg = _.shuffle([\"g\", \"e\", \"e\", \"k\", \"s\", \"f\", \"o\", \"r\", \"g\", \"e\", \"e\", \"k\", \"s\"]); // Printing the output console.log(gfg);", "e": 952, "s": 690, "text": null }, { "code": null, "e": 961, "s": 952, "text": "Output :" }, { "code": null, "e": 1029, "s": 961, "text": "[\"o\", \"e\", \"k\", \"s\", \"e\", \"e\", \"s\",\n \"g\", \"r\", \"e\", \"g\", \"f\", \"k\"]\n" }, { "code": null, "e": 1136, "s": 1029, "text": "Note: This code will not work in normal JavaScript because it requires the library lodash to be installed." }, { "code": null, "e": 1154, "s": 1136, "text": "JavaScript-Lodash" }, { "code": null, "e": 1165, "s": 1154, "text": "JavaScript" }, { "code": null, "e": 1182, "s": 1165, "text": "Web Technologies" }, { "code": null, "e": 1280, "s": 1182, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1341, "s": 1280, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1381, "s": 1341, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 1422, "s": 1381, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 1464, "s": 1422, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 1486, "s": 1464, "text": "JavaScript | Promises" }, { "code": null, "e": 1519, "s": 1486, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1581, "s": 1519, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1642, "s": 1581, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1692, "s": 1642, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Generating all possible Subsequences using Recursion including the empty one.
25 May, 2022 Given an array. The task is to generate and print all of the possible subsequences of the given array using recursion. Examples: Input : [1, 2, 3] Output : [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3], [] Input : [1, 2] Output : [2], [1], [1, 2], [] Approach: For every element in the array, there are two choices, either to include it in the subsequence or not include it. Apply this for every element in the array starting from index 0 until we reach the last index. Print the subsequence once the last index is reached. Below diagram shows the recursion tree for array, arr[] = {1, 2}. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ code to print all possible// subsequences for given array using// recursion#include <bits/stdc++.h>using namespace std; // Recursive function to print all// possible subsequences for given arrayvoid printSubsequences(int arr[], int index, vector<int> &subarr,int n){ // Print the subsequence when reach // the leaf of recursion tree if (index == n) { for (auto it:subarr){ cout << it << " "; } if(subarr.size()==0) cout<<"{}"; cout<<endl; return; } else { //pick the current index into the subsequence. subarr.push_back(arr[index]); printSubsequences(arr, index + 1, subarr,n); subarr.pop_back(); //not picking the element into the subsequence. printSubsequences(arr, index + 1, subarr,n); } } // Driver Codeint main(){ int arr[]={1, 2, 3}; int n=sizeof(arr)/sizeof(arr[0]); vector<int> vec; printSubsequences(arr, 0, vec,n); return 0;} // This code is contributed by// vivekr4400 // Java code to print all possible// subsequences for given array using// recursionimport java.io.*;import java.util.*; class GFG{ // Recursive function to print all// possible subsequences for given arraypublic static void printSubsequences(int[] arr, int index, ArrayList<Integer> path){ // Print the subsequence when reach // the leaf of recursion tree if (index == arr.length) { // Condition to avoid printing // empty subsequence if (path.size() > 0) System.out.println(path); } else { // Subsequence without including // the element at current index printSubsequences(arr, index + 1, path); path.add(arr[index]); // Subsequence including the element // at current index printSubsequences(arr, index + 1, path); // Backtrack to remove the recently // inserted element path.remove(path.size() - 1); } return;} // Driver codepublic static void main(String[] args){ int[] arr = { 1, 2, 3 }; // Auxiliary space to store each path ArrayList<Integer> path = new ArrayList<>(); printSubsequences(arr, 0, path);}} // This code is contributed by Mukul Sharma # Python3 code to print all possible # subsequences for given array using # recursion # Recursive function to print all# possible subsequences for given arraydef printSubsequences(arr, index, subarr): # Print the subsequence when reach # the leaf of recursion tree if index == len(arr): # Condition to avoid printing # empty subsequence if len(subarr) != 0: print(subarr) else: # Subsequence without including # the element at current index printSubsequences(arr, index + 1, subarr) # Subsequence including the element # at current index printSubsequences(arr, index + 1, subarr+[arr[index]]) return arr = [1, 2, 3] printSubsequences(arr, 0, []) #This code is contributed by Mayank Tyagi // C# code to print all possible// subsequences for given array using// recursionusing System;using System.Collections.Generic;class GFG { // Recursive function to print all // possible subsequences for given array static void printSubsequences(int[] arr, int index, List<int> path) { // Print the subsequence when reach // the leaf of recursion tree if (index == arr.Length) { // Condition to avoid printing // empty subsequence if (path.Count > 0) { Console.Write("["); for(int i = 0; i < path.Count - 1; i++) { Console.Write(path[i] + ", "); } Console.WriteLine(path[path.Count - 1] + "]"); } } else { // Subsequence without including // the element at current index printSubsequences(arr, index + 1, path); path.Add(arr[index]); // Subsequence including the element // at current index printSubsequences(arr, index + 1, path); // Backtrack to remove the recently // inserted element path.RemoveAt(path.Count - 1); } return; } static void Main() { int[] arr = { 1, 2, 3 }; // Auxiliary space to store each path List<int> path = new List<int>(); printSubsequences(arr, 0, path); }} // This code is contributed by rameshtravel07. <script>// Javascript code to print all possible// subsequences for given array using// recursion // Recursive function to print all// possible subsequences for given arrayfunction printSubsequences(arr, index, path){ // Print the subsequence when reach // the leaf of recursion tree if (index == arr.length) { // Condition to avoid printing // empty subsequence if (path.length > 0) document.write(`[${path}]<br>`); } else { // Subsequence without including // the element at current index printSubsequences(arr, index + 1, path); path.push(arr[index]); // Subsequence including the element // at current index printSubsequences(arr, index + 1, path); // Backtrack to remove the recently // inserted element path.pop(); } return;} // Driver codelet arr = [1, 2, 3]; // Auxiliary space to store each pathlet path = new Array(); printSubsequences(arr, 0, path); // This code is contributed by gfgking</script> output 1 2 3 1 2 1 3 1 2 3 2 3 {} Time Complexity: Space Complexity: O(n) , Because of the recursion stack. sanjeev2552 mayanktyagi1709 msharma04 gfgking adnanirshad158 rameshtravel07 vivekr4400 tausifsiddiqui C-String-Question subsequence Technical Scripter 2018 Python Recursion Technical Scripter Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() Write a program to print all permutations of a given string Recursion Program for Tower of Hanoi Backtracking | Introduction Recursive Practice Problems with Solutions
[ { "code": null, "e": 52, "s": 24, "text": "\n25 May, 2022" }, { "code": null, "e": 171, "s": 52, "text": "Given an array. The task is to generate and print all of the possible subsequences of the given array using recursion." }, { "code": null, "e": 182, "s": 171, "text": "Examples: " }, { "code": null, "e": 310, "s": 182, "text": "Input : [1, 2, 3]\nOutput : [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3], []\n\nInput : [1, 2]\nOutput : [2], [1], [1, 2], []\n " }, { "code": null, "e": 584, "s": 310, "text": "Approach: For every element in the array, there are two choices, either to include it in the subsequence or not include it. Apply this for every element in the array starting from index 0 until we reach the last index. Print the subsequence once the last index is reached. " }, { "code": null, "e": 652, "s": 584, "text": "Below diagram shows the recursion tree for array, arr[] = {1, 2}. " }, { "code": null, "e": 704, "s": 652, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 708, "s": 704, "text": "C++" }, { "code": null, "e": 713, "s": 708, "text": "Java" }, { "code": null, "e": 721, "s": 713, "text": "Python3" }, { "code": null, "e": 724, "s": 721, "text": "C#" }, { "code": null, "e": 735, "s": 724, "text": "Javascript" }, { "code": "// C++ code to print all possible// subsequences for given array using// recursion#include <bits/stdc++.h>using namespace std; // Recursive function to print all// possible subsequences for given arrayvoid printSubsequences(int arr[], int index, vector<int> &subarr,int n){ // Print the subsequence when reach // the leaf of recursion tree if (index == n) { for (auto it:subarr){ cout << it << \" \"; } if(subarr.size()==0) cout<<\"{}\"; cout<<endl; return; } else { //pick the current index into the subsequence. subarr.push_back(arr[index]); printSubsequences(arr, index + 1, subarr,n); subarr.pop_back(); //not picking the element into the subsequence. printSubsequences(arr, index + 1, subarr,n); } } // Driver Codeint main(){ int arr[]={1, 2, 3}; int n=sizeof(arr)/sizeof(arr[0]); vector<int> vec; printSubsequences(arr, 0, vec,n); return 0;} // This code is contributed by// vivekr4400", "e": 1837, "s": 735, "text": null }, { "code": "// Java code to print all possible// subsequences for given array using// recursionimport java.io.*;import java.util.*; class GFG{ // Recursive function to print all// possible subsequences for given arraypublic static void printSubsequences(int[] arr, int index, ArrayList<Integer> path){ // Print the subsequence when reach // the leaf of recursion tree if (index == arr.length) { // Condition to avoid printing // empty subsequence if (path.size() > 0) System.out.println(path); } else { // Subsequence without including // the element at current index printSubsequences(arr, index + 1, path); path.add(arr[index]); // Subsequence including the element // at current index printSubsequences(arr, index + 1, path); // Backtrack to remove the recently // inserted element path.remove(path.size() - 1); } return;} // Driver codepublic static void main(String[] args){ int[] arr = { 1, 2, 3 }; // Auxiliary space to store each path ArrayList<Integer> path = new ArrayList<>(); printSubsequences(arr, 0, path);}} // This code is contributed by Mukul Sharma", "e": 3150, "s": 1837, "text": null }, { "code": "# Python3 code to print all possible # subsequences for given array using # recursion # Recursive function to print all# possible subsequences for given arraydef printSubsequences(arr, index, subarr): # Print the subsequence when reach # the leaf of recursion tree if index == len(arr): # Condition to avoid printing # empty subsequence if len(subarr) != 0: print(subarr) else: # Subsequence without including # the element at current index printSubsequences(arr, index + 1, subarr) # Subsequence including the element # at current index printSubsequences(arr, index + 1, subarr+[arr[index]]) return arr = [1, 2, 3] printSubsequences(arr, 0, []) #This code is contributed by Mayank Tyagi", "e": 4014, "s": 3150, "text": null }, { "code": "// C# code to print all possible// subsequences for given array using// recursionusing System;using System.Collections.Generic;class GFG { // Recursive function to print all // possible subsequences for given array static void printSubsequences(int[] arr, int index, List<int> path) { // Print the subsequence when reach // the leaf of recursion tree if (index == arr.Length) { // Condition to avoid printing // empty subsequence if (path.Count > 0) { Console.Write(\"[\"); for(int i = 0; i < path.Count - 1; i++) { Console.Write(path[i] + \", \"); } Console.WriteLine(path[path.Count - 1] + \"]\"); } } else { // Subsequence without including // the element at current index printSubsequences(arr, index + 1, path); path.Add(arr[index]); // Subsequence including the element // at current index printSubsequences(arr, index + 1, path); // Backtrack to remove the recently // inserted element path.RemoveAt(path.Count - 1); } return; } static void Main() { int[] arr = { 1, 2, 3 }; // Auxiliary space to store each path List<int> path = new List<int>(); printSubsequences(arr, 0, path); }} // This code is contributed by rameshtravel07.", "e": 5616, "s": 4014, "text": null }, { "code": "<script>// Javascript code to print all possible// subsequences for given array using// recursion // Recursive function to print all// possible subsequences for given arrayfunction printSubsequences(arr, index, path){ // Print the subsequence when reach // the leaf of recursion tree if (index == arr.length) { // Condition to avoid printing // empty subsequence if (path.length > 0) document.write(`[${path}]<br>`); } else { // Subsequence without including // the element at current index printSubsequences(arr, index + 1, path); path.push(arr[index]); // Subsequence including the element // at current index printSubsequences(arr, index + 1, path); // Backtrack to remove the recently // inserted element path.pop(); } return;} // Driver codelet arr = [1, 2, 3]; // Auxiliary space to store each pathlet path = new Array(); printSubsequences(arr, 0, path); // This code is contributed by gfgking</script>", "e": 6583, "s": 5616, "text": null }, { "code": null, "e": 6590, "s": 6583, "text": "output" }, { "code": null, "e": 6598, "s": 6590, "text": "1 2 3 " }, { "code": null, "e": 6604, "s": 6598, "text": "1 2 " }, { "code": null, "e": 6610, "s": 6604, "text": "1 3 " }, { "code": null, "e": 6614, "s": 6610, "text": "1 " }, { "code": null, "e": 6620, "s": 6614, "text": "2 3 " }, { "code": null, "e": 6624, "s": 6620, "text": "2 " }, { "code": null, "e": 6628, "s": 6624, "text": "3 " }, { "code": null, "e": 6631, "s": 6628, "text": "{}" }, { "code": null, "e": 6649, "s": 6631, "text": "Time Complexity: " }, { "code": null, "e": 6708, "s": 6649, "text": "Space Complexity: O(n) , Because of the recursion stack. " }, { "code": null, "e": 6720, "s": 6708, "text": "sanjeev2552" }, { "code": null, "e": 6736, "s": 6720, "text": "mayanktyagi1709" }, { "code": null, "e": 6746, "s": 6736, "text": "msharma04" }, { "code": null, "e": 6754, "s": 6746, "text": "gfgking" }, { "code": null, "e": 6769, "s": 6754, "text": "adnanirshad158" }, { "code": null, "e": 6784, "s": 6769, "text": "rameshtravel07" }, { "code": null, "e": 6795, "s": 6784, "text": "vivekr4400" }, { "code": null, "e": 6810, "s": 6795, "text": "tausifsiddiqui" }, { "code": null, "e": 6828, "s": 6810, "text": "C-String-Question" }, { "code": null, "e": 6840, "s": 6828, "text": "subsequence" }, { "code": null, "e": 6864, "s": 6840, "text": "Technical Scripter 2018" }, { "code": null, "e": 6871, "s": 6864, "text": "Python" }, { "code": null, "e": 6881, "s": 6871, "text": "Recursion" }, { "code": null, "e": 6900, "s": 6881, "text": "Technical Scripter" }, { "code": null, "e": 6910, "s": 6900, "text": "Recursion" }, { "code": null, "e": 7008, "s": 6910, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7026, "s": 7008, "text": "Python Dictionary" }, { "code": null, "e": 7068, "s": 7026, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 7090, "s": 7068, "text": "Enumerate() in Python" }, { "code": null, "e": 7125, "s": 7090, "text": "Read a file line by line in Python" }, { "code": null, "e": 7151, "s": 7125, "text": "Python String | replace()" }, { "code": null, "e": 7211, "s": 7151, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 7221, "s": 7211, "text": "Recursion" }, { "code": null, "e": 7248, "s": 7221, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 7276, "s": 7248, "text": "Backtracking | Introduction" } ]
Python – Network Interface
24 Nov, 2020 Network interface is nothing but interconnection between two hardware equipment or protocol layers in a computer network. A network interface usually has some form of the network address. It is generally a network interface card that does not have any physical existence. It can be implemented in a software interface. It is difficult to keep track of interface names, status, or any other information related to them when we have multiple interfaces. For this purpose, Python has a library called netifaces which can list the interfaces and their status. The netifaces module is a portable third-party library which enumerates the network interfaces on the local machine. Below is a simple example using python netifaces module giving details of interfaces and their status. Installation: pip install netifaces Implementation of netifaces module for various network operations: Python3 # Import librariesimport netifaces # Showing gateway listnetifaces.gateways() # Getting interfacesinterfaces = netifaces.interfaces() # Showing interfacesfor interface in interfaces: print(interface) # Getting interface infoprint(netifaces.ifaddresses(str(interfaces[0]))) # Getting interface statusaddrs = netifaces.ifaddresses(str(interfaces[0]))print(addrs[netifaces.AF_INET])print(addrs[netifaces.AF_LINK]) Output: Python-Networking Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Get unique values from a list Defaultdict in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Nov, 2020" }, { "code": null, "e": 347, "s": 28, "text": "Network interface is nothing but interconnection between two hardware equipment or protocol layers in a computer network. A network interface usually has some form of the network address. It is generally a network interface card that does not have any physical existence. It can be implemented in a software interface." }, { "code": null, "e": 804, "s": 347, "text": "It is difficult to keep track of interface names, status, or any other information related to them when we have multiple interfaces. For this purpose, Python has a library called netifaces which can list the interfaces and their status. The netifaces module is a portable third-party library which enumerates the network interfaces on the local machine. Below is a simple example using python netifaces module giving details of interfaces and their status." }, { "code": null, "e": 818, "s": 804, "text": "Installation:" }, { "code": null, "e": 840, "s": 818, "text": "pip install netifaces" }, { "code": null, "e": 907, "s": 840, "text": "Implementation of netifaces module for various network operations:" }, { "code": null, "e": 915, "s": 907, "text": "Python3" }, { "code": "# Import librariesimport netifaces # Showing gateway listnetifaces.gateways() # Getting interfacesinterfaces = netifaces.interfaces() # Showing interfacesfor interface in interfaces: print(interface) # Getting interface infoprint(netifaces.ifaddresses(str(interfaces[0]))) # Getting interface statusaddrs = netifaces.ifaddresses(str(interfaces[0]))print(addrs[netifaces.AF_INET])print(addrs[netifaces.AF_LINK])", "e": 1334, "s": 915, "text": null }, { "code": null, "e": 1342, "s": 1334, "text": "Output:" }, { "code": null, "e": 1360, "s": 1342, "text": "Python-Networking" }, { "code": null, "e": 1384, "s": 1360, "text": "Technical Scripter 2020" }, { "code": null, "e": 1391, "s": 1384, "text": "Python" }, { "code": null, "e": 1410, "s": 1391, "text": "Technical Scripter" }, { "code": null, "e": 1508, "s": 1410, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1540, "s": 1508, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1567, "s": 1540, "text": "Python Classes and Objects" }, { "code": null, "e": 1588, "s": 1567, "text": "Python OOPs Concepts" }, { "code": null, "e": 1611, "s": 1588, "text": "Introduction To PYTHON" }, { "code": null, "e": 1667, "s": 1611, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1709, "s": 1667, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1740, "s": 1709, "text": "Python | os.path.join() method" }, { "code": null, "e": 1782, "s": 1740, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1821, "s": 1782, "text": "Python | Get unique values from a list" } ]
Tabs With Dropdown Bootstrap Example
To create tabs with Bootstrap, use the .nav and .nav-tabs classes. With that use the .dropdown-menu class. Start with a basic unordered list with the base class of .nav Add the class .nav-tabs. Now add an unordered list with a .dropdown-menu class. You can try to run the following code to create tabs with drop-down − Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet"> <script src = "/scripts/jquery.min.js"></script> <script src = "/bootstrap/js/bootstrap.min.js"></script> </head> <body style = "background: #FADBD8;"> <h2>Website</h2> <ul class = "nav nav-tabs"> <li class = "active"><a href = "#">Home</a></li> <li><a href = "#">About</a></li> <li class = "dropdown"> <a class = "dropdown-toggle" data-toggle = "dropdown" href = "#"> Products <span class = "caret"></span> </a> <ul class = "dropdown-menu"> <li><a href = "#">Online Compiler</a></li> <li><a href = "#">Image Editor</a></li> <li><a href = "#">Document Viewer</a></li> </ul> </li> <li><a href = "#">Services</a></li> <li><a href = "#">Contact</a></li> </ul> </body> </html>
[ { "code": null, "e": 1169, "s": 1062, "text": "To create tabs with Bootstrap, use the .nav and .nav-tabs classes. With that use the .dropdown-menu class." }, { "code": null, "e": 1231, "s": 1169, "text": "Start with a basic unordered list with the base class of .nav" }, { "code": null, "e": 1257, "s": 1231, "text": " Add the class .nav-tabs." }, { "code": null, "e": 1312, "s": 1257, "text": "Now add an unordered list with a .dropdown-menu class." }, { "code": null, "e": 1382, "s": 1312, "text": "You can try to run the following code to create tabs with drop-down −" }, { "code": null, "e": 1392, "s": 1382, "text": "Live Demo" }, { "code": null, "e": 2427, "s": 1392, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body style = \"background: #FADBD8;\">\n <h2>Website</h2>\n <ul class = \"nav nav-tabs\">\n <li class = \"active\"><a href = \"#\">Home</a></li>\n <li><a href = \"#\">About</a></li>\n <li class = \"dropdown\">\n <a class = \"dropdown-toggle\" data-toggle = \"dropdown\" href = \"#\">\n Products\n <span class = \"caret\"></span>\n </a>\n <ul class = \"dropdown-menu\">\n <li><a href = \"#\">Online Compiler</a></li>\n <li><a href = \"#\">Image Editor</a></li>\n <li><a href = \"#\">Document Viewer</a></li>\n </ul>\n </li>\n <li><a href = \"#\">Services</a></li>\n <li><a href = \"#\">Contact</a></li>\n </ul>\n </body>\n</html>" } ]
CSS overflow-y Property - GeeksforGeeks
09 Aug, 2019 The overflow-y property of CSS specifies the behavior of content when it overflows a block-level element’s top and bottom edges. The content may be clipped, hidden or a scrollbar may be displayed accordingly based on the value assigned to the overflow-y property. Syntax: overflow-y: scroll | hidden | visible | auto Property values: Scroll: If the value assigned to the property is “scroll” then the content is clipped to fit the element and a scrollbar is displayed by the browser to help scroll the overflowed content. The scrollbar is added regardless of the content being clipped.Example:<!DOCTYPE html><html><head> <title> CSS overflow-y Property </title> <style> .content { background-color: lightgreen; height: 100px; width: 250px; overflow-y: scroll; } </style></head> <body> <h1>The overflow-y Property</h1> <!-- Below paragraph doesnot have a fixed width or height and has no overflow set. So, it will just take up the complete width of it's parent to fit the content --> <p> The CSS overflow-y property specifies the behavior of content when it overflows a block-level element’s top and bottom edges. The content may be clipped, hidden or a scrollbar may be displayed as specified. </p> <h2>overflow-y: scroll</h2> <!-- Below div element has fixed height and width and thus overflow may occur. --> <div class="content"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles,quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html> Output: Example: <!DOCTYPE html><html><head> <title> CSS overflow-y Property </title> <style> .content { background-color: lightgreen; height: 100px; width: 250px; overflow-y: scroll; } </style></head> <body> <h1>The overflow-y Property</h1> <!-- Below paragraph doesnot have a fixed width or height and has no overflow set. So, it will just take up the complete width of it's parent to fit the content --> <p> The CSS overflow-y property specifies the behavior of content when it overflows a block-level element’s top and bottom edges. The content may be clipped, hidden or a scrollbar may be displayed as specified. </p> <h2>overflow-y: scroll</h2> <!-- Below div element has fixed height and width and thus overflow may occur. --> <div class="content"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles,quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html> Output: Hidden: On assigning “hidden” as the value to the property, the content is clipped to fit the element. No scrollbars are provided and the content is hidden.Example:<!DOCTYPE html><html><head> <title> CSS overflow-y Property </title> <style> .content { background-color: lightgreen; height: 100px; width: 250px; overflow-y: hidden; } </style></head><body> <h1>The overflow-y Property</h1> <!-- Below paragraph doesnot have a fixed width or height and has no overflow set. So, it will just take up the complete width of it's parent to fit the content --> <p> The CSS overflow-y property specifies the behavior of content when it overflows a block-level element’s top and bottom edges. The content may be clipped, hidden or a scrollbar may be displayed as specified. </p> <h2>overflow-y: scroll</h2> <!-- Below div element has fixed height and width and thus overflow may occur. --> <div class="content"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles,quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html> Output: Example: <!DOCTYPE html><html><head> <title> CSS overflow-y Property </title> <style> .content { background-color: lightgreen; height: 100px; width: 250px; overflow-y: hidden; } </style></head><body> <h1>The overflow-y Property</h1> <!-- Below paragraph doesnot have a fixed width or height and has no overflow set. So, it will just take up the complete width of it's parent to fit the content --> <p> The CSS overflow-y property specifies the behavior of content when it overflows a block-level element’s top and bottom edges. The content may be clipped, hidden or a scrollbar may be displayed as specified. </p> <h2>overflow-y: scroll</h2> <!-- Below div element has fixed height and width and thus overflow may occur. --> <div class="content"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles,quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html> Output: Visible: If the value assigned to the “overflow-y” property is “visible” then the content is not clipped and may overflow out to the top or bottom of the containing element.Example:<!DOCTYPE html><html><head> <title> CSS overflow-y Property </title> <style> .content { background-color: lightgreen; height: 100px; width: 250px; overflow-y: visible; } </style></head><body> <h1>The overflow-y Property</h1> <!-- Below paragraph doesnot have a fixed width or height and has no overflow set. So, it will just take up the complete width of it's parent to fit the content --> <p> The CSS overflow-y property specifies the behavior of content when it overflows a block-level element’s top and bottom edges. The content may be clipped, hidden or a scrollbar may be displayed as specified. </p> <h2>overflow-y: scroll</h2> <!-- Below div element has fixed height and width and thus overflow may occur. --> <div class="content"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles,quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html> Output: <!DOCTYPE html><html><head> <title> CSS overflow-y Property </title> <style> .content { background-color: lightgreen; height: 100px; width: 250px; overflow-y: visible; } </style></head><body> <h1>The overflow-y Property</h1> <!-- Below paragraph doesnot have a fixed width or height and has no overflow set. So, it will just take up the complete width of it's parent to fit the content --> <p> The CSS overflow-y property specifies the behavior of content when it overflows a block-level element’s top and bottom edges. The content may be clipped, hidden or a scrollbar may be displayed as specified. </p> <h2>overflow-y: scroll</h2> <!-- Below div element has fixed height and width and thus overflow may occur. --> <div class="content"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles,quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html> Output: Auto: The behavior of auto depends on the content and scrollbars are added only when the content overflows, unlike that of the scroll value where the scrollbar is added regardless of overflow.Example:<!DOCTYPE html><html><head> <title> CSS overflow-y Property </title> <style> .content { background-color: lightgreen; height: 100px; width: 250px; overflow-y: auto; } </style></head> <body> <h1>The overflow-y Property</h1> <!-- Below paragraph doesnot have a fixed width or height and has no overflow set. So, it will just take up the complete width of it's parent to fit the content --> <p> The CSS overflow-y property specifies the behavior of content when it overflows a block-level element’s top and bottom edges. The content may be clipped, hidden or a scrollbar may be displayed as specified. </p> <h2>overflow-y: scroll</h2> <!-- Below div element has fixed height and width and thus overflow may occur. --> <div class="content"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles,quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html> Output: Example: <!DOCTYPE html><html><head> <title> CSS overflow-y Property </title> <style> .content { background-color: lightgreen; height: 100px; width: 250px; overflow-y: auto; } </style></head> <body> <h1>The overflow-y Property</h1> <!-- Below paragraph doesnot have a fixed width or height and has no overflow set. So, it will just take up the complete width of it's parent to fit the content --> <p> The CSS overflow-y property specifies the behavior of content when it overflows a block-level element’s top and bottom edges. The content may be clipped, hidden or a scrollbar may be displayed as specified. </p> <h2>overflow-y: scroll</h2> <!-- Below div element has fixed height and width and thus overflow may occur. --> <div class="content"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles,quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html> Output: Supported Browsers: The browser supported by overflow-y property are listed below: Chrome Internet Explorer Firefox Opera Safari CSS-Basics 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 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 22782, "s": 22754, "text": "\n09 Aug, 2019" }, { "code": null, "e": 23046, "s": 22782, "text": "The overflow-y property of CSS specifies the behavior of content when it overflows a block-level element’s top and bottom edges. The content may be clipped, hidden or a scrollbar may be displayed accordingly based on the value assigned to the overflow-y property." }, { "code": null, "e": 23054, "s": 23046, "text": "Syntax:" }, { "code": null, "e": 23099, "s": 23054, "text": "overflow-y: scroll | hidden | visible | auto" }, { "code": null, "e": 23116, "s": 23099, "text": "Property values:" }, { "code": null, "e": 24652, "s": 23116, "text": "Scroll: If the value assigned to the property is “scroll” then the content is clipped to fit the element and a scrollbar is displayed by the browser to help scroll the overflowed content. The scrollbar is added regardless of the content being clipped.Example:<!DOCTYPE html><html><head> <title> CSS overflow-y Property </title> <style> .content { background-color: lightgreen; height: 100px; width: 250px; overflow-y: scroll; } </style></head> <body> <h1>The overflow-y Property</h1> <!-- Below paragraph doesnot have a fixed width or height and has no overflow set. So, it will just take up the complete width of it's parent to fit the content --> <p> The CSS overflow-y property specifies the behavior of content when it overflows a block-level element’s top and bottom edges. The content may be clipped, hidden or a scrollbar may be displayed as specified. </p> <h2>overflow-y: scroll</h2> <!-- Below div element has fixed height and width and thus overflow may occur. --> <div class=\"content\"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles,quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html> Output:" }, { "code": null, "e": 24661, "s": 24652, "text": "Example:" }, { "code": "<!DOCTYPE html><html><head> <title> CSS overflow-y Property </title> <style> .content { background-color: lightgreen; height: 100px; width: 250px; overflow-y: scroll; } </style></head> <body> <h1>The overflow-y Property</h1> <!-- Below paragraph doesnot have a fixed width or height and has no overflow set. So, it will just take up the complete width of it's parent to fit the content --> <p> The CSS overflow-y property specifies the behavior of content when it overflows a block-level element’s top and bottom edges. The content may be clipped, hidden or a scrollbar may be displayed as specified. </p> <h2>overflow-y: scroll</h2> <!-- Below div element has fixed height and width and thus overflow may occur. --> <div class=\"content\"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles,quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html> ", "e": 25931, "s": 24661, "text": null }, { "code": null, "e": 25939, "s": 25931, "text": "Output:" }, { "code": null, "e": 27378, "s": 25939, "text": "Hidden: On assigning “hidden” as the value to the property, the content is clipped to fit the element. No scrollbars are provided and the content is hidden.Example:<!DOCTYPE html><html><head> <title> CSS overflow-y Property </title> <style> .content { background-color: lightgreen; height: 100px; width: 250px; overflow-y: hidden; } </style></head><body> <h1>The overflow-y Property</h1> <!-- Below paragraph doesnot have a fixed width or height and has no overflow set. So, it will just take up the complete width of it's parent to fit the content --> <p> The CSS overflow-y property specifies the behavior of content when it overflows a block-level element’s top and bottom edges. The content may be clipped, hidden or a scrollbar may be displayed as specified. </p> <h2>overflow-y: scroll</h2> <!-- Below div element has fixed height and width and thus overflow may occur. --> <div class=\"content\"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles,quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html> Output:" }, { "code": null, "e": 27387, "s": 27378, "text": "Example:" }, { "code": "<!DOCTYPE html><html><head> <title> CSS overflow-y Property </title> <style> .content { background-color: lightgreen; height: 100px; width: 250px; overflow-y: hidden; } </style></head><body> <h1>The overflow-y Property</h1> <!-- Below paragraph doesnot have a fixed width or height and has no overflow set. So, it will just take up the complete width of it's parent to fit the content --> <p> The CSS overflow-y property specifies the behavior of content when it overflows a block-level element’s top and bottom edges. The content may be clipped, hidden or a scrollbar may be displayed as specified. </p> <h2>overflow-y: scroll</h2> <!-- Below div element has fixed height and width and thus overflow may occur. --> <div class=\"content\"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles,quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html> ", "e": 28655, "s": 27387, "text": null }, { "code": null, "e": 28663, "s": 28655, "text": "Output:" }, { "code": null, "e": 30120, "s": 28663, "text": "Visible: If the value assigned to the “overflow-y” property is “visible” then the content is not clipped and may overflow out to the top or bottom of the containing element.Example:<!DOCTYPE html><html><head> <title> CSS overflow-y Property </title> <style> .content { background-color: lightgreen; height: 100px; width: 250px; overflow-y: visible; } </style></head><body> <h1>The overflow-y Property</h1> <!-- Below paragraph doesnot have a fixed width or height and has no overflow set. So, it will just take up the complete width of it's parent to fit the content --> <p> The CSS overflow-y property specifies the behavior of content when it overflows a block-level element’s top and bottom edges. The content may be clipped, hidden or a scrollbar may be displayed as specified. </p> <h2>overflow-y: scroll</h2> <!-- Below div element has fixed height and width and thus overflow may occur. --> <div class=\"content\"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles,quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html> Output:" }, { "code": "<!DOCTYPE html><html><head> <title> CSS overflow-y Property </title> <style> .content { background-color: lightgreen; height: 100px; width: 250px; overflow-y: visible; } </style></head><body> <h1>The overflow-y Property</h1> <!-- Below paragraph doesnot have a fixed width or height and has no overflow set. So, it will just take up the complete width of it's parent to fit the content --> <p> The CSS overflow-y property specifies the behavior of content when it overflows a block-level element’s top and bottom edges. The content may be clipped, hidden or a scrollbar may be displayed as specified. </p> <h2>overflow-y: scroll</h2> <!-- Below div element has fixed height and width and thus overflow may occur. --> <div class=\"content\"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles,quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html> ", "e": 31389, "s": 30120, "text": null }, { "code": null, "e": 31397, "s": 31389, "text": "Output:" }, { "code": null, "e": 32872, "s": 31397, "text": "Auto: The behavior of auto depends on the content and scrollbars are added only when the content overflows, unlike that of the scroll value where the scrollbar is added regardless of overflow.Example:<!DOCTYPE html><html><head> <title> CSS overflow-y Property </title> <style> .content { background-color: lightgreen; height: 100px; width: 250px; overflow-y: auto; } </style></head> <body> <h1>The overflow-y Property</h1> <!-- Below paragraph doesnot have a fixed width or height and has no overflow set. So, it will just take up the complete width of it's parent to fit the content --> <p> The CSS overflow-y property specifies the behavior of content when it overflows a block-level element’s top and bottom edges. The content may be clipped, hidden or a scrollbar may be displayed as specified. </p> <h2>overflow-y: scroll</h2> <!-- Below div element has fixed height and width and thus overflow may occur. --> <div class=\"content\"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles,quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html> Output:" }, { "code": null, "e": 32881, "s": 32872, "text": "Example:" }, { "code": "<!DOCTYPE html><html><head> <title> CSS overflow-y Property </title> <style> .content { background-color: lightgreen; height: 100px; width: 250px; overflow-y: auto; } </style></head> <body> <h1>The overflow-y Property</h1> <!-- Below paragraph doesnot have a fixed width or height and has no overflow set. So, it will just take up the complete width of it's parent to fit the content --> <p> The CSS overflow-y property specifies the behavior of content when it overflows a block-level element’s top and bottom edges. The content may be clipped, hidden or a scrollbar may be displayed as specified. </p> <h2>overflow-y: scroll</h2> <!-- Below div element has fixed height and width and thus overflow may occur. --> <div class=\"content\"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles,quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html> ", "e": 34149, "s": 32881, "text": null }, { "code": null, "e": 34157, "s": 34149, "text": "Output:" }, { "code": null, "e": 34240, "s": 34157, "text": "Supported Browsers: The browser supported by overflow-y property are listed below:" }, { "code": null, "e": 34247, "s": 34240, "text": "Chrome" }, { "code": null, "e": 34265, "s": 34247, "text": "Internet Explorer" }, { "code": null, "e": 34273, "s": 34265, "text": "Firefox" }, { "code": null, "e": 34279, "s": 34273, "text": "Opera" }, { "code": null, "e": 34286, "s": 34279, "text": "Safari" }, { "code": null, "e": 34297, "s": 34286, "text": "CSS-Basics" }, { "code": null, "e": 34312, "s": 34297, "text": "CSS-Properties" }, { "code": null, "e": 34319, "s": 34312, "text": "Picked" }, { "code": null, "e": 34323, "s": 34319, "text": "CSS" }, { "code": null, "e": 34340, "s": 34323, "text": "Web Technologies" }, { "code": null, "e": 34438, "s": 34340, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34447, "s": 34438, "text": "Comments" }, { "code": null, "e": 34460, "s": 34447, "text": "Old Comments" }, { "code": null, "e": 34522, "s": 34460, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 34572, "s": 34522, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 34630, "s": 34572, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 34678, "s": 34630, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 34715, "s": 34678, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 34757, "s": 34715, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 34790, "s": 34757, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 34852, "s": 34790, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 34895, "s": 34852, "text": "How to fetch data from an API in ReactJS ?" } ]
JavaScript Data Types
JavaScript variables can hold different data types: numbers, strings, objects and more: In programming, data types is an important concept. To be able to operate on variables, it is important to know something about the type. Without data types, a computer cannot safely solve this: Does it make any sense to add "Volvo" to sixteen? Will it produce an error or will it produce a result? JavaScript will treat the example above as: When adding a number and a string, JavaScript will treat the number as a string. JavaScript evaluates expressions from left to right. Different sequences can produce different results: Result: Result: In the first example, JavaScript treats 16 and 4 as numbers, until it reaches "Volvo". In the second example, since the first operand is a string, all operands are treated as strings. JavaScript has dynamic types. This means that the same variable can be used to hold different data types: A string (or a text string) is a series of characters like "John Doe". Strings are written with quotes. You can use single or double quotes: You can use quotes inside a string, as long as they don't match the quotes surrounding the string: You will learn more about strings later in this tutorial. JavaScript has only one type of numbers. Numbers can be written with, or without decimals: Extra large or extra small numbers can be written with scientific (exponential) notation: You will learn more about numbers later in this tutorial. Booleans can only have two values: true or false. Booleans are often used in conditional testing. You will learn more about conditional testing later in this tutorial. JavaScript arrays are written with square brackets. Array items are separated by commas. The following code declares (creates) an array called cars, containing three items (car names): Array indexes are zero-based, which means the first item is [0], second is [1], and so on. You will learn more about arrays later in this tutorial. JavaScript objects are written with curly braces {}. Object properties are written as name:value pairs, separated by commas. The object (person) in the example above has 4 properties: firstName, lastName, age, and eyeColor. You will learn more about objects later in this tutorial. You can use the JavaScript typeof operator to find the type of a JavaScript variable. The typeof operator returns the type of a variable or an expression: You will learn more about typeof later in this tutorial. In JavaScript, a variable without a value, has the value undefined. The type is also undefined. Any variable can be emptied, by setting the value to undefined. The type will also be undefined. An empty value has nothing to do with undefined. An empty string has both a legal value and a type. Use comments to describe the correct data type of the following variables: let length = 16; // let lastName = "Johnson"; // const x = { firstName: "John", lastName: "Doe" }; // Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 89, "s": 0, "text": "JavaScript variables can hold different data types: numbers, \nstrings, objects and more:" }, { "code": null, "e": 141, "s": 89, "text": "In programming, data types is an important concept." }, { "code": null, "e": 228, "s": 141, "text": "To be able to operate on variables, it is important to know something about \nthe type." }, { "code": null, "e": 285, "s": 228, "text": "Without data types, a computer cannot safely solve this:" }, { "code": null, "e": 390, "s": 285, "text": "Does it make any sense to add \"Volvo\" to sixteen? Will it produce an \nerror or will it produce a result?" }, { "code": null, "e": 434, "s": 390, "text": "JavaScript will treat the example above as:" }, { "code": null, "e": 516, "s": 434, "text": "When adding a number and a string, JavaScript will treat the number as a \nstring." }, { "code": null, "e": 621, "s": 516, "text": "JavaScript evaluates expressions from left to right. Different sequences can \nproduce different results:" }, { "code": null, "e": 629, "s": 621, "text": "Result:" }, { "code": null, "e": 637, "s": 629, "text": "Result:" }, { "code": null, "e": 724, "s": 637, "text": "In the first example, JavaScript treats 16 and 4 as numbers, until it reaches \"Volvo\"." }, { "code": null, "e": 822, "s": 724, "text": "In the second example, since the first operand is a string, all operands are \ntreated as strings." }, { "code": null, "e": 930, "s": 822, "text": "JavaScript has dynamic types. This means that the same variable can be used \nto hold \ndifferent data types:" }, { "code": null, "e": 1001, "s": 930, "text": "A string (or a text string) is a series of characters like \"John Doe\"." }, { "code": null, "e": 1072, "s": 1001, "text": "Strings are written with quotes. You can use single or double quotes:\n" }, { "code": null, "e": 1172, "s": 1072, "text": "You can use quotes inside a string, as long as they don't match the quotes \nsurrounding the string:" }, { "code": null, "e": 1231, "s": 1172, "text": "You will learn more about strings later in this \ntutorial." }, { "code": null, "e": 1272, "s": 1231, "text": "JavaScript has only one type of numbers." }, { "code": null, "e": 1322, "s": 1272, "text": "Numbers can be written with, or without decimals:" }, { "code": null, "e": 1413, "s": 1322, "text": "Extra large or extra small numbers can be written with scientific \n(exponential) notation:" }, { "code": null, "e": 1472, "s": 1413, "text": "You will learn more about numbers later in this \ntutorial." }, { "code": null, "e": 1522, "s": 1472, "text": "Booleans can only have two values: true or false." }, { "code": null, "e": 1570, "s": 1522, "text": "Booleans are often used in conditional testing." }, { "code": null, "e": 1641, "s": 1570, "text": "You will learn more about \nconditional testing later in this tutorial." }, { "code": null, "e": 1693, "s": 1641, "text": "JavaScript arrays are written with square brackets." }, { "code": null, "e": 1730, "s": 1693, "text": "Array items are separated by commas." }, { "code": null, "e": 1827, "s": 1730, "text": "The following code declares (creates) an array called cars, containing three \nitems (car names):" }, { "code": null, "e": 1919, "s": 1827, "text": "Array indexes are zero-based, which means the first item is [0], second is \n[1], and so on." }, { "code": null, "e": 1976, "s": 1919, "text": "You will learn more about arrays later in this tutorial." }, { "code": null, "e": 2029, "s": 1976, "text": "JavaScript objects are written with curly braces {}." }, { "code": null, "e": 2102, "s": 2029, "text": "Object \nproperties are written as name:value pairs, separated by commas." }, { "code": null, "e": 2202, "s": 2102, "text": "The object (person) in the example above has 4 properties: firstName, \nlastName, age, and eyeColor." }, { "code": null, "e": 2260, "s": 2202, "text": "You will learn more about objects later in this tutorial." }, { "code": null, "e": 2347, "s": 2260, "text": "You can use the JavaScript typeof operator to find the type \nof a JavaScript variable." }, { "code": null, "e": 2416, "s": 2347, "text": "The typeof operator returns the type of a variable or an expression:" }, { "code": null, "e": 2473, "s": 2416, "text": "You will learn more about typeof later in this tutorial." }, { "code": null, "e": 2570, "s": 2473, "text": "In JavaScript, a variable without a value, has the value undefined. \nThe type is also undefined." }, { "code": null, "e": 2668, "s": 2570, "text": "Any variable can be emptied, by setting the value to undefined. \nThe type will also be undefined." }, { "code": null, "e": 2717, "s": 2668, "text": "An empty value has nothing to do with undefined." }, { "code": null, "e": 2768, "s": 2717, "text": "An empty string has both a legal value and a type." }, { "code": null, "e": 2843, "s": 2768, "text": "Use comments to describe the correct data type of the following variables:" }, { "code": null, "e": 2991, "s": 2843, "text": "let length = 16; // \nlet lastName = \"Johnson\"; // \nconst x = {\n firstName: \"John\",\n lastName: \"Doe\"\n}; // \n" }, { "code": null, "e": 3010, "s": 2991, "text": "Start the Exercise" }, { "code": null, "e": 3043, "s": 3010, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 3085, "s": 3043, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 3192, "s": 3085, "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": 3211, "s": 3192, "text": "help@w3schools.com" } ]
Submitting your MATLAB jobs using Slurm to High-Performance Clusters | by Rahul Bhadani | Towards Data Science
In my previous article, I wrote about using PBS job schedulers for submitting jobs to High-Performance Clusters (HPC) to meet our computation need. However, not all HPC support PBS jobs. Recently my institution also decided to use another kind of job scheduler called Slurm for its newly installed clusters. medium.com Taken from its documentation1, Slurm is an open-source, fault-tolerant, and scalable cluster management and job scheduler Linux cluster. As a cluster workload manager, Slurm has three key functions: It allocates access to resources to users for some duration of time so they can execute their computational jobs.It provides a framework to start, execute, and monitor work (normally a parallel job) on the set of allocated nodes.It arbitrates contention for resources by managing a queue of pending work. It allocates access to resources to users for some duration of time so they can execute their computational jobs. It provides a framework to start, execute, and monitor work (normally a parallel job) on the set of allocated nodes. It arbitrates contention for resources by managing a queue of pending work. In this article, I will demonstrate how to submit MATLAB jobs to the HPC node supporting the Slurm job scheduler. You must be wondering why MATLAB, after all, is not open-source. There are ample amount of reasons for that. First, MATLAB supports true parallelism, unlike most python packages — except for those that are actually implemented in C++ and just provide wrappers at python levels. MATLAB has excellent support for distributed computing and underlying implementation is indeed in C++ which is extremely fast. Besides, MATLAB provides out-of-the-box algorithms to support applications in the domain of Control Engineering, Digital Signal Processing, Robotics, and so on where the python community still lags. Chances are that if you are a part of large organizations such as a university, your organization may have an institutional license for MATLAB. Slurm submission scripts have two parts: (1) Resource Requests (2) Job Execution The first part of the scripts specifies the number of nodes, maximum CPU time, the maximum amount of RAM, whether GPUs are needed, etc. that the job will request for running the computation task. The second part of the script specifies which modules to load, what data files to load, and which program or code to run. I presenting a working example, where I want to compute something in parallel leveraging the distributed computing toolbox provided by MATLAB. For that, I can use parfor instead of a conventional signal core for . Since the HPC system where I want to run this code has 94 cores, I will specify to create 94 workers so that 94 parallel jobs2 can be created. Let’s begin, first, create a new file called minimal_parfor.m in /home/u100/username directory: L = linspace(0.000001, 200, 800000);index = 1:length(L);formatOut = 'yyyy_mm_dd_HH_MM_SS_FFF';dt = datestr(now,formatOut);datafolder = "/home/u100/username";outputfile = datafolder + "/"+"SIN_" + dt + ".csv";if ~isfile(outputfile) fprintf("SIN Output file doesn't exist .. creating\n"); fileID = fopen(outputfile,'w'); fprintf(fileID,'L,Sin(L)\n'); fclose(fileID);else fprintf("SIN Output file exists .. not creating\n");endparpool(94);parfor ii = index S = sin(L(ii)); fileID = fopen(outputfile,'a'); fprintf(fileID,'%.10f,%.10f\n', ... L(ii),S); fclose(fileID);end As we can see, I am requesting 94 workers using parpool . Further, I am computing sin values of a number in parallel and saving them in a file. I prefer the method of saving data in a file rather than storing it in a variable because I can take a look at the file while execution is still running. parfor randomly selects 94 indices as specified to run 94 parallel jobs. As a result, I won’t find indices being written in the file sequentially. However, I can always sort them later. In the second step, I create a SLURM file in /home/u100/username directory and name it minimal.slurm: #!/bin/bash# --------------------------------------------------------------### PART 1: Requests resources to run your job.# --------------------------------------------------------------### Optional. Set the job name#SBATCH --job-name=minimal_parfor### Optional. Set the output filename.### SLURM reads %x as the job name and %j as the job ID#SBATCH --output=%x-%j.out#SBATCH --error=%x-%j.err### REQUIRED. Specify the PI group for this job#SBATCH --account=manager### Optional. Request email when job begins and ends### Specify high priority jobs#SBATCH --qos=user_qos_manager# SBATCH --mail-type=ALL### Optional. Specify email address to use for notification# SBATCH --mail-user=user@email.edu### REQUIRED. Set the partition for your job.#SBATCH --partition=standard### REQUIRED. Set the number of cores that will be used for this job.#SBATCH --ntasks=1#SBATCH --cpus-per-task=94### REQUIRED. Set the memory required for this job.#SBATCH --mem=450gb### REQUIRED. Specify the time required for this job, hhh:mm:ss#SBATCH --time=200:00:00# --------------------------------------------------------------### PART 2: Executes bash commands to run your job# --------------------------------------------------------------### SLURM Inherits your environment. cd $SLURM_SUBMIT_DIR not neededpwd; hostname; dateecho "CPUs per task: $SLURM_CPUS_PER_TASK"### Load required modules/libraries if neededmodule load matlab/r2020b### This was recommended by MATLAb through technical supportulimit -u 63536 cd $PWDmatlab -nodisplay -nosplash -softwareopengl < /home/u100/username/mininal_parfor.m > /home/u100/username/out_mininal.txtdate~ minimal.slurm is a bash script that specifies the resources to request in HPC and how to execute the MATLAB job. I specify 94 cpus using the command SBATCH — cpus-per-task=94 so that it can be available to MATLAB when it requests 94 workers through parpool. Further, I request 450 GB of RAM which will be available when my job starts running. To submit the job to HPC, type sbatch minimal.slurm To get the status of your submitted job, you can type: sacct or squeue | grep username Once the job starts, finished, or terminated for any reason, I expect to receive an email on the specified email address in my slurm file. I hope this article will be helpful to anyone using SLURM for job submissions who want to use the power of MATLAB’s parallel computing toolbox at www.mathworks.com For more detail on MATLAB’s distributed computing toolbox, please check out https://slurm.schedmd.com/quickstart.htmlhttps://www.mathworks.com/help/parallel-computing/parpool.html https://slurm.schedmd.com/quickstart.html https://www.mathworks.com/help/parallel-computing/parpool.html Note: This article is in no way a solicitation for MATLAB or any product by Mathworks. The author holds no affiliation with Mathworks or a related entity.
[ { "code": null, "e": 480, "s": 172, "text": "In my previous article, I wrote about using PBS job schedulers for submitting jobs to High-Performance Clusters (HPC) to meet our computation need. However, not all HPC support PBS jobs. Recently my institution also decided to use another kind of job scheduler called Slurm for its newly installed clusters." }, { "code": null, "e": 491, "s": 480, "text": "medium.com" }, { "code": null, "e": 690, "s": 491, "text": "Taken from its documentation1, Slurm is an open-source, fault-tolerant, and scalable cluster management and job scheduler Linux cluster. As a cluster workload manager, Slurm has three key functions:" }, { "code": null, "e": 995, "s": 690, "text": "It allocates access to resources to users for some duration of time so they can execute their computational jobs.It provides a framework to start, execute, and monitor work (normally a parallel job) on the set of allocated nodes.It arbitrates contention for resources by managing a queue of pending work." }, { "code": null, "e": 1109, "s": 995, "text": "It allocates access to resources to users for some duration of time so they can execute their computational jobs." }, { "code": null, "e": 1226, "s": 1109, "text": "It provides a framework to start, execute, and monitor work (normally a parallel job) on the set of allocated nodes." }, { "code": null, "e": 1302, "s": 1226, "text": "It arbitrates contention for resources by managing a queue of pending work." }, { "code": null, "e": 1416, "s": 1302, "text": "In this article, I will demonstrate how to submit MATLAB jobs to the HPC node supporting the Slurm job scheduler." }, { "code": null, "e": 2164, "s": 1416, "text": "You must be wondering why MATLAB, after all, is not open-source. There are ample amount of reasons for that. First, MATLAB supports true parallelism, unlike most python packages — except for those that are actually implemented in C++ and just provide wrappers at python levels. MATLAB has excellent support for distributed computing and underlying implementation is indeed in C++ which is extremely fast. Besides, MATLAB provides out-of-the-box algorithms to support applications in the domain of Control Engineering, Digital Signal Processing, Robotics, and so on where the python community still lags. Chances are that if you are a part of large organizations such as a university, your organization may have an institutional license for MATLAB." }, { "code": null, "e": 2245, "s": 2164, "text": "Slurm submission scripts have two parts: (1) Resource Requests (2) Job Execution" }, { "code": null, "e": 2441, "s": 2245, "text": "The first part of the scripts specifies the number of nodes, maximum CPU time, the maximum amount of RAM, whether GPUs are needed, etc. that the job will request for running the computation task." }, { "code": null, "e": 2563, "s": 2441, "text": "The second part of the script specifies which modules to load, what data files to load, and which program or code to run." }, { "code": null, "e": 2920, "s": 2563, "text": "I presenting a working example, where I want to compute something in parallel leveraging the distributed computing toolbox provided by MATLAB. For that, I can use parfor instead of a conventional signal core for . Since the HPC system where I want to run this code has 94 cores, I will specify to create 94 workers so that 94 parallel jobs2 can be created." }, { "code": null, "e": 3016, "s": 2920, "text": "Let’s begin, first, create a new file called minimal_parfor.m in /home/u100/username directory:" }, { "code": null, "e": 3638, "s": 3016, "text": "L = linspace(0.000001, 200, 800000);index = 1:length(L);formatOut = 'yyyy_mm_dd_HH_MM_SS_FFF';dt = datestr(now,formatOut);datafolder = \"/home/u100/username\";outputfile = datafolder + \"/\"+\"SIN_\" + dt + \".csv\";if ~isfile(outputfile) fprintf(\"SIN Output file doesn't exist .. creating\\n\"); fileID = fopen(outputfile,'w'); fprintf(fileID,'L,Sin(L)\\n'); fclose(fileID);else fprintf(\"SIN Output file exists .. not creating\\n\");endparpool(94);parfor ii = index S = sin(L(ii)); fileID = fopen(outputfile,'a'); fprintf(fileID,'%.10f,%.10f\\n', ... L(ii),S); fclose(fileID);end" }, { "code": null, "e": 4122, "s": 3638, "text": "As we can see, I am requesting 94 workers using parpool . Further, I am computing sin values of a number in parallel and saving them in a file. I prefer the method of saving data in a file rather than storing it in a variable because I can take a look at the file while execution is still running. parfor randomly selects 94 indices as specified to run 94 parallel jobs. As a result, I won’t find indices being written in the file sequentially. However, I can always sort them later." }, { "code": null, "e": 4224, "s": 4122, "text": "In the second step, I create a SLURM file in /home/u100/username directory and name it minimal.slurm:" }, { "code": null, "e": 5848, "s": 4224, "text": "#!/bin/bash# --------------------------------------------------------------### PART 1: Requests resources to run your job.# --------------------------------------------------------------### Optional. Set the job name#SBATCH --job-name=minimal_parfor### Optional. Set the output filename.### SLURM reads %x as the job name and %j as the job ID#SBATCH --output=%x-%j.out#SBATCH --error=%x-%j.err### REQUIRED. Specify the PI group for this job#SBATCH --account=manager### Optional. Request email when job begins and ends### Specify high priority jobs#SBATCH --qos=user_qos_manager# SBATCH --mail-type=ALL### Optional. Specify email address to use for notification# SBATCH --mail-user=user@email.edu### REQUIRED. Set the partition for your job.#SBATCH --partition=standard### REQUIRED. Set the number of cores that will be used for this job.#SBATCH --ntasks=1#SBATCH --cpus-per-task=94### REQUIRED. Set the memory required for this job.#SBATCH --mem=450gb### REQUIRED. Specify the time required for this job, hhh:mm:ss#SBATCH --time=200:00:00# --------------------------------------------------------------### PART 2: Executes bash commands to run your job# --------------------------------------------------------------### SLURM Inherits your environment. cd $SLURM_SUBMIT_DIR not neededpwd; hostname; dateecho \"CPUs per task: $SLURM_CPUS_PER_TASK\"### Load required modules/libraries if neededmodule load matlab/r2020b### This was recommended by MATLAb through technical supportulimit -u 63536 cd $PWDmatlab -nodisplay -nosplash -softwareopengl < /home/u100/username/mininal_parfor.m > /home/u100/username/out_mininal.txtdate~" }, { "code": null, "e": 6191, "s": 5848, "text": "minimal.slurm is a bash script that specifies the resources to request in HPC and how to execute the MATLAB job. I specify 94 cpus using the command SBATCH — cpus-per-task=94 so that it can be available to MATLAB when it requests 94 workers through parpool. Further, I request 450 GB of RAM which will be available when my job starts running." }, { "code": null, "e": 6222, "s": 6191, "text": "To submit the job to HPC, type" }, { "code": null, "e": 6243, "s": 6222, "text": "sbatch minimal.slurm" }, { "code": null, "e": 6298, "s": 6243, "text": "To get the status of your submitted job, you can type:" }, { "code": null, "e": 6304, "s": 6298, "text": "sacct" }, { "code": null, "e": 6307, "s": 6304, "text": "or" }, { "code": null, "e": 6330, "s": 6307, "text": "squeue | grep username" }, { "code": null, "e": 6469, "s": 6330, "text": "Once the job starts, finished, or terminated for any reason, I expect to receive an email on the specified email address in my slurm file." }, { "code": null, "e": 6615, "s": 6469, "text": "I hope this article will be helpful to anyone using SLURM for job submissions who want to use the power of MATLAB’s parallel computing toolbox at" }, { "code": null, "e": 6633, "s": 6615, "text": "www.mathworks.com" }, { "code": null, "e": 6709, "s": 6633, "text": "For more detail on MATLAB’s distributed computing toolbox, please check out" }, { "code": null, "e": 6813, "s": 6709, "text": "https://slurm.schedmd.com/quickstart.htmlhttps://www.mathworks.com/help/parallel-computing/parpool.html" }, { "code": null, "e": 6855, "s": 6813, "text": "https://slurm.schedmd.com/quickstart.html" }, { "code": null, "e": 6918, "s": 6855, "text": "https://www.mathworks.com/help/parallel-computing/parpool.html" } ]
Convert vowels from upper to lower or lower to upper using C program
An array of characters is called a string. Following is the declaration for an array − char stringname [size]; For example − char a[50]; string of length 50 characters Using single character constant − char a[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’} Using string constants − char a[10] = "Hello":; There is a control string "%s" used for accessing the string till it encounters ‘\0’. The logic used to convert vowels from upper to lower or lower to upper is − for(i=0;string[i]!='\0';i++){ if(string[i]=='a'||string[i]=='e'||string[i]=='i'||string[i]=='o'||string[i]=='u'){ string[i]=toupper(string[i]); } } printf("The result string with converted vowels is : "); puts(string); Following is the C program using conversion functions to convert an Upper case string to Lower case string − #include<stdio.h> #include<ctype.h> void main(){ //Declaring variable for For loop (to read each position of alphabet) and string// int i; char string[40]; //Reading string// printf("Enter the string : "); gets(string); //For loop to read each alphabet// for(i=0;string[i]!='\0';i++){ if(string[i]=='a'||string[i]=='e'||string[i]=='i'||string[i]=='o'||string[i]=='u'){ string[i]=toupper(string[i]); } } printf("The result string with converted vowels is : "); puts(string); } When the above program is executed, it produces the following result − Run 1: Enter the string : TutoRialsPoint The result string with converted vowels is : TUtORIAlsPOInt Run 2: Enter the string : c programming The result string with converted vowels is : c programming
[ { "code": null, "e": 1105, "s": 1062, "text": "An array of characters is called a string." }, { "code": null, "e": 1149, "s": 1105, "text": "Following is the declaration for an array −" }, { "code": null, "e": 1173, "s": 1149, "text": "char stringname [size];" }, { "code": null, "e": 1230, "s": 1173, "text": "For example − char a[50]; string of length 50 characters" }, { "code": null, "e": 1264, "s": 1230, "text": "Using single character constant −" }, { "code": null, "e": 1310, "s": 1264, "text": "char a[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\\0’}" }, { "code": null, "e": 1335, "s": 1310, "text": "Using string constants −" }, { "code": null, "e": 1358, "s": 1335, "text": "char a[10] = \"Hello\":;" }, { "code": null, "e": 1444, "s": 1358, "text": "There is a control string \"%s\" used for accessing the string till it encounters ‘\\0’." }, { "code": null, "e": 1520, "s": 1444, "text": "The logic used to convert vowels from upper to lower or lower to upper is −" }, { "code": null, "e": 1751, "s": 1520, "text": "for(i=0;string[i]!='\\0';i++){\n if(string[i]=='a'||string[i]=='e'||string[i]=='i'||string[i]=='o'||string[i]=='u'){\n string[i]=toupper(string[i]);\n }\n}\nprintf(\"The result string with converted vowels is : \");\nputs(string);" }, { "code": null, "e": 1860, "s": 1751, "text": "Following is the C program using conversion functions to convert an Upper case string to Lower case string −" }, { "code": null, "e": 2390, "s": 1860, "text": "#include<stdio.h>\n#include<ctype.h>\nvoid main(){\n //Declaring variable for For loop (to read each position of alphabet) and string//\n int i;\n char string[40];\n //Reading string//\n printf(\"Enter the string : \");\n gets(string);\n //For loop to read each alphabet//\n for(i=0;string[i]!='\\0';i++){\n if(string[i]=='a'||string[i]=='e'||string[i]=='i'||string[i]=='o'||string[i]=='u'){\n string[i]=toupper(string[i]);\n }\n }\n printf(\"The result string with converted vowels is : \");\n puts(string);\n}" }, { "code": null, "e": 2461, "s": 2390, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 2661, "s": 2461, "text": "Run 1:\nEnter the string : TutoRialsPoint\nThe result string with converted vowels is : TUtORIAlsPOInt\nRun 2:\nEnter the string : c programming\nThe result string with converted vowels is : c programming" } ]
What is Network Analysis?. A brief introduction with examples | by Mengsay Loem | Towards Data Science
If you are using any social media applications, you may have experienced the friend or follower suggestions functions. Have you ever wondered how these functions work? One common technology used in these cases is Network Analysis. A network refers to a structure representing a group of objects/people and relationships between them. It is also known as a graph in mathematics. A network structure consists of nodes and edges. Here, nodes represent objects we are going to analyze while edges represent the relationships between those objects. For example, if we are studying a social relationship between Facebook users, nodes are target users and edges are relationships such as friendships between users or group memberships. In Twitter, edges can be following/follower relationships. Network Analysis is useful in many living application tasks. It helps us in deep understanding the structure of a relationship in social networks, a structure or process of change in natural phenomenons, or even the analysis of biological systems of organisms. Again, let’s use the network of social media users as an example. Analyzing this network helps in Identifying the most influent person/people in a group Defining characteristics of groups of users Prediction of suitable items for users Identifying CM targets ,etc. Other easy-to-understand examples are the Friend Suggestion function in Facebook or Follow Suggestion function in Twitter. A crucial application of network analysis is identifying the important node in a network. This task is called Measuring Network Centrality. In social network analysis, it can refer to the task of identifying the most influential member, or the representative of the group. For example, which node do you think is the most important one in the above figure? Of course, to define the most important node, we need a specific definition of the Important Node. There are several indicators used to measure the centrality of a node. Degree centrality: node with a higher degree has higher centrality Eigenvector centrality: adding to the degree of one node, the centralities of neighbor nodes are considered. As a result, the eigenvector corresponding to the highest eigenvalue of the adjacency matrix represents the centrality of nodes in the network Betweenness centrality: the number of paths between two nodes that go through the i-th node is considered as the i-th node’s betweenness centrality. Closeness centrality: the length of the path from the i-th node to other nodes in the network is considered as the i-th node’s closeness centrality. With this definition, for example, this centrality can be applied in the task of defining a suitable evacuation site in a city. import networkx as nximport numpy as npimport matplotlib.pyplot as pltG = nx.Graph()G.add_nodes_from(["A","B","C","D","E","F","G","H","I","J","K"])G.add_edges_from([("A","C"),("B","C"),("C","D"),("D","E"),("D","G"),("A","G"),("F","H"),("G","H"),("H","I"),("I","J"),("I","K")])nx.draw(G, node_size=400, node_color='red', with_labels=True, font_weight='bold')print("degree centrality:")for k, v in sorted(nx.degree_centrality(G).items(), key=lambda x: -x[1]): print(str(k)+":"+"{:.3}".format(v)+" ", end="")print("\n")print("eigenvector centrality:")for k, v in sorted(nx.eigenvector_centrality(G).items(), key=lambda x: -x[1]): print(str(k)+":"+"{:.3}".format(v)+" ", end="")print("\n")print("between centrality:")for k, v in sorted(nx.betweenness_centrality(G).items(), key=lambda x: -x[1]): print(str(k)+":"+"{:.3}".format(v)+" ", end="")print("\n")print("closeness centrality:")for k, v in sorted(nx.closeness_centrality(G).items(), key=lambda x: -x[1]): print(str(k)+":"+"{:.3}".format(v)+" ", end="")print("\n") Another application of network analysis is the Community Detection task. This task purpose to divide a network into groups of nodes that are similar in any specific features. Examples of this task are a task of defining groups of users in SNS who share common interests/opinions, find groups of customers to advertise specific items, recommendation systems in online shopping systems, etc. Many researchers are working on algorithms to effectively solve community detection problems. Some well-known algorithms/methods in this task are Kernighan-Lin algorithms, Spectral Clustering, Label propagation, Modularity Optimization, etc. Besides these applications, network analysis also plays important role in time series analysis, natural language processing, telecommunication network analysis, etc. Recently, the technology of Machine Learning (Deep Learning) is also used in network analysis. In this case, research on Graph Embedding and Graph Neural Networks are interesting topics. For more detail, I recommend the following sites and textbooks. Network Science (http://networksciencebook.com/) Networks: A Very Short Introduction (http://www.veryshortintroductions.com/view/10.1093/actrade/9780199588077.001.0001/actrade-9780199588077) Networks, Crowds, and Markets (https://www.cs.cornell.edu/home/kleinber/networks-book/)
[ { "code": null, "e": 403, "s": 172, "text": "If you are using any social media applications, you may have experienced the friend or follower suggestions functions. Have you ever wondered how these functions work? One common technology used in these cases is Network Analysis." }, { "code": null, "e": 716, "s": 403, "text": "A network refers to a structure representing a group of objects/people and relationships between them. It is also known as a graph in mathematics. A network structure consists of nodes and edges. Here, nodes represent objects we are going to analyze while edges represent the relationships between those objects." }, { "code": null, "e": 960, "s": 716, "text": "For example, if we are studying a social relationship between Facebook users, nodes are target users and edges are relationships such as friendships between users or group memberships. In Twitter, edges can be following/follower relationships." }, { "code": null, "e": 1221, "s": 960, "text": "Network Analysis is useful in many living application tasks. It helps us in deep understanding the structure of a relationship in social networks, a structure or process of change in natural phenomenons, or even the analysis of biological systems of organisms." }, { "code": null, "e": 1319, "s": 1221, "text": "Again, let’s use the network of social media users as an example. Analyzing this network helps in" }, { "code": null, "e": 1374, "s": 1319, "text": "Identifying the most influent person/people in a group" }, { "code": null, "e": 1418, "s": 1374, "text": "Defining characteristics of groups of users" }, { "code": null, "e": 1457, "s": 1418, "text": "Prediction of suitable items for users" }, { "code": null, "e": 1486, "s": 1457, "text": "Identifying CM targets ,etc." }, { "code": null, "e": 1609, "s": 1486, "text": "Other easy-to-understand examples are the Friend Suggestion function in Facebook or Follow Suggestion function in Twitter." }, { "code": null, "e": 1882, "s": 1609, "text": "A crucial application of network analysis is identifying the important node in a network. This task is called Measuring Network Centrality. In social network analysis, it can refer to the task of identifying the most influential member, or the representative of the group." }, { "code": null, "e": 1966, "s": 1882, "text": "For example, which node do you think is the most important one in the above figure?" }, { "code": null, "e": 2136, "s": 1966, "text": "Of course, to define the most important node, we need a specific definition of the Important Node. There are several indicators used to measure the centrality of a node." }, { "code": null, "e": 2203, "s": 2136, "text": "Degree centrality: node with a higher degree has higher centrality" }, { "code": null, "e": 2455, "s": 2203, "text": "Eigenvector centrality: adding to the degree of one node, the centralities of neighbor nodes are considered. As a result, the eigenvector corresponding to the highest eigenvalue of the adjacency matrix represents the centrality of nodes in the network" }, { "code": null, "e": 2604, "s": 2455, "text": "Betweenness centrality: the number of paths between two nodes that go through the i-th node is considered as the i-th node’s betweenness centrality." }, { "code": null, "e": 2881, "s": 2604, "text": "Closeness centrality: the length of the path from the i-th node to other nodes in the network is considered as the i-th node’s closeness centrality. With this definition, for example, this centrality can be applied in the task of defining a suitable evacuation site in a city." }, { "code": null, "e": 3917, "s": 2881, "text": "import networkx as nximport numpy as npimport matplotlib.pyplot as pltG = nx.Graph()G.add_nodes_from([\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"I\",\"J\",\"K\"])G.add_edges_from([(\"A\",\"C\"),(\"B\",\"C\"),(\"C\",\"D\"),(\"D\",\"E\"),(\"D\",\"G\"),(\"A\",\"G\"),(\"F\",\"H\"),(\"G\",\"H\"),(\"H\",\"I\"),(\"I\",\"J\"),(\"I\",\"K\")])nx.draw(G, node_size=400, node_color='red', with_labels=True, font_weight='bold')print(\"degree centrality:\")for k, v in sorted(nx.degree_centrality(G).items(), key=lambda x: -x[1]): print(str(k)+\":\"+\"{:.3}\".format(v)+\" \", end=\"\")print(\"\\n\")print(\"eigenvector centrality:\")for k, v in sorted(nx.eigenvector_centrality(G).items(), key=lambda x: -x[1]): print(str(k)+\":\"+\"{:.3}\".format(v)+\" \", end=\"\")print(\"\\n\")print(\"between centrality:\")for k, v in sorted(nx.betweenness_centrality(G).items(), key=lambda x: -x[1]): print(str(k)+\":\"+\"{:.3}\".format(v)+\" \", end=\"\")print(\"\\n\")print(\"closeness centrality:\")for k, v in sorted(nx.closeness_centrality(G).items(), key=lambda x: -x[1]): print(str(k)+\":\"+\"{:.3}\".format(v)+\" \", end=\"\")print(\"\\n\")" }, { "code": null, "e": 4307, "s": 3917, "text": "Another application of network analysis is the Community Detection task. This task purpose to divide a network into groups of nodes that are similar in any specific features. Examples of this task are a task of defining groups of users in SNS who share common interests/opinions, find groups of customers to advertise specific items, recommendation systems in online shopping systems, etc." }, { "code": null, "e": 4549, "s": 4307, "text": "Many researchers are working on algorithms to effectively solve community detection problems. Some well-known algorithms/methods in this task are Kernighan-Lin algorithms, Spectral Clustering, Label propagation, Modularity Optimization, etc." }, { "code": null, "e": 4902, "s": 4549, "text": "Besides these applications, network analysis also plays important role in time series analysis, natural language processing, telecommunication network analysis, etc. Recently, the technology of Machine Learning (Deep Learning) is also used in network analysis. In this case, research on Graph Embedding and Graph Neural Networks are interesting topics." }, { "code": null, "e": 4966, "s": 4902, "text": "For more detail, I recommend the following sites and textbooks." }, { "code": null, "e": 5015, "s": 4966, "text": "Network Science (http://networksciencebook.com/)" }, { "code": null, "e": 5157, "s": 5015, "text": "Networks: A Very Short Introduction (http://www.veryshortintroductions.com/view/10.1093/actrade/9780199588077.001.0001/actrade-9780199588077)" } ]
list push_back() function in C++ STL
13 Jun, 2022 The list:push_back() function in C++ STL is used to add a new element to an existing list container. It takes the element to be added as a parameter and adds it to the list container.Syntax: list_name.push_back(value) Parameters: This function accepts a single parameter which is mandatory value. This refers to the element needed to be added to the list, list_name.Return Value: The return type of this function is void and it does not returns any value. Below program illustrates the list::push_back() function. CPP // CPP program to illustrate the// list::push_back() function#include <bits/stdc++.h>using namespace std; int main(){ // Initialization of list list<int> demo_list; // initial size of list cout << "Initial Size of the list: " << demo_list.size() << endl; // Adding elements to the list // using push_back function demo_list.push_back(10); demo_list.push_back(20); demo_list.push_back(30); // Size of list after adding // some elements cout << "Size of list after adding three " << "elements: " << demo_list.size(); return 0;} Initial Size of the list: 0 Size of list after adding three elements: 3 Time Complexity: O(1) Auxiliary Space: O(1) simranarora5sos utkarshgupta110092 CPP-Functions STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bitwise Operators in C/C++ Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ unordered_map in C++ STL Inheritance in C++ Substring in C++ C++ Classes and Objects Sorting a vector in C++ Object Oriented Programming in C++ Priority Queue in C++ Standard Template Library (STL)
[ { "code": null, "e": 53, "s": 25, "text": "\n13 Jun, 2022" }, { "code": null, "e": 246, "s": 53, "text": "The list:push_back() function in C++ STL is used to add a new element to an existing list container. It takes the element to be added as a parameter and adds it to the list container.Syntax: " }, { "code": null, "e": 274, "s": 246, "text": "list_name.push_back(value) " }, { "code": null, "e": 572, "s": 274, "text": "Parameters: This function accepts a single parameter which is mandatory value. This refers to the element needed to be added to the list, list_name.Return Value: The return type of this function is void and it does not returns any value. Below program illustrates the list::push_back() function. " }, { "code": null, "e": 576, "s": 572, "text": "CPP" }, { "code": "// CPP program to illustrate the// list::push_back() function#include <bits/stdc++.h>using namespace std; int main(){ // Initialization of list list<int> demo_list; // initial size of list cout << \"Initial Size of the list: \" << demo_list.size() << endl; // Adding elements to the list // using push_back function demo_list.push_back(10); demo_list.push_back(20); demo_list.push_back(30); // Size of list after adding // some elements cout << \"Size of list after adding three \" << \"elements: \" << demo_list.size(); return 0;}", "e": 1108, "s": 576, "text": null }, { "code": null, "e": 1180, "s": 1108, "text": "Initial Size of the list: 0\nSize of list after adding three elements: 3" }, { "code": null, "e": 1204, "s": 1182, "text": "Time Complexity: O(1)" }, { "code": null, "e": 1226, "s": 1204, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 1242, "s": 1226, "text": "simranarora5sos" }, { "code": null, "e": 1261, "s": 1242, "text": "utkarshgupta110092" }, { "code": null, "e": 1275, "s": 1261, "text": "CPP-Functions" }, { "code": null, "e": 1279, "s": 1275, "text": "STL" }, { "code": null, "e": 1283, "s": 1279, "text": "C++" }, { "code": null, "e": 1287, "s": 1283, "text": "STL" }, { "code": null, "e": 1291, "s": 1287, "text": "CPP" }, { "code": null, "e": 1389, "s": 1291, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1416, "s": 1389, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 1459, "s": 1416, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 1493, "s": 1459, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 1518, "s": 1493, "text": "unordered_map in C++ STL" }, { "code": null, "e": 1537, "s": 1518, "text": "Inheritance in C++" }, { "code": null, "e": 1554, "s": 1537, "text": "Substring in C++" }, { "code": null, "e": 1578, "s": 1554, "text": "C++ Classes and Objects" }, { "code": null, "e": 1602, "s": 1578, "text": "Sorting a vector in C++" }, { "code": null, "e": 1637, "s": 1602, "text": "Object Oriented Programming in C++" } ]
Delete all occurrences of a given key in a linked list
03 Jul, 2022 Given a singly linked list, delete all occurrences of a given key in it. For example, consider the following list. Example: Input: 2 -> 2 -> 1 -> 8 -> 2 -> 3 -> 2 -> 7 Key to delete = 2 Output: 1 -> 8 -> 3 -> 7 This is mainly an extension of this post which deletes the first occurrence of a given key. We need to first check for all occurrences at the head node and change the head node appropriately. Then we need to check for all occurrences inside a loop and delete them one by one. Below is the implementation of the above idea: C++ C Java Python3 C# Javascript // C++ program to delete all occurrences// of a given key in linked list#include <bits/stdc++.h>using namespace std; // A linked list nodeclass Node {public: int data; Node* next;}; // Given a reference (pointer) to the head// of a list and an int, inserts a new node// on the front of the listNode* push(Node* head, int new_data){ Node* new_node = new Node(); new_node->data = new_data; new_node->next = head; head = new_node; return head;} // Given a reference (pointer)to the head// of a list and a key, deletes all// occurrence of the given key in// linked listNode* deleteKey(Node* head, int x){ // In Linked List is empty Just return it if (!head) return head; // Until the head data is equal to the key move the head // pointer while (head && head->data == x) head = head->next; Node *curr = head, *prev = nullptr; while (curr) { if (curr->data == x) prev->next = curr->next; else prev = curr; curr = curr->next; } return head;} // This function prints contents of// linked list starting from the// given nodevoid printList(Node* node){ while (node) { cout << node->data << " "; node = node->next; }} // Driver codeint main(){ // Start with the empty list Node* head = NULL; head = push(head, 7); head = push(head, 2); head = push(head, 3); head = push(head, 2); head = push(head, 8); head = push(head, 1); head = push(head, 2); head = push(head, 2); // Key to delete int key = 2; cout << "Created Linked List:\n "; printList(head); // Function call head = deleteKey(head, key); if (!head) cout << "\nNo element present in the Linked list" << endl; else { cout << "\nLinked List after Deletion is:\n"; printList(head); } return 0;} // This code is contributed by Aditya Kumar (aditykumar129) // C Program to delete all occurrences of a given key in// linked list#include <stdio.h>#include <stdlib.h> // A linked list nodetypedef struct Node { int data; struct Node* next;} Node; /* Given a reference (pointer to pointer) to the head of a list and an int, inserts a new node on the front of the list. */void push(struct Node** head_ref, int new_data){ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} /* Given a reference (pointer to pointer) to the head of a list and a key, deletes all occurrence of the given key in linked list */Node* deleteKey(Node* head, int x){ if (!head) return head; // Until the head data is equal to the key move the head // pointer while (head && head->data == x) head = head->next; Node *curr = head, *prev = NULL; while (curr) { if (curr->data == x) prev->next = curr->next; else prev = curr; curr = curr->next; } return head;} // This function prints contents of linked list starting// from the given nodevoid printList(Node* node){ while (node != NULL) { printf(" %d ", node->data); node = node->next; }} // Driver codeint main(){ // Start with the empty list struct Node* head = NULL; push(&head, 7); push(&head, 2); push(&head, 3); push(&head, 2); push(&head, 8); push(&head, 1); push(&head, 2); push(&head, 2); int key = 2; // key to delete puts("Created Linked List: "); printList(head); // Function call head = deleteKey(head, key); if (!head) printf("\nNo element present in the Linked list\n"); else { printf("\nLinked List after Deletion is:\n"); printList(head); } return 0;} // Java Program to delete all occurrences// of a given key in linked listclass LinkedList { static Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Given a key, deletes all occurrence of the given key in linked list */ void deleteKey(int key) { // Store head node Node temp = head, prev = null; // If head node itself holds the key // or multiple occurrences of key while (temp != null && temp.data == key) { head = temp.next; // Changed head temp = head; // Change Temp } // Delete occurrences other than head while (temp != null) { // Search for the key to be deleted, // keep track of the previous node // as we need to change 'prev->next' while (temp != null && temp.data != key) { prev = temp; temp = temp.next; } // If key was not present in linked list if (temp == null) return; // Unlink the node from linked list prev.next = temp.next; // Update Temp for next iteration of outer loop temp = prev.next; } } /* Inserts a new Node at front of the list. */ public void push(int new_data) { Node new_node = new Node(new_data); new_node.next = head; head = new_node; } /* This function prints contents of linked list starting from the given node */ public void printList() { Node tnode = head; while (tnode != null) { System.out.print(tnode.data + " "); tnode = tnode.next; } } // Driver Code public static void main(String[] args) { LinkedList llist = new LinkedList(); llist.push(7); llist.push(2); llist.push(3); llist.push(2); llist.push(8); llist.push(1); llist.push(2); llist.push(2); int key = 2; // key to delete System.out.println("Created Linked list is:"); llist.printList(); // Function call llist.deleteKey(key); System.out.println( "\nLinked List after Deletion is:"); llist.printList(); }} // This code is contributed by Shubham # Python3 program to delete all occurrences# of a given key in linked list # Link list node class Node: def __init__(self, data): self.data = data self.next = None # Given a reference (pointer to pointer)# to the head of a list and an int,# inserts a new node on the front of the list. def push(head_ref, new_data): new_node = Node(0) new_node.data = new_data new_node.next = (head_ref) (head_ref) = new_node return head_ref # Given a reference (pointer to pointer)# to the head of a list and a key,# deletes all occurrence of the given key# in linked list def deleteKey(head_ref, key): # Store head node temp = head_ref prev = None # If head node itself holds the key # or multiple occurrences of key while (temp != None and temp.data == key): head_ref = temp.next # Changed head temp = head_ref # Change Temp # Delete occurrences other than head while (temp != None): # Search for the key to be deleted, # keep track of the previous node # as we need to change 'prev.next' while (temp != None and temp.data != key): prev = temp temp = temp.next # If key was not present in linked list if (temp == None): return head_ref # Unlink the node from linked list prev.next = temp.next # Update Temp for next iteration of outer loop temp = prev.next return head_ref # This function prints contents of linked list# starting from the given node def printList(node): while (node != None): print(node.data, end=" ") node = node.next # Driver Codeif __name__ == '__main__': # Start with the empty list head = None head = push(head, 7) head = push(head, 2) head = push(head, 3) head = push(head, 2) head = push(head, 8) head = push(head, 1) head = push(head, 2) head = push(head, 2) key = 2 # key to delete print("Created Linked List: ") printList(head) # Function call head = deleteKey(head, key) print("\nLinked List after Deletion is: ") printList(head) # This code is contributed by Arnab Kundu // C# Program to delete all occurrences// of a given key in linked listusing System; class GFG { static Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Given a key, deletes all occurrence of the given key in linked list */ void deleteKey(int key) { // Store head node Node temp = head, prev = null; // If head node itself holds the key // or multiple occurrences of key while (temp != null && temp.data == key) { head = temp.next; // Changed head temp = head; // Change Temp } // Delete occurrences other than head while (temp != null) { // Search for the key to be deleted, // keep track of the previous node // as we need to change 'prev->next' while (temp != null && temp.data != key) { prev = temp; temp = temp.next; } // If key was not present in linked list if (temp == null) return; // Unlink the node from linked list prev.next = temp.next; // Update Temp for next iteration of outer loop temp = prev.next; } } /* Inserts a new Node at front of the list. */ public void Push(int new_data) { Node new_node = new Node(new_data); new_node.next = head; head = new_node; } /* This function prints contents of linked list starting from the given node */ public void printList() { Node tnode = head; while (tnode != null) { Console.Write(tnode.data + " "); tnode = tnode.next; } } // Driver Code public static void Main(String[] args) { GFG llist = new GFG(); llist.Push(7); llist.Push(2); llist.Push(3); llist.Push(2); llist.Push(8); llist.Push(1); llist.Push(2); llist.Push(2); int key = 2; // key to delete Console.WriteLine("Created Linked list is:"); llist.printList(); // Function call llist.deleteKey(key); Console.WriteLine( "\nLinked List after Deletion is:"); llist.printList(); }} // This code is contributed by 29AjayKumar <script> // JavaScript program to delete all occurrences// of a given key in linked list // Node for linked list class Node { constructor() { this.data = 0; this.next = null; }} // Given a reference (pointer) to the head// of a list and an int, inserts a new node// on the front of the listfunction push( head, new_data){ var new_node = new Node(); new_node.data = new_data; new_node.next = head; head = new_node; return head;} // Given a reference (pointer)to the head// of a list and a key, deletes all// occurrence of the given key in// linked listfunction deleteKey( head, x){ // Store head node var tmp = head; while (head.data == x) { head = head.next; } while (tmp.next != null) { if (tmp.next.data == x) { tmp.next = tmp.next.next; } else { tmp = tmp.next; } } return head;} // This function prints contents of// linked list starting from the// given nodefunction printList( node){ while (node.next != null) { document.write(node.data + " "); node = node.next; } document.write(node.data);} // Driver Code // Start with the empty listvar head = null;head = push(head, 7);head = push(head, 2);head = push(head, 3);head = push(head, 2);head = push(head, 8);head = push(head, 1);head = push(head, 2);head = push(head, 2); // Key to deletelet key = 2 ; document.write("Created Linked List: " + "</br>");printList(head); // Function callhead = deleteKey(head, key);document.write("</br>"+ "Linked List after Deletion is:" + "</br>"); printList(head); </script> Created Linked List: 2 2 1 8 2 3 2 7 Linked List after Deletion is: 1 8 3 7 Time complexity: O(n)Auxiliary Space: O(1) This article is contributed by Saransh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nobody_cares nidhi_biet 29AjayKumar andrew1234 shreeshtripathi05 SudheerKumar3 shibbbos jana_sayantan adityakumar129 technophpfij hardikkoriintern Amazon Samsung Linked List Amazon Samsung Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. LinkedList in Java Introduction to Data Structures Doubly Linked List | Set 1 (Introduction and Insertion) Merge two sorted linked lists What is Data Structure: Types, Classifications and Applications Linked List vs Array Merge Sort for Linked Lists Implementing a Linked List in Java using Class Queue - Linked List Implementation Function to check if a singly linked list is palindrome
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Jul, 2022" }, { "code": null, "e": 167, "s": 52, "text": "Given a singly linked list, delete all occurrences of a given key in it. For example, consider the following list." }, { "code": null, "e": 176, "s": 167, "text": "Example:" }, { "code": null, "e": 273, "s": 176, "text": "Input: 2 -> 2 -> 1 -> 8 -> 2 -> 3 -> 2 -> 7\n Key to delete = 2\nOutput: 1 -> 8 -> 3 -> 7 " }, { "code": null, "e": 550, "s": 273, "text": "This is mainly an extension of this post which deletes the first occurrence of a given key. We need to first check for all occurrences at the head node and change the head node appropriately. Then we need to check for all occurrences inside a loop and delete them one by one. " }, { "code": null, "e": 597, "s": 550, "text": "Below is the implementation of the above idea:" }, { "code": null, "e": 601, "s": 597, "text": "C++" }, { "code": null, "e": 603, "s": 601, "text": "C" }, { "code": null, "e": 608, "s": 603, "text": "Java" }, { "code": null, "e": 616, "s": 608, "text": "Python3" }, { "code": null, "e": 619, "s": 616, "text": "C#" }, { "code": null, "e": 630, "s": 619, "text": "Javascript" }, { "code": "// C++ program to delete all occurrences// of a given key in linked list#include <bits/stdc++.h>using namespace std; // A linked list nodeclass Node {public: int data; Node* next;}; // Given a reference (pointer) to the head// of a list and an int, inserts a new node// on the front of the listNode* push(Node* head, int new_data){ Node* new_node = new Node(); new_node->data = new_data; new_node->next = head; head = new_node; return head;} // Given a reference (pointer)to the head// of a list and a key, deletes all// occurrence of the given key in// linked listNode* deleteKey(Node* head, int x){ // In Linked List is empty Just return it if (!head) return head; // Until the head data is equal to the key move the head // pointer while (head && head->data == x) head = head->next; Node *curr = head, *prev = nullptr; while (curr) { if (curr->data == x) prev->next = curr->next; else prev = curr; curr = curr->next; } return head;} // This function prints contents of// linked list starting from the// given nodevoid printList(Node* node){ while (node) { cout << node->data << \" \"; node = node->next; }} // Driver codeint main(){ // Start with the empty list Node* head = NULL; head = push(head, 7); head = push(head, 2); head = push(head, 3); head = push(head, 2); head = push(head, 8); head = push(head, 1); head = push(head, 2); head = push(head, 2); // Key to delete int key = 2; cout << \"Created Linked List:\\n \"; printList(head); // Function call head = deleteKey(head, key); if (!head) cout << \"\\nNo element present in the Linked list\" << endl; else { cout << \"\\nLinked List after Deletion is:\\n\"; printList(head); } return 0;} // This code is contributed by Aditya Kumar (aditykumar129)", "e": 2561, "s": 630, "text": null }, { "code": "// C Program to delete all occurrences of a given key in// linked list#include <stdio.h>#include <stdlib.h> // A linked list nodetypedef struct Node { int data; struct Node* next;} Node; /* Given a reference (pointer to pointer) to the head of a list and an int, inserts a new node on the front of the list. */void push(struct Node** head_ref, int new_data){ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} /* Given a reference (pointer to pointer) to the head of a list and a key, deletes all occurrence of the given key in linked list */Node* deleteKey(Node* head, int x){ if (!head) return head; // Until the head data is equal to the key move the head // pointer while (head && head->data == x) head = head->next; Node *curr = head, *prev = NULL; while (curr) { if (curr->data == x) prev->next = curr->next; else prev = curr; curr = curr->next; } return head;} // This function prints contents of linked list starting// from the given nodevoid printList(Node* node){ while (node != NULL) { printf(\" %d \", node->data); node = node->next; }} // Driver codeint main(){ // Start with the empty list struct Node* head = NULL; push(&head, 7); push(&head, 2); push(&head, 3); push(&head, 2); push(&head, 8); push(&head, 1); push(&head, 2); push(&head, 2); int key = 2; // key to delete puts(\"Created Linked List: \"); printList(head); // Function call head = deleteKey(head, key); if (!head) printf(\"\\nNo element present in the Linked list\\n\"); else { printf(\"\\nLinked List after Deletion is:\\n\"); printList(head); } return 0;}", "e": 4411, "s": 2561, "text": null }, { "code": "// Java Program to delete all occurrences// of a given key in linked listclass LinkedList { static Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Given a key, deletes all occurrence of the given key in linked list */ void deleteKey(int key) { // Store head node Node temp = head, prev = null; // If head node itself holds the key // or multiple occurrences of key while (temp != null && temp.data == key) { head = temp.next; // Changed head temp = head; // Change Temp } // Delete occurrences other than head while (temp != null) { // Search for the key to be deleted, // keep track of the previous node // as we need to change 'prev->next' while (temp != null && temp.data != key) { prev = temp; temp = temp.next; } // If key was not present in linked list if (temp == null) return; // Unlink the node from linked list prev.next = temp.next; // Update Temp for next iteration of outer loop temp = prev.next; } } /* Inserts a new Node at front of the list. */ public void push(int new_data) { Node new_node = new Node(new_data); new_node.next = head; head = new_node; } /* This function prints contents of linked list starting from the given node */ public void printList() { Node tnode = head; while (tnode != null) { System.out.print(tnode.data + \" \"); tnode = tnode.next; } } // Driver Code public static void main(String[] args) { LinkedList llist = new LinkedList(); llist.push(7); llist.push(2); llist.push(3); llist.push(2); llist.push(8); llist.push(1); llist.push(2); llist.push(2); int key = 2; // key to delete System.out.println(\"Created Linked list is:\"); llist.printList(); // Function call llist.deleteKey(key); System.out.println( \"\\nLinked List after Deletion is:\"); llist.printList(); }} // This code is contributed by Shubham", "e": 6868, "s": 4411, "text": null }, { "code": "# Python3 program to delete all occurrences# of a given key in linked list # Link list node class Node: def __init__(self, data): self.data = data self.next = None # Given a reference (pointer to pointer)# to the head of a list and an int,# inserts a new node on the front of the list. def push(head_ref, new_data): new_node = Node(0) new_node.data = new_data new_node.next = (head_ref) (head_ref) = new_node return head_ref # Given a reference (pointer to pointer)# to the head of a list and a key,# deletes all occurrence of the given key# in linked list def deleteKey(head_ref, key): # Store head node temp = head_ref prev = None # If head node itself holds the key # or multiple occurrences of key while (temp != None and temp.data == key): head_ref = temp.next # Changed head temp = head_ref # Change Temp # Delete occurrences other than head while (temp != None): # Search for the key to be deleted, # keep track of the previous node # as we need to change 'prev.next' while (temp != None and temp.data != key): prev = temp temp = temp.next # If key was not present in linked list if (temp == None): return head_ref # Unlink the node from linked list prev.next = temp.next # Update Temp for next iteration of outer loop temp = prev.next return head_ref # This function prints contents of linked list# starting from the given node def printList(node): while (node != None): print(node.data, end=\" \") node = node.next # Driver Codeif __name__ == '__main__': # Start with the empty list head = None head = push(head, 7) head = push(head, 2) head = push(head, 3) head = push(head, 2) head = push(head, 8) head = push(head, 1) head = push(head, 2) head = push(head, 2) key = 2 # key to delete print(\"Created Linked List: \") printList(head) # Function call head = deleteKey(head, key) print(\"\\nLinked List after Deletion is: \") printList(head) # This code is contributed by Arnab Kundu", "e": 9054, "s": 6868, "text": null }, { "code": "// C# Program to delete all occurrences// of a given key in linked listusing System; class GFG { static Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Given a key, deletes all occurrence of the given key in linked list */ void deleteKey(int key) { // Store head node Node temp = head, prev = null; // If head node itself holds the key // or multiple occurrences of key while (temp != null && temp.data == key) { head = temp.next; // Changed head temp = head; // Change Temp } // Delete occurrences other than head while (temp != null) { // Search for the key to be deleted, // keep track of the previous node // as we need to change 'prev->next' while (temp != null && temp.data != key) { prev = temp; temp = temp.next; } // If key was not present in linked list if (temp == null) return; // Unlink the node from linked list prev.next = temp.next; // Update Temp for next iteration of outer loop temp = prev.next; } } /* Inserts a new Node at front of the list. */ public void Push(int new_data) { Node new_node = new Node(new_data); new_node.next = head; head = new_node; } /* This function prints contents of linked list starting from the given node */ public void printList() { Node tnode = head; while (tnode != null) { Console.Write(tnode.data + \" \"); tnode = tnode.next; } } // Driver Code public static void Main(String[] args) { GFG llist = new GFG(); llist.Push(7); llist.Push(2); llist.Push(3); llist.Push(2); llist.Push(8); llist.Push(1); llist.Push(2); llist.Push(2); int key = 2; // key to delete Console.WriteLine(\"Created Linked list is:\"); llist.printList(); // Function call llist.deleteKey(key); Console.WriteLine( \"\\nLinked List after Deletion is:\"); llist.printList(); }} // This code is contributed by 29AjayKumar", "e": 11529, "s": 9054, "text": null }, { "code": "<script> // JavaScript program to delete all occurrences// of a given key in linked list // Node for linked list class Node { constructor() { this.data = 0; this.next = null; }} // Given a reference (pointer) to the head// of a list and an int, inserts a new node// on the front of the listfunction push( head, new_data){ var new_node = new Node(); new_node.data = new_data; new_node.next = head; head = new_node; return head;} // Given a reference (pointer)to the head// of a list and a key, deletes all// occurrence of the given key in// linked listfunction deleteKey( head, x){ // Store head node var tmp = head; while (head.data == x) { head = head.next; } while (tmp.next != null) { if (tmp.next.data == x) { tmp.next = tmp.next.next; } else { tmp = tmp.next; } } return head;} // This function prints contents of// linked list starting from the// given nodefunction printList( node){ while (node.next != null) { document.write(node.data + \" \"); node = node.next; } document.write(node.data);} // Driver Code // Start with the empty listvar head = null;head = push(head, 7);head = push(head, 2);head = push(head, 3);head = push(head, 2);head = push(head, 8);head = push(head, 1);head = push(head, 2);head = push(head, 2); // Key to deletelet key = 2 ; document.write(\"Created Linked List: \" + \"</br>\");printList(head); // Function callhead = deleteKey(head, key);document.write(\"</br>\"+ \"Linked List after Deletion is:\" + \"</br>\"); printList(head); </script>", "e": 13212, "s": 11529, "text": null }, { "code": null, "e": 13303, "s": 13212, "text": "Created Linked List: \n 2 2 1 8 2 3 2 7 \nLinked List after Deletion is:\n 1 8 3 7 " }, { "code": null, "e": 13346, "s": 13303, "text": "Time complexity: O(n)Auxiliary Space: O(1)" }, { "code": null, "e": 13512, "s": 13346, "text": "This article is contributed by Saransh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 13525, "s": 13512, "text": "nobody_cares" }, { "code": null, "e": 13536, "s": 13525, "text": "nidhi_biet" }, { "code": null, "e": 13548, "s": 13536, "text": "29AjayKumar" }, { "code": null, "e": 13559, "s": 13548, "text": "andrew1234" }, { "code": null, "e": 13577, "s": 13559, "text": "shreeshtripathi05" }, { "code": null, "e": 13591, "s": 13577, "text": "SudheerKumar3" }, { "code": null, "e": 13600, "s": 13591, "text": "shibbbos" }, { "code": null, "e": 13614, "s": 13600, "text": "jana_sayantan" }, { "code": null, "e": 13629, "s": 13614, "text": "adityakumar129" }, { "code": null, "e": 13642, "s": 13629, "text": "technophpfij" }, { "code": null, "e": 13659, "s": 13642, "text": "hardikkoriintern" }, { "code": null, "e": 13666, "s": 13659, "text": "Amazon" }, { "code": null, "e": 13674, "s": 13666, "text": "Samsung" }, { "code": null, "e": 13686, "s": 13674, "text": "Linked List" }, { "code": null, "e": 13693, "s": 13686, "text": "Amazon" }, { "code": null, "e": 13701, "s": 13693, "text": "Samsung" }, { "code": null, "e": 13713, "s": 13701, "text": "Linked List" }, { "code": null, "e": 13811, "s": 13713, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13830, "s": 13811, "text": "LinkedList in Java" }, { "code": null, "e": 13862, "s": 13830, "text": "Introduction to Data Structures" }, { "code": null, "e": 13918, "s": 13862, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" }, { "code": null, "e": 13948, "s": 13918, "text": "Merge two sorted linked lists" }, { "code": null, "e": 14012, "s": 13948, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 14033, "s": 14012, "text": "Linked List vs Array" }, { "code": null, "e": 14061, "s": 14033, "text": "Merge Sort for Linked Lists" }, { "code": null, "e": 14108, "s": 14061, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 14143, "s": 14108, "text": "Queue - Linked List Implementation" } ]
Eigenspace and Eigenspectrum Values in a Matrix
15 Jan, 2020 Prerequisites: Mathematics | Eigen Values and Eigen Vectors Matrix Multiplication Null Space and Nullity of a Matrix For a given matrix A the set of all eigenvectors of A associated with an eigenvalue spans a subspace, which is called the Eigenspace of A with respect to and is denoted by . The set of all eigenvalues of A is called Eigenspectrum, or just spectrum, of A.If is an eigenvalue of A, then the corresponding eigenspace is the solution space of the homogeneous system of linear equations . Geometrically, the eigenvector corresponding to a non – zero eigenvalue points in a direction that is stretched by the linear mapping. The eigenvalue is the factor by which it is stretched. If the eigenvalue is negative, then the direction of the stretching is flipped. Below are some useful properties of eigenvalues and eigenvectors in addition to the properties which are already listed in the article Mathematics | Eigen Values and Eigen Vectors. A matrix A and its transpose possess the same eigenvalues but not necessarily the same eigenvectors. The eigenspace is the null space of since Note: ker stands for Kernel which is another name for null space. Computing Eigenvalues, Eigenvectors, and Eigenspaces: Consider given 2 X 2 matrix: Step 1: Characteristic polynomial and Eigenvalues. The characteristic polynomial is given by det() After we factorize the characteristic polynomial, we will get which gives eigenvalues as and Step 2: Eigenvectors and Eigenspaces We find the eigenvectors that correspond to these eigenvalues by looking at vectors x such that For we obtain After solving the above homogeneous system of equations, we will obtain a solution space This eigenspace is one dimensional as it possesses a single basis vector. Similarly, we find eigenvector for by solving the homogeneous system of equations This means any vector , where such as is an eigenvector with eigenvalue 2. This means eigenspace is given as The two eigenspaces and in the above example are one dimensional as they are each spanned by a single vector. However, in other cases, we may have multiple identical eigenvectors and the eigenspaces may have more than one dimension. Technical Scripter 2019 Machine Learning Mathematical Technical Scripter Mathematical Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Jan, 2020" }, { "code": null, "e": 43, "s": 28, "text": "Prerequisites:" }, { "code": null, "e": 88, "s": 43, "text": "Mathematics | Eigen Values and Eigen Vectors" }, { "code": null, "e": 110, "s": 88, "text": "Matrix Multiplication" }, { "code": null, "e": 145, "s": 110, "text": "Null Space and Nullity of a Matrix" }, { "code": null, "e": 803, "s": 145, "text": "For a given matrix A the set of all eigenvectors of A associated with an eigenvalue spans a subspace, which is called the Eigenspace of A with respect to and is denoted by . The set of all eigenvalues of A is called Eigenspectrum, or just spectrum, of A.If is an eigenvalue of A, then the corresponding eigenspace is the solution space of the homogeneous system of linear equations . Geometrically, the eigenvector corresponding to a non – zero eigenvalue points in a direction that is stretched by the linear mapping. The eigenvalue is the factor by which it is stretched. If the eigenvalue is negative, then the direction of the stretching is flipped." }, { "code": null, "e": 984, "s": 803, "text": "Below are some useful properties of eigenvalues and eigenvectors in addition to the properties which are already listed in the article Mathematics | Eigen Values and Eigen Vectors." }, { "code": null, "e": 1086, "s": 984, "text": "A matrix A and its transpose possess the same eigenvalues but not necessarily the same eigenvectors." }, { "code": null, "e": 1136, "s": 1086, "text": "The eigenspace is the null space of since " }, { "code": null, "e": 1202, "s": 1136, "text": "Note: ker stands for Kernel which is another name for null space." }, { "code": null, "e": 1256, "s": 1202, "text": "Computing Eigenvalues, Eigenvectors, and Eigenspaces:" }, { "code": null, "e": 2017, "s": 1256, "text": "Consider given 2 X 2 matrix:\n\n\nStep 1: Characteristic polynomial and Eigenvalues.\nThe characteristic polynomial is given by \ndet() \n\n\n\n\n\nAfter we factorize the characteristic polynomial, we will get\n\n\n\nwhich gives eigenvalues as and \n\nStep 2: Eigenvectors and Eigenspaces\nWe find the eigenvectors that correspond to these eigenvalues by looking \nat vectors x such that \n \n\n\nFor we obtain\n\n\n\nAfter solving the above homogeneous system of equations,\nwe will obtain a solution space\n\n\n\nThis eigenspace is one dimensional as it possesses a single basis vector.\nSimilarly, we find eigenvector for by solving\nthe homogeneous system of equations\n\n\n\nThis means any vector , where \nsuch as is an eigenvector with \neigenvalue 2. This means eigenspace is given as \n\n" }, { "code": null, "e": 2252, "s": 2017, "text": "The two eigenspaces and in the above example are one dimensional as they are each spanned by a single vector. However, in other cases, we may have multiple identical eigenvectors and the eigenspaces may have more than one dimension." }, { "code": null, "e": 2276, "s": 2252, "text": "Technical Scripter 2019" }, { "code": null, "e": 2293, "s": 2276, "text": "Machine Learning" }, { "code": null, "e": 2306, "s": 2293, "text": "Mathematical" }, { "code": null, "e": 2325, "s": 2306, "text": "Technical Scripter" }, { "code": null, "e": 2338, "s": 2325, "text": "Mathematical" }, { "code": null, "e": 2355, "s": 2338, "text": "Machine Learning" } ]
K-th Lexicographically smallest binary string with A 0s and B 1s
05 Oct, 2021 Given three positive integers A, B, and K, the task is to find the Kth lexicographically smallest binary string that contains exactly A number of 0s and B number of 1s. Example: Input: A = 2, B = 2, K = 4Output: 1001Explanation: The lexicographic order of the strings is 0011, 0101, 0110, 1001. Input: A = 3, B = 3, K = 7Output: 010110 Approach: The above problem can be solved by using Dynamic Programming. Follow the below steps to solve this problem: Initialize a 2D array dp[][] such that dp[i][j] will denote the total number of binary strings with i number of 0s and j number of 1s. All the dp table values are initially filled with zeroes except dp[0][0] = 1 which denotes an empty string. Now, dp[i][j] can be calculated as the sum of the total number of strings ending with 0(using the dp state as dp[i – 1][j]) and the string ending with 1(using the dp state as dp[i][j – 1]). So, the current dp state is calculated as dp[i][j] = dp[i – 1][j] + dp[i][j – 1]. After filling this dp table, a recursive function can be used to calculate the Kth lexicographically smallest binary string. So, define a function KthString having parameters A, B, K, and dp. Now, in each call of this recursive function:If the value of dp[A][B] is at least K then only ‘0’ can be present at this position in the Kth lexicographically smallest binary string and then recursively call function for the state (A – 1, B).Else ‘1’ is present here and recursively call function for the state (A, B – 1). If the value of dp[A][B] is at least K then only ‘0’ can be present at this position in the Kth lexicographically smallest binary string and then recursively call function for the state (A – 1, B). Else ‘1’ is present here and recursively call function for the state (A, B – 1). Print the answer according to the above observation. 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; // Recursive function to find the Kth// smallest binary stringstring KthString(int A, int B, long long K, vector<vector<int> >& dp){ // Base Case if (A == 0) { // Return string of all 1's // of length B return string(B, '1'); } if (B == 0) { // Return string of all 0's // of length A return string(A, '0'); } if (K <= dp[A - 1][B]) { return "0" + KthString( A - 1, B, K, dp); } else { return "1" + KthString( A, B - 1, K - dp[A - 1][B], dp); }} // Function to find the Kth lexicographically// smallest binary string with exactly// A zeroes and B onesint KthStringUtil(int A, int B, int K){ // Stores the recurring states vector<vector<int> > dp( A + 1, vector<int>(B + 1)); // Calculate the dp values iteratively dp[0][0] = 1; for (int i = 0; i <= A; ++i) { for (int j = 0; j <= B; ++j) { if (i > 0) { // The last character was '0' dp[i][j] += dp[i - 1][j]; } if (j > 0) { // The last character was '1' dp[i][j] += dp[i][j - 1]; } } } // Print the binary string obtained cout << KthString(A, B, K, dp); return 0;} // Driver Codeint main(){ int A = 3, B = 3, K = 7; KthStringUtil(A, B, K); return 0;} // Java program for the above approachimport java.io.*; class GFG { // Recursive function to find the Kth // smallest binary string static String KthString(int A, int B, long K, int[][] dp) { // Base Case if (A == 0) { // Return string of all 1's // of length B String ans = ""; for (int i = 0; i < B; i++) { ans += '1'; } return ans; } if (B == 0) { // Return string of all 0's // of length A String ans = ""; for (int i = 0; i < A; i++) { ans += '0'; } return ans; } if (K <= dp[A - 1][B]) { return "0" + KthString(A - 1, B, K, dp); } else { return "1" + KthString(A, B - 1, K - dp[A - 1][B], dp); } } // Function to find the Kth lexicographically // smallest binary string with exactly // A zeroes and B ones static int KthStringUtil(int A, int B, int K) { // Stores the recurring states int[][] dp = new int[A + 1][B + 1]; // Calculate the dp values iteratively dp[0][0] = 1; for (int i = 0; i <= A; ++i) { for (int j = 0; j <= B; ++j) { if (i > 0) { // The last character was '0' dp[i][j] += dp[i - 1][j]; } if (j > 0) { // The last character was '1' dp[i][j] += dp[i][j - 1]; } } } // Print the binary string obtained System.out.println(KthString(A, B, K, dp)); return 0; } // Driver Code public static void main(String[] args) { int A = 3, B = 3, K = 7; KthStringUtil(A, B, K); }} // This code is contributed by Dharanendra L V. # Python Program to implement# the above approach # Recursive function to find the Kth# smallest binary stringdef KthString(A, B, K, dp): # Base Case if (A == 0): # Return string of all 1's # of length B str = "" for i in range(B): str += '1' return str if (B == 0): # Return string of all 0's # of length A str = "" for i in range(A): str += '0' return str if (K <= dp[A - 1][B]): return "0" + KthString( A - 1, B, K, dp) else: return "1" + KthString( A, B - 1, K - dp[A - 1][B], dp) # Function to find the Kth lexicographically# smallest binary string with exactly# A zeroes and B onesdef KthStringUtil(A, B, K): # Stores the recurring states dp = [0] * (A + 1) for i in range(len(dp)): dp[i] = [0] * (B + 1) # Calculate the dp values iteratively dp[0][0] = 1 for i in range(A + 1): for j in range(B + 1): if (i > 0): # The last character was '0' dp[i][j] += dp[i - 1][j] if (j > 0): # The last character was '1' dp[i][j] += dp[i][j - 1] # Print the binary string obtained print(KthString(A, B, K, dp)) # Driver CodeA = 3B = 3K = 7KthStringUtil(A, B, K) # This code is contributed by gfgking. // C# program for the above approachusing System;class GFG { // Recursive function to find the Kth // smallest binary string static string KthString(int A, int B, long K, int[, ] dp) { // Base Case if (A == 0) { // Return string of all 1's // of length B string ans = ""; for (int i = 0; i < B; i++) { ans += '1'; } return ans; } if (B == 0) { // Return string of all 0's // of length A string ans = ""; for (int i = 0; i < A; i++) { ans += '0'; } return ans; } if (K <= dp[A - 1, B]) { return "0" + KthString(A - 1, B, K, dp); } else { return "1" + KthString(A, B - 1, K - dp[A - 1, B], dp); } } // Function to find the Kth lexicographically // smallest binary string with exactly // A zeroes and B ones static int KthStringUtil(int A, int B, int K) { // Stores the recurring states int[, ] dp = new int[A + 1, B + 1]; // Calculate the dp values iteratively dp[0, 0] = 1; for (int i = 0; i <= A; ++i) { for (int j = 0; j <= B; ++j) { if (i > 0) { // The last character was '0' dp[i, j] += dp[i - 1, j]; } if (j > 0) { // The last character was '1' dp[i, j] += dp[i, j - 1]; } } } // Print the binary string obtained Console.WriteLine(KthString(A, B, K, dp)); return 0; } // Driver Code public static void Main(string[] args) { int A = 3, B = 3, K = 7; KthStringUtil(A, B, K); }} // This code is contributed by ukasp. <script> // JavaScript Program to implement // the above approach // Recursive function to find the Kth // smallest binary string function KthString(A, B, K, dp) { // Base Case if (A == 0) { // Return string of all 1's // of length B let str = ""; for (let i = 0; i < B; i++) { str += '1'; } return str; } if (B == 0) { // Return string of all 0's // of length A let str = ""; for (let i = 0; i < A; i++) { str += '0'; } return str; } if (K <= dp[A - 1][B]) { return "0" + KthString( A - 1, B, K, dp); } else { return "1" + KthString( A, B - 1, K - dp[A - 1][B], dp); } } // Function to find the Kth lexicographically // smallest binary string with exactly // A zeroes and B ones function KthStringUtil(A, B, K) { // Stores the recurring states let dp = new Array(A + 1); for (let i = 0; i < dp.length; i++) { dp[i] = new Array(B + 1).fill(0); } // Calculate the dp values iteratively dp[0][0] = 1; for (let i = 0; i <= A; ++i) { for (let j = 0; j <= B; ++j) { if (i > 0) { // The last character was '0' dp[i][j] += dp[i - 1][j]; } if (j > 0) { // The last character was '1' dp[i][j] += dp[i][j - 1]; } } } // Print the binary string obtained document.write(KthString(A, B, K, dp)); return 0; } // Driver Code let A = 3, B = 3, K = 7; KthStringUtil(A, B, K); // This code is contributed by Potta Lokesh </script> 010110 Time Complexity: O(A*B)Auxiliary Space: O(A*B) dharanendralv23 lokeshpotta20 gfgking ukasp binary-string Blogathon-2021 Blogathon Dynamic Programming Mathematical Recursion Strings Strings Dynamic Programming Mathematical Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Connect Python with SQL Database? How to Import JSON Data into SQL Server? Difference Between Local Storage, Session Storage And Cookies Data Mining - Cluster Analysis Explain the purpose of render() in ReactJS Largest Sum Contiguous Subarray Program for Fibonacci numbers 0-1 Knapsack Problem | DP-10 Longest Common Subsequence | DP-4 Subset Sum Problem | DP-25
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Oct, 2021" }, { "code": null, "e": 197, "s": 28, "text": "Given three positive integers A, B, and K, the task is to find the Kth lexicographically smallest binary string that contains exactly A number of 0s and B number of 1s." }, { "code": null, "e": 206, "s": 197, "text": "Example:" }, { "code": null, "e": 323, "s": 206, "text": "Input: A = 2, B = 2, K = 4Output: 1001Explanation: The lexicographic order of the strings is 0011, 0101, 0110, 1001." }, { "code": null, "e": 364, "s": 323, "text": "Input: A = 3, B = 3, K = 7Output: 010110" }, { "code": null, "e": 482, "s": 364, "text": "Approach: The above problem can be solved by using Dynamic Programming. Follow the below steps to solve this problem:" }, { "code": null, "e": 617, "s": 482, "text": "Initialize a 2D array dp[][] such that dp[i][j] will denote the total number of binary strings with i number of 0s and j number of 1s." }, { "code": null, "e": 725, "s": 617, "text": "All the dp table values are initially filled with zeroes except dp[0][0] = 1 which denotes an empty string." }, { "code": null, "e": 997, "s": 725, "text": "Now, dp[i][j] can be calculated as the sum of the total number of strings ending with 0(using the dp state as dp[i – 1][j]) and the string ending with 1(using the dp state as dp[i][j – 1]). So, the current dp state is calculated as dp[i][j] = dp[i – 1][j] + dp[i][j – 1]." }, { "code": null, "e": 1122, "s": 997, "text": "After filling this dp table, a recursive function can be used to calculate the Kth lexicographically smallest binary string." }, { "code": null, "e": 1189, "s": 1122, "text": "So, define a function KthString having parameters A, B, K, and dp." }, { "code": null, "e": 1512, "s": 1189, "text": "Now, in each call of this recursive function:If the value of dp[A][B] is at least K then only ‘0’ can be present at this position in the Kth lexicographically smallest binary string and then recursively call function for the state (A – 1, B).Else ‘1’ is present here and recursively call function for the state (A, B – 1)." }, { "code": null, "e": 1710, "s": 1512, "text": "If the value of dp[A][B] is at least K then only ‘0’ can be present at this position in the Kth lexicographically smallest binary string and then recursively call function for the state (A – 1, B)." }, { "code": null, "e": 1791, "s": 1710, "text": "Else ‘1’ is present here and recursively call function for the state (A, B – 1)." }, { "code": null, "e": 1844, "s": 1791, "text": "Print the answer according to the above observation." }, { "code": null, "e": 1895, "s": 1844, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1899, "s": 1895, "text": "C++" }, { "code": null, "e": 1904, "s": 1899, "text": "Java" }, { "code": null, "e": 1912, "s": 1904, "text": "Python3" }, { "code": null, "e": 1915, "s": 1912, "text": "C#" }, { "code": null, "e": 1926, "s": 1915, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Recursive function to find the Kth// smallest binary stringstring KthString(int A, int B, long long K, vector<vector<int> >& dp){ // Base Case if (A == 0) { // Return string of all 1's // of length B return string(B, '1'); } if (B == 0) { // Return string of all 0's // of length A return string(A, '0'); } if (K <= dp[A - 1][B]) { return \"0\" + KthString( A - 1, B, K, dp); } else { return \"1\" + KthString( A, B - 1, K - dp[A - 1][B], dp); }} // Function to find the Kth lexicographically// smallest binary string with exactly// A zeroes and B onesint KthStringUtil(int A, int B, int K){ // Stores the recurring states vector<vector<int> > dp( A + 1, vector<int>(B + 1)); // Calculate the dp values iteratively dp[0][0] = 1; for (int i = 0; i <= A; ++i) { for (int j = 0; j <= B; ++j) { if (i > 0) { // The last character was '0' dp[i][j] += dp[i - 1][j]; } if (j > 0) { // The last character was '1' dp[i][j] += dp[i][j - 1]; } } } // Print the binary string obtained cout << KthString(A, B, K, dp); return 0;} // Driver Codeint main(){ int A = 3, B = 3, K = 7; KthStringUtil(A, B, K); return 0;}", "e": 3459, "s": 1926, "text": null }, { "code": "// Java program for the above approachimport java.io.*; class GFG { // Recursive function to find the Kth // smallest binary string static String KthString(int A, int B, long K, int[][] dp) { // Base Case if (A == 0) { // Return string of all 1's // of length B String ans = \"\"; for (int i = 0; i < B; i++) { ans += '1'; } return ans; } if (B == 0) { // Return string of all 0's // of length A String ans = \"\"; for (int i = 0; i < A; i++) { ans += '0'; } return ans; } if (K <= dp[A - 1][B]) { return \"0\" + KthString(A - 1, B, K, dp); } else { return \"1\" + KthString(A, B - 1, K - dp[A - 1][B], dp); } } // Function to find the Kth lexicographically // smallest binary string with exactly // A zeroes and B ones static int KthStringUtil(int A, int B, int K) { // Stores the recurring states int[][] dp = new int[A + 1][B + 1]; // Calculate the dp values iteratively dp[0][0] = 1; for (int i = 0; i <= A; ++i) { for (int j = 0; j <= B; ++j) { if (i > 0) { // The last character was '0' dp[i][j] += dp[i - 1][j]; } if (j > 0) { // The last character was '1' dp[i][j] += dp[i][j - 1]; } } } // Print the binary string obtained System.out.println(KthString(A, B, K, dp)); return 0; } // Driver Code public static void main(String[] args) { int A = 3, B = 3, K = 7; KthStringUtil(A, B, K); }} // This code is contributed by Dharanendra L V.", "e": 5357, "s": 3459, "text": null }, { "code": "# Python Program to implement# the above approach # Recursive function to find the Kth# smallest binary stringdef KthString(A, B, K, dp): # Base Case if (A == 0): # Return string of all 1's # of length B str = \"\" for i in range(B): str += '1' return str if (B == 0): # Return string of all 0's # of length A str = \"\" for i in range(A): str += '0' return str if (K <= dp[A - 1][B]): return \"0\" + KthString( A - 1, B, K, dp) else: return \"1\" + KthString( A, B - 1, K - dp[A - 1][B], dp) # Function to find the Kth lexicographically# smallest binary string with exactly# A zeroes and B onesdef KthStringUtil(A, B, K): # Stores the recurring states dp = [0] * (A + 1) for i in range(len(dp)): dp[i] = [0] * (B + 1) # Calculate the dp values iteratively dp[0][0] = 1 for i in range(A + 1): for j in range(B + 1): if (i > 0): # The last character was '0' dp[i][j] += dp[i - 1][j] if (j > 0): # The last character was '1' dp[i][j] += dp[i][j - 1] # Print the binary string obtained print(KthString(A, B, K, dp)) # Driver CodeA = 3B = 3K = 7KthStringUtil(A, B, K) # This code is contributed by gfgking.", "e": 6755, "s": 5357, "text": null }, { "code": "// C# program for the above approachusing System;class GFG { // Recursive function to find the Kth // smallest binary string static string KthString(int A, int B, long K, int[, ] dp) { // Base Case if (A == 0) { // Return string of all 1's // of length B string ans = \"\"; for (int i = 0; i < B; i++) { ans += '1'; } return ans; } if (B == 0) { // Return string of all 0's // of length A string ans = \"\"; for (int i = 0; i < A; i++) { ans += '0'; } return ans; } if (K <= dp[A - 1, B]) { return \"0\" + KthString(A - 1, B, K, dp); } else { return \"1\" + KthString(A, B - 1, K - dp[A - 1, B], dp); } } // Function to find the Kth lexicographically // smallest binary string with exactly // A zeroes and B ones static int KthStringUtil(int A, int B, int K) { // Stores the recurring states int[, ] dp = new int[A + 1, B + 1]; // Calculate the dp values iteratively dp[0, 0] = 1; for (int i = 0; i <= A; ++i) { for (int j = 0; j <= B; ++j) { if (i > 0) { // The last character was '0' dp[i, j] += dp[i - 1, j]; } if (j > 0) { // The last character was '1' dp[i, j] += dp[i, j - 1]; } } } // Print the binary string obtained Console.WriteLine(KthString(A, B, K, dp)); return 0; } // Driver Code public static void Main(string[] args) { int A = 3, B = 3, K = 7; KthStringUtil(A, B, K); }} // This code is contributed by ukasp.", "e": 8656, "s": 6755, "text": null }, { "code": "<script> // JavaScript Program to implement // the above approach // Recursive function to find the Kth // smallest binary string function KthString(A, B, K, dp) { // Base Case if (A == 0) { // Return string of all 1's // of length B let str = \"\"; for (let i = 0; i < B; i++) { str += '1'; } return str; } if (B == 0) { // Return string of all 0's // of length A let str = \"\"; for (let i = 0; i < A; i++) { str += '0'; } return str; } if (K <= dp[A - 1][B]) { return \"0\" + KthString( A - 1, B, K, dp); } else { return \"1\" + KthString( A, B - 1, K - dp[A - 1][B], dp); } } // Function to find the Kth lexicographically // smallest binary string with exactly // A zeroes and B ones function KthStringUtil(A, B, K) { // Stores the recurring states let dp = new Array(A + 1); for (let i = 0; i < dp.length; i++) { dp[i] = new Array(B + 1).fill(0); } // Calculate the dp values iteratively dp[0][0] = 1; for (let i = 0; i <= A; ++i) { for (let j = 0; j <= B; ++j) { if (i > 0) { // The last character was '0' dp[i][j] += dp[i - 1][j]; } if (j > 0) { // The last character was '1' dp[i][j] += dp[i][j - 1]; } } } // Print the binary string obtained document.write(KthString(A, B, K, dp)); return 0; } // Driver Code let A = 3, B = 3, K = 7; KthStringUtil(A, B, K); // This code is contributed by Potta Lokesh </script>", "e": 10867, "s": 8656, "text": null }, { "code": null, "e": 10874, "s": 10867, "text": "010110" }, { "code": null, "e": 10923, "s": 10876, "text": "Time Complexity: O(A*B)Auxiliary Space: O(A*B)" }, { "code": null, "e": 10939, "s": 10923, "text": "dharanendralv23" }, { "code": null, "e": 10953, "s": 10939, "text": "lokeshpotta20" }, { "code": null, "e": 10961, "s": 10953, "text": "gfgking" }, { "code": null, "e": 10967, "s": 10961, "text": "ukasp" }, { "code": null, "e": 10981, "s": 10967, "text": "binary-string" }, { "code": null, "e": 10996, "s": 10981, "text": "Blogathon-2021" }, { "code": null, "e": 11006, "s": 10996, "text": "Blogathon" }, { "code": null, "e": 11026, "s": 11006, "text": "Dynamic Programming" }, { "code": null, "e": 11039, "s": 11026, "text": "Mathematical" }, { "code": null, "e": 11049, "s": 11039, "text": "Recursion" }, { "code": null, "e": 11057, "s": 11049, "text": "Strings" }, { "code": null, "e": 11065, "s": 11057, "text": "Strings" }, { "code": null, "e": 11085, "s": 11065, "text": "Dynamic Programming" }, { "code": null, "e": 11098, "s": 11085, "text": "Mathematical" }, { "code": null, "e": 11108, "s": 11098, "text": "Recursion" }, { "code": null, "e": 11206, "s": 11108, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11247, "s": 11206, "text": "How to Connect Python with SQL Database?" }, { "code": null, "e": 11288, "s": 11247, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 11350, "s": 11288, "text": "Difference Between Local Storage, Session Storage And Cookies" }, { "code": null, "e": 11381, "s": 11350, "text": "Data Mining - Cluster Analysis" }, { "code": null, "e": 11424, "s": 11381, "text": "Explain the purpose of render() in ReactJS" }, { "code": null, "e": 11456, "s": 11424, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 11486, "s": 11456, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 11515, "s": 11486, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 11549, "s": 11515, "text": "Longest Common Subsequence | DP-4" } ]
Scala – Vector
03 Jul, 2020 Scala is an object-oriented programming language with functional and multi-paradigm support. Scala generates byte code and runs on Java Virtual Machine. Vectors in scala are immutable data structures providing random access for elements and is similar to the list. But, the list has incompetence of random access of elements. Below is an implementation of some of the operations performed on vectors in Scala: 1. Creating a vector: A new vector can be created in Scala using Vector() function and providing the elements in the parenthesis. Example: Scala import scala.collection.immutable._object GFG { def main(args: Array[String]){ // Creating vector var vector1 = Vector(2, 3, 4, 5) // Using println and foreach function // To print elements of vector println(vector1) vector1.foreach((element:Int) => print(element+" ")) }} Vector(2, 3, 4, 5) 2 3 4 5 2. Adding elements to the vector: A single element can be added to the vector in Scala using :+ operator and multiple elements can be added in the vector using ++ operator. Example: Scala import scala.collection.immutable._object GFG { def main(args: Array[String]){ // Creating vector var vector1 = Vector(2, 3, 4, 5) // Adding new elements into new vector var newVector = vector1 :+ 10 print("\nVector Elements after adding: ") newVector.foreach((element:Int) => print(element+" ")) // Creating vector var vector2 = Vector(7, 100) // Merging two vectors var mergeVector = newVector ++ vector2 print("\nVector Elements after merging: ") mergeVector.foreach((element:Int) => print(element+" ")) }} Vector Elements after adding: 2 3 4 5 10 Vector Elements after merging: 2 3 4 5 10 7 100 3. Reversing vector elements: Elements of a vector can be reversed in the order they are inserted using reverse function present in scala.collection.immutable package. Example: Scala import scala.collection.immutable._object GFG { def main(args: Array[String]){ // Creating vector var vector1 = Vector(2, 3, 4, 5) print("\nVector elements before reversing: ") vector1.foreach((element:Int) => print(element+" ")) // Reverse vector elements var rev = vector1.reverse print("\nVector Elements after reversing: ") rev.foreach((element:Int) => print(element+" ")) }} Vector elements before reversing: 2 3 4 5 Vector Elements after reversing: 5 4 3 2 4. Sorting elements of vector: Elements of a vector can be sorted using sorted function in Scala. Example: Scala import scala.collection.immutable._object GFG { def main(args: Array[String]){ // Creating vector var vector1 = Vector(5, 1, 9, 100, 2, 25, 17) print("\nVector elements before sorting:") vector1.foreach((element:Int) => print(element+" ")) // Sorting vector elements var st = vector1.sorted print("\nVector Elements after sorting: ") st.foreach((element:Int) => print(element+" ")) }} Vector elements before sorting:5 1 9 100 2 25 17 Vector Elements after sorting: 1 2 5 9 17 25 100 Scala scala Immutable-collection Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Type Casting in Scala Scala Map Scala Lists Scala String substring() method with example Scala | Arrays Enumeration in Scala How to get the first element of List in Scala Lambda Expression in Scala Scala String replace() method with example How to Install Scala with VSCode?
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Jul, 2020" }, { "code": null, "e": 440, "s": 28, "text": "Scala is an object-oriented programming language with functional and multi-paradigm support. Scala generates byte code and runs on Java Virtual Machine. Vectors in scala are immutable data structures providing random access for elements and is similar to the list. But, the list has incompetence of random access of elements. Below is an implementation of some of the operations performed on vectors in Scala: " }, { "code": null, "e": 571, "s": 440, "text": "1. Creating a vector: A new vector can be created in Scala using Vector() function and providing the elements in the parenthesis. " }, { "code": null, "e": 581, "s": 571, "text": "Example: " }, { "code": null, "e": 587, "s": 581, "text": "Scala" }, { "code": "import scala.collection.immutable._object GFG { def main(args: Array[String]){ // Creating vector var vector1 = Vector(2, 3, 4, 5) // Using println and foreach function // To print elements of vector println(vector1) vector1.foreach((element:Int) => print(element+\" \")) }}", "e": 922, "s": 587, "text": null }, { "code": null, "e": 950, "s": 922, "text": "Vector(2, 3, 4, 5)\n2 3 4 5 " }, { "code": null, "e": 1124, "s": 950, "text": "2. Adding elements to the vector: A single element can be added to the vector in Scala using :+ operator and multiple elements can be added in the vector using ++ operator. " }, { "code": null, "e": 1135, "s": 1124, "text": "Example: " }, { "code": null, "e": 1141, "s": 1135, "text": "Scala" }, { "code": "import scala.collection.immutable._object GFG { def main(args: Array[String]){ // Creating vector var vector1 = Vector(2, 3, 4, 5) // Adding new elements into new vector var newVector = vector1 :+ 10 print(\"\\nVector Elements after adding: \") newVector.foreach((element:Int) => print(element+\" \")) // Creating vector var vector2 = Vector(7, 100) // Merging two vectors var mergeVector = newVector ++ vector2 print(\"\\nVector Elements after merging: \") mergeVector.foreach((element:Int) => print(element+\" \")) }}", "e": 1775, "s": 1141, "text": null }, { "code": null, "e": 1866, "s": 1775, "text": "Vector Elements after adding: 2 3 4 5 10 \nVector Elements after merging: 2 3 4 5 10 7 100 " }, { "code": null, "e": 2035, "s": 1866, "text": "3. Reversing vector elements: Elements of a vector can be reversed in the order they are inserted using reverse function present in scala.collection.immutable package. " }, { "code": null, "e": 2046, "s": 2035, "text": "Example: " }, { "code": null, "e": 2052, "s": 2046, "text": "Scala" }, { "code": "import scala.collection.immutable._object GFG { def main(args: Array[String]){ // Creating vector var vector1 = Vector(2, 3, 4, 5) print(\"\\nVector elements before reversing: \") vector1.foreach((element:Int) => print(element+\" \")) // Reverse vector elements var rev = vector1.reverse print(\"\\nVector Elements after reversing: \") rev.foreach((element:Int) => print(element+\" \")) }}", "e": 2508, "s": 2052, "text": null }, { "code": null, "e": 2593, "s": 2508, "text": "Vector elements before reversing: 2 3 4 5 \nVector Elements after reversing: 5 4 3 2 " }, { "code": null, "e": 2692, "s": 2593, "text": "4. Sorting elements of vector: Elements of a vector can be sorted using sorted function in Scala. " }, { "code": null, "e": 2703, "s": 2692, "text": "Example: " }, { "code": null, "e": 2709, "s": 2703, "text": "Scala" }, { "code": "import scala.collection.immutable._object GFG { def main(args: Array[String]){ // Creating vector var vector1 = Vector(5, 1, 9, 100, 2, 25, 17) print(\"\\nVector elements before sorting:\") vector1.foreach((element:Int) => print(element+\" \")) // Sorting vector elements var st = vector1.sorted print(\"\\nVector Elements after sorting: \") st.foreach((element:Int) => print(element+\" \")) }}", "e": 3178, "s": 2709, "text": null }, { "code": null, "e": 3278, "s": 3178, "text": "Vector elements before sorting:5 1 9 100 2 25 17 \nVector Elements after sorting: 1 2 5 9 17 25 100 " }, { "code": null, "e": 3284, "s": 3278, "text": "Scala" }, { "code": null, "e": 3311, "s": 3284, "text": "scala Immutable-collection" }, { "code": null, "e": 3317, "s": 3311, "text": "Scala" }, { "code": null, "e": 3415, "s": 3317, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3437, "s": 3415, "text": "Type Casting in Scala" }, { "code": null, "e": 3447, "s": 3437, "text": "Scala Map" }, { "code": null, "e": 3459, "s": 3447, "text": "Scala Lists" }, { "code": null, "e": 3504, "s": 3459, "text": "Scala String substring() method with example" }, { "code": null, "e": 3519, "s": 3504, "text": "Scala | Arrays" }, { "code": null, "e": 3540, "s": 3519, "text": "Enumeration in Scala" }, { "code": null, "e": 3586, "s": 3540, "text": "How to get the first element of List in Scala" }, { "code": null, "e": 3613, "s": 3586, "text": "Lambda Expression in Scala" }, { "code": null, "e": 3656, "s": 3613, "text": "Scala String replace() method with example" } ]
How can we call the invokeLater() method in Java?
An invokeLater() method is a static method of the SwingUtilities class and it can be used to perform a task asynchronously in the AWT Event dispatcher thread. The SwingUtilities.invokeLater() method works like SwingUtilities.invokeAndWait() except that it puts the request on the event queue and returns immediately. An invokeLater() method does not wait for the block of code inside the Runnable referred by a target to execute. public static void invokeLater(Runnable target) import java.awt.*; import java.awt.event.*; import javax.swing.*; public class InvokeLaterTest extends Object { private static void print(String msg) { String name = Thread.currentThread().getName(); System.out.println(name + ": " + msg); } public static void main(String[] args) { final JLabel label= new JLabel("Initial text"); JPanel panel = new JPanel(new FlowLayout()); panel.add(label); JFrame f = new JFrame("InvokeLater Test"); f.setContentPane(panel); f.setSize(400, 300); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setLocationRelativeTo(null); f.setVisible(true); try { print("sleeping for 5 seconds"); Thread.sleep(5000); } catch(InterruptedException ie) { print("interrupted while sleeping"); } print("creating the code block for an event thread"); Runnable setTextRun = new Runnable() { public void run() { try { Thread.sleep(100); print("about to do setText()"); label.setText("New text"); } catch(Exception e) { e.printStackTrace(); } } }; print("about to call invokeLater()"); SwingUtilities.invokeLater(setTextRun); print("back from invokeLater()"); } } main: sleeping for 5 seconds main: creating the code block for an event thread main: about to call invokeLater() main: back from invokeLater() AWT-EventQueue-0: about to do setText()
[ { "code": null, "e": 1617, "s": 1187, "text": "An invokeLater() method is a static method of the SwingUtilities class and it can be used to perform a task asynchronously in the AWT Event dispatcher thread. The SwingUtilities.invokeLater() method works like SwingUtilities.invokeAndWait() except that it puts the request on the event queue and returns immediately. An invokeLater() method does not wait for the block of code inside the Runnable referred by a target to execute." }, { "code": null, "e": 1665, "s": 1617, "text": "public static void invokeLater(Runnable target)" }, { "code": null, "e": 3018, "s": 1665, "text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\npublic class InvokeLaterTest extends Object {\n private static void print(String msg) {\n String name = Thread.currentThread().getName();\n System.out.println(name + \": \" + msg);\n }\n public static void main(String[] args) {\n final JLabel label= new JLabel(\"Initial text\");\n JPanel panel = new JPanel(new FlowLayout());\n panel.add(label);\n JFrame f = new JFrame(\"InvokeLater Test\");\n f.setContentPane(panel);\n f.setSize(400, 300);\n f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n f.setLocationRelativeTo(null);\n f.setVisible(true);\n try {\n print(\"sleeping for 5 seconds\");\n Thread.sleep(5000);\n } catch(InterruptedException ie) {\n print(\"interrupted while sleeping\");\n }\n print(\"creating the code block for an event thread\");\n Runnable setTextRun = new Runnable() {\n public void run() {\n try {\n Thread.sleep(100);\n print(\"about to do setText()\");\n label.setText(\"New text\");\n } catch(Exception e) {\n e.printStackTrace();\n }\n }\n };\n print(\"about to call invokeLater()\");\n SwingUtilities.invokeLater(setTextRun);\n print(\"back from invokeLater()\");\n }\n}" }, { "code": null, "e": 3204, "s": 3018, "text": "main: sleeping for 5 seconds\nmain: creating the code block for an event thread \nmain: about to call invokeLater() \nmain: back from invokeLater() \nAWT-EventQueue-0: about to do setText()" } ]
How to Use COIL Image Loader Library in Android Apps?
23 Dec, 2020 COIL is an acronym for Coroutine Image Loader. COIL is one of the famous image loading libraries from URLs in Android. It is a modern library for loading images from the server. This library is used to load images from servers, assets folder as well as from the drawable folder in Android project. The important feature of this library is that it is fast, lightweight, and easy to use. In this article, we will see How to Use this Image Loader Library in Android Apps. COIL Image loading library is provided by Kotlin Coroutines which is used for loading images in Android. This library is specially designed for loading images in Kotlin. It is modern, easy to use, lightweight, and fast for loading images from the server. This is the new library and provides new optimization for loading images from the server very efficiently. As Kotlin is now been officially announced as the preferred language for Android development, that’s why for loading images we should prefer using COIL for loading images in Android. Google has officially announced Kotlin as a preferred language for Android development and COIL is the library that is better optimized with Kotlin. So the optimization of this library with Kotlin makes it easier to load images from the server. COIL loads images very faster with the number of optimizations which includes memory, disk caching, reusing of bitmaps, and down spacing the image in memory which makes it faster in comparison with other image loading libraries. COIL adds ~2000 methods to your APK which are very less in number in comparison with Picasso, Glide, and UIL. This makes this library very lightweight and easy to use. COIL is the first image loading library which is completely introduced in Kotlin and it uses some modern libraries of Android such as Okio, OkHttp, and AndroidX lifecycles. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language. Step 2: Add dependency of Coil Image Loading library in build.gradle file Navigate to gradle scripts and then to build.gradle(Module) level. Add below line in build.gradle file in the dependencies section. implementation(“io.coil-kt:coil:1.1.0”) After adding dependency click on the “sync now” option on the top right corner to sync the project. Step 3: Adding internet permission in the AndroidManifest.xml file Navigate to the app > Manifest to open the Manifest file. In the manifest file, we are adding internet permission to load images from the internet. Add the following lines in your manifest file. <!–Permission for Internet–> <uses-permission android:name=”android.permission.INTERNET” /> <uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE” /> Step 4: Create a new ImageView in your activity_main.xml. Navigate to the app > res > layout to open the activity_main.xml file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout 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"> <!--ImageView is created below--> <ImageView android:id="@+id/imageView" android:layout_width="200dp" android:layout_height="200dp" android:layout_centerInParent="true" android:contentDescription="@string/app_name" /> </RelativeLayout> Step 5: Working with the MainActivity.kt file Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Kotlin import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.ImageViewimport coil.load class MainActivity : AppCompatActivity() { // image url that we will load in our image view. val imgurl = "https://www.geeksforgeeks.org/wp-content/uploads/gfg_200X200-1.png" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // val created for our imageview and // initializing it with image id. val img = findViewById<ImageView>(R.id.imageView) // below line is for loading // image url inside imageview. img.load(imgurl) { // placeholder image is the image used // when our image url fails to load. placeholder(R.drawable.ic_launcher_background) } }} android Picked Technical Scripter 2020 Android Kotlin Technical Scripter Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Android SDK and it's Components Flutter - Custom Bottom Navigation Bar How to Add Views Dynamically and Store Data in Arraylist in Android? Retrofit with Kotlin Coroutine in Android How to Post Data to API using Retrofit in Android? Android UI Layouts Kotlin Array How to Add Views Dynamically and Store Data in Arraylist in Android? Retrofit with Kotlin Coroutine in Android
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Dec, 2020" }, { "code": null, "e": 497, "s": 28, "text": "COIL is an acronym for Coroutine Image Loader. COIL is one of the famous image loading libraries from URLs in Android. It is a modern library for loading images from the server. This library is used to load images from servers, assets folder as well as from the drawable folder in Android project. The important feature of this library is that it is fast, lightweight, and easy to use. In this article, we will see How to Use this Image Loader Library in Android Apps." }, { "code": null, "e": 1043, "s": 497, "text": "COIL Image loading library is provided by Kotlin Coroutines which is used for loading images in Android. This library is specially designed for loading images in Kotlin. It is modern, easy to use, lightweight, and fast for loading images from the server. This is the new library and provides new optimization for loading images from the server very efficiently. As Kotlin is now been officially announced as the preferred language for Android development, that’s why for loading images we should prefer using COIL for loading images in Android. " }, { "code": null, "e": 1288, "s": 1043, "text": "Google has officially announced Kotlin as a preferred language for Android development and COIL is the library that is better optimized with Kotlin. So the optimization of this library with Kotlin makes it easier to load images from the server." }, { "code": null, "e": 1517, "s": 1288, "text": "COIL loads images very faster with the number of optimizations which includes memory, disk caching, reusing of bitmaps, and down spacing the image in memory which makes it faster in comparison with other image loading libraries." }, { "code": null, "e": 1685, "s": 1517, "text": "COIL adds ~2000 methods to your APK which are very less in number in comparison with Picasso, Glide, and UIL. This makes this library very lightweight and easy to use." }, { "code": null, "e": 1858, "s": 1685, "text": "COIL is the first image loading library which is completely introduced in Kotlin and it uses some modern libraries of Android such as Okio, OkHttp, and AndroidX lifecycles." }, { "code": null, "e": 1887, "s": 1858, "text": "Step 1: Create a New Project" }, { "code": null, "e": 2051, "s": 1887, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language." }, { "code": null, "e": 2125, "s": 2051, "text": "Step 2: Add dependency of Coil Image Loading library in build.gradle file" }, { "code": null, "e": 2257, "s": 2125, "text": "Navigate to gradle scripts and then to build.gradle(Module) level. Add below line in build.gradle file in the dependencies section." }, { "code": null, "e": 2297, "s": 2257, "text": "implementation(“io.coil-kt:coil:1.1.0”)" }, { "code": null, "e": 2398, "s": 2297, "text": "After adding dependency click on the “sync now” option on the top right corner to sync the project. " }, { "code": null, "e": 2465, "s": 2398, "text": "Step 3: Adding internet permission in the AndroidManifest.xml file" }, { "code": null, "e": 2660, "s": 2465, "text": "Navigate to the app > Manifest to open the Manifest file. In the manifest file, we are adding internet permission to load images from the internet. Add the following lines in your manifest file." }, { "code": null, "e": 2689, "s": 2660, "text": "<!–Permission for Internet–>" }, { "code": null, "e": 2752, "s": 2689, "text": "<uses-permission android:name=”android.permission.INTERNET” />" }, { "code": null, "e": 2827, "s": 2752, "text": "<uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE” />" }, { "code": null, "e": 2885, "s": 2827, "text": "Step 4: Create a new ImageView in your activity_main.xml." }, { "code": null, "e": 3007, "s": 2885, "text": "Navigate to the app > res > layout to open the activity_main.xml file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 3011, "s": 3007, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout 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\"> <!--ImageView is created below--> <ImageView android:id=\"@+id/imageView\" android:layout_width=\"200dp\" android:layout_height=\"200dp\" android:layout_centerInParent=\"true\" android:contentDescription=\"@string/app_name\" /> </RelativeLayout>", "e": 3626, "s": 3011, "text": null }, { "code": null, "e": 3672, "s": 3626, "text": "Step 5: Working with the MainActivity.kt file" }, { "code": null, "e": 3858, "s": 3672, "text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 3865, "s": 3858, "text": "Kotlin" }, { "code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.ImageViewimport coil.load class MainActivity : AppCompatActivity() { // image url that we will load in our image view. val imgurl = \"https://www.geeksforgeeks.org/wp-content/uploads/gfg_200X200-1.png\" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // val created for our imageview and // initializing it with image id. val img = findViewById<ImageView>(R.id.imageView) // below line is for loading // image url inside imageview. img.load(imgurl) { // placeholder image is the image used // when our image url fails to load. placeholder(R.drawable.ic_launcher_background) } }}", "e": 4763, "s": 3865, "text": null }, { "code": null, "e": 4771, "s": 4763, "text": "android" }, { "code": null, "e": 4778, "s": 4771, "text": "Picked" }, { "code": null, "e": 4802, "s": 4778, "text": "Technical Scripter 2020" }, { "code": null, "e": 4810, "s": 4802, "text": "Android" }, { "code": null, "e": 4817, "s": 4810, "text": "Kotlin" }, { "code": null, "e": 4836, "s": 4817, "text": "Technical Scripter" }, { "code": null, "e": 4844, "s": 4836, "text": "Android" }, { "code": null, "e": 4942, "s": 4844, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4974, "s": 4942, "text": "Android SDK and it's Components" }, { "code": null, "e": 5013, "s": 4974, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 5082, "s": 5013, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 5124, "s": 5082, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 5175, "s": 5124, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 5194, "s": 5175, "text": "Android UI Layouts" }, { "code": null, "e": 5207, "s": 5194, "text": "Kotlin Array" }, { "code": null, "e": 5276, "s": 5207, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" } ]
Fromordinal() Function Of Datetime.date Class In Python
29 Aug, 2021 The fromordinal() function is used to return the Gregorian date corresponding to a specified Gregorian ordinal. This is the opposite of the toordinal() function that is used to convert a Gregorian date to a Gregorian ordinal. When a negative ordinal value or an ordinal beyond the value returned by the date.max.toordinal() is passed to the parameter of the toordinal() function, this function raises a ValueError. Syntax: @classmethod fromordinal(ordinal) Parameters: This function accepts a parameter which is illustrated below: ordinal: This is the specified Gregorian ordinal for which the Gregorian date is going to be found. Return values: This function returns the Gregorian date corresponding to a specified Gregorian ordinal. Example 1: From the specific day of the Gregorian calendar. Python3 # Python3 code for getting# the Gregorian date corresponding# to a given Gregorian ordinal. # Importing datetime moduleimport datetime # Specifying a Gregorian ordinalordinal = 123456; # Calling the fromordinal() function# over the specified Gregorian ordinaldate = datetime.date.fromordinal(ordinal); # Printing the Gregorian dateprint("The Gregorian date for the Gregorian\ordinal %d is: %s"%(ordinal, date)); Output: The Gregorian date for the Gregorian ordinal 123456 is: 0339-01-05 Example 2: From first day of the Gregorian calendar. Python3 # Python3 code for getting# the Gregorian date corresponding# to a given Gregorian ordinal. # Importing datetime moduleimport datetime # Calling the fromordinal() function over# the 1st day of Gregorian calendar as its parameterdate = datetime.date.fromordinal(1); # Printing the Gregorian date for the 1st date# of Gregorian calendarprint("Gregorian Date for the 1st day \of Gregorian calendar: %s"%date); Output: Gregorian Date for the 1st day of Gregorian calendar: 0001-01-01 simmytarika5 Picked Python-datetime Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Aug, 2021" }, { "code": null, "e": 443, "s": 28, "text": "The fromordinal() function is used to return the Gregorian date corresponding to a specified Gregorian ordinal. This is the opposite of the toordinal() function that is used to convert a Gregorian date to a Gregorian ordinal. When a negative ordinal value or an ordinal beyond the value returned by the date.max.toordinal() is passed to the parameter of the toordinal() function, this function raises a ValueError." }, { "code": null, "e": 486, "s": 443, "text": "Syntax: @classmethod fromordinal(ordinal)" }, { "code": null, "e": 560, "s": 486, "text": "Parameters: This function accepts a parameter which is illustrated below:" }, { "code": null, "e": 660, "s": 560, "text": "ordinal: This is the specified Gregorian ordinal for which the Gregorian date is going to be found." }, { "code": null, "e": 764, "s": 660, "text": "Return values: This function returns the Gregorian date corresponding to a specified Gregorian ordinal." }, { "code": null, "e": 825, "s": 764, "text": "Example 1: From the specific day of the Gregorian calendar." }, { "code": null, "e": 833, "s": 825, "text": "Python3" }, { "code": "# Python3 code for getting# the Gregorian date corresponding# to a given Gregorian ordinal. # Importing datetime moduleimport datetime # Specifying a Gregorian ordinalordinal = 123456; # Calling the fromordinal() function# over the specified Gregorian ordinaldate = datetime.date.fromordinal(ordinal); # Printing the Gregorian dateprint(\"The Gregorian date for the Gregorian\\ordinal %d is: %s\"%(ordinal, date));", "e": 1245, "s": 833, "text": null }, { "code": null, "e": 1253, "s": 1245, "text": "Output:" }, { "code": null, "e": 1320, "s": 1253, "text": "The Gregorian date for the Gregorian ordinal 123456 is: 0339-01-05" }, { "code": null, "e": 1373, "s": 1320, "text": "Example 2: From first day of the Gregorian calendar." }, { "code": null, "e": 1381, "s": 1373, "text": "Python3" }, { "code": "# Python3 code for getting# the Gregorian date corresponding# to a given Gregorian ordinal. # Importing datetime moduleimport datetime # Calling the fromordinal() function over# the 1st day of Gregorian calendar as its parameterdate = datetime.date.fromordinal(1); # Printing the Gregorian date for the 1st date# of Gregorian calendarprint(\"Gregorian Date for the 1st day \\of Gregorian calendar: %s\"%date);", "e": 1788, "s": 1381, "text": null }, { "code": null, "e": 1796, "s": 1788, "text": "Output:" }, { "code": null, "e": 1861, "s": 1796, "text": "Gregorian Date for the 1st day of Gregorian calendar: 0001-01-01" }, { "code": null, "e": 1874, "s": 1861, "text": "simmytarika5" }, { "code": null, "e": 1881, "s": 1874, "text": "Picked" }, { "code": null, "e": 1897, "s": 1881, "text": "Python-datetime" }, { "code": null, "e": 1904, "s": 1897, "text": "Python" }, { "code": null, "e": 2002, "s": 1904, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2034, "s": 2002, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2061, "s": 2034, "text": "Python Classes and Objects" }, { "code": null, "e": 2082, "s": 2061, "text": "Python OOPs Concepts" }, { "code": null, "e": 2105, "s": 2082, "text": "Introduction To PYTHON" }, { "code": null, "e": 2136, "s": 2105, "text": "Python | os.path.join() method" }, { "code": null, "e": 2192, "s": 2136, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2234, "s": 2192, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2276, "s": 2234, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2315, "s": 2276, "text": "Python | Get unique values from a list" } ]
How to send HTTP response code in PHP?
26 Mar, 2019 HTTP Response code: There are three approaches to accomplish the above requirement, depending on the version. For PHP versions 4.0: In order to send the HTTP response code, we need to assemble the response code. To achieve this, use header() function. The header() function contains a special use-case which can detect a HTTP response line and replace that with a custom one. header("HTTP/1.1 200 OK"); Example: $sapitype = php_sapi_name();if (substr($sapitype, 0, 3) == 'cgi') header("Status: 404 Not Found");else header("HTTP/1.1 404 Not Found"); For PHP versions 4.3: There are obviously a few problems when using first method. The biggest one is that it is partly parsed by PHP and is poorly documented. Since the version 4.3, the header() function has an additional 3rd argument through which we can set the response code. but to use the first argument should be a non-empty string. header(':', true, 400); header(‘X_PHP_Response_Code: 400', true, 400); The second one is recommended. The header field name in this variant is not standardized and can be modified. For PHP versions 5.4: This versions uses http_response_code() function to makes things easier. http_response_code(400); Example: This example uses http_response_code() function to send HTTP response code. <?php error_reporting(E_ERROR | E_PARSE); // Initialize a variable into domain name$domain1 = 'https://contribute.geeksforgeeks.org'; // Function to get HTTP response code function get_http_response_code($domain1) { $headers = get_headers($domain1); return substr($headers[0], 9, 3);} // Function call $get_http_response_code = get_http_response_code($domain1); // Display the HTTP response codeecho $get_http_response_code; // Check HTTP response code is 200 or notif ( $get_http_response_code == 200 ) echo "<br>HTTP request successfully";else echo "<br>HTTP request not successfully!"; ?> Output: 200 HTTP request successfully Picked PHP PHP Programs Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Mar, 2019" }, { "code": null, "e": 138, "s": 28, "text": "HTTP Response code: There are three approaches to accomplish the above requirement, depending on the version." }, { "code": null, "e": 404, "s": 138, "text": "For PHP versions 4.0: In order to send the HTTP response code, we need to assemble the response code. To achieve this, use header() function. The header() function contains a special use-case which can detect a HTTP response line and replace that with a custom one." }, { "code": null, "e": 431, "s": 404, "text": "header(\"HTTP/1.1 200 OK\");" }, { "code": null, "e": 440, "s": 431, "text": "Example:" }, { "code": "$sapitype = php_sapi_name();if (substr($sapitype, 0, 3) == 'cgi') header(\"Status: 404 Not Found\");else header(\"HTTP/1.1 404 Not Found\");", "e": 583, "s": 440, "text": null }, { "code": null, "e": 922, "s": 583, "text": "For PHP versions 4.3: There are obviously a few problems when using first method. The biggest one is that it is partly parsed by PHP and is poorly documented. Since the version 4.3, the header() function has an additional 3rd argument through which we can set the response code. but to use the first argument should be a non-empty string." }, { "code": null, "e": 994, "s": 922, "text": "header(':', true, 400);\nheader(‘X_PHP_Response_Code: 400', true, 400);\n" }, { "code": null, "e": 1104, "s": 994, "text": "The second one is recommended. The header field name in this variant is not standardized and can be modified." }, { "code": null, "e": 1199, "s": 1104, "text": "For PHP versions 5.4: This versions uses http_response_code() function to makes things easier." }, { "code": null, "e": 1224, "s": 1199, "text": "http_response_code(400);" }, { "code": null, "e": 1309, "s": 1224, "text": "Example: This example uses http_response_code() function to send HTTP response code." }, { "code": "<?php error_reporting(E_ERROR | E_PARSE); // Initialize a variable into domain name$domain1 = 'https://contribute.geeksforgeeks.org'; // Function to get HTTP response code function get_http_response_code($domain1) { $headers = get_headers($domain1); return substr($headers[0], 9, 3);} // Function call $get_http_response_code = get_http_response_code($domain1); // Display the HTTP response codeecho $get_http_response_code; // Check HTTP response code is 200 or notif ( $get_http_response_code == 200 ) echo \"<br>HTTP request successfully\";else echo \"<br>HTTP request not successfully!\"; ?>", "e": 1924, "s": 1309, "text": null }, { "code": null, "e": 1932, "s": 1924, "text": "Output:" }, { "code": null, "e": 1962, "s": 1932, "text": "200\nHTTP request successfully" }, { "code": null, "e": 1969, "s": 1962, "text": "Picked" }, { "code": null, "e": 1973, "s": 1969, "text": "PHP" }, { "code": null, "e": 1986, "s": 1973, "text": "PHP Programs" }, { "code": null, "e": 2003, "s": 1986, "text": "Web Technologies" }, { "code": null, "e": 2007, "s": 2003, "text": "PHP" } ]
How to get element at specific position in List in C++
01 Dec, 2020 The list doesn’t have random access operator [] to access elements by indices, because std::list internally store elements in a doubly-linked list. So, to access an element at any Kth location, the idea is to iterate one by one from beginning to Kth element. Instead of iterating for K times. For this, an STL std::advance() function is used to find it in linear time. Syntax: advance(InputIterator& it, Distance N) Parameters: This function accepts two parameters i.e., iterator that is to be traversed through the list and the position to where it has to be moved. The position can be negative for random access and bidirectional iterators. Return Type: This function has no return type. Below is the C++ implementation of the above approach: C++ // C++ program to access Kth element// of the list using advanced#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Create list with initial value 100 list<int> li(5, 100); // Insert 20 and 30 to the list li.push_back(20); li.push_back(30); // Elements of list are // 100, 100, 100, 100, 100, 20, 30 // Initialize iterator to list list<int>::iterator it = li.begin(); // Move the iterator by 5 elements advance(it, 5); // Print the element at the it cout << *it; return 0;} 20 cpp-list cpp-list-functions STL C++ C++ Programs STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) std::string class in C++ Header files in C/C++ and its uses Sorting a Map by value in C++ STL Program to print ASCII Value of a character How to return multiple values from a function in C or C++? Shallow Copy and Deep Copy in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Dec, 2020" }, { "code": null, "e": 421, "s": 52, "text": "The list doesn’t have random access operator [] to access elements by indices, because std::list internally store elements in a doubly-linked list. So, to access an element at any Kth location, the idea is to iterate one by one from beginning to Kth element. Instead of iterating for K times. For this, an STL std::advance() function is used to find it in linear time." }, { "code": null, "e": 429, "s": 421, "text": "Syntax:" }, { "code": null, "e": 468, "s": 429, "text": "advance(InputIterator& it, Distance N)" }, { "code": null, "e": 695, "s": 468, "text": "Parameters: This function accepts two parameters i.e., iterator that is to be traversed through the list and the position to where it has to be moved. The position can be negative for random access and bidirectional iterators." }, { "code": null, "e": 742, "s": 695, "text": "Return Type: This function has no return type." }, { "code": null, "e": 797, "s": 742, "text": "Below is the C++ implementation of the above approach:" }, { "code": null, "e": 801, "s": 797, "text": "C++" }, { "code": "// C++ program to access Kth element// of the list using advanced#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Create list with initial value 100 list<int> li(5, 100); // Insert 20 and 30 to the list li.push_back(20); li.push_back(30); // Elements of list are // 100, 100, 100, 100, 100, 20, 30 // Initialize iterator to list list<int>::iterator it = li.begin(); // Move the iterator by 5 elements advance(it, 5); // Print the element at the it cout << *it; return 0;}", "e": 1354, "s": 801, "text": null }, { "code": null, "e": 1358, "s": 1354, "text": "20\n" }, { "code": null, "e": 1367, "s": 1358, "text": "cpp-list" }, { "code": null, "e": 1386, "s": 1367, "text": "cpp-list-functions" }, { "code": null, "e": 1390, "s": 1386, "text": "STL" }, { "code": null, "e": 1394, "s": 1390, "text": "C++" }, { "code": null, "e": 1407, "s": 1394, "text": "C++ Programs" }, { "code": null, "e": 1411, "s": 1407, "text": "STL" }, { "code": null, "e": 1415, "s": 1411, "text": "CPP" }, { "code": null, "e": 1513, "s": 1415, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1537, "s": 1513, "text": "Sorting a vector in C++" }, { "code": null, "e": 1557, "s": 1537, "text": "Polymorphism in C++" }, { "code": null, "e": 1590, "s": 1557, "text": "Friend class and function in C++" }, { "code": null, "e": 1634, "s": 1590, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 1659, "s": 1634, "text": "std::string class in C++" }, { "code": null, "e": 1694, "s": 1659, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 1728, "s": 1694, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 1772, "s": 1728, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 1831, "s": 1772, "text": "How to return multiple values from a function in C or C++?" } ]
Difference between TreeMap and TreeSet in Java
28 Jan, 2021 TreeSet is mainly an implementation of SortedSet in java where duplication is not allowed and objects are stored in sorted and ascending order. Some important features of the TreeSet are: In TreeSet duplicate values are not allowed because it implements the SortedSet interface. Objects in a TreeSet are stored in ascending order. In TreeSet the insertion order of elements does not maintain. TreeMap is an implementation of Map Interface. TreeMap is also an implementation of NavigableMap along with AbstractMap class. Some important features of the TreeMap are: In TreeMap null keys(like Map) are not allowed and thus a NullPointerException is thrown (Multiple null values may be associated with different keys). TreeMap does not support the Entry.setValue method. Below is the illustration of TreeSet and TreeMap in Java: Example 1: Java // Illustration of TreeMap and TreeSet in Javaimport java.io.*;import java.util.*; class GFG { public static void main(String[] args) { TreeSet<Integer> set = new TreeSet<>(); set.add(3); set.add(4); set.add(3); set.add(5); TreeMap<Integer, Integer> tm = new TreeMap<>(); tm.put(2, 4); tm.put(3, 5); tm.put(4, 5); tm.put(2, 3); System.out.println(set); System.out.println(tm); }} [3, 4, 5] {2=3, 3=5, 4=5} Example 2: Java // Illustration of TreeMap and TreeSet in Javaimport java.io.*;import java.util.*; class GFG { public static void main(String[] args) { TreeSet<String> l = new TreeSet<>(); l.add("geeks"); l.add("FOR"); l.add("geeks"); l.add("tutorial"); TreeMap<Integer, String> l1 = new TreeMap<>(); l1.put(1, "geeks"); l1.put(2, "FOR"); l1.put(3, "geeks"); l1.put(4, "tutorial"); System.out.println(l); System.out.println(l1); }} [FOR, geeks, tutorial] {1=geeks, 2=FOR, 3=geeks, 4=tutorial} TreeSet TreeMap Java-Collections java-TreeMap java-treeset Picked Technical Scripter 2020 Difference Between Java Technical Scripter Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Difference between Process and Thread Difference between Clustered and Non-clustered index Differences between IPv4 and IPv6 Arrays in Java Reverse a string in Java Split() String method in Java with examples Queue Interface In Java For-each loop in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jan, 2021" }, { "code": null, "e": 172, "s": 28, "text": "TreeSet is mainly an implementation of SortedSet in java where duplication is not allowed and objects are stored in sorted and ascending order." }, { "code": null, "e": 216, "s": 172, "text": "Some important features of the TreeSet are:" }, { "code": null, "e": 307, "s": 216, "text": "In TreeSet duplicate values are not allowed because it implements the SortedSet interface." }, { "code": null, "e": 359, "s": 307, "text": "Objects in a TreeSet are stored in ascending order." }, { "code": null, "e": 421, "s": 359, "text": "In TreeSet the insertion order of elements does not maintain." }, { "code": null, "e": 548, "s": 421, "text": "TreeMap is an implementation of Map Interface. TreeMap is also an implementation of NavigableMap along with AbstractMap class." }, { "code": null, "e": 592, "s": 548, "text": "Some important features of the TreeMap are:" }, { "code": null, "e": 743, "s": 592, "text": "In TreeMap null keys(like Map) are not allowed and thus a NullPointerException is thrown (Multiple null values may be associated with different keys)." }, { "code": null, "e": 795, "s": 743, "text": "TreeMap does not support the Entry.setValue method." }, { "code": null, "e": 853, "s": 795, "text": "Below is the illustration of TreeSet and TreeMap in Java:" }, { "code": null, "e": 864, "s": 853, "text": "Example 1:" }, { "code": null, "e": 869, "s": 864, "text": "Java" }, { "code": "// Illustration of TreeMap and TreeSet in Javaimport java.io.*;import java.util.*; class GFG { public static void main(String[] args) { TreeSet<Integer> set = new TreeSet<>(); set.add(3); set.add(4); set.add(3); set.add(5); TreeMap<Integer, Integer> tm = new TreeMap<>(); tm.put(2, 4); tm.put(3, 5); tm.put(4, 5); tm.put(2, 3); System.out.println(set); System.out.println(tm); }}", "e": 1345, "s": 869, "text": null }, { "code": null, "e": 1371, "s": 1345, "text": "[3, 4, 5]\n{2=3, 3=5, 4=5}" }, { "code": null, "e": 1382, "s": 1371, "text": "Example 2:" }, { "code": null, "e": 1387, "s": 1382, "text": "Java" }, { "code": "// Illustration of TreeMap and TreeSet in Javaimport java.io.*;import java.util.*; class GFG { public static void main(String[] args) { TreeSet<String> l = new TreeSet<>(); l.add(\"geeks\"); l.add(\"FOR\"); l.add(\"geeks\"); l.add(\"tutorial\"); TreeMap<Integer, String> l1 = new TreeMap<>(); l1.put(1, \"geeks\"); l1.put(2, \"FOR\"); l1.put(3, \"geeks\"); l1.put(4, \"tutorial\"); System.out.println(l); System.out.println(l1); }}", "e": 1901, "s": 1387, "text": null }, { "code": null, "e": 1962, "s": 1901, "text": "[FOR, geeks, tutorial]\n{1=geeks, 2=FOR, 3=geeks, 4=tutorial}" }, { "code": null, "e": 1970, "s": 1962, "text": "TreeSet" }, { "code": null, "e": 1978, "s": 1970, "text": "TreeMap" }, { "code": null, "e": 1995, "s": 1978, "text": "Java-Collections" }, { "code": null, "e": 2008, "s": 1995, "text": "java-TreeMap" }, { "code": null, "e": 2021, "s": 2008, "text": "java-treeset" }, { "code": null, "e": 2028, "s": 2021, "text": "Picked" }, { "code": null, "e": 2052, "s": 2028, "text": "Technical Scripter 2020" }, { "code": null, "e": 2071, "s": 2052, "text": "Difference Between" }, { "code": null, "e": 2076, "s": 2071, "text": "Java" }, { "code": null, "e": 2095, "s": 2076, "text": "Technical Scripter" }, { "code": null, "e": 2100, "s": 2095, "text": "Java" }, { "code": null, "e": 2117, "s": 2100, "text": "Java-Collections" }, { "code": null, "e": 2215, "s": 2117, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2276, "s": 2215, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2344, "s": 2276, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 2382, "s": 2344, "text": "Difference between Process and Thread" }, { "code": null, "e": 2435, "s": 2382, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 2469, "s": 2435, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 2484, "s": 2469, "text": "Arrays in Java" }, { "code": null, "e": 2509, "s": 2484, "text": "Reverse a string in Java" }, { "code": null, "e": 2553, "s": 2509, "text": "Split() String method in Java with examples" }, { "code": null, "e": 2577, "s": 2553, "text": "Queue Interface In Java" } ]
SciPy – Spatial Distance Matrix
17 Nov, 2021 A distance matrix contains the distances computed pairwise between the vectors of matrix/ matrices. scipy.spatial package provides us distance_matrix() method to compute the distance matrix. Generally matrices are in the form of 2-D array and the vectors of the matrix are matrix rows ( 1-D array). Syntax: scipy.spatial.distance_matrix(x, y, p=2) Parameters: x : (M, K) Matrix of M vectors, each of dimension K. y : (N, K) Matrix of N vectors, each of dimension K. p : float, 1 <= p <= infinity, defines which Minkowski p-norm to use. Returns: (M, N) ndarray / matrix containing the distance from every vector in x to every vector in y. Note: the column dimensions of both x, and y matrices must be same. We can use different values for p to apply different types of the distances to compute the distance matrix. p = 1, Manhattan Distance p = 2, Euclidean Distance p = ∞, Chebychev Distance Example 1. We compute the distance matrix for two matrices x, and y. Both matrices have same dimension (3, 2). So the distance matrix has dimension (3,3). Using p=2, the distances are calculated as Minkowski 2-norm (or Euclidean distance). Python3 # Python program to compute distance matrix # import important librariesimport numpy as npfrom scipy.spatial import distance_matrix # Create the matricesx = np.array([[1,2],[2,1],[2,2]])y = np.array([[5,0],[1,2],[2,0]]) # Display the matricesprint("matrix x:\n", x)print("matrix y:\n", y) # compute the distance matrixdist_mat = distance_matrix(x, y, p=2) # display distance matrixprint("Distance Matrix:\n", dist_mat) Output: distance matrix example 1 Example 2. We compute the distance matrix for two matrices x, and y. Both matrices have different dimensions. Matrix x has dimension (3,2) and matrix y has dimension (5,2). So the distance matrix has dimension (3,5). Python3 # Python program to compute distance matrix # import important librariesimport numpy as npfrom scipy.spatial import distance_matrix # Create the matricesx = np.array([[1,2],[2,1],[2,2]])y = np.array([[0,0],[0,0],[1,1],[1,1],[1,2]]) # Display the matricesprint("matrix x:\n", x)print("matrix y:\n", y) # compute the distance matrixdist_mat = distance_matrix(x, y, p=2) # display distance matrixprint("Distance Matrix:\n", dist_mat) Output: distance matrix example 2 Example 3. We compute the distance matrix using single matrix ( i.e. x). Matrix x has dimension (3,2). Same matrix x is given as parameter y. The distance matrix has dimension (3,3). Python3 # Python program to compute distance matrix # import important librariesimport numpy as npfrom scipy.spatial import distance_matrix # Create the matrixx = np.array([[1,2],[2,1],[2,2]]) # Display the matrixprint("matrix x:\n", x) # compute the distance matrixdist_mat = distance_matrix(x, x, p=2) # display distance matrixprint("Distance Matrix:\n", dist_mat) output: distance matrix example 3 Note: Notice that the above distance matrix is a symmetric matrix. When both x, and y matrices are same, the distance matrix is a symmetric matrix. Example 4. We compute the distance matrix for two matrices x, and y. Both matrices have different dimensions. Matrix x has dimension (3,2) and matrix y has dimension (5,2). So the distance matrix has dimension (3,5). Using p=1, the distances are calculated as Minkowski 1-norm (or Manhattan Distance). Python3 # Python program to compute distance matrix # import important librariesimport numpy as npfrom scipy.spatial import distance_matrix # Create the matricesx = np.array([[1,2],[2,1],[2,2]])y = np.array([[5,0],[1,2],[2,0]]) # Display the matricesprint("matrix x:\n", x)print("matrix y:\n", y) # compute the distance matrixdist_mat = distance_matrix(x, y, p=1) # display distance matrixprint("Distance Matrix:\n", dist_mat) Output: distance matrix example 4 Example 5. We compute the distance matrix for two matrices x, and y. Both matrices have dimension (2, 5). So the distance matrix has dimension (3,5). Using p=2, the distances are calculated as Minkowski 2-norm (or Euclidean Distance). Python3 # Python program to compute distance matrix # import important librariesimport numpy as npfrom scipy.spatial import distance_matrix # Create the matricesx = np.array([[1,2,3,4,5],[2,1,0,3,4]])y = np.array([[0,0,0,0,1],[1,1,1,1,2]]) # Display the matricesprint("matrix x:\n", x)print("matrix y:\n", y) # compute the distance matrixdist_mat = distance_matrix(x, y, p=2) # display distance matrixprint("Distance Matrix:\n", dist_mat) Output: distance matrix example 5 sumitgumber28 Picked Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Nov, 2021" }, { "code": null, "e": 327, "s": 28, "text": "A distance matrix contains the distances computed pairwise between the vectors of matrix/ matrices. scipy.spatial package provides us distance_matrix() method to compute the distance matrix. Generally matrices are in the form of 2-D array and the vectors of the matrix are matrix rows ( 1-D array)." }, { "code": null, "e": 683, "s": 327, "text": "Syntax: scipy.spatial.distance_matrix(x, y, p=2)\n \nParameters:\n x : (M, K) Matrix of M vectors, each of dimension K. \n y : (N, K) Matrix of N vectors, each of dimension K. \n p : float, 1 <= p <= infinity, defines which Minkowski p-norm to use.\n\nReturns: (M, N) ndarray\n/ matrix containing the distance from every vector in x to every vector in y." }, { "code": null, "e": 751, "s": 683, "text": "Note: the column dimensions of both x, and y matrices must be same." }, { "code": null, "e": 859, "s": 751, "text": "We can use different values for p to apply different types of the distances to compute the distance matrix." }, { "code": null, "e": 937, "s": 859, "text": "p = 1, Manhattan Distance\np = 2, Euclidean Distance\np = ∞, Chebychev Distance" }, { "code": null, "e": 948, "s": 937, "text": "Example 1." }, { "code": null, "e": 1178, "s": 948, "text": "We compute the distance matrix for two matrices x, and y. Both matrices have same dimension (3, 2). So the distance matrix has dimension (3,3). Using p=2, the distances are calculated as Minkowski 2-norm (or Euclidean distance)." }, { "code": null, "e": 1186, "s": 1178, "text": "Python3" }, { "code": "# Python program to compute distance matrix # import important librariesimport numpy as npfrom scipy.spatial import distance_matrix # Create the matricesx = np.array([[1,2],[2,1],[2,2]])y = np.array([[5,0],[1,2],[2,0]]) # Display the matricesprint(\"matrix x:\\n\", x)print(\"matrix y:\\n\", y) # compute the distance matrixdist_mat = distance_matrix(x, y, p=2) # display distance matrixprint(\"Distance Matrix:\\n\", dist_mat)", "e": 1605, "s": 1186, "text": null }, { "code": null, "e": 1613, "s": 1605, "text": "Output:" }, { "code": null, "e": 1639, "s": 1613, "text": "distance matrix example 1" }, { "code": null, "e": 1650, "s": 1639, "text": "Example 2." }, { "code": null, "e": 1856, "s": 1650, "text": "We compute the distance matrix for two matrices x, and y. Both matrices have different dimensions. Matrix x has dimension (3,2) and matrix y has dimension (5,2). So the distance matrix has dimension (3,5)." }, { "code": null, "e": 1864, "s": 1856, "text": "Python3" }, { "code": "# Python program to compute distance matrix # import important librariesimport numpy as npfrom scipy.spatial import distance_matrix # Create the matricesx = np.array([[1,2],[2,1],[2,2]])y = np.array([[0,0],[0,0],[1,1],[1,1],[1,2]]) # Display the matricesprint(\"matrix x:\\n\", x)print(\"matrix y:\\n\", y) # compute the distance matrixdist_mat = distance_matrix(x, y, p=2) # display distance matrixprint(\"Distance Matrix:\\n\", dist_mat)", "e": 2295, "s": 1864, "text": null }, { "code": null, "e": 2303, "s": 2295, "text": "Output:" }, { "code": null, "e": 2329, "s": 2303, "text": "distance matrix example 2" }, { "code": null, "e": 2340, "s": 2329, "text": "Example 3." }, { "code": null, "e": 2512, "s": 2340, "text": "We compute the distance matrix using single matrix ( i.e. x). Matrix x has dimension (3,2). Same matrix x is given as parameter y. The distance matrix has dimension (3,3)." }, { "code": null, "e": 2520, "s": 2512, "text": "Python3" }, { "code": "# Python program to compute distance matrix # import important librariesimport numpy as npfrom scipy.spatial import distance_matrix # Create the matrixx = np.array([[1,2],[2,1],[2,2]]) # Display the matrixprint(\"matrix x:\\n\", x) # compute the distance matrixdist_mat = distance_matrix(x, x, p=2) # display distance matrixprint(\"Distance Matrix:\\n\", dist_mat)", "e": 2879, "s": 2520, "text": null }, { "code": null, "e": 2887, "s": 2879, "text": "output:" }, { "code": null, "e": 2913, "s": 2887, "text": "distance matrix example 3" }, { "code": null, "e": 3061, "s": 2913, "text": "Note: Notice that the above distance matrix is a symmetric matrix. When both x, and y matrices are same, the distance matrix is a symmetric matrix." }, { "code": null, "e": 3072, "s": 3061, "text": "Example 4." }, { "code": null, "e": 3363, "s": 3072, "text": "We compute the distance matrix for two matrices x, and y. Both matrices have different dimensions. Matrix x has dimension (3,2) and matrix y has dimension (5,2). So the distance matrix has dimension (3,5). Using p=1, the distances are calculated as Minkowski 1-norm (or Manhattan Distance)." }, { "code": null, "e": 3371, "s": 3363, "text": "Python3" }, { "code": "# Python program to compute distance matrix # import important librariesimport numpy as npfrom scipy.spatial import distance_matrix # Create the matricesx = np.array([[1,2],[2,1],[2,2]])y = np.array([[5,0],[1,2],[2,0]]) # Display the matricesprint(\"matrix x:\\n\", x)print(\"matrix y:\\n\", y) # compute the distance matrixdist_mat = distance_matrix(x, y, p=1) # display distance matrixprint(\"Distance Matrix:\\n\", dist_mat)", "e": 3790, "s": 3371, "text": null }, { "code": null, "e": 3798, "s": 3790, "text": "Output:" }, { "code": null, "e": 3824, "s": 3798, "text": "distance matrix example 4" }, { "code": null, "e": 3835, "s": 3824, "text": "Example 5." }, { "code": null, "e": 4059, "s": 3835, "text": "We compute the distance matrix for two matrices x, and y. Both matrices have dimension (2, 5). So the distance matrix has dimension (3,5). Using p=2, the distances are calculated as Minkowski 2-norm (or Euclidean Distance)." }, { "code": null, "e": 4067, "s": 4059, "text": "Python3" }, { "code": "# Python program to compute distance matrix # import important librariesimport numpy as npfrom scipy.spatial import distance_matrix # Create the matricesx = np.array([[1,2,3,4,5],[2,1,0,3,4]])y = np.array([[0,0,0,0,1],[1,1,1,1,2]]) # Display the matricesprint(\"matrix x:\\n\", x)print(\"matrix y:\\n\", y) # compute the distance matrixdist_mat = distance_matrix(x, y, p=2) # display distance matrixprint(\"Distance Matrix:\\n\", dist_mat)", "e": 4498, "s": 4067, "text": null }, { "code": null, "e": 4506, "s": 4498, "text": "Output:" }, { "code": null, "e": 4532, "s": 4506, "text": "distance matrix example 5" }, { "code": null, "e": 4546, "s": 4532, "text": "sumitgumber28" }, { "code": null, "e": 4553, "s": 4546, "text": "Picked" }, { "code": null, "e": 4560, "s": 4553, "text": "Python" } ]