title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Multimap vs Map in C++ STL with Examples
23 Nov, 2021 Map in C++ STL Map stores unique key-value pairs in a sorted manner. Each key is uniquely associated with a value that may or may not be unique. A key can be inserted or deleted from a map but cannot be modified. Values assigned to keys can be changed. It is a great way for quickly accessing value using the key and it is done in O(1) time. C++ #include <iostream>#include <iterator>#include <map> using namespace std; int main(){ // empty map container map<int, int> gquiz1; // insert elements in random order gquiz1.insert(pair<int, int>(1, 40)); gquiz1.insert(pair<int, int>(2, 30)); gquiz1.insert(pair<int, int>(3, 60)); gquiz1.insert(pair<int, int>(4, 20)); gquiz1.insert(pair<int, int>(5, 50)); gquiz1.insert(pair<int, int>(6, 50)); gquiz1.insert(pair<int, int>(7, 10)); // printing map gquiz1 map<int, int>::iterator itr; cout << "\nThe map gquiz1 is : \n"; cout << "\tKEY\tELEMENT\n"; for (itr = gquiz1.begin(); itr != gquiz1.end(); ++itr) { cout << '\t' << itr->first << '\t' << itr->second << '\n'; } cout << endl; // assigning the elements from gquiz1 to gquiz2 map<int, int> gquiz2(gquiz1.begin(), gquiz1.end()); // print all elements of the map gquiz2 cout << "\nThe map gquiz2 after" << " assign from gquiz1 is : \n"; cout << "\tKEY\tELEMENT\n"; for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << '\t' << itr->first << '\t' << itr->second << '\n'; } cout << endl; // remove all elements up to // element with key=3 in gquiz2 cout << "\ngquiz2 after removal of" " elements less than key=3 : \n"; cout << "\tKEY\tELEMENT\n"; gquiz2.erase(gquiz2.begin(), gquiz2.find(3)); for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << '\t' << itr->first << '\t' << itr->second << '\n'; } // remove all elements with key = 4 int num; num = gquiz2.erase(4); cout << "\ngquiz2.erase(4) : "; cout << num << " removed \n"; cout << "\tKEY\tELEMENT\n"; for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << '\t' << itr->first << '\t' << itr->second << '\n'; } cout << endl; // lower bound and upper bound // for map gquiz1 key = 5 cout << "gquiz1.lower_bound(5) : " << "\tKEY = "; cout << gquiz1.lower_bound(5)->first << '\t'; cout << "\tELEMENT = " << gquiz1.lower_bound(5)->second << endl; cout << "gquiz1.upper_bound(5) : " << "\tKEY = "; cout << gquiz1.upper_bound(5)->first << '\t'; cout << "\tELEMENT = " << gquiz1.upper_bound(5)->second << endl; return 0;} The map gquiz1 is :KEY ELEMENT1 402 303 604 205 506 507 10 The map gquiz2 after assign from gquiz1 is :KEY ELEMENT1 402 303 604 205 506 507 10 gquiz2 after removal of elements less than key=3 :KEY ELEMENT3 604 205 506 507 10 gquiz2.erase(4) : 1 removedKEY ELEMENT3 605 506 507 10 gquiz1.lower_bound(5) : KEY = 5 ELEMENT = 50gquiz1.upper_bound(5) : KEY = 6 ELEMENT = 50 Multimap in C++ STL Multimap is similar to map with an addition that multiple elements can have same keys. Also, it is NOT required that the key value and mapped value pair has to be unique in this case. One important thing to note about multimap is that multimap keeps all the keys in sorted order always. These properties of multimap makes it very much useful in competitive programming. C++ #include <iostream>#include <iterator>#include <map> using namespace std; int main(){ // empty multimap container multimap<int, int> gquiz1; // insert elements in random order gquiz1.insert(pair<int, int>(1, 40)); gquiz1.insert(pair<int, int>(2, 30)); gquiz1.insert(pair<int, int>(3, 60)); gquiz1.insert(pair<int, int>(6, 50)); gquiz1.insert(pair<int, int>(6, 10)); // printing multimap gquiz1 multimap<int, int>::iterator itr; cout << "\nThe multimap gquiz1 is : \n"; cout << "\tKEY\tELEMENT\n"; for (itr = gquiz1.begin(); itr != gquiz1.end(); ++itr) { cout << '\t' << itr->first << '\t' << itr->second << '\n'; } cout << endl; // adding elements randomly, // to check the sorted keys property gquiz1.insert(pair<int, int>(4, 50)); gquiz1.insert(pair<int, int>(5, 10)); // printing multimap gquiz1 again cout << "\nThe multimap gquiz1 after" << " adding extra elements is : \n"; cout << "\tKEY\tELEMENT\n"; for (itr = gquiz1.begin(); itr != gquiz1.end(); ++itr) { cout << '\t' << itr->first << '\t' << itr->second << '\n'; } cout << endl; // assigning the elements from gquiz1 to gquiz2 multimap<int, int> gquiz2(gquiz1.begin(), gquiz1.end()); // print all elements of the multimap gquiz2 cout << "\nThe multimap gquiz2 after" << " assign from gquiz1 is : \n"; cout << "\tKEY\tELEMENT\n"; for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << '\t' << itr->first << '\t' << itr->second << '\n'; } cout << endl; // remove all elements up to // key with value 3 in gquiz2 cout << "\ngquiz2 after removal of" << " elements less than key=3 : \n"; cout << "\tKEY\tELEMENT\n"; gquiz2.erase(gquiz2.begin(), gquiz2.find(3)); for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << '\t' << itr->first << '\t' << itr->second << '\n'; } // remove all elements with key = 4 int num; num = gquiz2.erase(4); cout << "\ngquiz2.erase(4) : "; cout << num << " removed \n"; cout << "\tKEY\tELEMENT\n"; for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << '\t' << itr->first << '\t' << itr->second << '\n'; } cout << endl; // lower bound and upper bound // for multimap gquiz1 key = 5 cout << "gquiz1.lower_bound(5) : " << "\tKEY = "; cout << gquiz1.lower_bound(5)->first << '\t'; cout << "\tELEMENT = " << gquiz1.lower_bound(5)->second << endl; cout << "gquiz1.upper_bound(5) : " << "\tKEY = "; cout << gquiz1.upper_bound(5)->first << '\t'; cout << "\tELEMENT = " << gquiz1.upper_bound(5)->second << endl; return 0;} The multimap gquiz1 is :KEY ELEMENT1 402 303 606 506 10 The multimap gquiz1 after adding extra elements is :KEY ELEMENT1 402 303 604 505 106 506 10 The multimap gquiz2 after assign from gquiz1 is :KEY ELEMENT1 402 303 604 505 106 506 10 gquiz2 after removal of elements less than key=3 :KEY ELEMENT3 604 505 106 506 10 gquiz2.erase(4) : 1 removedKEY ELEMENT3 605 106 506 10 gquiz1.lower_bound(5) : KEY = 5 ELEMENT = 10gquiz1.upper_bound(5) : KEY = 6 ELEMENT = 50 Difference between Map and Multimap in C++ STL cpp-map cpp-multimap C++ Difference Between CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Nov, 2021" }, { "code": null, "e": 43, "s": 28, "text": "Map in C++ STL" }, { "code": null, "e": 371, "s": 43, "text": "Map stores unique key-value pairs in a sorted manner. Each key is uniquely associated with a value that may or may not be unique. A key can be inserted or deleted from a map but cannot be modified. Values assigned to keys can be changed. It is a great way for quickly accessing value using the key and it is done in O(1) time. " }, { "code": null, "e": 375, "s": 371, "text": "C++" }, { "code": "#include <iostream>#include <iterator>#include <map> using namespace std; int main(){ // empty map container map<int, int> gquiz1; // insert elements in random order gquiz1.insert(pair<int, int>(1, 40)); gquiz1.insert(pair<int, int>(2, 30)); gquiz1.insert(pair<int, int>(3, 60)); gquiz1.insert(pair<int, int>(4, 20)); gquiz1.insert(pair<int, int>(5, 50)); gquiz1.insert(pair<int, int>(6, 50)); gquiz1.insert(pair<int, int>(7, 10)); // printing map gquiz1 map<int, int>::iterator itr; cout << \"\\nThe map gquiz1 is : \\n\"; cout << \"\\tKEY\\tELEMENT\\n\"; for (itr = gquiz1.begin(); itr != gquiz1.end(); ++itr) { cout << '\\t' << itr->first << '\\t' << itr->second << '\\n'; } cout << endl; // assigning the elements from gquiz1 to gquiz2 map<int, int> gquiz2(gquiz1.begin(), gquiz1.end()); // print all elements of the map gquiz2 cout << \"\\nThe map gquiz2 after\" << \" assign from gquiz1 is : \\n\"; cout << \"\\tKEY\\tELEMENT\\n\"; for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << '\\t' << itr->first << '\\t' << itr->second << '\\n'; } cout << endl; // remove all elements up to // element with key=3 in gquiz2 cout << \"\\ngquiz2 after removal of\" \" elements less than key=3 : \\n\"; cout << \"\\tKEY\\tELEMENT\\n\"; gquiz2.erase(gquiz2.begin(), gquiz2.find(3)); for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << '\\t' << itr->first << '\\t' << itr->second << '\\n'; } // remove all elements with key = 4 int num; num = gquiz2.erase(4); cout << \"\\ngquiz2.erase(4) : \"; cout << num << \" removed \\n\"; cout << \"\\tKEY\\tELEMENT\\n\"; for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << '\\t' << itr->first << '\\t' << itr->second << '\\n'; } cout << endl; // lower bound and upper bound // for map gquiz1 key = 5 cout << \"gquiz1.lower_bound(5) : \" << \"\\tKEY = \"; cout << gquiz1.lower_bound(5)->first << '\\t'; cout << \"\\tELEMENT = \" << gquiz1.lower_bound(5)->second << endl; cout << \"gquiz1.upper_bound(5) : \" << \"\\tKEY = \"; cout << gquiz1.upper_bound(5)->first << '\\t'; cout << \"\\tELEMENT = \" << gquiz1.upper_bound(5)->second << endl; return 0;}", "e": 2724, "s": 375, "text": null }, { "code": null, "e": 2783, "s": 2724, "text": "The map gquiz1 is :KEY ELEMENT1 402 303 604 205 506 507 10" }, { "code": null, "e": 2867, "s": 2783, "text": "The map gquiz2 after assign from gquiz1 is :KEY ELEMENT1 402 303 604 205 506 507 10" }, { "code": null, "e": 2949, "s": 2867, "text": "gquiz2 after removal of elements less than key=3 :KEY ELEMENT3 604 205 506 507 10" }, { "code": null, "e": 3004, "s": 2949, "text": "gquiz2.erase(4) : 1 removedKEY ELEMENT3 605 506 507 10" }, { "code": null, "e": 3093, "s": 3004, "text": "gquiz1.lower_bound(5) : KEY = 5 ELEMENT = 50gquiz1.upper_bound(5) : KEY = 6 ELEMENT = 50" }, { "code": null, "e": 3114, "s": 3093, "text": "Multimap in C++ STL " }, { "code": null, "e": 3484, "s": 3114, "text": "Multimap is similar to map with an addition that multiple elements can have same keys. Also, it is NOT required that the key value and mapped value pair has to be unique in this case. One important thing to note about multimap is that multimap keeps all the keys in sorted order always. These properties of multimap makes it very much useful in competitive programming." }, { "code": null, "e": 3488, "s": 3484, "text": "C++" }, { "code": "#include <iostream>#include <iterator>#include <map> using namespace std; int main(){ // empty multimap container multimap<int, int> gquiz1; // insert elements in random order gquiz1.insert(pair<int, int>(1, 40)); gquiz1.insert(pair<int, int>(2, 30)); gquiz1.insert(pair<int, int>(3, 60)); gquiz1.insert(pair<int, int>(6, 50)); gquiz1.insert(pair<int, int>(6, 10)); // printing multimap gquiz1 multimap<int, int>::iterator itr; cout << \"\\nThe multimap gquiz1 is : \\n\"; cout << \"\\tKEY\\tELEMENT\\n\"; for (itr = gquiz1.begin(); itr != gquiz1.end(); ++itr) { cout << '\\t' << itr->first << '\\t' << itr->second << '\\n'; } cout << endl; // adding elements randomly, // to check the sorted keys property gquiz1.insert(pair<int, int>(4, 50)); gquiz1.insert(pair<int, int>(5, 10)); // printing multimap gquiz1 again cout << \"\\nThe multimap gquiz1 after\" << \" adding extra elements is : \\n\"; cout << \"\\tKEY\\tELEMENT\\n\"; for (itr = gquiz1.begin(); itr != gquiz1.end(); ++itr) { cout << '\\t' << itr->first << '\\t' << itr->second << '\\n'; } cout << endl; // assigning the elements from gquiz1 to gquiz2 multimap<int, int> gquiz2(gquiz1.begin(), gquiz1.end()); // print all elements of the multimap gquiz2 cout << \"\\nThe multimap gquiz2 after\" << \" assign from gquiz1 is : \\n\"; cout << \"\\tKEY\\tELEMENT\\n\"; for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << '\\t' << itr->first << '\\t' << itr->second << '\\n'; } cout << endl; // remove all elements up to // key with value 3 in gquiz2 cout << \"\\ngquiz2 after removal of\" << \" elements less than key=3 : \\n\"; cout << \"\\tKEY\\tELEMENT\\n\"; gquiz2.erase(gquiz2.begin(), gquiz2.find(3)); for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << '\\t' << itr->first << '\\t' << itr->second << '\\n'; } // remove all elements with key = 4 int num; num = gquiz2.erase(4); cout << \"\\ngquiz2.erase(4) : \"; cout << num << \" removed \\n\"; cout << \"\\tKEY\\tELEMENT\\n\"; for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << '\\t' << itr->first << '\\t' << itr->second << '\\n'; } cout << endl; // lower bound and upper bound // for multimap gquiz1 key = 5 cout << \"gquiz1.lower_bound(5) : \" << \"\\tKEY = \"; cout << gquiz1.lower_bound(5)->first << '\\t'; cout << \"\\tELEMENT = \" << gquiz1.lower_bound(5)->second << endl; cout << \"gquiz1.upper_bound(5) : \" << \"\\tKEY = \"; cout << gquiz1.upper_bound(5)->first << '\\t'; cout << \"\\tELEMENT = \" << gquiz1.upper_bound(5)->second << endl; return 0;}", "e": 6315, "s": 3488, "text": null }, { "code": null, "e": 6371, "s": 6315, "text": "The multimap gquiz1 is :KEY ELEMENT1 402 303 606 506 10" }, { "code": null, "e": 6463, "s": 6371, "text": "The multimap gquiz1 after adding extra elements is :KEY ELEMENT1 402 303 604 505 106 506 10" }, { "code": null, "e": 6552, "s": 6463, "text": "The multimap gquiz2 after assign from gquiz1 is :KEY ELEMENT1 402 303 604 505 106 506 10" }, { "code": null, "e": 6634, "s": 6552, "text": "gquiz2 after removal of elements less than key=3 :KEY ELEMENT3 604 505 106 506 10" }, { "code": null, "e": 6689, "s": 6634, "text": "gquiz2.erase(4) : 1 removedKEY ELEMENT3 605 106 506 10" }, { "code": null, "e": 6778, "s": 6689, "text": "gquiz1.lower_bound(5) : KEY = 5 ELEMENT = 10gquiz1.upper_bound(5) : KEY = 6 ELEMENT = 50" }, { "code": null, "e": 6825, "s": 6778, "text": "Difference between Map and Multimap in C++ STL" }, { "code": null, "e": 6833, "s": 6825, "text": "cpp-map" }, { "code": null, "e": 6846, "s": 6833, "text": "cpp-multimap" }, { "code": null, "e": 6850, "s": 6846, "text": "C++" }, { "code": null, "e": 6869, "s": 6850, "text": "Difference Between" }, { "code": null, "e": 6873, "s": 6869, "text": "CPP" } ]
What is the use of `%p` in printf in C?
In C we have seen different format specifiers. Here we will see another format specifier called %p. This is used to print the pointer type data. Let us see the example to get a better idea. #include<stdio.h> main() { int x = 50; int *ptr = &x; printf("The address is: %p, the value is %d", ptr, *ptr); } The address is: 000000000022FE44, the value is 50
[ { "code": null, "e": 1377, "s": 1187, "text": "In C we have seen different format specifiers. Here we will see another format specifier called %p. This is used to print the pointer type data. Let us see the example to get a better idea." }, { "code": null, "e": 1500, "s": 1377, "text": "#include<stdio.h>\nmain() {\n int x = 50;\n int *ptr = &x;\n printf(\"The address is: %p, the value is %d\", ptr, *ptr);\n}" }, { "code": null, "e": 1550, "s": 1500, "text": "The address is: 000000000022FE44, the value is 50" } ]
Longest Increasing Path in Matrix
22 Jun, 2022 Given a matrix of N rows and M columns. From m[i][j], we can move to m[i+1][j], if m[i+1][j] > m[i][j], or can move to m[i][j+1] if m[i][j+1] > m[i][j]. The task is print longest path length if we start from (0, 0).Examples: Input : N = 4, M = 4 m[][] = { { 1, 2, 3, 4 }, { 2, 2, 3, 4 }, { 3, 2, 3, 4 }, { 4, 5, 6, 7 } }; Output : 7 Longest path is 1 2 3 4 5 6 7. Input : N = 2, M =2 m[][] = { { 1, 2 }, { 3, 4 } }; Output :3 Longest path is either 1 2 4 or 1 3 4. The idea is to use dynamic programming. Maintain the 2D matrix, dp[][], where dp[i][j] store the value of the length of the longest increasing sequence for submatrix starting from the ith row and jth column. Let the longest increasing sub sequence values for m[i+1][j] and m[i][j+1] be known already as v1 and v2 respectively. Then the value for m[i][j] will be max(v1, v2) + 1. We can start from m[n-1][m-1] as the base case with the length of longest increasing subsequence be 1, moving upwards and leftwards updating the value of cells. Then the LIP value for cell m[0][0] will be the answer. Below is the implementation of this approach: C++ Java Python3 C# Javascript // CPP program to find longest increasing// path in a matrix.#include <bits/stdc++.h>#define MAX 10using namespace std; // Return the length of LIP in 2D matrixint LIP(int dp[][MAX], int mat[][MAX], int n, int m, int x, int y){ // If value not calculated yet. if (dp[x][y] < 0) { int result = 0; // If reach bottom right cell, return 1. if (x == n - 1 && y == m - 1) return dp[x][y] = 1; // If reach the corner of the matrix. if (x == n - 1 || y == m - 1) result = 1; // If value greater than below cell. if(x != n-1) // x reaches last row if (mat[x][y] < mat[x + 1][y]) result = 1 + LIP(dp, mat, n, m, x + 1, y); // If value greater than left cell. if(y != m-1) // y reaches last column if (mat[x][y] < mat[x][y + 1]) result = max(result, 1 + LIP(dp, mat, n, m, x, y + 1)); dp[x][y] = result; } return dp[x][y];} // Wrapper functionint wrapper(int mat[][MAX], int n, int m){ int dp[MAX][MAX]; memset(dp, -1, sizeof dp); return LIP(dp, mat, n, m, 0, 0);} // Driven Programint main(){ int mat[][MAX] = { { 1, 2, 3, 4 }, { 2, 2, 3, 4 }, { 3, 2, 3, 4 }, { 4, 5, 6, 7 }, }; int n = 4, m = 4; cout << wrapper(mat, n, m) << endl; return 0;} // Java program to find longest increasing// path in a matrix.import java.util.*; class GFG { // Return the length of LIP in 2D matrix static int LIP(int dp[][], int mat[][], int n, int m, int x, int y) { // If value not calculated yet. if (dp[x][y] < 0) { int result = 0; // If reach bottom right cell, return 1. if (x == n - 1 && y == m - 1) return dp[x][y] = 1; // If reach the corner of the matrix. if (x == n - 1 || y == m - 1) result = 1; // If value greater than below cell. if (x + 1 < n && mat[x][y] < mat[x + 1][y]) result = 1 + LIP(dp, mat, n, m, x + 1, y); // If value greater than left cell. if (y + 1 < m && mat[x][y] < mat[x][y + 1]) result = Math.max(result, 1 + LIP(dp, mat, n, m, x, y + 1)); dp[x][y] = result; } return dp[x][y]; } // Wrapper function static int wrapper(int mat[][], int n, int m) { int dp[][] = new int[10][10]; for (int i = 0; i < 10; i++) Arrays.fill(dp[i], -1); return LIP(dp, mat, n, m, 0, 0); } /* Driver program to test above function */ public static void main(String[] args) { int mat[][] = { { 1, 2, 3, 4 }, { 2, 2, 3, 4 }, { 3, 2, 3, 4 }, { 4, 5, 6, 7 }, }; int n = 4, m = 4; System.out.println(wrapper(mat, n, m)); }} // This code is contributed by Arnav Kr. Mandal. # Python3 program to find longest# increasing path in a matrix.MAX = 20 # Return the length of# LIP in 2D matrixdef LIP(dp, mat, n, m, x, y): # If value not calculated yet. if (dp[x][y] < 0): result = 0 # // If reach bottom right cell, return 1 if (x == n - 1 and y == m - 1): dp[x][y] = 1 return dp[x][y] # If reach the corner # of the matrix. if (x == n - 1 or y == m - 1): result = 1 # If value greater than below cell. if (x + 1 < n and mat[x][y] < mat[x + 1][y]): result = 1 + LIP(dp, mat, n, m, x + 1, y) # If value greater than left cell. if (y + 1 < m and mat[x][y] < mat[x][y + 1]): result = max(result, 1 + LIP(dp, mat, n, m, x, y + 1)) dp[x][y] = result return dp[x][y] # Wrapper functiondef wrapper(mat, n, m): dp = [[-1 for i in range(MAX)] for i in range(MAX)] return LIP(dp, mat, n, m, 0, 0) # Driver Codemat = [[1, 2, 3, 4 ], [2, 2, 3, 4 ], [3, 2, 3, 4 ], [4, 5, 6, 7 ]]n = 4m = 4print(wrapper(mat, n, m)) # This code is contributed# by Sahil Shelangia // C# program to find longest increasing// path in a matrix.using System; public class GFG { // Return the length of LIP in 2D matrix static int LIP(int[, ] dp, int[, ] mat, int n, int m, int x, int y) { // If value not calculated yet. if (dp[x, y] < 0) { int result = 0; // If reach bottom right cell, return 1. if (x == n - 1 && y == m - 1) return dp[x, y] = 1; // If reach the corner of the matrix. if (x == n - 1 || y == m - 1) result = 1; // If value greater than below cell. if (x + 1 < n && mat[x, y] < mat[x + 1, y]) result = 1 + LIP(dp, mat, n, m, x + 1, y); // If value greater than left cell. if (y + 1 < m && mat[x, y] < mat[x, y + 1]) result = Math.Max(result, 1 + LIP(dp, mat, n, m, x, y + 1)); dp[x, y] = result; } return dp[x, y]; } // Wrapper function static int wrapper(int[, ] mat, int n, int m) { int[, ] dp = new int[10, 10]; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { dp[i, j] = -1; } } return LIP(dp, mat, n, m, 0, 0); } /* Driver code */ public static void Main() { int[, ] mat = { { 1, 2, 3, 4 }, { 2, 2, 3, 4 }, { 3, 2, 3, 4 }, { 4, 5, 6, 7 }, }; int n = 4, m = 4; Console.WriteLine(wrapper(mat, n, m)); }} /* This code contributed by PrinciRaj1992 */ <script> // Javascript program to find longest increasing path in a matrix. // Return the length of LIP in 2D matrix function LIP(dp, mat, n, m, x, y) { // If value not calculated yet. if (dp[x][y] < 0) { let result = 0; // If reach bottom right cell, return 1. if (x == n - 1 && y == m - 1) return dp[x][y] = 1; // If reach the corner of the matrix. if (x == n - 1 || y == m - 1) result = 1; // If value greater than below cell. if (x + 1 < n && mat[x][y] < mat[x + 1][y]) result = 1 + LIP(dp, mat, n, m, x + 1, y); // If value greater than left cell. if (y + 1 < m && mat[x][y] < mat[x][y + 1]) result = Math.max(result, 1 + LIP(dp, mat, n, m, x, y + 1)); dp[x][y] = result; } return dp[x][y]; } // Wrapper function function wrapper(mat, n, m) { let dp = new Array(10); for (let i = 0; i < 10; i++) { dp[i] = new Array(10); for (let j = 0; j < 10; j++) { dp[i][j] = -1; } } return LIP(dp, mat, n, m, 0, 0); } let mat = [ [ 1, 2, 3, 4 ], [ 2, 2, 3, 4 ], [ 3, 2, 3, 4 ], [ 4, 5, 6, 7 ], ]; let n = 4, m = 4; document.write(wrapper(mat, n, m)); </script> Output: 7 Time Complexity: O(N*M). Space Complexity: O(N*M) This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. sahilshelangia princiraj1992 wektorall rameshtravel07 abhishekasc3 sanskar84 Dynamic Programming Matrix Dynamic Programming Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Find if there is a path between two vertices in an undirected graph Count number of binary strings without consecutive 1's Find if a string is interleaved of two other strings | DP-33 Optimal Substructure Property in Dynamic Programming | DP-2 Maximum sum such that no two elements are adjacent Print a given matrix in spiral form Program to find largest element in an array Rat in a Maze | Backtracking-2 Sudoku | Backtracking-7 The Celebrity Problem
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Jun, 2022" }, { "code": null, "e": 281, "s": 54, "text": "Given a matrix of N rows and M columns. From m[i][j], we can move to m[i+1][j], if m[i+1][j] > m[i][j], or can move to m[i][j+1] if m[i][j+1] > m[i][j]. The task is print longest path length if we start from (0, 0).Examples: " }, { "code": null, "e": 611, "s": 281, "text": "Input : N = 4, M = 4\n m[][] = { { 1, 2, 3, 4 },\n { 2, 2, 3, 4 },\n { 3, 2, 3, 4 },\n { 4, 5, 6, 7 } };\nOutput : 7\nLongest path is 1 2 3 4 5 6 7.\n\nInput : N = 2, M =2\n m[][] = { { 1, 2 },\n { 3, 4 } };\nOutput :3\nLongest path is either 1 2 4 or \n1 3 4." }, { "code": null, "e": 1257, "s": 613, "text": "The idea is to use dynamic programming. Maintain the 2D matrix, dp[][], where dp[i][j] store the value of the length of the longest increasing sequence for submatrix starting from the ith row and jth column. Let the longest increasing sub sequence values for m[i+1][j] and m[i][j+1] be known already as v1 and v2 respectively. Then the value for m[i][j] will be max(v1, v2) + 1. We can start from m[n-1][m-1] as the base case with the length of longest increasing subsequence be 1, moving upwards and leftwards updating the value of cells. Then the LIP value for cell m[0][0] will be the answer. Below is the implementation of this approach: " }, { "code": null, "e": 1261, "s": 1257, "text": "C++" }, { "code": null, "e": 1266, "s": 1261, "text": "Java" }, { "code": null, "e": 1274, "s": 1266, "text": "Python3" }, { "code": null, "e": 1277, "s": 1274, "text": "C#" }, { "code": null, "e": 1288, "s": 1277, "text": "Javascript" }, { "code": "// CPP program to find longest increasing// path in a matrix.#include <bits/stdc++.h>#define MAX 10using namespace std; // Return the length of LIP in 2D matrixint LIP(int dp[][MAX], int mat[][MAX], int n, int m, int x, int y){ // If value not calculated yet. if (dp[x][y] < 0) { int result = 0; // If reach bottom right cell, return 1. if (x == n - 1 && y == m - 1) return dp[x][y] = 1; // If reach the corner of the matrix. if (x == n - 1 || y == m - 1) result = 1; // If value greater than below cell. if(x != n-1) // x reaches last row if (mat[x][y] < mat[x + 1][y]) result = 1 + LIP(dp, mat, n, m, x + 1, y); // If value greater than left cell. if(y != m-1) // y reaches last column if (mat[x][y] < mat[x][y + 1]) result = max(result, 1 + LIP(dp, mat, n, m, x, y + 1)); dp[x][y] = result; } return dp[x][y];} // Wrapper functionint wrapper(int mat[][MAX], int n, int m){ int dp[MAX][MAX]; memset(dp, -1, sizeof dp); return LIP(dp, mat, n, m, 0, 0);} // Driven Programint main(){ int mat[][MAX] = { { 1, 2, 3, 4 }, { 2, 2, 3, 4 }, { 3, 2, 3, 4 }, { 4, 5, 6, 7 }, }; int n = 4, m = 4; cout << wrapper(mat, n, m) << endl; return 0;}", "e": 2627, "s": 1288, "text": null }, { "code": "// Java program to find longest increasing// path in a matrix.import java.util.*; class GFG { // Return the length of LIP in 2D matrix static int LIP(int dp[][], int mat[][], int n, int m, int x, int y) { // If value not calculated yet. if (dp[x][y] < 0) { int result = 0; // If reach bottom right cell, return 1. if (x == n - 1 && y == m - 1) return dp[x][y] = 1; // If reach the corner of the matrix. if (x == n - 1 || y == m - 1) result = 1; // If value greater than below cell. if (x + 1 < n && mat[x][y] < mat[x + 1][y]) result = 1 + LIP(dp, mat, n, m, x + 1, y); // If value greater than left cell. if (y + 1 < m && mat[x][y] < mat[x][y + 1]) result = Math.max(result, 1 + LIP(dp, mat, n, m, x, y + 1)); dp[x][y] = result; } return dp[x][y]; } // Wrapper function static int wrapper(int mat[][], int n, int m) { int dp[][] = new int[10][10]; for (int i = 0; i < 10; i++) Arrays.fill(dp[i], -1); return LIP(dp, mat, n, m, 0, 0); } /* Driver program to test above function */ public static void main(String[] args) { int mat[][] = { { 1, 2, 3, 4 }, { 2, 2, 3, 4 }, { 3, 2, 3, 4 }, { 4, 5, 6, 7 }, }; int n = 4, m = 4; System.out.println(wrapper(mat, n, m)); }} // This code is contributed by Arnav Kr. Mandal.", "e": 4208, "s": 2627, "text": null }, { "code": "# Python3 program to find longest# increasing path in a matrix.MAX = 20 # Return the length of# LIP in 2D matrixdef LIP(dp, mat, n, m, x, y): # If value not calculated yet. if (dp[x][y] < 0): result = 0 # // If reach bottom right cell, return 1 if (x == n - 1 and y == m - 1): dp[x][y] = 1 return dp[x][y] # If reach the corner # of the matrix. if (x == n - 1 or y == m - 1): result = 1 # If value greater than below cell. if (x + 1 < n and mat[x][y] < mat[x + 1][y]): result = 1 + LIP(dp, mat, n, m, x + 1, y) # If value greater than left cell. if (y + 1 < m and mat[x][y] < mat[x][y + 1]): result = max(result, 1 + LIP(dp, mat, n, m, x, y + 1)) dp[x][y] = result return dp[x][y] # Wrapper functiondef wrapper(mat, n, m): dp = [[-1 for i in range(MAX)] for i in range(MAX)] return LIP(dp, mat, n, m, 0, 0) # Driver Codemat = [[1, 2, 3, 4 ], [2, 2, 3, 4 ], [3, 2, 3, 4 ], [4, 5, 6, 7 ]]n = 4m = 4print(wrapper(mat, n, m)) # This code is contributed# by Sahil Shelangia", "e": 5428, "s": 4208, "text": null }, { "code": "// C# program to find longest increasing// path in a matrix.using System; public class GFG { // Return the length of LIP in 2D matrix static int LIP(int[, ] dp, int[, ] mat, int n, int m, int x, int y) { // If value not calculated yet. if (dp[x, y] < 0) { int result = 0; // If reach bottom right cell, return 1. if (x == n - 1 && y == m - 1) return dp[x, y] = 1; // If reach the corner of the matrix. if (x == n - 1 || y == m - 1) result = 1; // If value greater than below cell. if (x + 1 < n && mat[x, y] < mat[x + 1, y]) result = 1 + LIP(dp, mat, n, m, x + 1, y); // If value greater than left cell. if (y + 1 < m && mat[x, y] < mat[x, y + 1]) result = Math.Max(result, 1 + LIP(dp, mat, n, m, x, y + 1)); dp[x, y] = result; } return dp[x, y]; } // Wrapper function static int wrapper(int[, ] mat, int n, int m) { int[, ] dp = new int[10, 10]; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { dp[i, j] = -1; } } return LIP(dp, mat, n, m, 0, 0); } /* Driver code */ public static void Main() { int[, ] mat = { { 1, 2, 3, 4 }, { 2, 2, 3, 4 }, { 3, 2, 3, 4 }, { 4, 5, 6, 7 }, }; int n = 4, m = 4; Console.WriteLine(wrapper(mat, n, m)); }} /* This code contributed by PrinciRaj1992 */", "e": 7024, "s": 5428, "text": null }, { "code": "<script> // Javascript program to find longest increasing path in a matrix. // Return the length of LIP in 2D matrix function LIP(dp, mat, n, m, x, y) { // If value not calculated yet. if (dp[x][y] < 0) { let result = 0; // If reach bottom right cell, return 1. if (x == n - 1 && y == m - 1) return dp[x][y] = 1; // If reach the corner of the matrix. if (x == n - 1 || y == m - 1) result = 1; // If value greater than below cell. if (x + 1 < n && mat[x][y] < mat[x + 1][y]) result = 1 + LIP(dp, mat, n, m, x + 1, y); // If value greater than left cell. if (y + 1 < m && mat[x][y] < mat[x][y + 1]) result = Math.max(result, 1 + LIP(dp, mat, n, m, x, y + 1)); dp[x][y] = result; } return dp[x][y]; } // Wrapper function function wrapper(mat, n, m) { let dp = new Array(10); for (let i = 0; i < 10; i++) { dp[i] = new Array(10); for (let j = 0; j < 10; j++) { dp[i][j] = -1; } } return LIP(dp, mat, n, m, 0, 0); } let mat = [ [ 1, 2, 3, 4 ], [ 2, 2, 3, 4 ], [ 3, 2, 3, 4 ], [ 4, 5, 6, 7 ], ]; let n = 4, m = 4; document.write(wrapper(mat, n, m)); </script>", "e": 8495, "s": 7024, "text": null }, { "code": null, "e": 8505, "s": 8495, "text": "Output: " }, { "code": null, "e": 8507, "s": 8505, "text": "7" }, { "code": null, "e": 8532, "s": 8507, "text": "Time Complexity: O(N*M)." }, { "code": null, "e": 8557, "s": 8532, "text": "Space Complexity: O(N*M)" }, { "code": null, "e": 8978, "s": 8557, "text": "This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 8993, "s": 8978, "text": "sahilshelangia" }, { "code": null, "e": 9007, "s": 8993, "text": "princiraj1992" }, { "code": null, "e": 9017, "s": 9007, "text": "wektorall" }, { "code": null, "e": 9032, "s": 9017, "text": "rameshtravel07" }, { "code": null, "e": 9045, "s": 9032, "text": "abhishekasc3" }, { "code": null, "e": 9055, "s": 9045, "text": "sanskar84" }, { "code": null, "e": 9075, "s": 9055, "text": "Dynamic Programming" }, { "code": null, "e": 9082, "s": 9075, "text": "Matrix" }, { "code": null, "e": 9102, "s": 9082, "text": "Dynamic Programming" }, { "code": null, "e": 9109, "s": 9102, "text": "Matrix" }, { "code": null, "e": 9207, "s": 9109, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9275, "s": 9207, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 9330, "s": 9275, "text": "Count number of binary strings without consecutive 1's" }, { "code": null, "e": 9391, "s": 9330, "text": "Find if a string is interleaved of two other strings | DP-33" }, { "code": null, "e": 9451, "s": 9391, "text": "Optimal Substructure Property in Dynamic Programming | DP-2" }, { "code": null, "e": 9502, "s": 9451, "text": "Maximum sum such that no two elements are adjacent" }, { "code": null, "e": 9538, "s": 9502, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 9582, "s": 9538, "text": "Program to find largest element in an array" }, { "code": null, "e": 9613, "s": 9582, "text": "Rat in a Maze | Backtracking-2" }, { "code": null, "e": 9637, "s": 9613, "text": "Sudoku | Backtracking-7" } ]
How to check if a file is readable, writable, or, executable in Java?
In general, whenever you create a file you can restrict/permit certain users from reading/writing/executing a file. In Java files (their abstract paths) are represented by the File class of the java.io package. This class provides various methods to perform various operations on files such as read, write, delete, rename, etc. In addition, this class also provides the following methods − setExecutble() − This method issued to set the execute permissions to the file represented by the current (File) object. setExecutble() − This method issued to set the execute permissions to the file represented by the current (File) object. setWritable() − This method is used to set the write permissions to the file represented by the current (File) object. setWritable() − This method is used to set the write permissions to the file represented by the current (File) object. setReadable() − This method is used to set the read permissions to the file represented by the current (File) object. setReadable() − This method is used to set the read permissions to the file represented by the current (File) object. Following Java program creates a file writes some data into It and set read, write and execute permission to it. Live Demo import java.io.File; import java.io.FileWriter; import java.io.IOException; public class FilePermissions { public static void main(String args[]) throws IOException { String filePath = "D:\\sample.txt"; //Creating a file File file = new File(filePath); System.out.println("File created........."); //Writing data into the file FileWriter writer = new FileWriter(file); String data = "Hello welcome to Tutorialspoint"; writer.write(data); System.out.println("Data entered........."); //Setting permissions to the file file.setReadable(true); //read file.setWritable(true); //write file.setExecutable(true); //execute System.out.println("Permissions granted........."); } } Directory created......... File created......... Data entered......... Permissions granted......... In addition to the class File of the java.io package, since Java 7 the Files class was introduced this contains (static) methods that operate on files, directories, or other types of files. You can verify whether a particular file has read, write, execute permissions you can use the isReadable(), isWritable() and, isExecutable() methods of this class. The isReadable() method − This method accepts an object of the Path class and verifies whether the file represented by the given path exists in the system and JVM has permission to read it. If so, it returns true else it returns false. The isWritable() method − This method accepts an object of the Path class and verifies whether the file represented by the given path exists in the system and JVM has permission to write to it. If so, it returns true else it returns false. The isExecutable() method − This method accepts an object of the Path class and verifies whether the file represented by the given path exists in the system and JVM has permissions to execute it. If so, it returns true else it returns false. The class to provides a method named exists(), which returns true if the file represented by the current object(s) exists in the system else it returns false. The following Java program verifies whether a specified file exists in the system. It uses the methods of the Files class. Live Demo import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class FilesExample { public static void main(String args[]) { //Creating a Path object Path path = Paths.get("D:\\sample.txt"); //Verifying if the file is readable boolean bool = Files.isReadable(path); if(bool) { System.out.println("readable"); } else { System.out.println("not readable"); } bool = Files.isWritable(path); if(bool) { System.out.println("writable"); } else { System.out.println("not writable"); } bool = Files.isExecutable(path); if(bool) { System.out.println("executable"); } else { System.out.println("not executable"); } } } readable writable executable
[ { "code": null, "e": 1303, "s": 1187, "text": "In general, whenever you create a file you can restrict/permit certain users from reading/writing/executing a file." }, { "code": null, "e": 1515, "s": 1303, "text": "In Java files (their abstract paths) are represented by the File class of the java.io package. This class provides various methods to perform various operations on files such as read, write, delete, rename, etc." }, { "code": null, "e": 1577, "s": 1515, "text": "In addition, this class also provides the following methods −" }, { "code": null, "e": 1698, "s": 1577, "text": "setExecutble() − This method issued to set the execute permissions to the file represented by the current (File) object." }, { "code": null, "e": 1819, "s": 1698, "text": "setExecutble() − This method issued to set the execute permissions to the file represented by the current (File) object." }, { "code": null, "e": 1938, "s": 1819, "text": "setWritable() − This method is used to set the write permissions to the file represented by the current (File) object." }, { "code": null, "e": 2057, "s": 1938, "text": "setWritable() − This method is used to set the write permissions to the file represented by the current (File) object." }, { "code": null, "e": 2175, "s": 2057, "text": "setReadable() − This method is used to set the read permissions to the file represented by the current (File) object." }, { "code": null, "e": 2293, "s": 2175, "text": "setReadable() − This method is used to set the read permissions to the file represented by the current (File) object." }, { "code": null, "e": 2406, "s": 2293, "text": "Following Java program creates a file writes some data into It and set read, write and execute permission to it." }, { "code": null, "e": 2417, "s": 2406, "text": " Live Demo" }, { "code": null, "e": 3179, "s": 2417, "text": "import java.io.File;\nimport java.io.FileWriter;\nimport java.io.IOException;\npublic class FilePermissions {\n public static void main(String args[]) throws IOException {\n String filePath = \"D:\\\\sample.txt\";\n //Creating a file\n File file = new File(filePath);\n System.out.println(\"File created.........\");\n //Writing data into the file\n FileWriter writer = new FileWriter(file);\n String data = \"Hello welcome to Tutorialspoint\";\n writer.write(data);\n System.out.println(\"Data entered.........\");\n //Setting permissions to the file\n file.setReadable(true); //read\n file.setWritable(true); //write\n file.setExecutable(true); //execute\n System.out.println(\"Permissions granted.........\");\n }\n}" }, { "code": null, "e": 3279, "s": 3179, "text": "Directory created.........\nFile created.........\nData entered.........\nPermissions granted........." }, { "code": null, "e": 3469, "s": 3279, "text": "In addition to the class File of the java.io package, since Java 7 the Files class was introduced this contains (static) methods that operate on files, directories, or other types of files." }, { "code": null, "e": 3633, "s": 3469, "text": "You can verify whether a particular file has read, write, execute permissions you can use the isReadable(), isWritable() and, isExecutable() methods of this class." }, { "code": null, "e": 3869, "s": 3633, "text": "The isReadable() method − This method accepts an object of the Path class and verifies whether the file represented by the given path exists in the system and JVM has permission to read it. If so, it returns true else it returns false." }, { "code": null, "e": 4109, "s": 3869, "text": "The isWritable() method − This method accepts an object of the Path class and verifies whether the file represented by the given path exists in the system and JVM has permission to write to it. If so, it returns true else it returns false." }, { "code": null, "e": 4351, "s": 4109, "text": "The isExecutable() method − This method accepts an object of the Path class and verifies whether the file represented by the given path exists in the system and JVM has permissions to execute it. If so, it returns true else it returns false." }, { "code": null, "e": 4510, "s": 4351, "text": "The class to provides a method named exists(), which returns true if the file represented by the current object(s) exists in the system else it returns false." }, { "code": null, "e": 4633, "s": 4510, "text": "The following Java program verifies whether a specified file exists in the system. It uses the methods of the Files class." }, { "code": null, "e": 4644, "s": 4633, "text": " Live Demo" }, { "code": null, "e": 5429, "s": 4644, "text": "import java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\npublic class FilesExample {\n public static void main(String args[]) {\n //Creating a Path object\n Path path = Paths.get(\"D:\\\\sample.txt\");\n //Verifying if the file is readable\n boolean bool = Files.isReadable(path);\n if(bool) {\n System.out.println(\"readable\");\n } else {\n System.out.println(\"not readable\");\n }\n bool = Files.isWritable(path);\n if(bool) {\n System.out.println(\"writable\");\n } else {\n System.out.println(\"not writable\");\n }\n bool = Files.isExecutable(path);\n if(bool) {\n System.out.println(\"executable\");\n } else {\n System.out.println(\"not executable\");\n }\n }\n}" }, { "code": null, "e": 5458, "s": 5429, "text": "readable\nwritable\nexecutable" } ]
Python | Print number of leap years from given list of years
24 Sep, 2021 The problem of finding leap year is quite generic and we might face the issue of finding the number of leap years in given list of years. Let’s discuss certain ways in which this can be performed. Method #1: Using Iteration Check whether year is a multiple of 4 and not multiple of 100 or year is multiple of 400. Python3 # Python code to finding number of# leap years in list of years. # Input list initializationInput = [2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012] # Find whether it is leap year or notdef checkYear(year): return (((year % 4 == 0) and (year % 100 != 0)) or (year % 400 == 0)) # Answer InitializationAnswer = 0 for elem in Input: if checkYear(elem): Answer = Answer + 1 # Printingprint("No of leap years are:", Answer) No of leap years are: 3 Method #2: Using calendar Python3 # Python code to finding number of# leap years in list of years. # Importing calendarimport calendar # Input list initializationInput = [2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010] # Using calendar to find leap yeardef FindLeapYear(Input): ans = 0 for elem in Input: if calendar.isleap(int(elem)): ans = ans + 1 return ans Output = FindLeapYear(Input) # Printingprint("No of leap years are:", Output) No of leap years are: 2 khushboogoyal499 Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate through Excel rows in Python? Deque in Python Defaultdict in Python Queue in Python Rotate axis tick labels in Seaborn and Matplotlib Defaultdict in Python Python program to add two numbers Python | Get dictionary keys as a list Python Program for Fibonacci numbers Python Program for factorial of a number
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Sep, 2021" }, { "code": null, "e": 225, "s": 28, "text": "The problem of finding leap year is quite generic and we might face the issue of finding the number of leap years in given list of years. Let’s discuss certain ways in which this can be performed." }, { "code": null, "e": 343, "s": 225, "text": "Method #1: Using Iteration Check whether year is a multiple of 4 and not multiple of 100 or year is multiple of 400. " }, { "code": null, "e": 351, "s": 343, "text": "Python3" }, { "code": "# Python code to finding number of# leap years in list of years. # Input list initializationInput = [2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012] # Find whether it is leap year or notdef checkYear(year): return (((year % 4 == 0) and (year % 100 != 0)) or (year % 400 == 0)) # Answer InitializationAnswer = 0 for elem in Input: if checkYear(elem): Answer = Answer + 1 # Printingprint(\"No of leap years are:\", Answer)", "e": 840, "s": 351, "text": null }, { "code": null, "e": 864, "s": 840, "text": "No of leap years are: 3" }, { "code": null, "e": 894, "s": 866, "text": "Method #2: Using calendar " }, { "code": null, "e": 902, "s": 894, "text": "Python3" }, { "code": "# Python code to finding number of# leap years in list of years. # Importing calendarimport calendar # Input list initializationInput = [2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010] # Using calendar to find leap yeardef FindLeapYear(Input): ans = 0 for elem in Input: if calendar.isleap(int(elem)): ans = ans + 1 return ans Output = FindLeapYear(Input) # Printingprint(\"No of leap years are:\", Output)", "e": 1354, "s": 902, "text": null }, { "code": null, "e": 1378, "s": 1354, "text": "No of leap years are: 2" }, { "code": null, "e": 1397, "s": 1380, "text": "khushboogoyal499" }, { "code": null, "e": 1418, "s": 1397, "text": "Python list-programs" }, { "code": null, "e": 1425, "s": 1418, "text": "Python" }, { "code": null, "e": 1441, "s": 1425, "text": "Python Programs" }, { "code": null, "e": 1539, "s": 1441, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1584, "s": 1539, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 1600, "s": 1584, "text": "Deque in Python" }, { "code": null, "e": 1622, "s": 1600, "text": "Defaultdict in Python" }, { "code": null, "e": 1638, "s": 1622, "text": "Queue in Python" }, { "code": null, "e": 1688, "s": 1638, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 1710, "s": 1688, "text": "Defaultdict in Python" }, { "code": null, "e": 1744, "s": 1710, "text": "Python program to add two numbers" }, { "code": null, "e": 1783, "s": 1744, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 1820, "s": 1783, "text": "Python Program for Fibonacci numbers" } ]
KNN Model Complexity
05 Sep, 2020 KNN is a machine learning algorithm which is used for both classification (using KNearestClassifier) and Regression (using KNearestRegressor) problems.In KNN algorithm K is the Hyperparameter. Choosing the right value of K matters. A machine learning model is said to have high model complexity if the built model is having low Bias and High Variance. We know that, High Bias and Low Variance = Under-fitting model.Low Bias and High Variance = Over-fitting model. [Indicated highly complex model ].Low Bias and Low Variance = Best fitting model. [This is preferred ].High training accuracy and Low test accuracy ( out of sample accuracy ) = High Variance = Over-fitting model = More model complexity.Low training accuracy and Low test accuracy ( out of sample accuracy ) = High Bias = Under-fitting model. High Bias and Low Variance = Under-fitting model. Low Bias and High Variance = Over-fitting model. [Indicated highly complex model ]. Low Bias and Low Variance = Best fitting model. [This is preferred ]. High training accuracy and Low test accuracy ( out of sample accuracy ) = High Variance = Over-fitting model = More model complexity. Low training accuracy and Low test accuracy ( out of sample accuracy ) = High Bias = Under-fitting model. Code: To understand how K value in KNN algorithm affects the model complexity. # This code may not run on GFG ide# As required modules are not found. # Import required modulesimport matplotlib.pyplot as pltfrom sklearn.datasets import make_regressionfrom sklearn.neighbors import KNeighborsRegressorfrom sklearn.model_selection import train_test_splitimport numpy as np # Synthetically Create Data Setplt.figure()plt.title('SIMPLE-LINEAR-REGRESSION')x, y = make_regression( n_samples = 100, n_features = 1, n_informative = 1, noise = 15, random_state = 3)plt.scatter(x, y, color ='red', marker ='o', s = 30) # Train the model.knn = KNeighborsRegressor(n_neighbors = 7)x_train, x_test, y_train, y_test = train_test_split( x, y, test_size = 0.2, random_state = 0)knn.fit(x_train, y_train)predict = knn.predict(x_test)print('Test Accuracy:', knn.score(x_test, y_test))print('Training Accuracy:', knn.score(x_train, y_train)) # Plot The Outputx_new = np.linspace(-3, 2, 100).reshape(100, 1)predict_new = knn.predict(x_new)plt.plot( x_new, predict_new, color ='blue', label ="K = 7")plt.scatter(x_train, y_train, color ='red' )plt.scatter(x_test, predict, marker ='^', s = 90)plt.legend() Output: Test Accuracy: 0.6465919540035108 Training Accuracy: 0.8687977824212627 Now let’s vary the value of K (Hyperparameter) from Low to High and observe the model complexityK = 1 Observations: When K value is small i.e. K=1, The model complexity is high ( Over-fitting or High Variance). When K value is very large i.e. K=70, The model complexity decreases ( Under-fitting or High Bias ). Conclusion:As K value becomes small model complexity increases and as K value becomes large the model complexity decreases. Code: Let’s consider the below plot # This code may not run on GFG# As required modules are not found. # To plot test accuracy and train accuracy Vs K value.p = list(range(1, 31))lst_test =[]lst_train =[]for i in p: knn = KNeighborsRegressor(n_neighbors = i) knn.fit(x_train, y_train) z = knn.score(x_test, y_test) t = knn.score(x_train, y_train) lst_test.append(z) lst_train.append(t) plt.plot(p, lst_test, color ='red', label ='Test Accuracy')plt.plot(p, lst_train, color ='b', label ='Train Accuracy')plt.xlabel('K VALUES --->')plt.title('FINDING BEST VALUE FOR K')plt.legend() Output: Observation:From the above graph, we can conclude that when K is small i.e. K=1, Training Accuracy is High but Test Accuracy is Low which means the model is over-fitting ( High Variance or High Model Complexity). When the value of K is large i.e. K=50, Training Accuracy is Low as well as Test Accuracy is Low which means the model is under-fitting ( High Bias or Low Model Complexity ). So Hyperparameter tuning is necessary i.e. to select the best value of K in KNN algorithm for which the model has Low Bias and Low Variance and results in a good model with high out of sample accuracy. We can use GridSearchCV or RandomSearchCv to find the best value of hyper parameter K. ML-Clustering Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network ML | Monte Carlo Tree Search (MCTS) Markov Decision Process Support Vector Machine Algorithm DBSCAN Clustering in ML | Density based clustering Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function Python Dictionary How to get column names in Pandas dataframe
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Sep, 2020" }, { "code": null, "e": 406, "s": 54, "text": "KNN is a machine learning algorithm which is used for both classification (using KNearestClassifier) and Regression (using KNearestRegressor) problems.In KNN algorithm K is the Hyperparameter. Choosing the right value of K matters. A machine learning model is said to have high model complexity if the built model is having low Bias and High Variance." }, { "code": null, "e": 420, "s": 406, "text": "We know that," }, { "code": null, "e": 860, "s": 420, "text": "High Bias and Low Variance = Under-fitting model.Low Bias and High Variance = Over-fitting model. [Indicated highly complex model ].Low Bias and Low Variance = Best fitting model. [This is preferred ].High training accuracy and Low test accuracy ( out of sample accuracy ) = High Variance = Over-fitting model = More model complexity.Low training accuracy and Low test accuracy ( out of sample accuracy ) = High Bias = Under-fitting model." }, { "code": null, "e": 910, "s": 860, "text": "High Bias and Low Variance = Under-fitting model." }, { "code": null, "e": 994, "s": 910, "text": "Low Bias and High Variance = Over-fitting model. [Indicated highly complex model ]." }, { "code": null, "e": 1064, "s": 994, "text": "Low Bias and Low Variance = Best fitting model. [This is preferred ]." }, { "code": null, "e": 1198, "s": 1064, "text": "High training accuracy and Low test accuracy ( out of sample accuracy ) = High Variance = Over-fitting model = More model complexity." }, { "code": null, "e": 1304, "s": 1198, "text": "Low training accuracy and Low test accuracy ( out of sample accuracy ) = High Bias = Under-fitting model." }, { "code": null, "e": 1383, "s": 1304, "text": "Code: To understand how K value in KNN algorithm affects the model complexity." }, { "code": "# This code may not run on GFG ide# As required modules are not found. # Import required modulesimport matplotlib.pyplot as pltfrom sklearn.datasets import make_regressionfrom sklearn.neighbors import KNeighborsRegressorfrom sklearn.model_selection import train_test_splitimport numpy as np # Synthetically Create Data Setplt.figure()plt.title('SIMPLE-LINEAR-REGRESSION')x, y = make_regression( n_samples = 100, n_features = 1, n_informative = 1, noise = 15, random_state = 3)plt.scatter(x, y, color ='red', marker ='o', s = 30) # Train the model.knn = KNeighborsRegressor(n_neighbors = 7)x_train, x_test, y_train, y_test = train_test_split( x, y, test_size = 0.2, random_state = 0)knn.fit(x_train, y_train)predict = knn.predict(x_test)print('Test Accuracy:', knn.score(x_test, y_test))print('Training Accuracy:', knn.score(x_train, y_train)) # Plot The Outputx_new = np.linspace(-3, 2, 100).reshape(100, 1)predict_new = knn.predict(x_new)plt.plot( x_new, predict_new, color ='blue', label =\"K = 7\")plt.scatter(x_train, y_train, color ='red' )plt.scatter(x_test, predict, marker ='^', s = 90)plt.legend()", "e": 2513, "s": 1383, "text": null }, { "code": null, "e": 2521, "s": 2513, "text": "Output:" }, { "code": null, "e": 2594, "s": 2521, "text": "Test Accuracy: 0.6465919540035108\nTraining Accuracy: 0.8687977824212627\n" }, { "code": null, "e": 2696, "s": 2594, "text": "Now let’s vary the value of K (Hyperparameter) from Low to High and observe the model complexityK = 1" }, { "code": null, "e": 2710, "s": 2696, "text": "Observations:" }, { "code": null, "e": 2805, "s": 2710, "text": "When K value is small i.e. K=1, The model complexity is high ( Over-fitting or High Variance)." }, { "code": null, "e": 2906, "s": 2805, "text": "When K value is very large i.e. K=70, The model complexity decreases ( Under-fitting or High Bias )." }, { "code": null, "e": 3030, "s": 2906, "text": "Conclusion:As K value becomes small model complexity increases and as K value becomes large the model complexity decreases." }, { "code": null, "e": 3066, "s": 3030, "text": "Code: Let’s consider the below plot" }, { "code": "# This code may not run on GFG# As required modules are not found. # To plot test accuracy and train accuracy Vs K value.p = list(range(1, 31))lst_test =[]lst_train =[]for i in p: knn = KNeighborsRegressor(n_neighbors = i) knn.fit(x_train, y_train) z = knn.score(x_test, y_test) t = knn.score(x_train, y_train) lst_test.append(z) lst_train.append(t) plt.plot(p, lst_test, color ='red', label ='Test Accuracy')plt.plot(p, lst_train, color ='b', label ='Train Accuracy')plt.xlabel('K VALUES --->')plt.title('FINDING BEST VALUE FOR K')plt.legend()", "e": 3635, "s": 3066, "text": null }, { "code": null, "e": 3643, "s": 3635, "text": "Output:" }, { "code": null, "e": 4031, "s": 3643, "text": "Observation:From the above graph, we can conclude that when K is small i.e. K=1, Training Accuracy is High but Test Accuracy is Low which means the model is over-fitting ( High Variance or High Model Complexity). When the value of K is large i.e. K=50, Training Accuracy is Low as well as Test Accuracy is Low which means the model is under-fitting ( High Bias or Low Model Complexity )." }, { "code": null, "e": 4233, "s": 4031, "text": "So Hyperparameter tuning is necessary i.e. to select the best value of K in KNN algorithm for which the model has Low Bias and Low Variance and results in a good model with high out of sample accuracy." }, { "code": null, "e": 4320, "s": 4233, "text": "We can use GridSearchCV or RandomSearchCv to find the best value of hyper parameter K." }, { "code": null, "e": 4334, "s": 4320, "text": "ML-Clustering" }, { "code": null, "e": 4351, "s": 4334, "text": "Machine Learning" }, { "code": null, "e": 4358, "s": 4351, "text": "Python" }, { "code": null, "e": 4375, "s": 4358, "text": "Machine Learning" }, { "code": null, "e": 4473, "s": 4375, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4514, "s": 4473, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 4550, "s": 4514, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 4574, "s": 4550, "text": "Markov Decision Process" }, { "code": null, "e": 4607, "s": 4574, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 4658, "s": 4607, "text": "DBSCAN Clustering in ML | Density based clustering" }, { "code": null, "e": 4686, "s": 4658, "text": "Read JSON file using Python" }, { "code": null, "e": 4736, "s": 4686, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 4758, "s": 4736, "text": "Python map() function" }, { "code": null, "e": 4776, "s": 4758, "text": "Python Dictionary" } ]
GATE | GATE CS 2013 | Question 65
09 Oct, 2019 Consider the following relational schema. Students(rollno: integer, sname: string) Courses(courseno: integer, cname: string) Registration(rollno: integer, courseno: integer, percent: real) Which of the following queries are equivalent to this query in English? "Find the distinct names of all students who score more than 90% in the course numbered 107" (A) I, II, III and IV(B) I, II and III only(C) I, II and IV only(D) II, III and IV onlyAnswer: (A)Explanation: Option A: This is a SQL query expression. It first perform a cross product of Students and Registration, then WHERE clause only keeps those rows in the cross product set where the student is registered for course no 107, and percentage is > 90. Then select distinct statement gives the distinct names of those students as the result set. Option B: This is a relational algebra expression. It first perform a NATURAL JOIN of Students and Registration (NATURAL JOIN implicitly joins on the basis of common attribute, which here is rollno ), then the select operation( sigma) keeps only those rows where the student is registered for courseno 107, and percentage is > 90. And then the projection operation (pi) projects only distinct student names from the set. Note: Projection operation (pi) always gives the distinct result. Option C: This is a Tuple Relational Calculus (TRC) language expression, It is not a procedural language (i.e. it only tells “what to do”, not “how to do”). It just represents a declarative mathematical expression. Here T is a Tuple variable. From left to right, it can be read like this, “It is a set of tuples T, where, there exists a tuple S in Relation Students, and there exist a tuple R in relation Registration, such that S.rollno = R.rollno AND R.couseno = 107 AND R.percent > 90 AND T.sname = S.sname”. And the schema of this result is (sname), i.e. each tuple T will contain only student name, because only T.sname has been defined in the expression. As TRC is a mathematical expression, hence it is expected to give only distinct result set. Option D: This is a Domain Relational Calculus (DRC) language expression. This is also not procedural. Here SN is a Domain Variable. It can be read from left to right like this “The set of domain variable SN, where, there exist a domain variable SR , and a domain variable Rp, such that, SN and SR domain variables is in relation Students and SR,107,RP is a domain variables set in relation Registration, AND RP > 90 “ Above, SN represents sname domain attribute in Students relation, SR represents rollno domain attribute in Students relation, and RP represents percentage domain attribute in Registration relation. The schema for the result set is (SN), i.e. only student name. As DRC is a mathematical expression, hence it is expected to give only distinct result set. Quiz of this Question GATE-CS-2013 GATE-GATE CS 2013 DBMS Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... Must Do Coding Questions for Product Based Companies Spring Boot - Annotations How to Install Git in VS Code? Git - Difference Between Git Fetch and Git Pull ReactJS useNavigate() Hook SDE SHEET - A Complete Guide for SDE Preparation How to Install and Use NVM on Windows? How to Set Upstream Branch on Git? DSA Sheet by Love Babbar
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Oct, 2019" }, { "code": null, "e": 96, "s": 54, "text": "Consider the following relational schema." }, { "code": null, "e": 255, "s": 96, "text": " Students(rollno: integer, sname: string)\n Courses(courseno: integer, cname: string)\n Registration(rollno: integer, courseno: integer, percent: real)" }, { "code": null, "e": 327, "s": 255, "text": "Which of the following queries are equivalent to this query in English?" }, { "code": null, "e": 434, "s": 327, "text": " \"Find the distinct names of all students who score \n more than 90% in the course numbered 107\"" }, { "code": null, "e": 545, "s": 434, "text": "(A) I, II, III and IV(B) I, II and III only(C) I, II and IV only(D) II, III and IV onlyAnswer: (A)Explanation:" }, { "code": null, "e": 890, "s": 545, "text": "Option A:\n\nThis is a SQL query expression. It first perform a cross product of Students \nand Registration, then WHERE clause only keeps those rows in the cross product \nset where the student is registered for course no 107, and percentage is > 90. \nThen select distinct statement gives the distinct names of those students as the \nresult set.\n\n" }, { "code": null, "e": 1384, "s": 890, "text": "Option B:\n\nThis is a relational algebra expression. It first perform a NATURAL JOIN \nof Students and Registration (NATURAL JOIN implicitly joins on the basis \nof common attribute, which here is rollno ), then the select operation( sigma) \nkeeps only those rows where the student is registered for courseno 107,\nand percentage is > 90. And then the projection operation (pi) projects only \ndistinct student names from the set.\n\nNote: Projection operation (pi) always gives the distinct result.\n" }, { "code": null, "e": 2149, "s": 1384, "text": "Option C:\n\nThis is a Tuple Relational Calculus (TRC) language expression,\nIt is not a procedural language (i.e. it only tells “what to do”, \nnot “how to do”). It just represents a declarative mathematical \nexpression.\n\nHere T is a Tuple variable.\n\nFrom left to right, it can be read like this, “It is a set of\ntuples T, where, there exists a tuple S in Relation Students, and \nthere exist a tuple R in relation Registration, such that \nS.rollno = R.rollno AND R.couseno = 107 AND R.percent > 90 AND \nT.sname = S.sname”. And the schema of this result is (sname), i.e. each \ntuple T will contain only student name, because only T.sname has been defined \nin the expression.\n\nAs TRC is a mathematical expression, hence it is expected to give only distinct result set.\n" }, { "code": null, "e": 2932, "s": 2149, "text": "Option D:\n\nThis is a Domain Relational Calculus (DRC) language expression. \nThis is also not procedural. Here SN is a Domain Variable. It can be read \nfrom left to right like this “The set of domain variable SN, where, \nthere exist a domain variable SR , and a domain variable Rp, such that, \nSN and SR domain variables is in relation Students and SR,107,RP is a domain\nvariables set in relation Registration, AND RP > 90 “\n\nAbove, SN represents sname domain attribute in Students relation, SR \nrepresents rollno domain attribute in Students relation, and RP represents \npercentage domain attribute in Registration relation.\nThe schema for the result set is (SN), i.e. only student name.\n\nAs DRC is a mathematical expression, hence it is expected to\ngive only distinct result set.\n\n" }, { "code": null, "e": 2954, "s": 2932, "text": "Quiz of this Question" }, { "code": null, "e": 2967, "s": 2954, "text": "GATE-CS-2013" }, { "code": null, "e": 2985, "s": 2967, "text": "GATE-GATE CS 2013" }, { "code": null, "e": 2995, "s": 2985, "text": "DBMS Quiz" }, { "code": null, "e": 3093, "s": 2995, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3167, "s": 3093, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 3220, "s": 3167, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 3246, "s": 3220, "text": "Spring Boot - Annotations" }, { "code": null, "e": 3277, "s": 3246, "text": "How to Install Git in VS Code?" }, { "code": null, "e": 3325, "s": 3277, "text": "Git - Difference Between Git Fetch and Git Pull" }, { "code": null, "e": 3352, "s": 3325, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 3401, "s": 3352, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 3440, "s": 3401, "text": "How to Install and Use NVM on Windows?" }, { "code": null, "e": 3475, "s": 3440, "text": "How to Set Upstream Branch on Git?" } ]
How to get or set the resolution of an image using imageresolution() function in PHP?
imageresoulution() is an inbuilt function in PHP that is used to get or set the resolution of an image in dots per inch. If no optional parameters are given, then the current resolution is returned as an indexed array. If one of the optional parameters is given, then it will set both the width and height to that parameter. The resolution is only used as meta information when the images are read from and written to formats supporting this kind of information (currently PNG and JPEG). It does not affect any drawing operations. The 96 DPI (dots per inch) is the default resolution for new images. mixed imageresolution(resource $image, int $res_x, int $res_y) imageresolution() accepts three parameters: $image, $res_x, $res_y. $image − Specifies the image resource to work on. $image − Specifies the image resource to work on. $res_x − Specifies the horizontal resolution in dots per inch (DPI). $res_x − Specifies the horizontal resolution in dots per inch (DPI). $res_y − Specifies the vertical resolution in dots per inch (DPI). $res_y − Specifies the vertical resolution in dots per inch (DPI). imageresolution() returns the indexed array of the image. <?php $img = imagecreatetruecolor(100, 100); imageresolution($img, 200); print_r(imageresolution($img)); imageresolution($img, 300, 72); print_r(imageresolution($img)); ?> Array ( [0] => 200 [1] => 200 ) Array ( [0] => 300 [1] => 72 ) <?php // Load the png image using imagecreatefrompng() function $img = imagecreatefrompng('C:\xampp\htdocs\Images\img34.png'); // Set the image resolution imageresolution($img, 300, 100); // Get the image resolution $imageresolution = imageresolution($img); print("<pre>".print_r($imageresolution, true)."</pre>"); ?> Array ( [0] => 300 [1] => 100 )
[ { "code": null, "e": 1512, "s": 1187, "text": "imageresoulution() is an inbuilt function in PHP that is used to get or set the resolution of an image in dots per inch. If no optional parameters are given, then the current resolution is returned as an indexed array. If one of the optional parameters is given, then it will set both the width and height to that parameter." }, { "code": null, "e": 1787, "s": 1512, "text": "The resolution is only used as meta information when the images are read from and written to formats supporting this kind of information (currently PNG and JPEG). It does not affect any drawing operations. The 96 DPI (dots per inch) is the default resolution for new images." }, { "code": null, "e": 1850, "s": 1787, "text": "mixed imageresolution(resource $image, int $res_x, int $res_y)" }, { "code": null, "e": 1918, "s": 1850, "text": "imageresolution() accepts three parameters: $image, $res_x, $res_y." }, { "code": null, "e": 1968, "s": 1918, "text": "$image − Specifies the image resource to work on." }, { "code": null, "e": 2018, "s": 1968, "text": "$image − Specifies the image resource to work on." }, { "code": null, "e": 2087, "s": 2018, "text": "$res_x − Specifies the horizontal resolution in dots per inch (DPI)." }, { "code": null, "e": 2156, "s": 2087, "text": "$res_x − Specifies the horizontal resolution in dots per inch (DPI)." }, { "code": null, "e": 2223, "s": 2156, "text": "$res_y − Specifies the vertical resolution in dots per inch (DPI)." }, { "code": null, "e": 2290, "s": 2223, "text": "$res_y − Specifies the vertical resolution in dots per inch (DPI)." }, { "code": null, "e": 2348, "s": 2290, "text": "imageresolution() returns the indexed array of the image." }, { "code": null, "e": 2535, "s": 2348, "text": "<?php\n $img = imagecreatetruecolor(100, 100);\n imageresolution($img, 200);\n print_r(imageresolution($img));\n imageresolution($img, 300, 72);\n print_r(imageresolution($img));\n?>" }, { "code": null, "e": 2610, "s": 2535, "text": "Array\n(\n [0] => 200\n [1] => 200\n)\nArray\n(\n [0] => 300\n [1] => 72\n)" }, { "code": null, "e": 2957, "s": 2610, "text": "<?php\n // Load the png image using imagecreatefrompng() function\n $img = imagecreatefrompng('C:\\xampp\\htdocs\\Images\\img34.png');\n \n // Set the image resolution\n imageresolution($img, 300, 100);\n \n // Get the image resolution\n $imageresolution = imageresolution($img);\n print(\"<pre>\".print_r($imageresolution, true).\"</pre>\");\n?>" }, { "code": null, "e": 2995, "s": 2957, "text": "Array\n(\n [0] => 300\n [1] => 100\n)" } ]
Python | Pandas DataFrame.dtypes
20 Feb, 2019 Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dict-like container for Series objects. This is the primary data structure of the Pandas. Pandas DataFrame.dtypes attribute return the dtypes in the DataFrame. It returns a Series with the data type of each column. Syntax: DataFrame.dtypes Parameter : None Returns : dtype of each column Example #1: Use DataFrame.dtypes attribute to find out the data type (dtype) of each column in the given dataframe. # importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({'Weight':[45, 88, 56, 15, 71], 'Name':['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'], 'Age':[14, 25, 55, 8, 21]}) # Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5'] # Set the indexdf.index = index_ # Print the DataFrameprint(df) Output :Now we will use DataFrame.dtypes attribute to find out the data type of each column in the given dataframe. # return the dtype of each columnresult = df.dtypes # Print the resultprint(result) Output :As we can see in the output, the DataFrame.dtypes attribute has successfully returned the data types of each column in the given dataframe. Example #2: Use DataFrame.dtypes attribute to find out the data type (dtype) of each column in the given dataframe. # importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({"A":[12, 4, 5, None, 1], "B":[7, 2, 54, 3, None], "C":[20, 16, 11, 3, 8], "D":[14, 3, None, 2, 6]}) # Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5'] # Set the indexdf.index = index_ # Print the DataFrameprint(df) Output : Now we will use DataFrame.dtypes attribute to find out the data type of each column in the given dataframe. # return the dtype of each columnresult = df.dtypes # Print the resultprint(result) Output :As we can see in the output, the DataFrame.dtypes attribute has successfully returned the data types of each column in the given dataframe. Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n20 Feb, 2019" }, { "code": null, "e": 367, "s": 53, "text": "Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dict-like container for Series objects. This is the primary data structure of the Pandas." }, { "code": null, "e": 492, "s": 367, "text": "Pandas DataFrame.dtypes attribute return the dtypes in the DataFrame. It returns a Series with the data type of each column." }, { "code": null, "e": 517, "s": 492, "text": "Syntax: DataFrame.dtypes" }, { "code": null, "e": 534, "s": 517, "text": "Parameter : None" }, { "code": null, "e": 565, "s": 534, "text": "Returns : dtype of each column" }, { "code": null, "e": 681, "s": 565, "text": "Example #1: Use DataFrame.dtypes attribute to find out the data type (dtype) of each column in the given dataframe." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({'Weight':[45, 88, 56, 15, 71], 'Name':['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'], 'Age':[14, 25, 55, 8, 21]}) # Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5'] # Set the indexdf.index = index_ # Print the DataFrameprint(df)", "e": 1054, "s": 681, "text": null }, { "code": null, "e": 1170, "s": 1054, "text": "Output :Now we will use DataFrame.dtypes attribute to find out the data type of each column in the given dataframe." }, { "code": "# return the dtype of each columnresult = df.dtypes # Print the resultprint(result)", "e": 1255, "s": 1170, "text": null }, { "code": null, "e": 1519, "s": 1255, "text": "Output :As we can see in the output, the DataFrame.dtypes attribute has successfully returned the data types of each column in the given dataframe. Example #2: Use DataFrame.dtypes attribute to find out the data type (dtype) of each column in the given dataframe." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({\"A\":[12, 4, 5, None, 1], \"B\":[7, 2, 54, 3, None], \"C\":[20, 16, 11, 3, 8], \"D\":[14, 3, None, 2, 6]}) # Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5'] # Set the indexdf.index = index_ # Print the DataFrameprint(df)", "e": 1905, "s": 1519, "text": null }, { "code": null, "e": 1914, "s": 1905, "text": "Output :" }, { "code": null, "e": 2022, "s": 1914, "text": "Now we will use DataFrame.dtypes attribute to find out the data type of each column in the given dataframe." }, { "code": "# return the dtype of each columnresult = df.dtypes # Print the resultprint(result)", "e": 2107, "s": 2022, "text": null }, { "code": null, "e": 2255, "s": 2107, "text": "Output :As we can see in the output, the DataFrame.dtypes attribute has successfully returned the data types of each column in the given dataframe." }, { "code": null, "e": 2279, "s": 2255, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2311, "s": 2279, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 2325, "s": 2311, "text": "Python-pandas" }, { "code": null, "e": 2332, "s": 2325, "text": "Python" } ]
Using htop to Monitor System Processes on Linux
30 Jun, 2021 htop a Linux tool that is used in process-managing and terminal-based system monitoring. It allows real-time monitoring of processes and performs every task to monitor the process in the Linux system. The tool is written in the C programming language by Hisham Muhammad. It displays a complete list of processes running on the system and gives information on CPU use, memory and Processor. With the help of htop, we can sort the processes depending on CPU, memory use, and processes run by the user. There are various commands and options available for the htop command. Ubuntu/Linux $ sudo apt-get install htop CentOS/RedHat/Fedora sudo dnf install htop Mac brew install htop From source file To install the latest version of htop you can download the tarball file from here. To extract the tarball file use the command, htop.tar.gz is the name of the file you download. tar -zxvf htop.tar.gz Go to the extracted htop directory using cd. cd htop To compile htop execute these commands ./configure make sudo make install After we’re done with the installation of htop tool, we can now launch it by entering htop command in the terminal. In the topmost left corner, CPU usage is depicted by percentages using different color bars for different types of processes, and the core of the CPU is denoted by the number of bars. Two Modes of CPU Metric are Default Mode Detailed Mode Color denotation for Default Mode is given in the following: Blue: Low priority thread (nice > 0) Green: Normal Priority thread (for users) Red: Kernel Thread (kernel, iowait) Orange: Virt time (steal time + guest time) Memory Usage and Swap are present below the CPU Usage bars. It displays the amount of memory consumed by processes. Green: RAM Consumption by Memory Pages Blue: RAM Consumption by Buffer Pages Orange: RAM Consumption by Cache Pages Tasks, Threads, Running Processes, Load Average, and Uptime are shown in the system which is present next to the color bars. Tasks – Shows the number of open processes present in the system. Here it displays 3 values that include the total number of tasks (77), the number of threads (147 thr), and the number of tasks currently running (1 running). Load Average – Shows the average load of the system by CPU. Three average load numbers are displayed: Average load of system for last 1 minute (0.13), average load of the system for last 5 minutes (0.49), average load of system for last 15 minutes (0.57) Uptime – Total system uptime from the last reboot. Customizations are done in htop setup menu and to access the menu press F2. There are four categories where you can customize the top menu: Setup, Left Column, Right Column, and Available Meters. They are used to configure meters, set display options, set color patterns and choose the columns to print them in order. Display Options Customizing display using htop command by pressing F2 and then navigate to display options. In the settings we have chosen highlight new and old processes where it’ll separate all the old and new processes and display them. By navigating to the display column we can change the display options for htop terminal, here we have changes the color of the terminal to black night. On htop, you can scroll horizontally and vertically with the help of “Up and Down” and “Left and Right” keys to scroll through processes. Kill process using htop: Select the process and press F9 or k to display the signal menu where there is a list of signals for the process. Then choose “SIGKILL” to kill the chosen process and press enter. Here we kill the signal with PID 1989. To multiple processes select a process and click the spacebar which will tag the selected process. After that, the changed tag of the process will change the colour and then scroll through the list to tag multiple processes. Press F9 to kill all tagged process. Note: Press space bar to untag specific tagged process and press U to untag all tagged processes Output Sorting: In this menu, it has different options to sort the output and to display output options press the F6 key, then, select the criteria as per your choice to sort the output by default it is set PERCENT_CPU For PERCENT_MEM sorting, choose the option and hit enter. Process in tree format: We can display the process in tree-like order or hierarchical order by creating a parent-child relationship. To do so, press F5. Filter processes: To filter the process,Here press F4 function key. You have to enter the path in the footer section where you’re prompted to give the input by providing the path i.e “/usr/bin” Search Processes: Press F3 key to search through processes and type the name in the search prompt. Here we will search for ryslogd process in /usr/bin path. After searching, it will be highlighted in yellow. To check what other shortcuts are available for the htop command, then you can press F1 key, then a list of key options will be displayed. linux-command Linux-system-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples chown command in Linux with Examples SED command in Linux | Set 2 mv command in Linux with examples nohup Command in Linux with Examples chmod command in Linux with examples Introduction to Linux Operating System Array Basics in Shell Scripting | Set 1 Basic Operators in Shell Scripting
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2021" }, { "code": null, "e": 600, "s": 28, "text": "htop a Linux tool that is used in process-managing and terminal-based system monitoring. It allows real-time monitoring of processes and performs every task to monitor the process in the Linux system. The tool is written in the C programming language by Hisham Muhammad. It displays a complete list of processes running on the system and gives information on CPU use, memory and Processor. With the help of htop, we can sort the processes depending on CPU, memory use, and processes run by the user. There are various commands and options available for the htop command. " }, { "code": null, "e": 613, "s": 600, "text": "Ubuntu/Linux" }, { "code": null, "e": 641, "s": 613, "text": "$ sudo apt-get install htop" }, { "code": null, "e": 662, "s": 641, "text": "CentOS/RedHat/Fedora" }, { "code": null, "e": 684, "s": 662, "text": "sudo dnf install htop" }, { "code": null, "e": 688, "s": 684, "text": "Mac" }, { "code": null, "e": 706, "s": 688, "text": "brew install htop" }, { "code": null, "e": 724, "s": 706, "text": "From source file " }, { "code": null, "e": 902, "s": 724, "text": "To install the latest version of htop you can download the tarball file from here. To extract the tarball file use the command, htop.tar.gz is the name of the file you download." }, { "code": null, "e": 924, "s": 902, "text": "tar -zxvf htop.tar.gz" }, { "code": null, "e": 969, "s": 924, "text": "Go to the extracted htop directory using cd." }, { "code": null, "e": 977, "s": 969, "text": "cd htop" }, { "code": null, "e": 1016, "s": 977, "text": "To compile htop execute these commands" }, { "code": null, "e": 1051, "s": 1016, "text": "./configure\nmake\nsudo make install" }, { "code": null, "e": 1167, "s": 1051, "text": "After we’re done with the installation of htop tool, we can now launch it by entering htop command in the terminal." }, { "code": null, "e": 1380, "s": 1167, "text": " In the topmost left corner, CPU usage is depicted by percentages using different color bars for different types of processes, and the core of the CPU is denoted by the number of bars. Two Modes of CPU Metric are" }, { "code": null, "e": 1393, "s": 1380, "text": "Default Mode" }, { "code": null, "e": 1407, "s": 1393, "text": "Detailed Mode" }, { "code": null, "e": 1468, "s": 1407, "text": "Color denotation for Default Mode is given in the following:" }, { "code": null, "e": 1505, "s": 1468, "text": "Blue: Low priority thread (nice > 0)" }, { "code": null, "e": 1547, "s": 1505, "text": "Green: Normal Priority thread (for users)" }, { "code": null, "e": 1583, "s": 1547, "text": "Red: Kernel Thread (kernel, iowait)" }, { "code": null, "e": 1627, "s": 1583, "text": "Orange: Virt time (steal time + guest time)" }, { "code": null, "e": 1744, "s": 1627, "text": "Memory Usage and Swap are present below the CPU Usage bars. It displays the amount of memory consumed by processes. " }, { "code": null, "e": 1783, "s": 1744, "text": "Green: RAM Consumption by Memory Pages" }, { "code": null, "e": 1821, "s": 1783, "text": "Blue: RAM Consumption by Buffer Pages" }, { "code": null, "e": 1860, "s": 1821, "text": "Orange: RAM Consumption by Cache Pages" }, { "code": null, "e": 1985, "s": 1860, "text": "Tasks, Threads, Running Processes, Load Average, and Uptime are shown in the system which is present next to the color bars." }, { "code": null, "e": 2211, "s": 1985, "text": "Tasks – Shows the number of open processes present in the system. Here it displays 3 values that include the total number of tasks (77), the number of threads (147 thr), and the number of tasks currently running (1 running)." }, { "code": null, "e": 2468, "s": 2211, "text": "Load Average – Shows the average load of the system by CPU. Three average load numbers are displayed: Average load of system for last 1 minute (0.13), average load of the system for last 5 minutes (0.49), average load of system for last 15 minutes (0.57) " }, { "code": null, "e": 2519, "s": 2468, "text": "Uptime – Total system uptime from the last reboot." }, { "code": null, "e": 2837, "s": 2519, "text": "Customizations are done in htop setup menu and to access the menu press F2. There are four categories where you can customize the top menu: Setup, Left Column, Right Column, and Available Meters. They are used to configure meters, set display options, set color patterns and choose the columns to print them in order." }, { "code": null, "e": 2853, "s": 2837, "text": "Display Options" }, { "code": null, "e": 3078, "s": 2853, "text": "Customizing display using htop command by pressing F2 and then navigate to display options. In the settings we have chosen highlight new and old processes where it’ll separate all the old and new processes and display them. " }, { "code": null, "e": 3230, "s": 3078, "text": "By navigating to the display column we can change the display options for htop terminal, here we have changes the color of the terminal to black night." }, { "code": null, "e": 3369, "s": 3230, "text": "On htop, you can scroll horizontally and vertically with the help of “Up and Down” and “Left and Right” keys to scroll through processes. " }, { "code": null, "e": 3875, "s": 3369, "text": "Kill process using htop: Select the process and press F9 or k to display the signal menu where there is a list of signals for the process. Then choose “SIGKILL” to kill the chosen process and press enter. Here we kill the signal with PID 1989. To multiple processes select a process and click the spacebar which will tag the selected process. After that, the changed tag of the process will change the colour and then scroll through the list to tag multiple processes. Press F9 to kill all tagged process." }, { "code": null, "e": 3972, "s": 3875, "text": "Note: Press space bar to untag specific tagged process and press U to untag all tagged processes" }, { "code": null, "e": 4191, "s": 3972, "text": "Output Sorting: In this menu, it has different options to sort the output and to display output options press the F6 key, then, select the criteria as per your choice to sort the output by default it is set PERCENT_CPU" }, { "code": null, "e": 4249, "s": 4191, "text": "For PERCENT_MEM sorting, choose the option and hit enter." }, { "code": null, "e": 4402, "s": 4249, "text": "Process in tree format: We can display the process in tree-like order or hierarchical order by creating a parent-child relationship. To do so, press F5." }, { "code": null, "e": 4596, "s": 4402, "text": "Filter processes: To filter the process,Here press F4 function key. You have to enter the path in the footer section where you’re prompted to give the input by providing the path i.e “/usr/bin”" }, { "code": null, "e": 4805, "s": 4596, "text": "Search Processes: Press F3 key to search through processes and type the name in the search prompt. Here we will search for ryslogd process in /usr/bin path. After searching, it will be highlighted in yellow." }, { "code": null, "e": 4945, "s": 4805, "text": "To check what other shortcuts are available for the htop command, then you can press F1 key, then a list of key options will be displayed. " }, { "code": null, "e": 4959, "s": 4945, "text": "linux-command" }, { "code": null, "e": 4981, "s": 4959, "text": "Linux-system-commands" }, { "code": null, "e": 4988, "s": 4981, "text": "Picked" }, { "code": null, "e": 4999, "s": 4988, "text": "Linux-Unix" }, { "code": null, "e": 5097, "s": 4999, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5123, "s": 5097, "text": "Docker - COPY Instruction" }, { "code": null, "e": 5158, "s": 5123, "text": "scp command in Linux with Examples" }, { "code": null, "e": 5195, "s": 5158, "text": "chown command in Linux with Examples" }, { "code": null, "e": 5224, "s": 5195, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 5258, "s": 5224, "text": "mv command in Linux with examples" }, { "code": null, "e": 5295, "s": 5258, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 5332, "s": 5295, "text": "chmod command in Linux with examples" }, { "code": null, "e": 5371, "s": 5332, "text": "Introduction to Linux Operating System" }, { "code": null, "e": 5411, "s": 5371, "text": "Array Basics in Shell Scripting | Set 1" } ]
Python | Separate odd and even index elements
20 May, 2021 Python list are quite popular and no matter what type of field one is coding, one has to deal with lists and its various applications. In this particular article, we discuss ways to separate odd and even indexed elements and its reconstruction join. Let’s discuss ways to achieve this. Method #1 : Using Naive methodUsing Naive method, this task can be performed by using the loops. One can use two containers one each to store alternate elements and later joining them. Python3 # Python3 code to demonstrate# Separating odd and even index elements# using naive method # initializing listtest_list = [3, 6, 7, 8, 9, 2, 1, 5] # printing original listprint("The original list : " + str(test_list)) # using naive method# Separating odd and even index elementsodd_i = []even_i = []for i in range(0, len(test_list)): if i % 2: even_i.append(test_list[i]) else : odd_i.append(test_list[i]) res = odd_i + even_i # print resultprint("Separated odd and even index list: " + str(res)) The original list : [3, 6, 7, 8, 9, 2, 1, 5] Separated odd and even index list: [3, 7, 9, 1, 6, 8, 2, 5] Method #2 : Using list slicing This particular task can be easily performed using the list slicing method in a more compact and efficient manner, this is a recommended method to solve this problem. Python3 # Python3 code to demonstrate# Separating odd and even index elements# Using list slicing # initializing listtest_list = [3, 6, 7, 8, 9, 2, 1, 5] # printing original listprint("The original list : " + str(test_list)) # Using list slicing# Separating odd and even index elementsres = test_list[::2] + test_list[1::2] # print resultprint("Separated odd and even index list : " + str(res)) The original list : [3, 6, 7, 8, 9, 2, 1, 5] Separated odd and even index list : [3, 7, 9, 1, 6, 8, 2, 5] akshaysingh98088 Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n20 May, 2021" }, { "code": null, "e": 341, "s": 54, "text": "Python list are quite popular and no matter what type of field one is coding, one has to deal with lists and its various applications. In this particular article, we discuss ways to separate odd and even indexed elements and its reconstruction join. Let’s discuss ways to achieve this. " }, { "code": null, "e": 526, "s": 341, "text": "Method #1 : Using Naive methodUsing Naive method, this task can be performed by using the loops. One can use two containers one each to store alternate elements and later joining them." }, { "code": null, "e": 534, "s": 526, "text": "Python3" }, { "code": "# Python3 code to demonstrate# Separating odd and even index elements# using naive method # initializing listtest_list = [3, 6, 7, 8, 9, 2, 1, 5] # printing original listprint(\"The original list : \" + str(test_list)) # using naive method# Separating odd and even index elementsodd_i = []even_i = []for i in range(0, len(test_list)): if i % 2: even_i.append(test_list[i]) else : odd_i.append(test_list[i]) res = odd_i + even_i # print resultprint(\"Separated odd and even index list: \" + str(res))", "e": 1050, "s": 534, "text": null }, { "code": null, "e": 1155, "s": 1050, "text": "The original list : [3, 6, 7, 8, 9, 2, 1, 5]\nSeparated odd and even index list: [3, 7, 9, 1, 6, 8, 2, 5]" }, { "code": null, "e": 1354, "s": 1155, "text": " Method #2 : Using list slicing This particular task can be easily performed using the list slicing method in a more compact and efficient manner, this is a recommended method to solve this problem." }, { "code": null, "e": 1362, "s": 1354, "text": "Python3" }, { "code": "# Python3 code to demonstrate# Separating odd and even index elements# Using list slicing # initializing listtest_list = [3, 6, 7, 8, 9, 2, 1, 5] # printing original listprint(\"The original list : \" + str(test_list)) # Using list slicing# Separating odd and even index elementsres = test_list[::2] + test_list[1::2] # print resultprint(\"Separated odd and even index list : \" + str(res))", "e": 1749, "s": 1362, "text": null }, { "code": null, "e": 1855, "s": 1749, "text": "The original list : [3, 6, 7, 8, 9, 2, 1, 5]\nSeparated odd and even index list : [3, 7, 9, 1, 6, 8, 2, 5]" }, { "code": null, "e": 1872, "s": 1855, "text": "akshaysingh98088" }, { "code": null, "e": 1893, "s": 1872, "text": "Python list-programs" }, { "code": null, "e": 1900, "s": 1893, "text": "Python" }, { "code": null, "e": 1916, "s": 1900, "text": "Python Programs" } ]
Build a Simple static file web server in Node.js
14 Oct, 2021 In this article, we will build a static file web server which will list out all the files in the directory and on clicking the file name it displays the file content. Steps for creating a static file server is as follows: Step 1: Importing necessary modules, and defining MIME types which helps browser to understand the type of file that is being sent. Javascript // Importing necessary modulesconst http = require('http');const url = require('url');const fs = require('fs');const path = require('path'); // Port on which the server will createconst PORT = 1800; // Maps file extension to MIME types which// helps the browser to understand what to// do with the fileconst mimeType = { '.ico': 'image/x-icon', '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.css': 'text/css', '.png': 'image/png', '.jpg': 'image/jpeg', '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.svg': 'image/svg+xml', '.pdf': 'application/pdf', '.doc': 'application/msword', '.eot': 'application/vnd.ms-fontobject', '.ttf': 'application/font-sfnt'}; Step 2: Creating a server at the port specified (say 1800). Javascript // Creating a server and listening the port 1800http.createServer( (req, res) => { }).listen(PORT); Step 3: We will respond the URL “/” to list all the files in the directory. We will limit this article to the current working directory only. Add the below code to the server’s function call. Javascript // Parsing the requested URLconst parsedUrl = url.parse(req.url); // If requested url is "/" like "http://localhost:8100/"if(parsedUrl.pathname==="/") { var filesLink="<ul>"; res.setHeader('Content-type', 'text/html'); var filesList=fs.readdirSync("./"); filesList.forEach(element => { if(fs.statSync("./"+element).isFile()) { filesLink +=`<br/><li><a href='./${element}'> ${element} </a></li>` ; } }); filesLink+="</ul>"; res.end("<h1>List of files:</h1> " + filesLink);} Step 4: Preprocessing the requested file pathname to avoid directory traversal (like http://localhost:1800/../fileOutofContext.txt) by replacing ‘../’ with ‘ ’. Javascript /* processing the requested file pathname toavoid directory traversal like,http://localhost:1800/../fileOutofContext.txtby limiting to the current directory only */const sanitizePath = path.normalize(parsedUrl.pathname).replace(/^(\.\.[\/\\])+/, ''); let pathname = path.join(__dirname, sanitizePath); Step 5: Finally, check whether the file exists. If exists then send the file with the proper header ‘Content-type’ having value as per the file extension mapped with the MIME type above. Else if not exist then send File not found! with 404 status code. Javascript if(!fs.existsSync(pathname)) { // If the file is not found, return 404 res.statusCode = 404; res.end(`File ${pathname} not found!`);}else { // Read file from file system limit to the // current directory only. fs.readFile(pathname, function(err, data) { if(err) { res.statusCode = 500; res.end(`Error in getting the file.`); } else { // Based on the URL path, extract the file // extension. Ex .js, .doc, ... const ext = path.parse(pathname).ext; // If the file is found, set Content-type // and send data res.setHeader('Content-type', mimeType[ext] || 'text/plain' ); res.end(data); } });} Complete Code: Javascript /* Node.js static file web server */ // Importing necessary modulesconst http = require('http');const url = require('url');const fs = require('fs');const path = require('path'); // Port on which the server will createconst PORT = 1800; // Maps file extension to MIME types which// helps browser to understand what to do// with the fileconst mimeType = { '.ico': 'image/x-icon', '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.css': 'text/css', '.png': 'image/png', '.jpg': 'image/jpeg', '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.svg': 'image/svg+xml', '.pdf': 'application/pdf', '.doc': 'application/msword', '.eot': 'application/vnd.ms-fontobject', '.ttf': 'application/font-sfnt'}; // Creating a server and listening at port 1800http.createServer( (req, res) => { // Parsing the requested URL const parsedUrl = url.parse(req.url); // If requested url is "/" like "http://localhost:1800/" if(parsedUrl.pathname==="/"){ var filesLink="<ul>"; res.setHeader('Content-type', 'text/html'); var filesList=fs.readdirSync("./"); filesList.forEach(element => { if(fs.statSync("./"+element).isFile()){ filesLink+=`<br/><li><a href='./${element}'> ${element} </a></li>` ; } }); filesLink+="</ul>"; res.end("<h1>List of files:</h1> " + filesLink); } /* Processing the requested file pathname to avoid directory traversal like, http://localhost:1800/../fileOutofContext.txt by limiting to the current directory only. */ const sanitizePath = path.normalize(parsedUrl.pathname).replace(/^(\.\.[\/\\])+/, ''); let pathname = path.join(__dirname, sanitizePath); if(!fs.existsSync(pathname)) { // If the file is not found, return 404 res.statusCode = 404; res.end(`File ${pathname} not found!`); } else { // Read file from file system limit to // the current directory only. fs.readFile(pathname, function(err, data) { if(err){ res.statusCode = 500; res.end(`Error in getting the file.`); } else { // Based on the URL path, extract the // file extension. Ex .js, .doc, ... const ext = path.parse(pathname).ext; // If the file is found, set Content-type // and send data res.setHeader('Content-type', mimeType[ext] || 'text/plain' ); res.end(data); } }); }}).listen(PORT); console.log(`Server listening on port ${PORT}`); Output simmytarika5 arorakashish0911 Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.writeFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js Mongoose | findByIdAndUpdate() Function JWT Authentication with Node.js 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 ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Oct, 2021" }, { "code": null, "e": 250, "s": 28, "text": "In this article, we will build a static file web server which will list out all the files in the directory and on clicking the file name it displays the file content. Steps for creating a static file server is as follows:" }, { "code": null, "e": 382, "s": 250, "text": "Step 1: Importing necessary modules, and defining MIME types which helps browser to understand the type of file that is being sent." }, { "code": null, "e": 393, "s": 382, "text": "Javascript" }, { "code": "// Importing necessary modulesconst http = require('http');const url = require('url');const fs = require('fs');const path = require('path'); // Port on which the server will createconst PORT = 1800; // Maps file extension to MIME types which// helps the browser to understand what to// do with the fileconst mimeType = { '.ico': 'image/x-icon', '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.css': 'text/css', '.png': 'image/png', '.jpg': 'image/jpeg', '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.svg': 'image/svg+xml', '.pdf': 'application/pdf', '.doc': 'application/msword', '.eot': 'application/vnd.ms-fontobject', '.ttf': 'application/font-sfnt'};", "e": 1124, "s": 393, "text": null }, { "code": null, "e": 1184, "s": 1124, "text": "Step 2: Creating a server at the port specified (say 1800)." }, { "code": null, "e": 1195, "s": 1184, "text": "Javascript" }, { "code": "// Creating a server and listening the port 1800http.createServer( (req, res) => { }).listen(PORT);", "e": 1296, "s": 1195, "text": null }, { "code": null, "e": 1488, "s": 1296, "text": "Step 3: We will respond the URL “/” to list all the files in the directory. We will limit this article to the current working directory only. Add the below code to the server’s function call." }, { "code": null, "e": 1499, "s": 1488, "text": "Javascript" }, { "code": "// Parsing the requested URLconst parsedUrl = url.parse(req.url); // If requested url is \"/\" like \"http://localhost:8100/\"if(parsedUrl.pathname===\"/\") { var filesLink=\"<ul>\"; res.setHeader('Content-type', 'text/html'); var filesList=fs.readdirSync(\"./\"); filesList.forEach(element => { if(fs.statSync(\"./\"+element).isFile()) { filesLink +=`<br/><li><a href='./${element}'> ${element} </a></li>` ; } }); filesLink+=\"</ul>\"; res.end(\"<h1>List of files:</h1> \" + filesLink);}", "e": 2065, "s": 1499, "text": null }, { "code": null, "e": 2226, "s": 2065, "text": "Step 4: Preprocessing the requested file pathname to avoid directory traversal (like http://localhost:1800/../fileOutofContext.txt) by replacing ‘../’ with ‘ ’." }, { "code": null, "e": 2237, "s": 2226, "text": "Javascript" }, { "code": "/* processing the requested file pathname toavoid directory traversal like,http://localhost:1800/../fileOutofContext.txtby limiting to the current directory only */const sanitizePath = path.normalize(parsedUrl.pathname).replace(/^(\\.\\.[\\/\\\\])+/, ''); let pathname = path.join(__dirname, sanitizePath);", "e": 2540, "s": 2237, "text": null }, { "code": null, "e": 2793, "s": 2540, "text": "Step 5: Finally, check whether the file exists. If exists then send the file with the proper header ‘Content-type’ having value as per the file extension mapped with the MIME type above. Else if not exist then send File not found! with 404 status code." }, { "code": null, "e": 2804, "s": 2793, "text": "Javascript" }, { "code": "if(!fs.existsSync(pathname)) { // If the file is not found, return 404 res.statusCode = 404; res.end(`File ${pathname} not found!`);}else { // Read file from file system limit to the // current directory only. fs.readFile(pathname, function(err, data) { if(err) { res.statusCode = 500; res.end(`Error in getting the file.`); } else { // Based on the URL path, extract the file // extension. Ex .js, .doc, ... const ext = path.parse(pathname).ext; // If the file is found, set Content-type // and send data res.setHeader('Content-type', mimeType[ext] || 'text/plain' ); res.end(data); } });}", "e": 3605, "s": 2804, "text": null }, { "code": null, "e": 3621, "s": 3605, "text": "Complete Code: " }, { "code": null, "e": 3632, "s": 3621, "text": "Javascript" }, { "code": "/* Node.js static file web server */ // Importing necessary modulesconst http = require('http');const url = require('url');const fs = require('fs');const path = require('path'); // Port on which the server will createconst PORT = 1800; // Maps file extension to MIME types which// helps browser to understand what to do// with the fileconst mimeType = { '.ico': 'image/x-icon', '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.css': 'text/css', '.png': 'image/png', '.jpg': 'image/jpeg', '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.svg': 'image/svg+xml', '.pdf': 'application/pdf', '.doc': 'application/msword', '.eot': 'application/vnd.ms-fontobject', '.ttf': 'application/font-sfnt'}; // Creating a server and listening at port 1800http.createServer( (req, res) => { // Parsing the requested URL const parsedUrl = url.parse(req.url); // If requested url is \"/\" like \"http://localhost:1800/\" if(parsedUrl.pathname===\"/\"){ var filesLink=\"<ul>\"; res.setHeader('Content-type', 'text/html'); var filesList=fs.readdirSync(\"./\"); filesList.forEach(element => { if(fs.statSync(\"./\"+element).isFile()){ filesLink+=`<br/><li><a href='./${element}'> ${element} </a></li>` ; } }); filesLink+=\"</ul>\"; res.end(\"<h1>List of files:</h1> \" + filesLink); } /* Processing the requested file pathname to avoid directory traversal like, http://localhost:1800/../fileOutofContext.txt by limiting to the current directory only. */ const sanitizePath = path.normalize(parsedUrl.pathname).replace(/^(\\.\\.[\\/\\\\])+/, ''); let pathname = path.join(__dirname, sanitizePath); if(!fs.existsSync(pathname)) { // If the file is not found, return 404 res.statusCode = 404; res.end(`File ${pathname} not found!`); } else { // Read file from file system limit to // the current directory only. fs.readFile(pathname, function(err, data) { if(err){ res.statusCode = 500; res.end(`Error in getting the file.`); } else { // Based on the URL path, extract the // file extension. Ex .js, .doc, ... const ext = path.parse(pathname).ext; // If the file is found, set Content-type // and send data res.setHeader('Content-type', mimeType[ext] || 'text/plain' ); res.end(data); } }); }}).listen(PORT); console.log(`Server listening on port ${PORT}`);", "e": 6469, "s": 3632, "text": null }, { "code": null, "e": 6477, "s": 6469, "text": "Output " }, { "code": null, "e": 6494, "s": 6481, "text": "simmytarika5" }, { "code": null, "e": 6511, "s": 6494, "text": "arorakashish0911" }, { "code": null, "e": 6518, "s": 6511, "text": "Picked" }, { "code": null, "e": 6526, "s": 6518, "text": "Node.js" }, { "code": null, "e": 6543, "s": 6526, "text": "Web Technologies" }, { "code": null, "e": 6641, "s": 6543, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6671, "s": 6641, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 6728, "s": 6671, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 6782, "s": 6728, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 6822, "s": 6782, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 6854, "s": 6822, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 6916, "s": 6854, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 6977, "s": 6916, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 7027, "s": 6977, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 7070, "s": 7027, "text": "How to fetch data from an API in ReactJS ?" } ]
How to use flex to shrink an image in CSS ?
30 Jul, 2021 You can easily shrink an image by using the flex-wrap property in CSS and it specifies whether flex items are forced into a single line or wrapped onto multiple lines. The flex-wrap property allows enabling the control direction in which lines are stacked. It is used to designate a single line or multi-line format to flex items inside the flex container. Syntax: flex-wrap: wrap Note: wrap is used to break the flex item into multiples lines. It makes flex items wrap to multiple lines according to flex item width. Example: In order to shrink the image, you have to make the width of the image to 100%, so that image occupies 100% of the size of the <div>. HTML <!DOCTYPE html><html> <head> <style> .container { display: -webkit-flex; -webkit-flex-wrap: wrap; display: flex; flex-wrap: wrap; background-color: grey; } img { width: 100%; } div { flex: 1; padding: 10px; margin: 10px; } </style></head> <body> <div class="container"> <div class="image"> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" /> </div> <div class="image"> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" /> </div> <div class="image"> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" /> </div> </div></body> </html> Output: flex-wrap property CSS-Properties CSS-Questions HTML-Questions Picked CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Design a web page using HTML and CSS Form validation using jQuery REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jul, 2021" }, { "code": null, "e": 386, "s": 28, "text": "You can easily shrink an image by using the flex-wrap property in CSS and it specifies whether flex items are forced into a single line or wrapped onto multiple lines. The flex-wrap property allows enabling the control direction in which lines are stacked. It is used to designate a single line or multi-line format to flex items inside the flex container. " }, { "code": null, "e": 394, "s": 386, "text": "Syntax:" }, { "code": null, "e": 410, "s": 394, "text": "flex-wrap: wrap" }, { "code": null, "e": 547, "s": 410, "text": "Note: wrap is used to break the flex item into multiples lines. It makes flex items wrap to multiple lines according to flex item width." }, { "code": null, "e": 689, "s": 547, "text": "Example: In order to shrink the image, you have to make the width of the image to 100%, so that image occupies 100% of the size of the <div>." }, { "code": null, "e": 694, "s": 689, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> .container { display: -webkit-flex; -webkit-flex-wrap: wrap; display: flex; flex-wrap: wrap; background-color: grey; } img { width: 100%; } div { flex: 1; padding: 10px; margin: 10px; } </style></head> <body> <div class=\"container\"> <div class=\"image\"> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\" /> </div> <div class=\"image\"> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\" /> </div> <div class=\"image\"> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\" /> </div> </div></body> </html>", "e": 1596, "s": 694, "text": null }, { "code": null, "e": 1604, "s": 1596, "text": "Output:" }, { "code": null, "e": 1623, "s": 1604, "text": "flex-wrap property" }, { "code": null, "e": 1638, "s": 1623, "text": "CSS-Properties" }, { "code": null, "e": 1652, "s": 1638, "text": "CSS-Questions" }, { "code": null, "e": 1667, "s": 1652, "text": "HTML-Questions" }, { "code": null, "e": 1674, "s": 1667, "text": "Picked" }, { "code": null, "e": 1678, "s": 1674, "text": "CSS" }, { "code": null, "e": 1683, "s": 1678, "text": "HTML" }, { "code": null, "e": 1700, "s": 1683, "text": "Web Technologies" }, { "code": null, "e": 1705, "s": 1700, "text": "HTML" }, { "code": null, "e": 1803, "s": 1705, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1842, "s": 1803, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 1881, "s": 1842, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 1920, "s": 1881, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 1957, "s": 1920, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 1986, "s": 1957, "text": "Form validation using jQuery" }, { "code": null, "e": 2010, "s": 1986, "text": "REST API (Introduction)" }, { "code": null, "e": 2063, "s": 2010, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2123, "s": 2063, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 2184, "s": 2123, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Working with BigDecimal values in Java
The java.math.BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion. Two types of operations are provided for manipulating the scale of a BigDecimal − scaling/rounding operations decimal point motion operations The following are some of the constructors of the BigDecimal values − The following is an example − Live Demo import java.math.BigDecimal; public class Demo { public static void main(String[] argv) throws Exception { BigDecimal val1 = new BigDecimal("37578975.8768"); BigDecimal val2 = new BigDecimal("62567878.9768"); BigDecimal val3 = new BigDecimal("72567874.3768"); System.out.println("Value 1 : "+val1); System.out.println("Value 2 : "+val2); val1 = val1.add(val2); System.out.println("Addition Operation = " + val1); val1 = val1.multiply(val2); System.out.println("Multiplication Operation = " + val1); val2 = val3.subtract(val2); System.out.println("Subtract Operation = " + val2); val2 = val3.divide(val2,BigDecimal.ROUND_UP); System.out.println("Division Operation = " + val2); } } Value 1 : 37578975.8768 Value 2 : 62567878.9768 Addition Operation = 100146854.8536 Multiplication Operation = 6265976294387200.48179648 Subtract Operation = 9999995.4000 Division Operation = 7.2568
[ { "code": null, "e": 1203, "s": 1062, "text": "The java.math.BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion." }, { "code": null, "e": 1285, "s": 1203, "text": "Two types of operations are provided for manipulating the scale of a BigDecimal −" }, { "code": null, "e": 1313, "s": 1285, "text": "scaling/rounding operations" }, { "code": null, "e": 1345, "s": 1313, "text": "decimal point motion operations" }, { "code": null, "e": 1415, "s": 1345, "text": "The following are some of the constructors of the BigDecimal values −" }, { "code": null, "e": 1445, "s": 1415, "text": "The following is an example −" }, { "code": null, "e": 1456, "s": 1445, "text": " Live Demo" }, { "code": null, "e": 2221, "s": 1456, "text": "import java.math.BigDecimal;\npublic class Demo {\n public static void main(String[] argv) throws Exception {\n BigDecimal val1 = new BigDecimal(\"37578975.8768\");\n BigDecimal val2 = new BigDecimal(\"62567878.9768\");\n BigDecimal val3 = new BigDecimal(\"72567874.3768\");\n System.out.println(\"Value 1 : \"+val1);\n System.out.println(\"Value 2 : \"+val2);\n val1 = val1.add(val2);\n System.out.println(\"Addition Operation = \" + val1);\n val1 = val1.multiply(val2);\n System.out.println(\"Multiplication Operation = \" + val1);\n val2 = val3.subtract(val2);\n System.out.println(\"Subtract Operation = \" + val2);\n val2 = val3.divide(val2,BigDecimal.ROUND_UP);\n System.out.println(\"Division Operation = \" + val2);\n }\n}" }, { "code": null, "e": 2420, "s": 2221, "text": "Value 1 : 37578975.8768\nValue 2 : 62567878.9768\nAddition Operation = 100146854.8536\nMultiplication Operation = 6265976294387200.48179648\nSubtract Operation = 9999995.4000\nDivision Operation = 7.2568" } ]
Spring Declarative Transaction Management
Declarative transaction management approach allows you to manage the transaction with the help of configuration instead of hard coding in your source code. This means that you can separate transaction management from the business code. You only use annotations or XML-based configuration to manage the transactions. The bean configuration will specify the methods to be transactional. Here are the steps associated with declarative transaction − We use <tx:advice /> tag, which creates a transaction-handling advice and at the same time we define a pointcut that matches all methods we wish to make transaction and reference the transactional advice. We use <tx:advice /> tag, which creates a transaction-handling advice and at the same time we define a pointcut that matches all methods we wish to make transaction and reference the transactional advice. If a method name has been included in the transactional configuration, then the created advice will begin the transaction before calling the method. If a method name has been included in the transactional configuration, then the created advice will begin the transaction before calling the method. Target method will be executed in a try / catch block. Target method will be executed in a try / catch block. If the method finishes normally, the AOP advice commits the transaction successfully otherwise it performs a rollback. If the method finishes normally, the AOP advice commits the transaction successfully otherwise it performs a rollback. Let us see how the above-mentioned steps work but before we begin, it is important to have at least two database tables on which we can perform various CRUD operations with the help of transactions. Let us take a Student table, which can be created in MySQL TEST database with the following DDL − CREATE TABLE Student( ID INT NOT NULL AUTO_INCREMENT, NAME VARCHAR(20) NOT NULL, AGE INT NOT NULL, PRIMARY KEY (ID) ); Second table is Marks in which we will maintain marks for the students based on years. Here SID is the foreign key for the Student table. CREATE TABLE Marks( SID INT NOT NULL, MARKS INT NOT NULL, YEAR INT NOT NULL ); Now, let us write our Spring JDBC application which will implement simple operations on the Student and Marks tables. Let us have a working Eclipse IDE in place and take the following steps to create a Spring application − Following is the content of the Data Access Object interface file StudentDAO.java package com.tutorialspoint; import java.util.List; import javax.sql.DataSource; public interface StudentDAO { /** * This is the method to be used to initialize * database resources ie. connection. */ public void setDataSource(DataSource ds); /** * This is the method to be used to create * a record in the Student and Marks tables. */ public void create(String name, Integer age, Integer marks, Integer year); /** * This is the method to be used to list down * all the records from the Student and Marks tables. */ public List<StudentMarks> listStudents(); } Following is the content of the StudentMarks.java file package com.tutorialspoint; public class StudentMarks { private Integer age; private String name; private Integer id; private Integer marks; private Integer year; private Integer sid; public void setAge(Integer age) { this.age = age; } public Integer getAge() { return age; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setId(Integer id) { this.id = id; } public Integer getId() { return id; } public void setMarks(Integer marks) { this.marks = marks; } public Integer getMarks() { return marks; } public void setYear(Integer year) { this.year = year; } public Integer getYear() { return year; } public void setSid(Integer sid) { this.sid = sid; } public Integer getSid() { return sid; } } Following is the content of the StudentMarksMapper.java file package com.tutorialspoint; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; public class StudentMarksMapper implements RowMapper<StudentMarks> { public StudentMarks mapRow(ResultSet rs, int rowNum) throws SQLException { StudentMarks studentMarks = new StudentMarks(); studentMarks.setId(rs.getInt("id")); studentMarks.setName(rs.getString("name")); studentMarks.setAge(rs.getInt("age")); studentMarks.setSid(rs.getInt("sid")); studentMarks.setMarks(rs.getInt("marks")); studentMarks.setYear(rs.getInt("year")); return studentMarks; } } Following is the implementation class file StudentJDBCTemplate.java for the defined DAO interface StudentDAO package com.tutorialspoint; import java.util.List; import javax.sql.DataSource; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; public class StudentJDBCTemplate implements StudentDAO { private JdbcTemplate jdbcTemplateObject; public void setDataSource(DataSource dataSource) { this.jdbcTemplateObject = new JdbcTemplate(dataSource); } public void create(String name, Integer age, Integer marks, Integer year){ try { String SQL1 = "insert into Student (name, age) values (?, ?)"; jdbcTemplateObject.update( SQL1, name, age); // Get the latest student id to be used in Marks table String SQL2 = "select max(id) from Student"; int sid = jdbcTemplateObject.queryForInt( SQL2 ); String SQL3 = "insert into Marks(sid, marks, year) " + "values (?, ?, ?)"; jdbcTemplateObject.update( SQL3, sid, marks, year); System.out.println("Created Name = " + name + ", Age = " + age); // to simulate the exception. throw new RuntimeException("simulate Error condition") ; } catch (DataAccessException e) { System.out.println("Error in creating record, rolling back"); throw e; } } public List<StudentMarks> listStudents() { String SQL = "select * from Student, Marks where Student.id = Marks.sid"; List <StudentMarks> studentMarks = jdbcTemplateObject.query(SQL, new StudentMarksMapper()); return studentMarks; } } Now let us move with the main application file MainApp.java, which is as follows package com.tutorialspoint; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); StudentDAO studentJDBCTemplate = (StudentDAO)context.getBean("studentJDBCTemplate"); System.out.println("------Records creation--------" ); studentJDBCTemplate.create("Zara", 11, 99, 2010); studentJDBCTemplate.create("Nuha", 20, 97, 2010); studentJDBCTemplate.create("Ayan", 25, 100, 2011); System.out.println("------Listing all the records--------" ); List<StudentMarks> studentMarks = studentJDBCTemplate.listStudents(); for (StudentMarks record : studentMarks) { System.out.print("ID : " + record.getId() ); System.out.print(", Name : " + record.getName() ); System.out.print(", Marks : " + record.getMarks()); System.out.print(", Year : " + record.getYear()); System.out.println(", Age : " + record.getAge()); } } } Following is the configuration file Beans.xml <?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:tx = "http://www.springframework.org/schema/tx" xmlns:aop = "http://www.springframework.org/schema/aop" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <!-- Initialization for data source --> <bean id="dataSource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name = "driverClassName" value = "com.mysql.jdbc.Driver"/> <property name = "url" value = "jdbc:mysql://localhost:3306/TEST"/> <property name = "username" value = "root"/> <property name = "password" value = "cohondob"/> </bean> <tx:advice id = "txAdvice" transaction-manager = "transactionManager"> <tx:attributes> <tx:method name = "create"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id = "createOperation" expression = "execution(* com.tutorialspoint.StudentJDBCTemplate.create(..))"/> <aop:advisor advice-ref = "txAdvice" pointcut-ref = "createOperation"/> </aop:config> <!-- Initialization for TransactionManager --> <bean id = "transactionManager" class = "org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name = "dataSource" ref = "dataSource" /> </bean> <!-- Definition for studentJDBCTemplate bean --> <bean id = "studentJDBCTemplate" class = "com.tutorialspoint.StudentJDBCTemplate"> <property name = "dataSource" ref = "dataSource"/> </bean> </beans> Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following exception. In this case, the transaction will be rolled back and no record will be created in the database table. ------Records creation-------- Created Name = Zara, Age = 11 Exception in thread "main" java.lang.RuntimeException: simulate Error condition You can try the above example after removing the exception, and in this case it should commit the transaction and you should see a record in the database. 102 Lectures 8 hours Karthikeya T 39 Lectures 5 hours Chaand Sheikh 73 Lectures 5.5 hours Senol Atac 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac 69 Lectures 5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2738, "s": 2292, "text": "Declarative transaction management approach allows you to manage the transaction with the help of configuration instead of hard coding in your source code. This means that you can separate transaction management from the business code. You only use annotations or XML-based configuration to manage the transactions. The bean configuration will specify the methods to be transactional. Here are the steps associated with declarative transaction −" }, { "code": null, "e": 2943, "s": 2738, "text": "We use <tx:advice /> tag, which creates a transaction-handling advice and at the same time we define a pointcut that matches all methods we wish to make transaction and reference the transactional advice." }, { "code": null, "e": 3148, "s": 2943, "text": "We use <tx:advice /> tag, which creates a transaction-handling advice and at the same time we define a pointcut that matches all methods we wish to make transaction and reference the transactional advice." }, { "code": null, "e": 3297, "s": 3148, "text": "If a method name has been included in the transactional configuration, then the created advice will begin the transaction before calling the method." }, { "code": null, "e": 3446, "s": 3297, "text": "If a method name has been included in the transactional configuration, then the created advice will begin the transaction before calling the method." }, { "code": null, "e": 3501, "s": 3446, "text": "Target method will be executed in a try / catch block." }, { "code": null, "e": 3556, "s": 3501, "text": "Target method will be executed in a try / catch block." }, { "code": null, "e": 3675, "s": 3556, "text": "If the method finishes normally, the AOP advice commits the transaction successfully otherwise it performs a rollback." }, { "code": null, "e": 3794, "s": 3675, "text": "If the method finishes normally, the AOP advice commits the transaction successfully otherwise it performs a rollback." }, { "code": null, "e": 4091, "s": 3794, "text": "Let us see how the above-mentioned steps work but before we begin, it is important to have at least two database tables on which we can perform various CRUD operations with the help of transactions. Let us take a Student table, which can be created in MySQL TEST database with the following DDL −" }, { "code": null, "e": 4225, "s": 4091, "text": "CREATE TABLE Student(\n ID INT NOT NULL AUTO_INCREMENT,\n NAME VARCHAR(20) NOT NULL,\n AGE INT NOT NULL,\n PRIMARY KEY (ID)\n);" }, { "code": null, "e": 4363, "s": 4225, "text": "Second table is Marks in which we will maintain marks for the students based on years. Here SID is the foreign key for the Student table." }, { "code": null, "e": 4454, "s": 4363, "text": "CREATE TABLE Marks(\n SID INT NOT NULL,\n MARKS INT NOT NULL,\n YEAR INT NOT NULL\n);" }, { "code": null, "e": 4677, "s": 4454, "text": "Now, let us write our Spring JDBC application which will implement simple operations on the Student and Marks tables. Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −" }, { "code": null, "e": 4759, "s": 4677, "text": "Following is the content of the Data Access Object interface file StudentDAO.java" }, { "code": null, "e": 5394, "s": 4759, "text": "package com.tutorialspoint;\n\nimport java.util.List;\nimport javax.sql.DataSource;\n\npublic interface StudentDAO {\n /** \n * This is the method to be used to initialize\n * database resources ie. connection.\n */\n public void setDataSource(DataSource ds);\n \n /** \n * This is the method to be used to create\n * a record in the Student and Marks tables.\n */\n public void create(String name, Integer age, Integer marks, Integer year);\n \n /** \n * This is the method to be used to list down\n * all the records from the Student and Marks tables.\n */\n public List<StudentMarks> listStudents();\n}" }, { "code": null, "e": 5449, "s": 5394, "text": "Following is the content of the StudentMarks.java file" }, { "code": null, "e": 6367, "s": 5449, "text": "package com.tutorialspoint;\n\npublic class StudentMarks {\n private Integer age;\n private String name;\n private Integer id;\n private Integer marks;\n private Integer year;\n private Integer sid;\n\n public void setAge(Integer age) {\n this.age = age;\n }\n public Integer getAge() {\n return age;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getName() {\n return name;\n }\n public void setId(Integer id) {\n this.id = id;\n }\n public Integer getId() {\n return id;\n }\n public void setMarks(Integer marks) {\n this.marks = marks;\n }\n public Integer getMarks() {\n return marks;\n }\n public void setYear(Integer year) {\n this.year = year;\n }\n public Integer getYear() {\n return year;\n }\n public void setSid(Integer sid) {\n this.sid = sid;\n }\n public Integer getSid() {\n return sid;\n }\n}" }, { "code": null, "e": 6428, "s": 6367, "text": "Following is the content of the StudentMarksMapper.java file" }, { "code": null, "e": 7078, "s": 6428, "text": "package com.tutorialspoint;\n\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport org.springframework.jdbc.core.RowMapper;\n\npublic class StudentMarksMapper implements RowMapper<StudentMarks> {\n public StudentMarks mapRow(ResultSet rs, int rowNum) throws SQLException {\n StudentMarks studentMarks = new StudentMarks();\n studentMarks.setId(rs.getInt(\"id\"));\n studentMarks.setName(rs.getString(\"name\"));\n studentMarks.setAge(rs.getInt(\"age\"));\n studentMarks.setSid(rs.getInt(\"sid\"));\n studentMarks.setMarks(rs.getInt(\"marks\"));\n studentMarks.setYear(rs.getInt(\"year\"));\n\n return studentMarks;\n }\n}" }, { "code": null, "e": 7187, "s": 7078, "text": "Following is the implementation class file StudentJDBCTemplate.java for the defined DAO interface StudentDAO" }, { "code": null, "e": 8748, "s": 7187, "text": "package com.tutorialspoint;\n\nimport java.util.List;\nimport javax.sql.DataSource;\nimport org.springframework.dao.DataAccessException;\nimport org.springframework.jdbc.core.JdbcTemplate;\n\npublic class StudentJDBCTemplate implements StudentDAO {\n private JdbcTemplate jdbcTemplateObject;\n\n public void setDataSource(DataSource dataSource) {\n this.jdbcTemplateObject = new JdbcTemplate(dataSource);\n }\n public void create(String name, Integer age, Integer marks, Integer year){\n try {\n String SQL1 = \"insert into Student (name, age) values (?, ?)\";\n jdbcTemplateObject.update( SQL1, name, age);\n\n // Get the latest student id to be used in Marks table\n String SQL2 = \"select max(id) from Student\";\n int sid = jdbcTemplateObject.queryForInt( SQL2 );\n\n String SQL3 = \"insert into Marks(sid, marks, year) \" + \"values (?, ?, ?)\";\n jdbcTemplateObject.update( SQL3, sid, marks, year);\n System.out.println(\"Created Name = \" + name + \", Age = \" + age);\n \n // to simulate the exception.\n throw new RuntimeException(\"simulate Error condition\") ;\n } \n catch (DataAccessException e) {\n System.out.println(\"Error in creating record, rolling back\");\n throw e;\n }\n }\n public List<StudentMarks> listStudents() {\n String SQL = \"select * from Student, Marks where Student.id = Marks.sid\";\n List <StudentMarks> studentMarks = jdbcTemplateObject.query(SQL, \n new StudentMarksMapper());\n \n return studentMarks;\n }\n}" }, { "code": null, "e": 8829, "s": 8748, "text": "Now let us move with the main application file MainApp.java, which is as follows" }, { "code": null, "e": 10011, "s": 8829, "text": "package com.tutorialspoint;\n\nimport java.util.List;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\npublic class MainApp {\n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n\n StudentDAO studentJDBCTemplate = \n (StudentDAO)context.getBean(\"studentJDBCTemplate\");\n \n System.out.println(\"------Records creation--------\" );\n studentJDBCTemplate.create(\"Zara\", 11, 99, 2010);\n studentJDBCTemplate.create(\"Nuha\", 20, 97, 2010);\n studentJDBCTemplate.create(\"Ayan\", 25, 100, 2011);\n\n System.out.println(\"------Listing all the records--------\" );\n List<StudentMarks> studentMarks = studentJDBCTemplate.listStudents();\n \n for (StudentMarks record : studentMarks) {\n System.out.print(\"ID : \" + record.getId() );\n System.out.print(\", Name : \" + record.getName() );\n System.out.print(\", Marks : \" + record.getMarks());\n System.out.print(\", Year : \" + record.getYear());\n System.out.println(\", Age : \" + record.getAge());\n }\n }\n}" }, { "code": null, "e": 10057, "s": 10011, "text": "Following is the configuration file Beans.xml" }, { "code": null, "e": 12006, "s": 10057, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns:tx = \"http://www.springframework.org/schema/tx\"\n xmlns:aop = \"http://www.springframework.org/schema/aop\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd \n http://www.springframework.org/schema/tx\n http://www.springframework.org/schema/tx/spring-tx-3.0.xsd\n http://www.springframework.org/schema/aop\n http://www.springframework.org/schema/aop/spring-aop-3.0.xsd\">\n\n <!-- Initialization for data source -->\n <bean id=\"dataSource\" \n class = \"org.springframework.jdbc.datasource.DriverManagerDataSource\">\n <property name = \"driverClassName\" value = \"com.mysql.jdbc.Driver\"/>\n <property name = \"url\" value = \"jdbc:mysql://localhost:3306/TEST\"/>\n <property name = \"username\" value = \"root\"/>\n <property name = \"password\" value = \"cohondob\"/>\n </bean>\n \n <tx:advice id = \"txAdvice\" transaction-manager = \"transactionManager\">\n <tx:attributes>\n <tx:method name = \"create\"/>\n </tx:attributes>\n </tx:advice>\n\t\n <aop:config>\n <aop:pointcut id = \"createOperation\" \n expression = \"execution(* com.tutorialspoint.StudentJDBCTemplate.create(..))\"/>\n \n <aop:advisor advice-ref = \"txAdvice\" pointcut-ref = \"createOperation\"/>\n </aop:config>\n\t\n <!-- Initialization for TransactionManager -->\n <bean id = \"transactionManager\"\n class = \"org.springframework.jdbc.datasource.DataSourceTransactionManager\">\n \n <property name = \"dataSource\" ref = \"dataSource\" /> \n </bean>\n\n <!-- Definition for studentJDBCTemplate bean -->\n <bean id = \"studentJDBCTemplate\" \n class = \"com.tutorialspoint.StudentJDBCTemplate\">\n <property name = \"dataSource\" ref = \"dataSource\"/> \n </bean>\n\n</beans>" }, { "code": null, "e": 12289, "s": 12006, "text": "Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following exception. In this case, the transaction will be rolled back and no record will be created in the database table." }, { "code": null, "e": 12431, "s": 12289, "text": "------Records creation--------\nCreated Name = Zara, Age = 11\nException in thread \"main\" java.lang.RuntimeException: simulate Error condition\n" }, { "code": null, "e": 12586, "s": 12431, "text": "You can try the above example after removing the exception, and in this case it should commit the transaction and you should see a record in the database." }, { "code": null, "e": 12620, "s": 12586, "text": "\n 102 Lectures \n 8 hours \n" }, { "code": null, "e": 12634, "s": 12620, "text": " Karthikeya T" }, { "code": null, "e": 12667, "s": 12634, "text": "\n 39 Lectures \n 5 hours \n" }, { "code": null, "e": 12682, "s": 12667, "text": " Chaand Sheikh" }, { "code": null, "e": 12717, "s": 12682, "text": "\n 73 Lectures \n 5.5 hours \n" }, { "code": null, "e": 12729, "s": 12717, "text": " Senol Atac" }, { "code": null, "e": 12764, "s": 12729, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 12776, "s": 12764, "text": " Senol Atac" }, { "code": null, "e": 12811, "s": 12776, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 12823, "s": 12811, "text": " Senol Atac" }, { "code": null, "e": 12856, "s": 12823, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 12868, "s": 12856, "text": " Senol Atac" }, { "code": null, "e": 12875, "s": 12868, "text": " Print" }, { "code": null, "e": 12886, "s": 12875, "text": " Add Notes" } ]
Biopython - Sequence
A sequence is series of letters used to represent an organism’s protein, DNA or RNA. It is represented by Seq class. Seq class is defined in Bio.Seq module. Let’s create a simple sequence in Biopython as shown below − >>> from Bio.Seq import Seq >>> seq = Seq("AGCT") >>> seq Seq('AGCT') >>> print(seq) AGCT Here, we have created a simple protein sequence AGCT and each letter represents Alanine, Glycine, Cysteine and Threonine. Each Seq object has two important attributes − data − the actual sequence string (AGCT) data − the actual sequence string (AGCT) alphabet − used to represent the type of sequence. e.g. DNA sequence, RNA sequence, etc. By default, it does not represent any sequence and is generic in nature. alphabet − used to represent the type of sequence. e.g. DNA sequence, RNA sequence, etc. By default, it does not represent any sequence and is generic in nature. Seq objects contain Alphabet attribute to specify sequence type, letters and possible operations. It is defined in Bio.Alphabet module. Alphabet can be defined as below − >>> from Bio.Seq import Seq >>> myseq = Seq("AGCT") >>> myseq Seq('AGCT') >>> myseq.alphabet Alphabet() Alphabet module provides below classes to represent different types of sequences. Alphabet - base class for all types of alphabets. SingleLetterAlphabet - Generic alphabet with letters of size one. It derives from Alphabet and all other alphabets type derives from it. >>> from Bio.Seq import Seq >>> from Bio.Alphabet import single_letter_alphabet >>> test_seq = Seq('AGTACACTGGT', single_letter_alphabet) >>> test_seq Seq('AGTACACTGGT', SingleLetterAlphabet()) ProteinAlphabet − Generic single letter protein alphabet. >>> from Bio.Seq import Seq >>> from Bio.Alphabet import generic_protein >>> test_seq = Seq('AGTACACTGGT', generic_protein) >>> test_seq Seq('AGTACACTGGT', ProteinAlphabet()) NucleotideAlphabet − Generic single letter nucleotide alphabet. >>> from Bio.Seq import Seq >>> from Bio.Alphabet import generic_nucleotide >>> test_seq = Seq('AGTACACTGGT', generic_nucleotide) >>> test_seq Seq('AGTACACTGGT', NucleotideAlphabet()) DNAAlphabet − Generic single letter DNA alphabet. >>> from Bio.Seq import Seq >>> from Bio.Alphabet import generic_dna >>> test_seq = Seq('AGTACACTGGT', generic_dna) >>> test_seq Seq('AGTACACTGGT', DNAAlphabet()) RNAAlphabet − Generic single letter RNA alphabet. >>> from Bio.Seq import Seq >>> from Bio.Alphabet import generic_rna >>> test_seq = Seq('AGTACACTGGT', generic_rna) >>> test_seq Seq('AGTACACTGGT', RNAAlphabet()) Biopython module, Bio.Alphabet.IUPAC provides basic sequence types as defined by IUPAC community. It contains the following classes − IUPACProtein (protein) − IUPAC protein alphabet of 20 standard amino acids. IUPACProtein (protein) − IUPAC protein alphabet of 20 standard amino acids. ExtendedIUPACProtein (extended_protein) − Extended uppercase IUPAC protein single letter alphabet including X. ExtendedIUPACProtein (extended_protein) − Extended uppercase IUPAC protein single letter alphabet including X. IUPACAmbiguousDNA (ambiguous_dna) − Uppercase IUPAC ambiguous DNA. IUPACAmbiguousDNA (ambiguous_dna) − Uppercase IUPAC ambiguous DNA. IUPACUnambiguousDNA (unambiguous_dna) − Uppercase IUPAC unambiguous DNA (GATC). IUPACUnambiguousDNA (unambiguous_dna) − Uppercase IUPAC unambiguous DNA (GATC). ExtendedIUPACDNA (extended_dna) − Extended IUPAC DNA alphabet. ExtendedIUPACDNA (extended_dna) − Extended IUPAC DNA alphabet. IUPACAmbiguousRNA (ambiguous_rna) − Uppercase IUPAC ambiguous RNA. IUPACAmbiguousRNA (ambiguous_rna) − Uppercase IUPAC ambiguous RNA. IUPACUnambiguousRNA (unambiguous_rna) − Uppercase IUPAC unambiguous RNA (GAUC). IUPACUnambiguousRNA (unambiguous_rna) − Uppercase IUPAC unambiguous RNA (GAUC). Consider a simple example for IUPACProtein class as shown below − >>> from Bio.Alphabet import IUPAC >>> protein_seq = Seq("AGCT", IUPAC.protein) >>> protein_seq Seq('AGCT', IUPACProtein()) >>> protein_seq.alphabet Also, Biopython exposes all the bioinformatics related configuration data through Bio.Data module. For example, IUPACData.protein_letters has the possible letters of IUPACProtein alphabet. >>> from Bio.Data import IUPACData >>> IUPACData.protein_letters 'ACDEFGHIKLMNPQRSTVWY' This section briefly explains about all the basic operations available in the Seq class. Sequences are similar to python strings. We can perform python string operations like slicing, counting, concatenation, find, split and strip in sequences. Use the below codes to get various outputs. To get the first value in sequence. >>> seq_string = Seq("AGCTAGCT") >>> seq_string[0] 'A' To print the first two values. >>> seq_string[0:2] Seq('AG') To print all the values. >>> seq_string[ : ] Seq('AGCTAGCT') To perform length and count operations. >>> len(seq_string) 8 >>> seq_string.count('A') 2 To add two sequences. >>> from Bio.Alphabet import generic_dna, generic_protein >>> seq1 = Seq("AGCT", generic_dna) >>> seq2 = Seq("TCGA", generic_dna) >>> seq1+seq2 Seq('AGCTTCGA', DNAAlphabet()) Here, the above two sequence objects, seq1, seq2 are generic DNA sequences and so you can add them and produce new sequence. You can’t add sequences with incompatible alphabets, such as a protein sequence and a DNA sequence as specified below − >>> dna_seq = Seq('AGTACACTGGT', generic_dna) >>> protein_seq = Seq('AGUACACUGGU', generic_protein) >>> dna_seq + protein_seq ..... ..... TypeError: Incompatible alphabets DNAAlphabet() and ProteinAlphabet() >>> To add two or more sequences, first store it in a python list, then retrieve it using ‘for loop’ and finally add it together as shown below − >>> from Bio.Alphabet import generic_dna >>> list = [Seq("AGCT",generic_dna),Seq("TCGA",generic_dna),Seq("AAA",generic_dna)] >>> for s in list: ... print(s) ... AGCT TCGA AAA >>> final_seq = Seq(" ",generic_dna) >>> for s in list: ... final_seq = final_seq + s ... >>> final_seq Seq('AGCTTCGAAAA', DNAAlphabet()) In the below section, various codes are given to get outputs based on the requirement. To change the case of sequence. >>> from Bio.Alphabet import generic_rna >>> rna = Seq("agct", generic_rna) >>> rna.upper() Seq('AGCT', RNAAlphabet()) To check python membership and identity operator. >>> rna = Seq("agct", generic_rna) >>> 'a' in rna True >>> 'A' in rna False >>> rna1 = Seq("AGCT", generic_dna) >>> rna is rna1 False To find single letter or sequence of letter inside the given sequence. >>> protein_seq = Seq('AGUACACUGGU', generic_protein) >>> protein_seq.find('G') 1 >>> protein_seq.find('GG') 8 To perform splitting operation. >>> protein_seq = Seq('AGUACACUGGU', generic_protein) >>> protein_seq.split('A') [Seq('', ProteinAlphabet()), Seq('GU', ProteinAlphabet()), Seq('C', ProteinAlphabet()), Seq('CUGGU', ProteinAlphabet())] To perform strip operations in the sequence. >>> strip_seq = Seq(" AGCT ") >>> strip_seq Seq(' AGCT ') >>> strip_seq.strip() Seq('AGCT') Print Add Notes Bookmark this page
[ { "code": null, "e": 2263, "s": 2106, "text": "A sequence is series of letters used to represent an organism’s protein, DNA or RNA. It is represented by Seq class. Seq class is defined in Bio.Seq module." }, { "code": null, "e": 2324, "s": 2263, "text": "Let’s create a simple sequence in Biopython as shown below −" }, { "code": null, "e": 2419, "s": 2324, "text": ">>> from Bio.Seq import Seq \n>>> seq = Seq(\"AGCT\") \n>>> seq \nSeq('AGCT') \n>>> print(seq) \nAGCT" }, { "code": null, "e": 2541, "s": 2419, "text": "Here, we have created a simple protein sequence AGCT and each letter represents Alanine, Glycine, Cysteine and Threonine." }, { "code": null, "e": 2588, "s": 2541, "text": "Each Seq object has two important attributes −" }, { "code": null, "e": 2629, "s": 2588, "text": "data − the actual sequence string (AGCT)" }, { "code": null, "e": 2670, "s": 2629, "text": "data − the actual sequence string (AGCT)" }, { "code": null, "e": 2832, "s": 2670, "text": "alphabet − used to represent the type of sequence. e.g. DNA sequence, RNA sequence, etc. By default, it does not represent any sequence and is generic in nature." }, { "code": null, "e": 2994, "s": 2832, "text": "alphabet − used to represent the type of sequence. e.g. DNA sequence, RNA sequence, etc. By default, it does not represent any sequence and is generic in nature." }, { "code": null, "e": 3165, "s": 2994, "text": "Seq objects contain Alphabet attribute to specify sequence type, letters and possible operations. It is defined in Bio.Alphabet module. Alphabet can be defined as below −" }, { "code": null, "e": 3274, "s": 3165, "text": ">>> from Bio.Seq import Seq \n>>> myseq = Seq(\"AGCT\") \n>>> myseq \nSeq('AGCT') \n>>> myseq.alphabet \nAlphabet()" }, { "code": null, "e": 3406, "s": 3274, "text": "Alphabet module provides below classes to represent different types of sequences. Alphabet - base class for all types of alphabets." }, { "code": null, "e": 3543, "s": 3406, "text": "SingleLetterAlphabet - Generic alphabet with letters of size one. It derives from Alphabet and all other alphabets type derives from it." }, { "code": null, "e": 3741, "s": 3543, "text": ">>> from Bio.Seq import Seq \n>>> from Bio.Alphabet import single_letter_alphabet \n>>> test_seq = Seq('AGTACACTGGT', single_letter_alphabet) \n>>> test_seq \nSeq('AGTACACTGGT', SingleLetterAlphabet())" }, { "code": null, "e": 3799, "s": 3741, "text": "ProteinAlphabet − Generic single letter protein alphabet." }, { "code": null, "e": 3978, "s": 3799, "text": ">>> from Bio.Seq import Seq \n>>> from Bio.Alphabet import generic_protein \n>>> test_seq = Seq('AGTACACTGGT', generic_protein) \n>>> test_seq \nSeq('AGTACACTGGT', ProteinAlphabet())" }, { "code": null, "e": 4042, "s": 3978, "text": "NucleotideAlphabet − Generic single letter nucleotide alphabet." }, { "code": null, "e": 4229, "s": 4042, "text": ">>> from Bio.Seq import Seq \n>>> from Bio.Alphabet import generic_nucleotide \n>>> test_seq = Seq('AGTACACTGGT', generic_nucleotide) >>> test_seq \nSeq('AGTACACTGGT', NucleotideAlphabet())" }, { "code": null, "e": 4279, "s": 4229, "text": "DNAAlphabet − Generic single letter DNA alphabet." }, { "code": null, "e": 4446, "s": 4279, "text": ">>> from Bio.Seq import Seq \n>>> from Bio.Alphabet import generic_dna \n>>> test_seq = Seq('AGTACACTGGT', generic_dna) \n>>> test_seq \nSeq('AGTACACTGGT', DNAAlphabet())" }, { "code": null, "e": 4496, "s": 4446, "text": "RNAAlphabet − Generic single letter RNA alphabet." }, { "code": null, "e": 4663, "s": 4496, "text": ">>> from Bio.Seq import Seq \n>>> from Bio.Alphabet import generic_rna \n>>> test_seq = Seq('AGTACACTGGT', generic_rna) \n>>> test_seq \nSeq('AGTACACTGGT', RNAAlphabet())" }, { "code": null, "e": 4797, "s": 4663, "text": "Biopython module, Bio.Alphabet.IUPAC provides basic sequence types as defined by IUPAC community. It contains the following classes −" }, { "code": null, "e": 4873, "s": 4797, "text": "IUPACProtein (protein) − IUPAC protein alphabet of 20 standard amino acids." }, { "code": null, "e": 4949, "s": 4873, "text": "IUPACProtein (protein) − IUPAC protein alphabet of 20 standard amino acids." }, { "code": null, "e": 5060, "s": 4949, "text": "ExtendedIUPACProtein (extended_protein) − Extended uppercase IUPAC protein single letter alphabet including X." }, { "code": null, "e": 5171, "s": 5060, "text": "ExtendedIUPACProtein (extended_protein) − Extended uppercase IUPAC protein single letter alphabet including X." }, { "code": null, "e": 5238, "s": 5171, "text": "IUPACAmbiguousDNA (ambiguous_dna) − Uppercase IUPAC ambiguous DNA." }, { "code": null, "e": 5305, "s": 5238, "text": "IUPACAmbiguousDNA (ambiguous_dna) − Uppercase IUPAC ambiguous DNA." }, { "code": null, "e": 5385, "s": 5305, "text": "IUPACUnambiguousDNA (unambiguous_dna) − Uppercase IUPAC unambiguous DNA (GATC)." }, { "code": null, "e": 5465, "s": 5385, "text": "IUPACUnambiguousDNA (unambiguous_dna) − Uppercase IUPAC unambiguous DNA (GATC)." }, { "code": null, "e": 5528, "s": 5465, "text": "ExtendedIUPACDNA (extended_dna) − Extended IUPAC DNA alphabet." }, { "code": null, "e": 5591, "s": 5528, "text": "ExtendedIUPACDNA (extended_dna) − Extended IUPAC DNA alphabet." }, { "code": null, "e": 5658, "s": 5591, "text": "IUPACAmbiguousRNA (ambiguous_rna) − Uppercase IUPAC ambiguous RNA." }, { "code": null, "e": 5725, "s": 5658, "text": "IUPACAmbiguousRNA (ambiguous_rna) − Uppercase IUPAC ambiguous RNA." }, { "code": null, "e": 5805, "s": 5725, "text": "IUPACUnambiguousRNA (unambiguous_rna) − Uppercase IUPAC unambiguous RNA (GAUC)." }, { "code": null, "e": 5885, "s": 5805, "text": "IUPACUnambiguousRNA (unambiguous_rna) − Uppercase IUPAC unambiguous RNA (GAUC)." }, { "code": null, "e": 5951, "s": 5885, "text": "Consider a simple example for IUPACProtein class as shown below −" }, { "code": null, "e": 6104, "s": 5951, "text": ">>> from Bio.Alphabet import IUPAC \n>>> protein_seq = Seq(\"AGCT\", IUPAC.protein) \n>>> protein_seq \nSeq('AGCT', IUPACProtein()) \n>>> protein_seq.alphabet" }, { "code": null, "e": 6293, "s": 6104, "text": "Also, Biopython exposes all the bioinformatics related configuration data through Bio.Data module. For example, IUPACData.protein_letters has the possible letters of IUPACProtein alphabet." }, { "code": null, "e": 6383, "s": 6293, "text": ">>> from Bio.Data import IUPACData \n>>> IUPACData.protein_letters \n'ACDEFGHIKLMNPQRSTVWY'" }, { "code": null, "e": 6628, "s": 6383, "text": "This section briefly explains about all the basic operations available in the Seq class. Sequences are similar to python strings. We can perform python string operations like slicing, counting, concatenation, find, split and strip in sequences." }, { "code": null, "e": 6672, "s": 6628, "text": "Use the below codes to get various outputs." }, { "code": null, "e": 6708, "s": 6672, "text": "To get the first value in sequence." }, { "code": null, "e": 6765, "s": 6708, "text": ">>> seq_string = Seq(\"AGCTAGCT\") \n>>> seq_string[0] \n'A'" }, { "code": null, "e": 6796, "s": 6765, "text": "To print the first two values." }, { "code": null, "e": 6827, "s": 6796, "text": ">>> seq_string[0:2] \nSeq('AG')" }, { "code": null, "e": 6852, "s": 6827, "text": "To print all the values." }, { "code": null, "e": 6889, "s": 6852, "text": ">>> seq_string[ : ] \nSeq('AGCTAGCT')" }, { "code": null, "e": 6929, "s": 6889, "text": "To perform length and count operations." }, { "code": null, "e": 6982, "s": 6929, "text": ">>> len(seq_string) \n8 \n>>> seq_string.count('A') \n2" }, { "code": null, "e": 7004, "s": 6982, "text": "To add two sequences." }, { "code": null, "e": 7182, "s": 7004, "text": ">>> from Bio.Alphabet import generic_dna, generic_protein \n>>> seq1 = Seq(\"AGCT\", generic_dna) \n>>> seq2 = Seq(\"TCGA\", generic_dna)\n>>> seq1+seq2 \nSeq('AGCTTCGA', DNAAlphabet())" }, { "code": null, "e": 7427, "s": 7182, "text": "Here, the above two sequence objects, seq1, seq2 are generic DNA sequences and so you can add them and produce new sequence. You can’t add sequences with incompatible alphabets, such as a protein sequence and a DNA sequence as specified below −" }, { "code": null, "e": 7645, "s": 7427, "text": ">>> dna_seq = Seq('AGTACACTGGT', generic_dna) \n>>> protein_seq = Seq('AGUACACUGGU', generic_protein) \n>>> dna_seq + protein_seq \n..... \n..... \nTypeError: Incompatible alphabets DNAAlphabet() and ProteinAlphabet() \n>>>" }, { "code": null, "e": 7787, "s": 7645, "text": "To add two or more sequences, first store it in a python list, then retrieve it using ‘for loop’ and finally add it together as shown below −" }, { "code": null, "e": 8113, "s": 7787, "text": ">>> from Bio.Alphabet import generic_dna \n>>> list = [Seq(\"AGCT\",generic_dna),Seq(\"TCGA\",generic_dna),Seq(\"AAA\",generic_dna)] \n>>> for s in list: \n... print(s) \n... \nAGCT \nTCGA \nAAA \n>>> final_seq = Seq(\" \",generic_dna) \n>>> for s in list: \n... final_seq = final_seq + s \n... \n>>> final_seq \nSeq('AGCTTCGAAAA', DNAAlphabet())" }, { "code": null, "e": 8200, "s": 8113, "text": "In the below section, various codes are given to get outputs based on the requirement." }, { "code": null, "e": 8232, "s": 8200, "text": "To change the case of sequence." }, { "code": null, "e": 8354, "s": 8232, "text": ">>> from Bio.Alphabet import generic_rna \n>>> rna = Seq(\"agct\", generic_rna) \n>>> rna.upper() \nSeq('AGCT', RNAAlphabet())" }, { "code": null, "e": 8404, "s": 8354, "text": "To check python membership and identity operator." }, { "code": null, "e": 8545, "s": 8404, "text": ">>> rna = Seq(\"agct\", generic_rna) \n>>> 'a' in rna \nTrue \n>>> 'A' in rna \nFalse \n>>> rna1 = Seq(\"AGCT\", generic_dna) \n>>> rna is rna1 \nFalse" }, { "code": null, "e": 8616, "s": 8545, "text": "To find single letter or sequence of letter inside the given sequence." }, { "code": null, "e": 8731, "s": 8616, "text": ">>> protein_seq = Seq('AGUACACUGGU', generic_protein) \n>>> protein_seq.find('G') \n1 \n>>> protein_seq.find('GG') \n8" }, { "code": null, "e": 8763, "s": 8731, "text": "To perform splitting operation." }, { "code": null, "e": 8971, "s": 8763, "text": ">>> protein_seq = Seq('AGUACACUGGU', generic_protein) \n>>> protein_seq.split('A') \n[Seq('', ProteinAlphabet()), Seq('GU', ProteinAlphabet()), \n Seq('C', ProteinAlphabet()), Seq('CUGGU', ProteinAlphabet())]" }, { "code": null, "e": 9016, "s": 8971, "text": "To perform strip operations in the sequence." }, { "code": null, "e": 9112, "s": 9016, "text": ">>> strip_seq = Seq(\" AGCT \") \n>>> strip_seq \nSeq(' AGCT ') \n>>> strip_seq.strip() \nSeq('AGCT')" }, { "code": null, "e": 9119, "s": 9112, "text": " Print" }, { "code": null, "e": 9130, "s": 9119, "text": " Add Notes" } ]
Analyzing my weight loss with machine learning | by Khanh Nguyen | Towards Data Science
To see the code I wrote for this project, you can check out its Github repo I began my weight loss journey at the start of 2018, following the oft-cited advice of “weight loss = diet + exercise”. On the diet side, I started tracking my daily food consumption (using a food scale and recording calories via the Loseit app). On the exercise side, I started following the Couch to 5K program, and to date have finished four 5K’s, one 10K, and from a few weeks ago, a half-marathon. Lastly, every morning, I weighed myself right after waking up and recorded my weight in the same Loseit app. Anyone trying to lose weight will inevitably hit a weight-loss plateau, where the initial speedy weight loss starts to slow down. Personally, I hit a major plateau right after my vacation at the start of May. After that, I abandoned tracking my progress for nearly three months. Only after I replaced my dying Pebble smartwatch with an Amazfit Bip did I gain back some motivation to hit the resume button, partly since I could start tracking my steps with the new watch. However, my weight continued to plateau, and after a further two months of frustrating weight fluctuations (see dotted region below), I stopped tracking my weight and calories altogether. That was November of last year. It’s now 2019, and as Tet (Vietnamese New Year) recently drew to a close, I’ve decided to look more closely at the data collected during that two-month period, hoping to discover interesting relationships between my weight loss and the tracked calories/steps so that I could build a more effective weight loss plan than before. Calories: exported from my Loseit account as CSV files. For some strange reason, Loseit only allows calories data to be exported one week at a time, but joining them together is nothing a quick Python script can’t do. Each date has corresponding calories counts from all the food I logged during that day, as well as a calories “budget” that the app calculated for me based on my weight that day and the weight loss goal that I initially specified (to lose 0.75 kg/week). Steps: the Android app of my Amazfit Bip smartwatch doesn’t allow data export unless one uses some hairy workaround with third-party tools. Therefore, the quickest method to obtain my steps data was to manually scroll through the dozens of dates (within this two-month period) on my phone and enter the steps for each date into a CSV file. Not elegant at all, but hey, it works! Weight: thankfully the Loseit website allows me to export all my recorded weights — and the dates on which they were taken — as a single CSV file. After joining these 3 data sources together by date, I end up with calories+steps+weight data for only 46 dates out of this two-month period. Apparently I neglected to record at least one of these three data in quite a few dates (many of them weekends, for obvious reasons). From those three raw data sources, three additional data fields are calculated: Surplus = calories consumed - calories budget. Positive surplus means I had eaten more calories than the budget allowed for that day, and vice versa. I choose to use calories surplus instead of raw calories consumed since the calories budget from the app naturally varies as my weights rise and fall, so calories surplus (which takes into account said budget) is a more accurate measure of my eating habits than calories alone. Weight gain = tomorrow weight - today weight. Positive weight gain of a given date means I had gained weight over that day (duh!), and vice versa. Weight gain status: positive weight gain would be labeled as 1, and negative or zero weight gain would be labeled as 0. I decide to use the binary weight gain status–whether I had gained weight or not– rather than the more granular weight gain amount since obsessing over gaining 0.5 kg versus 0.3 kg is quite counter-productive, not least because the amount of weight gain can be influenced by many factors beside calories and steps (such as water intake, time of eating, etc). When plotting calories surplus and number of steps of each day against my weight gain status over that day (see first two panels below), there seems to be no apparent patterns on how these two reportedly important factors can predict whether I would gain weight or not. However, when plotting both calories surplus and steps together (right panel above), very interesting patterns emerge! For example, right away I can tell that there are two distinct groups of dates in terms of my step counts: those below 5000 steps (my "baseline" lazy days) that lie neatly around a horizontal line, and those above 5000 steps (my active days), largely thanks to my running. In terms of calories surplus, there are three main observations: 1. On my lazy days, if I eat above my calories budget limit, it's gonna be bad news the following day when I step onto the scale. There were some miracles, such as that one day where I ate almost 1500 calories above my limit and did not gain weight the next day, but those are few and far between. 2. On the other hand, if I eat below my calories budget limit on my lazy days, I'm not totally in the clear either: there are quite a few days where I was a good boy and ate my salads (figuratively), yet still gained weight. This suggests that I should be even more conservative in my eating on lazy days. 3. However, on my active days, it seems I can afford to eat more than my calories limit, as there are several active days where I ate more than what the limit allowed and still did not gain weight. These observations suggest that I should factor in my daily activity (in the form of step counts) instead of using the default limit from the Loseit app. For example, on the surplus-step plot above, I can draw a straight line that largely separates my weight gain days (red) from my weight loss days (green). I can then use that linear boundary to inform my weight loss strategy i.e. how I can stay on the weight loss side of the boundary instead of the other side. In machine learning parlance, this is equivalent to building a linear classifier for binary classification of my data (classify weight gain from weight loss). There are several common methods to build a linear classifier from data, such as logistic regression, linear discriminant analysis, or support vector machine. However, for this project, I will use logistic regression because: It's easy to interpret: for example, the equation for the classification boundary can be easily obtained from the logistic regression coefficients. It's easy to implement: a very important reason since another goal for this project is for me to implement a machine learning project without using pre-existing libraries (such as scikit-learn). As I will show later, the core of the learning algorithm for logistic regression can be accomplished in just 3 lines of code! With this choice of model, let's see how logistic regression can implemented and interpreted using my data. However, this requires us to review some math on how the logistic regression classifier works and how it can be learned from data. Please note that this math review is primarily to establish a common notation so that we are on the same page before the algorithm is implemented from the mathematical equations. If you want to understand how these equations are derived and the intuition behind them, I have linked to further resources at the end of this blog post that can do these jobs way better than I can. In logistic regression, the predicted probability that I will gain weight on a given day is the sigmoid function applied to a weighted linear combination of my features (calories surplus and step counts) plus an constant intercept term. This relationship is mathematically expressed as: where y(i): weight again status of date i (1=weight gain, 0=weight loss) P(y(i)=1): predicted probability that I will gain weight on date i x(i): observed values of the respective features (calories surplus and step counts) at date i* θ: regression coefficients/weights of the respective features (to be learned from data)* * Note that I have added an additional feature (x_intercept), which will always be equal to 1 so that the intercept term (θ_intercept) could be learned along with the coefficients of the two existing features. Therefore, once θ’s have been learned from data, logistic regression can be used to classify whether I will gain weight on any given day — given my calories surplus and step count — by checking if the probability that I will gain weight on that day is above a certain threshold (usually 50%). The regression coefficients (θ’s) are learned via maximizing the logarithm of the probability of observing my training data (also called the log-likelihood). The formula for log-likelihood is: where L: log-likelihood of training data (m data points) y(i): true weight gain status of date i (1=weight gain, 0=weight loss) P(y(i)=1): predicted probability that I will gain weight on date i (obtained from the sigmoid function earlier) From the sigmoid function, different values of θ’s will produce different predicted probabilities of weight gain — P(y(i)=1) — and as a result, different log-likelihood. Therefore, the goal is to find the set of θ’s that maximize the log-likelihood of my training data i.e. the θ’s that “explain” my training data the best. One straightforward algorithm to find the θ’s that maximize the log-likelihood of my training data is batch gradient ascent, which is described below: Step 0: Initialize some values for θ’s (θ_intercept, θ_surplus, θ_step) Step 1: For each training data point i, calculate the probability of weight gain using the feature values of that data point (x_intercept*, x_surplus, x_step), and the values of θ’s initialized in step 0. This is done using the familiar sigmoid function: *recall x_intercept = 1 Step 2: For each feature j — intercept/surplus/step — find the partial derivative of the log-likelihood with respect to the θ of that feature using the below equation: where ∂L/∂θj: partial derivative of log-likelihood with respect to θ of feature j y(i): true weight again status of date i (1=weight gain, 0=weight loss) P(y(i)=1): predicted probability of weight gain of date i (from step 1) xj(i): observed value of feature j (intercept/surplus/step) on date i, with x_intercept(i) = 1 for any i Step 3: For each feature j, update its θ by the partial derivative of the log-likelihood with respect to that θ (from step 2), multiplied by a small constant (also called the learning rate α): This learning rate controls how fast the algorithm will converge to the maximum of the log-likelihood, or even whether it converges at all (see the later section on visualizing the convergence of the algorithm for more details). Step 4: With these updated θ’s, repeat step 1 to step 3 until convergence. One way to test for convergence is to see if the log-likelihood has converged to a stable value i.e. that it has reached the likely maximum. The summation sign within step 2 — summing (y(i) - P(y(i)=1)) * xj(i) over all data points i to calculate partial derivative— is the reason why this gradient ascent algorithm is of the batch variety, as each partial derivative is computed using all data points in the training data. Without this summation sign i.e. the partial derivative is computed using only one data point; assuming that data point is randomly chosen, the gradient ascent algorithm is called stochastic. For this project, I choose to implement batch gradient ascent since my training data is very small (only 46 data points), so there’s no problem using the entire training data set at once to calculate partial derivatives. Another reason is that batch gradient ascent can be implemented more easily using numpy’s vectorized operations (please refer to its implementation below to see how). From my previous data table, I use the calories surplus and step count columns as my features, and the weight gain status column as the label (see left) to train my logistic regression classifier. However, before I can implement the batch gradient ascent algorithm on this data, I first need to: Add a column of 1’s to my training data to represent the values of the x_intercept feature.Rescale my calories surplus and step count features by (a) subtracting each feature column by its mean and (b) dividing by its standard deviation. This is done for two reasons: Add a column of 1’s to my training data to represent the values of the x_intercept feature. Rescale my calories surplus and step count features by (a) subtracting each feature column by its mean and (b) dividing by its standard deviation. This is done for two reasons: Recall that the sigmoid function (left) involves an exponential of linear combination of x’s, so very small/large values of x will make this exponential implode/explode. Indeed, before I rescaled my features, I had terrible convergence that I could not figure out why. Only when I by chance looked at the Jupyter terminal (not the Jupyter notebook output) did I see the pages of underflow/overflow warnings that numpy had silently produced! After I rescaled my features, these warnings went away and my algorithm was able to converge. By reducing my features to the same scale, I can use the regression coefficients for these features (θ’s) to weigh their relative importance in my weight gain/loss. This will be elaborated later in the interpretation section of my model. After the above two steps, my feature matrix (X) is converted to a 2–D numpy array of dimension (46, 3), and my label vector (y) to a 1-D numpy array of dimension (46). Step 0: Initialize θ’s theta = np.array([0.5, 0.5, 0.5]) I initialize all my θ’s to 0.5. The result is a 1-D numpy array theta of dimension (3) Step 1: For each data point, calculate the probability of weight gain using θ’s from step 0 and the sigmoid function prob = 1 / (1 + np.exp(-X @ theta)) This is where numpy’s vectorized operations come in handy, as instead of calculating the probability of weight gain for each data point, numpy does it for all data points at once: X @ theta: by multiplying matrix X with vector theta , numpy essentially calculates the linear combinations of x’s and θ’s for each and every data point by taking the dot product of each row of X with the theta column (see bolded cells in the diagram). 1 / (1 + np.exp(-X @ theta)): after linear combinations of x’s and θ’s for all data point are calculated, the sigmoid function is applied to each of them to get the final probabilities of weight gain for all data points. Notice that the operations in this sigmoid function (/, +, -, np.exp) all represent vectorized functions that numpy runs behind the scene. This finally output the probability vector prob, a 1-D numpy array of dimension (46). Step 2: For each feature, calculate the partial derivative of log-likelihood to its corresponding θ using the calculated probabilities from step 1 gradient = (y - prob) @ X This is also where numpy’s vectorized operations shine: y - prob: a straightforward element-by-element subtraction of the real label and the predicted probability for all data points, resulting in a 1-D numpy array of dimension (46) representing the differences. (y - prob) @ X: before the y - prob differences vector (46) is multiplied with the feature matrix X, it is transposed by numpy behind the scenes into a row vector of dimension (1, 46), which allows its dimension to line up with that of X(46, 3). This transpose is also called in numpy as “prepending 1 to dimension” of the column vector. Once the dimensions are lined up, the vector-matrix multiplication between y - prob and X can occur: dot products are taken between the row vector of y - prob and each feature column of X (see bolded cells in the diagram). This is indeed the summation of (y(i) — P(y(i)=1)) * xj(i) over all data point i’s to get the partial derivative of the log-likelihood for feature j (Equation 2). More impressively, this partial derivative can be calculated for all three features at once under this vector-matrix multiplication, resulting in a vector of partial derivatives called the gradient. Technically, this vector should be of dimension (1, 3) from multiplying a (1, 46) vector with a (46, 3) matrix. However, behind the scenes, the “prepended 1 (before multiplication) is removed” by numpy after multiplication, and the final gradient vector is a 1-D array of dimension (3). These behind-the-scenes “contortions” that numpy applies to its arrays before and after multiplication can be referred from the documentation of numpy.matmul, which implements the matrix multiplication operator @. If the first argument is 1-D, it is promoted to a matrix by prepending a 1 to its dimensions. After matrix multiplication the prepended 1 is removed. — numpy.matmul documentation Step 3: For each feature, update its θ by the partial derivative in step 2 multiplied by the learning rate α alpha = 0.01theta = theta + alpha * gradient This can’t be more straightforward: instead of updating each θ, we can update all 3 θ’s at once by multiplying the gradient vector of partial derivatives with some pre-defined learning rate alpha, and adding the product to the theta vector. Step 4: Repeat step 1 to 3 until convergence This can be easily done by nesting the previous 3 lines of code— one for each step (see bolded code block below)— into a for loop that iterates many times. Presented below is the entire algorithm for batch gradient ascent running for 100 iterations (isn’t it amazing how simple the implementation can be?!): theta = np.array([0.5, 0.5, 0.5])alpha = 0.01for _ in range(100): prob = 1 / (1 + np.exp(-X @ theta)) gradient = (y - prob) @ X theta = theta + alpha * gradient One way to check for convergence of the algorithm is to see if the difference in log-likelihood stays below some small tolerance level for the past few iterations of the loop, which indicates that the log likelihood has likely reached its maximum. Using the dot products of y and prob(and of their respective complements), the log-likelihood can be computed simply as: log_likelihood = y @ np.log(prob) + (1 - y) @ np.log(1 - prob) Another (perhaps more fun) way is to run the algorithm for some number of iterations and visualize whether the log-likelihood has reached its likely maximum. Below is a visualization of 60 iterations of the batch gradient ascent algorithm with learning rate α = 0.01: As seen from the above animation, the average log-likelihood (log-likelihood divided by number of training data, see middle panel) rises quickly for the first 10 iterations but starts to plateau after that. At the 60th iteration, the difference in average log-likelihood between iterations is in the order of 10^-5, which indicates a good enough convergence. This also corresponds to the convergence of the regression coefficients (θ’s) in the left panel. Another way to visualize this convergence is through the classification boundary (see right panel). The classification boundary, also called the decision boundary, represents the line where the predicted probability of weight gain is 50%: every point above it will have predicted probability below 50% — hence classified as weight loss — and every point below it will have probability above 50% — hence classified as weight gain. Over these 60 iterations, the decision boundary seems to settle down to a reasonable boundary that separates most of the weight loss days (green) from the weight gain days (red). Now that we have a converged logistic regression model that classifies my training data pretty well (at least from eyeballing the decision boundary), let’s see how we can improve on it. Given a fixed number of iterations, the value of learning rate (α) can determine whether the algorithm will converge after these iterations, or even if it will converge at all: When α is reduced to 0.001 (from the original 0.01), learning of θ’s happens much slower, and after 60 iterations, the average log-likelihood still shows signs of increase. Therefore, the number of iterations should be increased at this small learning rate, or the learning rate itself should be bumped up. However, if the learning rate is too high, the θ’s could be “over-corrected” and bounce around the optimum point after each update. This can be seen from the convergence animation below when α = 1, which doesn’t seem to converge after 60 iterations. Therefore, the learning rate should be reduced in those cases. With α = 0.01 as the sweet spot for our learning rate, we can of course always increase the number of iterations to make sure our model converges well and good to the maximum log-likelihood. Indeed, at 1000 iterations, the difference in average log-likelihood between iterations is effectively zero. Even though my logistic regression model has converged to the max log-likelihood of my training data, it might have overfit that training data i.e. it learns from the data a little too well. As a result, the model might predict well on past data that I’ve collected in 2018, but might be terrible if I were to use it to predict my weight gain in 2019. One solution to reduce the overfitting of logistic regression is to used the L2-regularized version of the regression (also called ridge regression), which subtracts the original log-likelihood by a term consisting of squares of the θ’s: As a result, maximizing the above function is equivalent to maximizing the log-likelihood of training data as much as possible while keeping θ’s low (as higher θ’s will lower L). The lambda symbol (λ) represents the degree that θ’s are kept low (often called the regularization hyper-parameter of the model). When λ = 0, ridge regression returns exactly to the original, non-regularized logistic regression. In terms of implementation of ridge regression, the only difference from the original logistic regression is in the calculation of partial derivatives (equation 2) of batch gradient ascent, where a λ*θj regularization term is subtracted from the partial derivative of each feature j: One caveat is that this regularization is not often done to the intercept θ, so the partial derivatives of θ_intercept is calculated the same as the non-regularized version i.e. without subtracting this λ*θ term. This implementation is easily integrated into our existing Python code by: Multiplying theta with the regularization hyperparameter lambda_reg to get reg_term — the λ*θ regularization term of dimension (3).Setting the first element of reg_term to zero to represent the fact that θ_intercept is not regularizedSubtracting reg_term from (y - prob) @ X to find the gradient. Multiplying theta with the regularization hyperparameter lambda_reg to get reg_term — the λ*θ regularization term of dimension (3). Setting the first element of reg_term to zero to represent the fact that θ_intercept is not regularized Subtracting reg_term from (y - prob) @ X to find the gradient. Below is the code for ridge regression with λ = 10, with modifications to the original algorithm shown in bold: theta = np.array([0.5, 0.5, 0.5])alpha = 0.01lambda_reg = 10for _ in range(100): prob = 1 / (1 + np.exp(-X @ theta)) reg_term = lambda_reg * theta reg_term[0] = 0 gradient = (y - prob) @ X - reg_term theta = theta + alpha * gradient When convergence is monitored for this ridge regression at 60 iterations, we can see that: At λ = 10, the θ for my two main features (calories surplus and step count, see left panel) converge to values much closer to zero i.e. lower in magnitude compared to the non-regularized version (λ = 0). The convergence of the intercept θ, however, is largely unaffected. The average log-likelihood of ridge regression converges to a lower value than that of the non-regularized version (see middle panel), indicating that ridge regression provides a less perfect fit to my training data, but this might also mean it overfits my training data less. The decision boundary of the ridge regression is a little off from the non-regularized boundary (see right panel). However, it still seems to separate my training data points (red from green) pretty well. As λ increases, the learned regression coefficients (θ) are further squeezed towards zero, except that of the intercept (see left panel below). Furthermore, ridge regression becomes less and less effective in classifying my training data, as seen from the decision boundaries: the decision boundary at λ = 1 is quite close from the non-regularized boundary, while at λ = 100, the boundary is virtually unusable (see right panel). However, the purpose of ridge regression is not to improve the fit on training data (because if so, it will always perform worse than the non-regularized version, as seen above). Rather, it is to improve the prediction on new data i.e. data that the ridge regression had not been trained from. To compare ridge regression with its non-regularized counterpart, I use 2-fold cross-validation as outlined below: 1. Split the 46 data points randomly into 2 equal folds/parts: A & B (each 23 data points) 2. Train ridge regression on part A — the training set — and record the recall on the training set (days with correctly predicted weight gain / days with true weight gain in part A) 3. Use the θ’s trained on part A to predict whether I would gain weight on the days of part B — the validation set — and record the recall on the validation set (days with correctly predicted weight gain / days with true weight gain in part B) 4. Repeat step 2 and 3 with the parts switched i.e. part B is now the training set, and part A the validation set 5. Average the training set recalls across both trials, and similarly for the validation set recalls There are two fundamental metrics to measure how well a classifier works: precision and recall. In this context: Personally, I would not care if the classifier predicts that I would gain weight while it turns out I don’t; in fact, that would even be a welcome surprise! Therefore, I’m not too concerned about false positives among the predicted weight gain days. In other words, precision is not that important to me. On the other hand, I’m more likely to obsess over whether the classifier would flag all the days where I truly end up gaining weight, lest they escape as false negatives (classifier predicts I would lose weight when it’s the exact opposite). In other words, I will try to improve recall as much as possible. Below are the average train and validation recalls at different levels of regularization, with λ ranging from 0 (non-regularized) to 10: From the left graph, the average training set recall stays at a constant level as λ increases from 0, and only starts to drop at λ near 10. This is consistent with the earlier observation that the performance of ridge regression on training data gets worse as λ increases. On the other hand, the average validation set recall has a noticeable bump for λ between 0.1 and 1, indicating that the ridge regression at these λ’s performs better than its non-regularized counterpart on new validation data, even though both perform equally well on training data. Upon further inspection, it turns out a true weight gain day (red with black border, see below graph) in one of the validation sets was incorrectly classified as weight loss by the non-regularized regression: it stays above the (solid) decision boundary. On the other hand, when λ = 0.5 — halfway between 0.1 and 1 — the decision boundary twists slightly. As a result, this point stays below this (dashed) decision boundary, and was correctly classified. This was the sole reason that ridge regression at λ = 0.5 has better recall on the validation set compared to its non-regularized counterpart. Although these results suggest I should choose the λ value with the highest average validation set recall (λ = 0.5), the small number of data points in the validation set (23), within which there are even smaller number of weight gain points (red), suggests that this improved performance might just be due to luck. This also explains why for some λ’s, the performance on the validation set is higher than that of the training set at the same λ, even though the opposite usually happens; I could just have a “lucky” validation set. That said, there is no harm in choosing λ = 0.5, given that when trained on my entire data of 46 points, its decision boundary is virtually indistinguishable from that of λ = 0, as seen from the earlier graph on decision boundaries at different λ’s (from 0 to 100). Therefore, I choose to stay with λ = 0.5 for my final model. Choosing λ is not the most the most influential decision in tweaking my model. Rather, choosing the threshold for my decision boundary is: For all the regression models that I have built thus far, the classification threshold, hence the decision boundary, is set at 50% (or 0.5). This is a reasonable threshold, as days with predicted probability of weight gain above 50% should naturally be classified as days with weight gain, and vice versa. However, when this weight gain threshold is lowered, more and more data points will be classified as weight gain (correctly or not). Recall, which also goes by true positive rate, will of course increase, but false positive rate — days mistakenly predicted as weight gain out of days with true weight loss — will increase in lockstep (see the left panel, and also the ROC curve in the middle panel below). Nevertheless, as mentioned earlier, since I’m not too worried about false positives, I can tolerate many weight loss days mistakenly classified as weight gain i.e. high false positive rate, if that means my true weight gain days are better detected i.e. high true positive rate/recall. If that’s the case, should the threshold be set as low as possible, even to 0%? No, because: When the threshold is lowered, the decision boundary shifts up. For example, for recall to increase to the nearest upper level, the threshold must decrease from 50% to 44% (from black to brown in the left panel). As a result, the decision boundary shifts up to capture one more weight gain point (red point with brown border in the right panel). This corresponds to a leftward shift of 107 kcal. In other words, if I were at the 50% boundary before, I have to eat 107 kcal less at the same step count in order to stay on the good weight loss side of the 44% boundary. At the extreme end where threshold is near 0% (orange point in the left panel), the boundary shifts way up so that it captures all weight gain points, including the topmost red point with orange border (right panel). This decision boundary dictates that on my lazy day, where I average nearly 2500 steps, I should eat 1740 kcal below my budget to stay on the good side. Given that the average budget in my data is around 1715 kcal, this translates to an upper limit of -25 calories on those lazy days (yes, you read that right). Sure, my recall would be amazing at this physics-defying limit, but I would be dead! So should I reduce my threshold after all? Given that the 50% decision boundary learned from my data is already quite conservative — on lazy days, it suggests that I should eat around 140 kcal below the usual 1700+ kcal budget — I’ve decided to stick with the default 50% threshold. Dropping that threshold to the next possible level of 44% would gain me few more points on recall, but the extra 107 kcal restriction is not worth losing my sanity over. To recap, we have trained a logistic regression classifier via the gradient ascent algorithm, using my daily calories surplus and step counts as features, and my weight gain status as labels. The parameters for our model are: Learning rate: α = 0.01 Regularization parameter: λ = 0.5 Threshold: 50% After training the classifier on the entire data set, the learned regression coefficients (θ’s) come out to: One common interpretation of the logistic regression coefficients is through odds ratio: how many times the odds of the outcome changes for one unit change of the feature. For a feature j, the odds ratio of that feature is just the exponential of its θ. Recall that logistic regression was performed on the normalized values of calories surplus (found by subtracting the surplus mean and dividing by the surplus standard deviation). Therefore, θ_surplus = 0.9 implies that at any step count, a standard deviation decrease in calories surplus — about 420 kcal — corresponds to e^0.9, or 2.5 times decrease in the odds that I will gain weight. On the other hand, with θ_step = -1.2, a standard deviation increase in my step count — about 5980 steps — corresponds to e^1.2, or 3.3 times decrease in the odds that I will gain weight (at any amount of calories surplus). From my last 10 workouts, I have an average cadence of 1366 steps/km. As a result, these 5890 steps translates to about 4.4 km. In other words: A standard deviation increase in step counts (5980 steps) is 36% more effective in reducing my weight gain odds than a standard deviation decrease in calories consumed (420 kcal). Of course, my willingness to run 4.4 km instead of not eating that 420-kcal bowl of pho is another matter entirely! Although odds ratio offers some insights in how I should strategize my weight loss, a more actionable plan could be drawn from the decision boundary of my logistic regression classifier. Recall our trusty sigmoid function from earlier: It can easily be seen that for the probability of weight loss to be 50% (where the classification threshold is), the linear combination of θ’s and x’s must be zero* (I’ve also replaced x_intercept by 1): * For other probability thresholds, the linear combination of θ’s and x’s can be found by taking the logit of the threshold: ln(p/(1-p)) However, the x’s used in our logistic regression were the normalized values of our original features. Therefore, we can rewrite the above equation as: Rearranging, we have: Plugging θ’s and the feature means (μ) and standard deviations (σ) to the above equation gives the linear equation between the original calories surplus and step count features: Graphically, this equation represents the decision boundary in the original surplus-step plot (see left panel below). From this decision boundary, there are 3 important numbers that I should keep in mind (see right panel): This is how much I should be eating below the Loseit app’s calories budget on my lazy days (in which I average 2480 steps). With the average budget of just above 1700 kcal, this means on those days I should be eating below 1560 kcal on average. This number sounds quite restrictive indeed. However, one saving grace is that according to the decision boundary, for any 1 km I run beyond my normal activity, I am allowed to increase this limit by 130 kcal. For example, if I had scheduled a 5K run on a given day, I can afford to eat -140 + 130 * 5 = 510 kcal above the calories budget from the app for that day. Hopefully this will encourage me to keep up my running schedule. On the flip side, when I’m tempted to overeat beyond the calories limit (as dictated by the first two rules), any 100 kcal that I eat beyond the limit must be earned with at least 1070 steps. This can be done either by: Walking that 1070 steps around the block before chowing down on that banh bao, or Realizing I’m too lazy for that and putting said food out of my stupid mouth (hey, I just built my own Slap Chef!) I hope to use the above guidelines to be more successful in my weight loss journey in 2019 than in 2018. Of course I won’t always succeed even with the numbers behind me, but the most important lesson I’ve learned from this project is: I should be kind to myself. For example, I do lose weight even if I eat more than the budget on my active days, so I should not feel guilty for doing so. Hopefully, with this new model that incorporates both diet and exercise, I can feel less guilt and shame (like I did before) during my ongoing weight loss journey. Another big reason that I embarked on this project is to implement a machine project without using pre-existing libraries such as scikit-learn. Below are some lessons I learned from that process: When I first learned Python (or any serious programming for that matter) more than a year ago, I was not sure why one would ever use classes. Well, after few dozen times during this project of (a) using the global variable theta, (b) getting some weird result like non-convergence, and (c) realizing said theta belongs to some other model that I ran many moons ago, I now realize why encapsulation in classes is so important: a model object could have its own attributes (theta, alpha, lambda_reg) and methods (fit, predict) that do not clash with those from other model objects, and I can merrily pick it up in one piece the next time I need it. I’m really interested on how classes could be used to model data science problems, and I think with more relevant examples I might be able to appreciate more the powers of object-oriented programming (for now I’m still not quite sure when or how I should use them). — Me when first learning Python This project also allows me to implement and understand the practical benefit of some neat programming concepts that I never had the chance to use, such as using generators i.e. yield statements to return my training and validation folds one at a time. This allows me to evaluate my model only on those folds, then go back and generate more folds, instead of storing all folds in memory at once (although for my data size it makes virtually no difference). Even something as CS101 as writing clear pseudocode turns out to be quite important, especially when implementing mathematically-flavored algorithms like logistic regression; it’s embarrassing to admit the hours I’ve spent debugging from not writing explicit pseudocode beforehand and swapping alpha and theta by mistake. Lastly, this project helps me grok in more details the implementations of some of the machine learning libraries that I often used, such as the occasional warning that I have to specify either max_iter or tol when training a scikit-learn model: the former to specify the number of iterations to let the model converge, the latter to specify the tolerance level below which iterations are stopped — exactly the two choices I faced when checking for convergence for my own model. Another example of this is I now learn some of the scikit-learn models do not behave like I would expect them to: SGDClassifier(loss=’log’, penalty=’l2', learning_rate=’constant’) does not seem to shrink the θ of the intercept, and gave similar θ’s to my model, while LogisticRegression(penalty=’l2') shrinks the θ of intercept at the default setting, unless one fiddles with the intercept_scaling parameter. As a result, I will be more careful when using third-party libraries to analyze my data in the future, and validate the result when necessary. I took most of the derivations for logistic regression and its gradient ascent method from the corresponding lecture note and video lectures of CS229 (a machine learning course taught by professor Andrew Ng that I highly recommend). The note provides the formula for stochastic gradient ascent, but the batch version can be easily modified from that (as seen in the math review section earlier). A more accessible explanation can be found in week 3 of his machine course on Coursera. This course also covers the application of ridge regression on logistic regression, which the CS229 course does not. One small detail: the Coursera course refers to logistic regression as minimizing the log-loss using stochastic gradient descent. However, this is identical to maximizing the log-likelihood using stochastic gradient ascent that I had implemented, with the log-loss nothing more than the negative of the log-likelihood (with some minor modifications). Another good explanation for logistic regression and ridge regression is from the University of Washington’s Coursera course on classification methods. This course thankfully uses log-likelihood maximization to explain logistic regression so it should be consistent with the notations from CS229 and mine. Last but not least are two weight loss analysis projects I found on the web that really inspired my own project: one from Will Koehrsen, who uses only his past weights to forecast future weight loss, and at the other end of the spectrum is one from Ariel Faigon, who uses dozens of factors to predict how much weight he gains or loses each day, and comes up with very interesting results: apparently sleep is the most important factor for his weight loss! My approach is somewhere in the middle, using only 2 features to predict whether I would lose weight or not, which allows for easy visualization and simple, actionable insights that I can take away for my weight loss journey I hope that my project can inspire others to use machine learning and data science to help them understand more about themselves and accomplish personal goals such as weight loss. Please don’t hesitate to contact me on Medium if you have any question or feedback!
[ { "code": null, "e": 248, "s": 172, "text": "To see the code I wrote for this project, you can check out its Github repo" }, { "code": null, "e": 760, "s": 248, "text": "I began my weight loss journey at the start of 2018, following the oft-cited advice of “weight loss = diet + exercise”. On the diet side, I started tracking my daily food consumption (using a food scale and recording calories via the Loseit app). On the exercise side, I started following the Couch to 5K program, and to date have finished four 5K’s, one 10K, and from a few weeks ago, a half-marathon. Lastly, every morning, I weighed myself right after waking up and recorded my weight in the same Loseit app." }, { "code": null, "e": 1451, "s": 760, "text": "Anyone trying to lose weight will inevitably hit a weight-loss plateau, where the initial speedy weight loss starts to slow down. Personally, I hit a major plateau right after my vacation at the start of May. After that, I abandoned tracking my progress for nearly three months. Only after I replaced my dying Pebble smartwatch with an Amazfit Bip did I gain back some motivation to hit the resume button, partly since I could start tracking my steps with the new watch. However, my weight continued to plateau, and after a further two months of frustrating weight fluctuations (see dotted region below), I stopped tracking my weight and calories altogether. That was November of last year." }, { "code": null, "e": 1779, "s": 1451, "text": "It’s now 2019, and as Tet (Vietnamese New Year) recently drew to a close, I’ve decided to look more closely at the data collected during that two-month period, hoping to discover interesting relationships between my weight loss and the tracked calories/steps so that I could build a more effective weight loss plan than before." }, { "code": null, "e": 2251, "s": 1779, "text": "Calories: exported from my Loseit account as CSV files. For some strange reason, Loseit only allows calories data to be exported one week at a time, but joining them together is nothing a quick Python script can’t do. Each date has corresponding calories counts from all the food I logged during that day, as well as a calories “budget” that the app calculated for me based on my weight that day and the weight loss goal that I initially specified (to lose 0.75 kg/week)." }, { "code": null, "e": 2630, "s": 2251, "text": "Steps: the Android app of my Amazfit Bip smartwatch doesn’t allow data export unless one uses some hairy workaround with third-party tools. Therefore, the quickest method to obtain my steps data was to manually scroll through the dozens of dates (within this two-month period) on my phone and enter the steps for each date into a CSV file. Not elegant at all, but hey, it works!" }, { "code": null, "e": 2777, "s": 2630, "text": "Weight: thankfully the Loseit website allows me to export all my recorded weights — and the dates on which they were taken — as a single CSV file." }, { "code": null, "e": 3052, "s": 2777, "text": "After joining these 3 data sources together by date, I end up with calories+steps+weight data for only 46 dates out of this two-month period. Apparently I neglected to record at least one of these three data in quite a few dates (many of them weekends, for obvious reasons)." }, { "code": null, "e": 3132, "s": 3052, "text": "From those three raw data sources, three additional data fields are calculated:" }, { "code": null, "e": 3560, "s": 3132, "text": "Surplus = calories consumed - calories budget. Positive surplus means I had eaten more calories than the budget allowed for that day, and vice versa. I choose to use calories surplus instead of raw calories consumed since the calories budget from the app naturally varies as my weights rise and fall, so calories surplus (which takes into account said budget) is a more accurate measure of my eating habits than calories alone." }, { "code": null, "e": 3707, "s": 3560, "text": "Weight gain = tomorrow weight - today weight. Positive weight gain of a given date means I had gained weight over that day (duh!), and vice versa." }, { "code": null, "e": 4186, "s": 3707, "text": "Weight gain status: positive weight gain would be labeled as 1, and negative or zero weight gain would be labeled as 0. I decide to use the binary weight gain status–whether I had gained weight or not– rather than the more granular weight gain amount since obsessing over gaining 0.5 kg versus 0.3 kg is quite counter-productive, not least because the amount of weight gain can be influenced by many factors beside calories and steps (such as water intake, time of eating, etc)." }, { "code": null, "e": 4456, "s": 4186, "text": "When plotting calories surplus and number of steps of each day against my weight gain status over that day (see first two panels below), there seems to be no apparent patterns on how these two reportedly important factors can predict whether I would gain weight or not." }, { "code": null, "e": 4913, "s": 4456, "text": "However, when plotting both calories surplus and steps together (right panel above), very interesting patterns emerge! For example, right away I can tell that there are two distinct groups of dates in terms of my step counts: those below 5000 steps (my \"baseline\" lazy days) that lie neatly around a horizontal line, and those above 5000 steps (my active days), largely thanks to my running. In terms of calories surplus, there are three main observations:" }, { "code": null, "e": 5211, "s": 4913, "text": "1. On my lazy days, if I eat above my calories budget limit, it's gonna be bad news the following day when I step onto the scale. There were some miracles, such as that one day where I ate almost 1500 calories above my limit and did not gain weight the next day, but those are few and far between." }, { "code": null, "e": 5517, "s": 5211, "text": "2. On the other hand, if I eat below my calories budget limit on my lazy days, I'm not totally in the clear either: there are quite a few days where I was a good boy and ate my salads (figuratively), yet still gained weight. This suggests that I should be even more conservative in my eating on lazy days." }, { "code": null, "e": 5715, "s": 5517, "text": "3. However, on my active days, it seems I can afford to eat more than my calories limit, as there are several active days where I ate more than what the limit allowed and still did not gain weight." }, { "code": null, "e": 5869, "s": 5715, "text": "These observations suggest that I should factor in my daily activity (in the form of step counts) instead of using the default limit from the Loseit app." }, { "code": null, "e": 6024, "s": 5869, "text": "For example, on the surplus-step plot above, I can draw a straight line that largely separates my weight gain days (red) from my weight loss days (green)." }, { "code": null, "e": 6181, "s": 6024, "text": "I can then use that linear boundary to inform my weight loss strategy i.e. how I can stay on the weight loss side of the boundary instead of the other side." }, { "code": null, "e": 6340, "s": 6181, "text": "In machine learning parlance, this is equivalent to building a linear classifier for binary classification of my data (classify weight gain from weight loss)." }, { "code": null, "e": 6566, "s": 6340, "text": "There are several common methods to build a linear classifier from data, such as logistic regression, linear discriminant analysis, or support vector machine. However, for this project, I will use logistic regression because:" }, { "code": null, "e": 6714, "s": 6566, "text": "It's easy to interpret: for example, the equation for the classification boundary can be easily obtained from the logistic regression coefficients." }, { "code": null, "e": 7035, "s": 6714, "text": "It's easy to implement: a very important reason since another goal for this project is for me to implement a machine learning project without using pre-existing libraries (such as scikit-learn). As I will show later, the core of the learning algorithm for logistic regression can be accomplished in just 3 lines of code!" }, { "code": null, "e": 7274, "s": 7035, "text": "With this choice of model, let's see how logistic regression can implemented and interpreted using my data. However, this requires us to review some math on how the logistic regression classifier works and how it can be learned from data." }, { "code": null, "e": 7652, "s": 7274, "text": "Please note that this math review is primarily to establish a common notation so that we are on the same page before the algorithm is implemented from the mathematical equations. If you want to understand how these equations are derived and the intuition behind them, I have linked to further resources at the end of this blog post that can do these jobs way better than I can." }, { "code": null, "e": 7939, "s": 7652, "text": "In logistic regression, the predicted probability that I will gain weight on a given day is the sigmoid function applied to a weighted linear combination of my features (calories surplus and step counts) plus an constant intercept term. This relationship is mathematically expressed as:" }, { "code": null, "e": 7945, "s": 7939, "text": "where" }, { "code": null, "e": 8012, "s": 7945, "text": "y(i): weight again status of date i (1=weight gain, 0=weight loss)" }, { "code": null, "e": 8079, "s": 8012, "text": "P(y(i)=1): predicted probability that I will gain weight on date i" }, { "code": null, "e": 8174, "s": 8079, "text": "x(i): observed values of the respective features (calories surplus and step counts) at date i*" }, { "code": null, "e": 8263, "s": 8174, "text": "θ: regression coefficients/weights of the respective features (to be learned from data)*" }, { "code": null, "e": 8473, "s": 8263, "text": "* Note that I have added an additional feature (x_intercept), which will always be equal to 1 so that the intercept term (θ_intercept) could be learned along with the coefficients of the two existing features." }, { "code": null, "e": 8766, "s": 8473, "text": "Therefore, once θ’s have been learned from data, logistic regression can be used to classify whether I will gain weight on any given day — given my calories surplus and step count — by checking if the probability that I will gain weight on that day is above a certain threshold (usually 50%)." }, { "code": null, "e": 8959, "s": 8766, "text": "The regression coefficients (θ’s) are learned via maximizing the logarithm of the probability of observing my training data (also called the log-likelihood). The formula for log-likelihood is:" }, { "code": null, "e": 8965, "s": 8959, "text": "where" }, { "code": null, "e": 9016, "s": 8965, "text": "L: log-likelihood of training data (m data points)" }, { "code": null, "e": 9087, "s": 9016, "text": "y(i): true weight gain status of date i (1=weight gain, 0=weight loss)" }, { "code": null, "e": 9199, "s": 9087, "text": "P(y(i)=1): predicted probability that I will gain weight on date i (obtained from the sigmoid function earlier)" }, { "code": null, "e": 9523, "s": 9199, "text": "From the sigmoid function, different values of θ’s will produce different predicted probabilities of weight gain — P(y(i)=1) — and as a result, different log-likelihood. Therefore, the goal is to find the set of θ’s that maximize the log-likelihood of my training data i.e. the θ’s that “explain” my training data the best." }, { "code": null, "e": 9674, "s": 9523, "text": "One straightforward algorithm to find the θ’s that maximize the log-likelihood of my training data is batch gradient ascent, which is described below:" }, { "code": null, "e": 9746, "s": 9674, "text": "Step 0: Initialize some values for θ’s (θ_intercept, θ_surplus, θ_step)" }, { "code": null, "e": 10001, "s": 9746, "text": "Step 1: For each training data point i, calculate the probability of weight gain using the feature values of that data point (x_intercept*, x_surplus, x_step), and the values of θ’s initialized in step 0. This is done using the familiar sigmoid function:" }, { "code": null, "e": 10025, "s": 10001, "text": "*recall x_intercept = 1" }, { "code": null, "e": 10193, "s": 10025, "text": "Step 2: For each feature j — intercept/surplus/step — find the partial derivative of the log-likelihood with respect to the θ of that feature using the below equation:" }, { "code": null, "e": 10199, "s": 10193, "text": "where" }, { "code": null, "e": 10275, "s": 10199, "text": "∂L/∂θj: partial derivative of log-likelihood with respect to θ of feature j" }, { "code": null, "e": 10347, "s": 10275, "text": "y(i): true weight again status of date i (1=weight gain, 0=weight loss)" }, { "code": null, "e": 10419, "s": 10347, "text": "P(y(i)=1): predicted probability of weight gain of date i (from step 1)" }, { "code": null, "e": 10524, "s": 10419, "text": "xj(i): observed value of feature j (intercept/surplus/step) on date i, with x_intercept(i) = 1 for any i" }, { "code": null, "e": 10717, "s": 10524, "text": "Step 3: For each feature j, update its θ by the partial derivative of the log-likelihood with respect to that θ (from step 2), multiplied by a small constant (also called the learning rate α):" }, { "code": null, "e": 10946, "s": 10717, "text": "This learning rate controls how fast the algorithm will converge to the maximum of the log-likelihood, or even whether it converges at all (see the later section on visualizing the convergence of the algorithm for more details)." }, { "code": null, "e": 11162, "s": 10946, "text": "Step 4: With these updated θ’s, repeat step 1 to step 3 until convergence. One way to test for convergence is to see if the log-likelihood has converged to a stable value i.e. that it has reached the likely maximum." }, { "code": null, "e": 11637, "s": 11162, "text": "The summation sign within step 2 — summing (y(i) - P(y(i)=1)) * xj(i) over all data points i to calculate partial derivative— is the reason why this gradient ascent algorithm is of the batch variety, as each partial derivative is computed using all data points in the training data. Without this summation sign i.e. the partial derivative is computed using only one data point; assuming that data point is randomly chosen, the gradient ascent algorithm is called stochastic." }, { "code": null, "e": 12025, "s": 11637, "text": "For this project, I choose to implement batch gradient ascent since my training data is very small (only 46 data points), so there’s no problem using the entire training data set at once to calculate partial derivatives. Another reason is that batch gradient ascent can be implemented more easily using numpy’s vectorized operations (please refer to its implementation below to see how)." }, { "code": null, "e": 12222, "s": 12025, "text": "From my previous data table, I use the calories surplus and step count columns as my features, and the weight gain status column as the label (see left) to train my logistic regression classifier." }, { "code": null, "e": 12321, "s": 12222, "text": "However, before I can implement the batch gradient ascent algorithm on this data, I first need to:" }, { "code": null, "e": 12589, "s": 12321, "text": "Add a column of 1’s to my training data to represent the values of the x_intercept feature.Rescale my calories surplus and step count features by (a) subtracting each feature column by its mean and (b) dividing by its standard deviation. This is done for two reasons:" }, { "code": null, "e": 12681, "s": 12589, "text": "Add a column of 1’s to my training data to represent the values of the x_intercept feature." }, { "code": null, "e": 12858, "s": 12681, "text": "Rescale my calories surplus and step count features by (a) subtracting each feature column by its mean and (b) dividing by its standard deviation. This is done for two reasons:" }, { "code": null, "e": 13393, "s": 12858, "text": "Recall that the sigmoid function (left) involves an exponential of linear combination of x’s, so very small/large values of x will make this exponential implode/explode. Indeed, before I rescaled my features, I had terrible convergence that I could not figure out why. Only when I by chance looked at the Jupyter terminal (not the Jupyter notebook output) did I see the pages of underflow/overflow warnings that numpy had silently produced! After I rescaled my features, these warnings went away and my algorithm was able to converge." }, { "code": null, "e": 13631, "s": 13393, "text": "By reducing my features to the same scale, I can use the regression coefficients for these features (θ’s) to weigh their relative importance in my weight gain/loss. This will be elaborated later in the interpretation section of my model." }, { "code": null, "e": 13800, "s": 13631, "text": "After the above two steps, my feature matrix (X) is converted to a 2–D numpy array of dimension (46, 3), and my label vector (y) to a 1-D numpy array of dimension (46)." }, { "code": null, "e": 13823, "s": 13800, "text": "Step 0: Initialize θ’s" }, { "code": null, "e": 13857, "s": 13823, "text": "theta = np.array([0.5, 0.5, 0.5])" }, { "code": null, "e": 13944, "s": 13857, "text": "I initialize all my θ’s to 0.5. The result is a 1-D numpy array theta of dimension (3)" }, { "code": null, "e": 14061, "s": 13944, "text": "Step 1: For each data point, calculate the probability of weight gain using θ’s from step 0 and the sigmoid function" }, { "code": null, "e": 14097, "s": 14061, "text": "prob = 1 / (1 + np.exp(-X @ theta))" }, { "code": null, "e": 14277, "s": 14097, "text": "This is where numpy’s vectorized operations come in handy, as instead of calculating the probability of weight gain for each data point, numpy does it for all data points at once:" }, { "code": null, "e": 14530, "s": 14277, "text": "X @ theta: by multiplying matrix X with vector theta , numpy essentially calculates the linear combinations of x’s and θ’s for each and every data point by taking the dot product of each row of X with the theta column (see bolded cells in the diagram)." }, { "code": null, "e": 14976, "s": 14530, "text": "1 / (1 + np.exp(-X @ theta)): after linear combinations of x’s and θ’s for all data point are calculated, the sigmoid function is applied to each of them to get the final probabilities of weight gain for all data points. Notice that the operations in this sigmoid function (/, +, -, np.exp) all represent vectorized functions that numpy runs behind the scene. This finally output the probability vector prob, a 1-D numpy array of dimension (46)." }, { "code": null, "e": 15123, "s": 14976, "text": "Step 2: For each feature, calculate the partial derivative of log-likelihood to its corresponding θ using the calculated probabilities from step 1" }, { "code": null, "e": 15149, "s": 15123, "text": "gradient = (y - prob) @ X" }, { "code": null, "e": 15205, "s": 15149, "text": "This is also where numpy’s vectorized operations shine:" }, { "code": null, "e": 15412, "s": 15205, "text": "y - prob: a straightforward element-by-element subtraction of the real label and the predicted probability for all data points, resulting in a 1-D numpy array of dimension (46) representing the differences." }, { "code": null, "e": 15750, "s": 15412, "text": "(y - prob) @ X: before the y - prob differences vector (46) is multiplied with the feature matrix X, it is transposed by numpy behind the scenes into a row vector of dimension (1, 46), which allows its dimension to line up with that of X(46, 3). This transpose is also called in numpy as “prepending 1 to dimension” of the column vector." }, { "code": null, "e": 16335, "s": 15750, "text": "Once the dimensions are lined up, the vector-matrix multiplication between y - prob and X can occur: dot products are taken between the row vector of y - prob and each feature column of X (see bolded cells in the diagram). This is indeed the summation of (y(i) — P(y(i)=1)) * xj(i) over all data point i’s to get the partial derivative of the log-likelihood for feature j (Equation 2). More impressively, this partial derivative can be calculated for all three features at once under this vector-matrix multiplication, resulting in a vector of partial derivatives called the gradient." }, { "code": null, "e": 16836, "s": 16335, "text": "Technically, this vector should be of dimension (1, 3) from multiplying a (1, 46) vector with a (46, 3) matrix. However, behind the scenes, the “prepended 1 (before multiplication) is removed” by numpy after multiplication, and the final gradient vector is a 1-D array of dimension (3). These behind-the-scenes “contortions” that numpy applies to its arrays before and after multiplication can be referred from the documentation of numpy.matmul, which implements the matrix multiplication operator @." }, { "code": null, "e": 16986, "s": 16836, "text": "If the first argument is 1-D, it is promoted to a matrix by prepending a 1 to its dimensions. After matrix multiplication the prepended 1 is removed." }, { "code": null, "e": 17015, "s": 16986, "text": "— numpy.matmul documentation" }, { "code": null, "e": 17124, "s": 17015, "text": "Step 3: For each feature, update its θ by the partial derivative in step 2 multiplied by the learning rate α" }, { "code": null, "e": 17169, "s": 17124, "text": "alpha = 0.01theta = theta + alpha * gradient" }, { "code": null, "e": 17410, "s": 17169, "text": "This can’t be more straightforward: instead of updating each θ, we can update all 3 θ’s at once by multiplying the gradient vector of partial derivatives with some pre-defined learning rate alpha, and adding the product to the theta vector." }, { "code": null, "e": 17455, "s": 17410, "text": "Step 4: Repeat step 1 to 3 until convergence" }, { "code": null, "e": 17763, "s": 17455, "text": "This can be easily done by nesting the previous 3 lines of code— one for each step (see bolded code block below)— into a for loop that iterates many times. Presented below is the entire algorithm for batch gradient ascent running for 100 iterations (isn’t it amazing how simple the implementation can be?!):" }, { "code": null, "e": 17933, "s": 17763, "text": "theta = np.array([0.5, 0.5, 0.5])alpha = 0.01for _ in range(100): prob = 1 / (1 + np.exp(-X @ theta)) gradient = (y - prob) @ X theta = theta + alpha * gradient" }, { "code": null, "e": 18302, "s": 17933, "text": "One way to check for convergence of the algorithm is to see if the difference in log-likelihood stays below some small tolerance level for the past few iterations of the loop, which indicates that the log likelihood has likely reached its maximum. Using the dot products of y and prob(and of their respective complements), the log-likelihood can be computed simply as:" }, { "code": null, "e": 18365, "s": 18302, "text": "log_likelihood = y @ np.log(prob) + (1 - y) @ np.log(1 - prob)" }, { "code": null, "e": 18633, "s": 18365, "text": "Another (perhaps more fun) way is to run the algorithm for some number of iterations and visualize whether the log-likelihood has reached its likely maximum. Below is a visualization of 60 iterations of the batch gradient ascent algorithm with learning rate α = 0.01:" }, { "code": null, "e": 19089, "s": 18633, "text": "As seen from the above animation, the average log-likelihood (log-likelihood divided by number of training data, see middle panel) rises quickly for the first 10 iterations but starts to plateau after that. At the 60th iteration, the difference in average log-likelihood between iterations is in the order of 10^-5, which indicates a good enough convergence. This also corresponds to the convergence of the regression coefficients (θ’s) in the left panel." }, { "code": null, "e": 19698, "s": 19089, "text": "Another way to visualize this convergence is through the classification boundary (see right panel). The classification boundary, also called the decision boundary, represents the line where the predicted probability of weight gain is 50%: every point above it will have predicted probability below 50% — hence classified as weight loss — and every point below it will have probability above 50% — hence classified as weight gain. Over these 60 iterations, the decision boundary seems to settle down to a reasonable boundary that separates most of the weight loss days (green) from the weight gain days (red)." }, { "code": null, "e": 19884, "s": 19698, "text": "Now that we have a converged logistic regression model that classifies my training data pretty well (at least from eyeballing the decision boundary), let’s see how we can improve on it." }, { "code": null, "e": 20061, "s": 19884, "text": "Given a fixed number of iterations, the value of learning rate (α) can determine whether the algorithm will converge after these iterations, or even if it will converge at all:" }, { "code": null, "e": 20368, "s": 20061, "text": "When α is reduced to 0.001 (from the original 0.01), learning of θ’s happens much slower, and after 60 iterations, the average log-likelihood still shows signs of increase. Therefore, the number of iterations should be increased at this small learning rate, or the learning rate itself should be bumped up." }, { "code": null, "e": 20681, "s": 20368, "text": "However, if the learning rate is too high, the θ’s could be “over-corrected” and bounce around the optimum point after each update. This can be seen from the convergence animation below when α = 1, which doesn’t seem to converge after 60 iterations. Therefore, the learning rate should be reduced in those cases." }, { "code": null, "e": 20981, "s": 20681, "text": "With α = 0.01 as the sweet spot for our learning rate, we can of course always increase the number of iterations to make sure our model converges well and good to the maximum log-likelihood. Indeed, at 1000 iterations, the difference in average log-likelihood between iterations is effectively zero." }, { "code": null, "e": 21333, "s": 20981, "text": "Even though my logistic regression model has converged to the max log-likelihood of my training data, it might have overfit that training data i.e. it learns from the data a little too well. As a result, the model might predict well on past data that I’ve collected in 2018, but might be terrible if I were to use it to predict my weight gain in 2019." }, { "code": null, "e": 21571, "s": 21333, "text": "One solution to reduce the overfitting of logistic regression is to used the L2-regularized version of the regression (also called ridge regression), which subtracts the original log-likelihood by a term consisting of squares of the θ’s:" }, { "code": null, "e": 21979, "s": 21571, "text": "As a result, maximizing the above function is equivalent to maximizing the log-likelihood of training data as much as possible while keeping θ’s low (as higher θ’s will lower L). The lambda symbol (λ) represents the degree that θ’s are kept low (often called the regularization hyper-parameter of the model). When λ = 0, ridge regression returns exactly to the original, non-regularized logistic regression." }, { "code": null, "e": 22263, "s": 21979, "text": "In terms of implementation of ridge regression, the only difference from the original logistic regression is in the calculation of partial derivatives (equation 2) of batch gradient ascent, where a λ*θj regularization term is subtracted from the partial derivative of each feature j:" }, { "code": null, "e": 22476, "s": 22263, "text": "One caveat is that this regularization is not often done to the intercept θ, so the partial derivatives of θ_intercept is calculated the same as the non-regularized version i.e. without subtracting this λ*θ term." }, { "code": null, "e": 22551, "s": 22476, "text": "This implementation is easily integrated into our existing Python code by:" }, { "code": null, "e": 22848, "s": 22551, "text": "Multiplying theta with the regularization hyperparameter lambda_reg to get reg_term — the λ*θ regularization term of dimension (3).Setting the first element of reg_term to zero to represent the fact that θ_intercept is not regularizedSubtracting reg_term from (y - prob) @ X to find the gradient." }, { "code": null, "e": 22980, "s": 22848, "text": "Multiplying theta with the regularization hyperparameter lambda_reg to get reg_term — the λ*θ regularization term of dimension (3)." }, { "code": null, "e": 23084, "s": 22980, "text": "Setting the first element of reg_term to zero to represent the fact that θ_intercept is not regularized" }, { "code": null, "e": 23147, "s": 23084, "text": "Subtracting reg_term from (y - prob) @ X to find the gradient." }, { "code": null, "e": 23259, "s": 23147, "text": "Below is the code for ridge regression with λ = 10, with modifications to the original algorithm shown in bold:" }, { "code": null, "e": 23511, "s": 23259, "text": "theta = np.array([0.5, 0.5, 0.5])alpha = 0.01lambda_reg = 10for _ in range(100): prob = 1 / (1 + np.exp(-X @ theta)) reg_term = lambda_reg * theta reg_term[0] = 0 gradient = (y - prob) @ X - reg_term theta = theta + alpha * gradient" }, { "code": null, "e": 23602, "s": 23511, "text": "When convergence is monitored for this ridge regression at 60 iterations, we can see that:" }, { "code": null, "e": 23874, "s": 23602, "text": "At λ = 10, the θ for my two main features (calories surplus and step count, see left panel) converge to values much closer to zero i.e. lower in magnitude compared to the non-regularized version (λ = 0). The convergence of the intercept θ, however, is largely unaffected." }, { "code": null, "e": 24151, "s": 23874, "text": "The average log-likelihood of ridge regression converges to a lower value than that of the non-regularized version (see middle panel), indicating that ridge regression provides a less perfect fit to my training data, but this might also mean it overfits my training data less." }, { "code": null, "e": 24356, "s": 24151, "text": "The decision boundary of the ridge regression is a little off from the non-regularized boundary (see right panel). However, it still seems to separate my training data points (red from green) pretty well." }, { "code": null, "e": 24786, "s": 24356, "text": "As λ increases, the learned regression coefficients (θ) are further squeezed towards zero, except that of the intercept (see left panel below). Furthermore, ridge regression becomes less and less effective in classifying my training data, as seen from the decision boundaries: the decision boundary at λ = 1 is quite close from the non-regularized boundary, while at λ = 100, the boundary is virtually unusable (see right panel)." }, { "code": null, "e": 25080, "s": 24786, "text": "However, the purpose of ridge regression is not to improve the fit on training data (because if so, it will always perform worse than the non-regularized version, as seen above). Rather, it is to improve the prediction on new data i.e. data that the ridge regression had not been trained from." }, { "code": null, "e": 25195, "s": 25080, "text": "To compare ridge regression with its non-regularized counterpart, I use 2-fold cross-validation as outlined below:" }, { "code": null, "e": 25286, "s": 25195, "text": "1. Split the 46 data points randomly into 2 equal folds/parts: A & B (each 23 data points)" }, { "code": null, "e": 25468, "s": 25286, "text": "2. Train ridge regression on part A — the training set — and record the recall on the training set (days with correctly predicted weight gain / days with true weight gain in part A)" }, { "code": null, "e": 25712, "s": 25468, "text": "3. Use the θ’s trained on part A to predict whether I would gain weight on the days of part B — the validation set — and record the recall on the validation set (days with correctly predicted weight gain / days with true weight gain in part B)" }, { "code": null, "e": 25826, "s": 25712, "text": "4. Repeat step 2 and 3 with the parts switched i.e. part B is now the training set, and part A the validation set" }, { "code": null, "e": 25927, "s": 25826, "text": "5. Average the training set recalls across both trials, and similarly for the validation set recalls" }, { "code": null, "e": 26040, "s": 25927, "text": "There are two fundamental metrics to measure how well a classifier works: precision and recall. In this context:" }, { "code": null, "e": 26345, "s": 26040, "text": "Personally, I would not care if the classifier predicts that I would gain weight while it turns out I don’t; in fact, that would even be a welcome surprise! Therefore, I’m not too concerned about false positives among the predicted weight gain days. In other words, precision is not that important to me." }, { "code": null, "e": 26653, "s": 26345, "text": "On the other hand, I’m more likely to obsess over whether the classifier would flag all the days where I truly end up gaining weight, lest they escape as false negatives (classifier predicts I would lose weight when it’s the exact opposite). In other words, I will try to improve recall as much as possible." }, { "code": null, "e": 26790, "s": 26653, "text": "Below are the average train and validation recalls at different levels of regularization, with λ ranging from 0 (non-regularized) to 10:" }, { "code": null, "e": 27063, "s": 26790, "text": "From the left graph, the average training set recall stays at a constant level as λ increases from 0, and only starts to drop at λ near 10. This is consistent with the earlier observation that the performance of ridge regression on training data gets worse as λ increases." }, { "code": null, "e": 27346, "s": 27063, "text": "On the other hand, the average validation set recall has a noticeable bump for λ between 0.1 and 1, indicating that the ridge regression at these λ’s performs better than its non-regularized counterpart on new validation data, even though both perform equally well on training data." }, { "code": null, "e": 27944, "s": 27346, "text": "Upon further inspection, it turns out a true weight gain day (red with black border, see below graph) in one of the validation sets was incorrectly classified as weight loss by the non-regularized regression: it stays above the (solid) decision boundary. On the other hand, when λ = 0.5 — halfway between 0.1 and 1 — the decision boundary twists slightly. As a result, this point stays below this (dashed) decision boundary, and was correctly classified. This was the sole reason that ridge regression at λ = 0.5 has better recall on the validation set compared to its non-regularized counterpart." }, { "code": null, "e": 28476, "s": 27944, "text": "Although these results suggest I should choose the λ value with the highest average validation set recall (λ = 0.5), the small number of data points in the validation set (23), within which there are even smaller number of weight gain points (red), suggests that this improved performance might just be due to luck. This also explains why for some λ’s, the performance on the validation set is higher than that of the training set at the same λ, even though the opposite usually happens; I could just have a “lucky” validation set." }, { "code": null, "e": 28803, "s": 28476, "text": "That said, there is no harm in choosing λ = 0.5, given that when trained on my entire data of 46 points, its decision boundary is virtually indistinguishable from that of λ = 0, as seen from the earlier graph on decision boundaries at different λ’s (from 0 to 100). Therefore, I choose to stay with λ = 0.5 for my final model." }, { "code": null, "e": 28942, "s": 28803, "text": "Choosing λ is not the most the most influential decision in tweaking my model. Rather, choosing the threshold for my decision boundary is:" }, { "code": null, "e": 29248, "s": 28942, "text": "For all the regression models that I have built thus far, the classification threshold, hence the decision boundary, is set at 50% (or 0.5). This is a reasonable threshold, as days with predicted probability of weight gain above 50% should naturally be classified as days with weight gain, and vice versa." }, { "code": null, "e": 29940, "s": 29248, "text": "However, when this weight gain threshold is lowered, more and more data points will be classified as weight gain (correctly or not). Recall, which also goes by true positive rate, will of course increase, but false positive rate — days mistakenly predicted as weight gain out of days with true weight loss — will increase in lockstep (see the left panel, and also the ROC curve in the middle panel below). Nevertheless, as mentioned earlier, since I’m not too worried about false positives, I can tolerate many weight loss days mistakenly classified as weight gain i.e. high false positive rate, if that means my true weight gain days are better detected i.e. high true positive rate/recall." }, { "code": null, "e": 30033, "s": 29940, "text": "If that’s the case, should the threshold be set as low as possible, even to 0%? No, because:" }, { "code": null, "e": 30097, "s": 30033, "text": "When the threshold is lowered, the decision boundary shifts up." }, { "code": null, "e": 30601, "s": 30097, "text": "For example, for recall to increase to the nearest upper level, the threshold must decrease from 50% to 44% (from black to brown in the left panel). As a result, the decision boundary shifts up to capture one more weight gain point (red point with brown border in the right panel). This corresponds to a leftward shift of 107 kcal. In other words, if I were at the 50% boundary before, I have to eat 107 kcal less at the same step count in order to stay on the good weight loss side of the 44% boundary." }, { "code": null, "e": 31215, "s": 30601, "text": "At the extreme end where threshold is near 0% (orange point in the left panel), the boundary shifts way up so that it captures all weight gain points, including the topmost red point with orange border (right panel). This decision boundary dictates that on my lazy day, where I average nearly 2500 steps, I should eat 1740 kcal below my budget to stay on the good side. Given that the average budget in my data is around 1715 kcal, this translates to an upper limit of -25 calories on those lazy days (yes, you read that right). Sure, my recall would be amazing at this physics-defying limit, but I would be dead!" }, { "code": null, "e": 31668, "s": 31215, "text": "So should I reduce my threshold after all? Given that the 50% decision boundary learned from my data is already quite conservative — on lazy days, it suggests that I should eat around 140 kcal below the usual 1700+ kcal budget — I’ve decided to stick with the default 50% threshold. Dropping that threshold to the next possible level of 44% would gain me few more points on recall, but the extra 107 kcal restriction is not worth losing my sanity over." }, { "code": null, "e": 31894, "s": 31668, "text": "To recap, we have trained a logistic regression classifier via the gradient ascent algorithm, using my daily calories surplus and step counts as features, and my weight gain status as labels. The parameters for our model are:" }, { "code": null, "e": 31918, "s": 31894, "text": "Learning rate: α = 0.01" }, { "code": null, "e": 31952, "s": 31918, "text": "Regularization parameter: λ = 0.5" }, { "code": null, "e": 31967, "s": 31952, "text": "Threshold: 50%" }, { "code": null, "e": 32076, "s": 31967, "text": "After training the classifier on the entire data set, the learned regression coefficients (θ’s) come out to:" }, { "code": null, "e": 32330, "s": 32076, "text": "One common interpretation of the logistic regression coefficients is through odds ratio: how many times the odds of the outcome changes for one unit change of the feature. For a feature j, the odds ratio of that feature is just the exponential of its θ." }, { "code": null, "e": 32718, "s": 32330, "text": "Recall that logistic regression was performed on the normalized values of calories surplus (found by subtracting the surplus mean and dividing by the surplus standard deviation). Therefore, θ_surplus = 0.9 implies that at any step count, a standard deviation decrease in calories surplus — about 420 kcal — corresponds to e^0.9, or 2.5 times decrease in the odds that I will gain weight." }, { "code": null, "e": 33070, "s": 32718, "text": "On the other hand, with θ_step = -1.2, a standard deviation increase in my step count — about 5980 steps — corresponds to e^1.2, or 3.3 times decrease in the odds that I will gain weight (at any amount of calories surplus). From my last 10 workouts, I have an average cadence of 1366 steps/km. As a result, these 5890 steps translates to about 4.4 km." }, { "code": null, "e": 33086, "s": 33070, "text": "In other words:" }, { "code": null, "e": 33266, "s": 33086, "text": "A standard deviation increase in step counts (5980 steps) is 36% more effective in reducing my weight gain odds than a standard deviation decrease in calories consumed (420 kcal)." }, { "code": null, "e": 33382, "s": 33266, "text": "Of course, my willingness to run 4.4 km instead of not eating that 420-kcal bowl of pho is another matter entirely!" }, { "code": null, "e": 33569, "s": 33382, "text": "Although odds ratio offers some insights in how I should strategize my weight loss, a more actionable plan could be drawn from the decision boundary of my logistic regression classifier." }, { "code": null, "e": 33618, "s": 33569, "text": "Recall our trusty sigmoid function from earlier:" }, { "code": null, "e": 33822, "s": 33618, "text": "It can easily be seen that for the probability of weight loss to be 50% (where the classification threshold is), the linear combination of θ’s and x’s must be zero* (I’ve also replaced x_intercept by 1):" }, { "code": null, "e": 33959, "s": 33822, "text": "* For other probability thresholds, the linear combination of θ’s and x’s can be found by taking the logit of the threshold: ln(p/(1-p))" }, { "code": null, "e": 34110, "s": 33959, "text": "However, the x’s used in our logistic regression were the normalized values of our original features. Therefore, we can rewrite the above equation as:" }, { "code": null, "e": 34132, "s": 34110, "text": "Rearranging, we have:" }, { "code": null, "e": 34310, "s": 34132, "text": "Plugging θ’s and the feature means (μ) and standard deviations (σ) to the above equation gives the linear equation between the original calories surplus and step count features:" }, { "code": null, "e": 34533, "s": 34310, "text": "Graphically, this equation represents the decision boundary in the original surplus-step plot (see left panel below). From this decision boundary, there are 3 important numbers that I should keep in mind (see right panel):" }, { "code": null, "e": 34823, "s": 34533, "text": "This is how much I should be eating below the Loseit app’s calories budget on my lazy days (in which I average 2480 steps). With the average budget of just above 1700 kcal, this means on those days I should be eating below 1560 kcal on average. This number sounds quite restrictive indeed." }, { "code": null, "e": 35209, "s": 34823, "text": "However, one saving grace is that according to the decision boundary, for any 1 km I run beyond my normal activity, I am allowed to increase this limit by 130 kcal. For example, if I had scheduled a 5K run on a given day, I can afford to eat -140 + 130 * 5 = 510 kcal above the calories budget from the app for that day. Hopefully this will encourage me to keep up my running schedule." }, { "code": null, "e": 35429, "s": 35209, "text": "On the flip side, when I’m tempted to overeat beyond the calories limit (as dictated by the first two rules), any 100 kcal that I eat beyond the limit must be earned with at least 1070 steps. This can be done either by:" }, { "code": null, "e": 35511, "s": 35429, "text": "Walking that 1070 steps around the block before chowing down on that banh bao, or" }, { "code": null, "e": 35626, "s": 35511, "text": "Realizing I’m too lazy for that and putting said food out of my stupid mouth (hey, I just built my own Slap Chef!)" }, { "code": null, "e": 35862, "s": 35626, "text": "I hope to use the above guidelines to be more successful in my weight loss journey in 2019 than in 2018. Of course I won’t always succeed even with the numbers behind me, but the most important lesson I’ve learned from this project is:" }, { "code": null, "e": 35890, "s": 35862, "text": "I should be kind to myself." }, { "code": null, "e": 36180, "s": 35890, "text": "For example, I do lose weight even if I eat more than the budget on my active days, so I should not feel guilty for doing so. Hopefully, with this new model that incorporates both diet and exercise, I can feel less guilt and shame (like I did before) during my ongoing weight loss journey." }, { "code": null, "e": 36376, "s": 36180, "text": "Another big reason that I embarked on this project is to implement a machine project without using pre-existing libraries such as scikit-learn. Below are some lessons I learned from that process:" }, { "code": null, "e": 37023, "s": 36376, "text": "When I first learned Python (or any serious programming for that matter) more than a year ago, I was not sure why one would ever use classes. Well, after few dozen times during this project of (a) using the global variable theta, (b) getting some weird result like non-convergence, and (c) realizing said theta belongs to some other model that I ran many moons ago, I now realize why encapsulation in classes is so important: a model object could have its own attributes (theta, alpha, lambda_reg) and methods (fit, predict) that do not clash with those from other model objects, and I can merrily pick it up in one piece the next time I need it." }, { "code": null, "e": 37289, "s": 37023, "text": "I’m really interested on how classes could be used to model data science problems, and I think with more relevant examples I might be able to appreciate more the powers of object-oriented programming (for now I’m still not quite sure when or how I should use them)." }, { "code": null, "e": 37321, "s": 37289, "text": "— Me when first learning Python" }, { "code": null, "e": 38100, "s": 37321, "text": "This project also allows me to implement and understand the practical benefit of some neat programming concepts that I never had the chance to use, such as using generators i.e. yield statements to return my training and validation folds one at a time. This allows me to evaluate my model only on those folds, then go back and generate more folds, instead of storing all folds in memory at once (although for my data size it makes virtually no difference). Even something as CS101 as writing clear pseudocode turns out to be quite important, especially when implementing mathematically-flavored algorithms like logistic regression; it’s embarrassing to admit the hours I’ve spent debugging from not writing explicit pseudocode beforehand and swapping alpha and theta by mistake." }, { "code": null, "e": 38578, "s": 38100, "text": "Lastly, this project helps me grok in more details the implementations of some of the machine learning libraries that I often used, such as the occasional warning that I have to specify either max_iter or tol when training a scikit-learn model: the former to specify the number of iterations to let the model converge, the latter to specify the tolerance level below which iterations are stopped — exactly the two choices I faced when checking for convergence for my own model." }, { "code": null, "e": 39130, "s": 38578, "text": "Another example of this is I now learn some of the scikit-learn models do not behave like I would expect them to: SGDClassifier(loss=’log’, penalty=’l2', learning_rate=’constant’) does not seem to shrink the θ of the intercept, and gave similar θ’s to my model, while LogisticRegression(penalty=’l2') shrinks the θ of intercept at the default setting, unless one fiddles with the intercept_scaling parameter. As a result, I will be more careful when using third-party libraries to analyze my data in the future, and validate the result when necessary." }, { "code": null, "e": 39526, "s": 39130, "text": "I took most of the derivations for logistic regression and its gradient ascent method from the corresponding lecture note and video lectures of CS229 (a machine learning course taught by professor Andrew Ng that I highly recommend). The note provides the formula for stochastic gradient ascent, but the batch version can be easily modified from that (as seen in the math review section earlier)." }, { "code": null, "e": 40082, "s": 39526, "text": "A more accessible explanation can be found in week 3 of his machine course on Coursera. This course also covers the application of ridge regression on logistic regression, which the CS229 course does not. One small detail: the Coursera course refers to logistic regression as minimizing the log-loss using stochastic gradient descent. However, this is identical to maximizing the log-likelihood using stochastic gradient ascent that I had implemented, with the log-loss nothing more than the negative of the log-likelihood (with some minor modifications)." }, { "code": null, "e": 40388, "s": 40082, "text": "Another good explanation for logistic regression and ridge regression is from the University of Washington’s Coursera course on classification methods. This course thankfully uses log-likelihood maximization to explain logistic regression so it should be consistent with the notations from CS229 and mine." }, { "code": null, "e": 41069, "s": 40388, "text": "Last but not least are two weight loss analysis projects I found on the web that really inspired my own project: one from Will Koehrsen, who uses only his past weights to forecast future weight loss, and at the other end of the spectrum is one from Ariel Faigon, who uses dozens of factors to predict how much weight he gains or loses each day, and comes up with very interesting results: apparently sleep is the most important factor for his weight loss! My approach is somewhere in the middle, using only 2 features to predict whether I would lose weight or not, which allows for easy visualization and simple, actionable insights that I can take away for my weight loss journey" } ]
How to use BooleanSupplier in lambda expression in Java?
BooleanSupplier is a functional interface defined in the "java.util.function" package. This interface can be used as an assignment target for a lambda expression or method reference. BooleanSupplier interface has only one method getAsBoolean() and returns a boolean result, true or false. @FunctionalInterface public interface BooleanSupplier { boolean getBoolean(); } import java.util.function.BooleanSupplier; public class BooleanSupplierLambdaTest { public static void main(String[] args) { BooleanSupplier Obj1 = () -> true; BooleanSupplier Obj2 = () -> 5 < 50; // lambda expression BooleanSupplier Obj3 = () -> "tutorialspoint.com".equals("tutorix.com"); System.out.println("Result of Obj1: " + Obj1.getAsBoolean()); System.out.println("Result of Obj2: " + Obj2.getAsBoolean()); System.out.println("Result of Obj3: " + Obj3.getAsBoolean()); } } Result of Obj1: true Result of Obj2: true Result of Obj3: false
[ { "code": null, "e": 1351, "s": 1062, "text": "BooleanSupplier is a functional interface defined in the \"java.util.function\" package. This interface can be used as an assignment target for a lambda expression or method reference. BooleanSupplier interface has only one method getAsBoolean() and returns a boolean result, true or false." }, { "code": null, "e": 1434, "s": 1351, "text": "@FunctionalInterface\npublic interface BooleanSupplier {\n boolean getBoolean();\n}" }, { "code": null, "e": 1958, "s": 1434, "text": "import java.util.function.BooleanSupplier;\n\npublic class BooleanSupplierLambdaTest {\n public static void main(String[] args) {\n BooleanSupplier Obj1 = () -> true;\n BooleanSupplier Obj2 = () -> 5 < 50; // lambda expression\n BooleanSupplier Obj3 = () -> \"tutorialspoint.com\".equals(\"tutorix.com\");\n System.out.println(\"Result of Obj1: \" + Obj1.getAsBoolean());\n System.out.println(\"Result of Obj2: \" + Obj2.getAsBoolean());\n System.out.println(\"Result of Obj3: \" + Obj3.getAsBoolean());\n }\n}" }, { "code": null, "e": 2022, "s": 1958, "text": "Result of Obj1: true\nResult of Obj2: true\nResult of Obj3: false" } ]
NumPy Searching Arrays
You can search an array for a certain value, and return the indexes that get a match. To search an array, use the where() method. Find the indexes where the value is 4: The example above will return a tuple: (array([3, 5, 6],) Which means that the value 4 is present at index 3, 5, and 6. Find the indexes where the values are even: Find the indexes where the values are odd: There is a method called searchsorted() which performs a binary search in the array, and returns the index where the specified value would be inserted to maintain the search order. The searchsorted() method is assumed to be used on sorted arrays. Find the indexes where the value 7 should be inserted: Example explained: The number 7 should be inserted on index 1 to remain the sort order. The method starts the search from the left and returns the first index where the number 7 is no longer larger than the next value. By default the left most index is returned, but we can give side='right' to return the right most index instead. Find the indexes where the value 7 should be inserted, starting from the right: Example explained: The number 7 should be inserted on index 2 to remain the sort order. The method starts the search from the right and returns the first index where the number 7 is no longer less than the next value. To search for more than one value, use an array with the specified values. Find the indexes where the values 2, 4, and 6 should be inserted: The return value is an array: [1 2 3] containing the three indexes where 2, 4, 6 would be inserted in the original array to maintain the order. Use the correct NumPy method to find all items with the value 4. arr = np.array([1, 2, 3, 4, 5, 4, 4]) x = np.(arr == 4) 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: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 86, "s": 0, "text": "You can search an array for a certain value, and return the indexes that get a match." }, { "code": null, "e": 130, "s": 86, "text": "To search an array, use the where() method." }, { "code": null, "e": 169, "s": 130, "text": "Find the indexes where the value is 4:" }, { "code": null, "e": 227, "s": 169, "text": "The example above will return a tuple: (array([3, 5, 6],)" }, { "code": null, "e": 289, "s": 227, "text": "Which means that the value 4 is present at index 3, 5, and 6." }, { "code": null, "e": 333, "s": 289, "text": "Find the indexes where the values are even:" }, { "code": null, "e": 376, "s": 333, "text": "Find the indexes where the values are odd:" }, { "code": null, "e": 558, "s": 376, "text": "There is a method called searchsorted() which performs a binary search in the array,\nand returns the index where the specified value would be inserted to maintain the \nsearch order." }, { "code": null, "e": 627, "s": 558, "text": "The searchsorted() method is assumed to be \n used on sorted arrays." }, { "code": null, "e": 682, "s": 627, "text": "Find the indexes where the value 7 should be inserted:" }, { "code": null, "e": 770, "s": 682, "text": "Example explained: The number 7 should be inserted on index 1 to remain the sort order." }, { "code": null, "e": 902, "s": 770, "text": "The method starts the search from the left and returns the first index where the number \n7 is no longer larger than the next value." }, { "code": null, "e": 1015, "s": 902, "text": "By default the left most index is returned, but we can give side='right' to return the right most index instead." }, { "code": null, "e": 1096, "s": 1015, "text": "Find the indexes where the value 7 should be inserted, starting from the \nright:" }, { "code": null, "e": 1184, "s": 1096, "text": "Example explained: The number 7 should be inserted on index 2 to remain the sort order." }, { "code": null, "e": 1315, "s": 1184, "text": "The method starts the search from the right and returns the first index where the number \n7 is no longer less than the next value." }, { "code": null, "e": 1390, "s": 1315, "text": "To search for more than one value, use an array with the specified values." }, { "code": null, "e": 1456, "s": 1390, "text": "Find the indexes where the values 2, 4, and 6 should be inserted:" }, { "code": null, "e": 1601, "s": 1456, "text": "The return value is an array: [1 2 3] containing the three indexes where 2, 4, 6 would be inserted \nin the original array to maintain the order." }, { "code": null, "e": 1666, "s": 1601, "text": "Use the correct NumPy method to find all items with the value 4." }, { "code": null, "e": 1724, "s": 1666, "text": "arr = np.array([1, 2, 3, 4, 5, 4, 4])\n\nx = np.(arr == 4)\n" }, { "code": null, "e": 1743, "s": 1724, "text": "Start the Exercise" }, { "code": null, "e": 1776, "s": 1743, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1818, "s": 1776, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1925, "s": 1818, "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": 1944, "s": 1925, "text": "[email protected]" } ]
Program to Interchange Diagonals of Matrix
24 May, 2022 Given a square matrix of order n*n, you have to interchange the elements of both diagonals. Examples : Input : matrix[][] = {1, 2, 3, 4, 5, 6, 7, 8, 9} Output : matrix[][] = {3, 2, 1, 4, 5, 6, 9, 8, 7} Input : matrix[][] = {4, 2, 3, 1, 5, 7, 6, 8, 9, 11, 10, 12, 16, 14, 15, 13} Output : matrix[][] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 11, 14, 15, 16} Explanation : Idea behind interchanging diagonals of a square matrix is simple. Iterate from 0 to n-1 and for each iteration you have to swap a[i][i] and a[i][n-i-1]. C++ C Java Python3 C# Javascript // C++ program to interchange// the diagonals of matrix#include<bits/stdc++.h>using namespace std; #define N 3 // Function to interchange diagonalsvoid interchangeDiagonals(int array[][N]){ // swap elements of diagonal for (int i = 0; i < N; ++i) if (i != N / 2) swap(array[i][i], array[i][N - i - 1]); for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) cout<<" "<< array[i][j]; cout<<endl; }} // Driver Codeint main(){ int array[N][N] = {4, 5, 6, 1, 2, 3, 7, 8, 9}; interchangeDiagonals(array); return 0;} // This code is contributed by noob2000. // C program to interchange// the diagonals of matrix#include<bits/stdc++.h>using namespace std; #define N 3 // Function to interchange diagonalsvoid interchangeDiagonals(int array[][N]){ // swap elements of diagonal for (int i = 0; i < N; ++i) if (i != N / 2) swap(array[i][i], array[i][N - i - 1]); for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) printf(" %d", array[i][j]); printf("\n"); }} // Driver Codeint main(){ int array[N][N] = {4, 5, 6, 1, 2, 3, 7, 8, 9}; interchangeDiagonals(array); return 0;} // Java program to interchange// the diagonals of matriximport java.io.*; class GFG{ public static int N = 3; // Function to interchange diagonals static void interchangeDiagonals(int array[][]) { // swap elements of diagonal for (int i = 0; i < N; ++i) if (i != N / 2) { int temp = array[i][i]; array[i][i] = array[i][N - i - 1]; array[i][N - i - 1] = temp; } for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) System.out.print(array[i][j]+" "); System.out.println(); } } // Driver Code public static void main (String[] args) { int array[][] = { {4, 5, 6}, {1, 2, 3}, {7, 8, 9} }; interchangeDiagonals(array); }} // This code is contributed by Pramod Kumar # Python program to interchange# the diagonals of matrixN = 3; # Function to interchange diagonalsdef interchangeDiagonals(array): # swap elements of diagonal for i in range(N): if (i != N / 2): temp = array[i][i]; array[i][i] = array[i][N - i - 1]; array[i][N - i - 1] = temp; for i in range(N): for j in range(N): print(array[i][j], end = " "); print(); # Driver Codeif __name__ == '__main__': array = [ 4, 5, 6 ],[ 1, 2, 3 ],[ 7, 8, 9 ]; interchangeDiagonals(array); # This code is contributed by Rajput-Ji // C# program to interchange// the diagonals of matrixusing System; class GFG{ public static int N = 3; // Function to interchange diagonals static void interchangeDiagonals(int [,]array) { // swap elements of diagonal for (int i = 0; i < N; ++i) if (i != N / 2) { int temp = array[i, i]; array[i, i] = array[i, N - i - 1]; array[i, N - i - 1] = temp; } for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) Console.Write(array[i, j]+" "); Console.WriteLine(); } } // Driver Code public static void Main () { int [,]array = { {4, 5, 6}, {1, 2, 3}, {7, 8, 9} }; interchangeDiagonals(array); }} // This code is contributed by vt_m. <script>// Javascript program to interchange// the diagonals of matrixlet N = 3; // Function to interchange diagonalsfunction interchangeDiagonals(array){ // swap elements of diagonal for (let i = 0; i < N; ++i) if (i != parseInt(N / 2)) { let temp = array[i][i]; array[i][i] = array[i][N - i - 1]; array[i][N - i - 1] = temp; } for (let i = 0; i < N; ++i) { for (let j = 0; j < N; ++j) document.write(" " + array[i][j]); document.write("<br>"); }} // Driver Code let array = [[4, 5, 6], [1, 2, 3], [7, 8, 9]]; interchangeDiagonals(array); // This code is contributed by subham348.</script> Output: 6 5 4 1 2 3 9 8 7 Time Complexity: O(N*N), as we are using nested loops for traversing the matrix. Auxiliary Space: O(1), as we are not using any extra space. 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m Rajput-Ji Akanksha_Rai subham348 noob2000 rohitkumarsinghcna Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n24 May, 2022" }, { "code": null, "e": 159, "s": 54, "text": "Given a square matrix of order n*n, you have to interchange the elements of both diagonals. Examples : " }, { "code": null, "e": 652, "s": 159, "text": "Input : matrix[][] = {1, 2, 3,\n 4, 5, 6,\n 7, 8, 9} \nOutput : matrix[][] = {3, 2, 1,\n 4, 5, 6,\n 9, 8, 7} \n\nInput : matrix[][] = {4, 2, 3, 1,\n 5, 7, 6, 8,\n 9, 11, 10, 12,\n 16, 14, 15, 13} \nOutput : matrix[][] = {1, 2, 3, 4,\n 5, 6, 7, 8,\n 9, 10, 11, 12,\n 11, 14, 15, 16}" }, { "code": null, "e": 823, "s": 654, "text": "Explanation : Idea behind interchanging diagonals of a square matrix is simple. Iterate from 0 to n-1 and for each iteration you have to swap a[i][i] and a[i][n-i-1]. " }, { "code": null, "e": 829, "s": 825, "text": "C++" }, { "code": null, "e": 831, "s": 829, "text": "C" }, { "code": null, "e": 836, "s": 831, "text": "Java" }, { "code": null, "e": 844, "s": 836, "text": "Python3" }, { "code": null, "e": 847, "s": 844, "text": "C#" }, { "code": null, "e": 858, "s": 847, "text": "Javascript" }, { "code": "// C++ program to interchange// the diagonals of matrix#include<bits/stdc++.h>using namespace std; #define N 3 // Function to interchange diagonalsvoid interchangeDiagonals(int array[][N]){ // swap elements of diagonal for (int i = 0; i < N; ++i) if (i != N / 2) swap(array[i][i], array[i][N - i - 1]); for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) cout<<\" \"<< array[i][j]; cout<<endl; }} // Driver Codeint main(){ int array[N][N] = {4, 5, 6, 1, 2, 3, 7, 8, 9}; interchangeDiagonals(array); return 0;} // This code is contributed by noob2000.", "e": 1499, "s": 858, "text": null }, { "code": "// C program to interchange// the diagonals of matrix#include<bits/stdc++.h>using namespace std; #define N 3 // Function to interchange diagonalsvoid interchangeDiagonals(int array[][N]){ // swap elements of diagonal for (int i = 0; i < N; ++i) if (i != N / 2) swap(array[i][i], array[i][N - i - 1]); for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) printf(\" %d\", array[i][j]); printf(\"\\n\"); }} // Driver Codeint main(){ int array[N][N] = {4, 5, 6, 1, 2, 3, 7, 8, 9}; interchangeDiagonals(array); return 0;}", "e": 2102, "s": 1499, "text": null }, { "code": "// Java program to interchange// the diagonals of matriximport java.io.*; class GFG{ public static int N = 3; // Function to interchange diagonals static void interchangeDiagonals(int array[][]) { // swap elements of diagonal for (int i = 0; i < N; ++i) if (i != N / 2) { int temp = array[i][i]; array[i][i] = array[i][N - i - 1]; array[i][N - i - 1] = temp; } for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) System.out.print(array[i][j]+\" \"); System.out.println(); } } // Driver Code public static void main (String[] args) { int array[][] = { {4, 5, 6}, {1, 2, 3}, {7, 8, 9} }; interchangeDiagonals(array); }} // This code is contributed by Pramod Kumar", "e": 3039, "s": 2102, "text": null }, { "code": "# Python program to interchange# the diagonals of matrixN = 3; # Function to interchange diagonalsdef interchangeDiagonals(array): # swap elements of diagonal for i in range(N): if (i != N / 2): temp = array[i][i]; array[i][i] = array[i][N - i - 1]; array[i][N - i - 1] = temp; for i in range(N): for j in range(N): print(array[i][j], end = \" \"); print(); # Driver Codeif __name__ == '__main__': array = [ 4, 5, 6 ],[ 1, 2, 3 ],[ 7, 8, 9 ]; interchangeDiagonals(array); # This code is contributed by Rajput-Ji", "e": 3643, "s": 3039, "text": null }, { "code": "// C# program to interchange// the diagonals of matrixusing System; class GFG{ public static int N = 3; // Function to interchange diagonals static void interchangeDiagonals(int [,]array) { // swap elements of diagonal for (int i = 0; i < N; ++i) if (i != N / 2) { int temp = array[i, i]; array[i, i] = array[i, N - i - 1]; array[i, N - i - 1] = temp; } for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) Console.Write(array[i, j]+\" \"); Console.WriteLine(); } } // Driver Code public static void Main () { int [,]array = { {4, 5, 6}, {1, 2, 3}, {7, 8, 9} }; interchangeDiagonals(array); }} // This code is contributed by vt_m.", "e": 4548, "s": 3643, "text": null }, { "code": "<script>// Javascript program to interchange// the diagonals of matrixlet N = 3; // Function to interchange diagonalsfunction interchangeDiagonals(array){ // swap elements of diagonal for (let i = 0; i < N; ++i) if (i != parseInt(N / 2)) { let temp = array[i][i]; array[i][i] = array[i][N - i - 1]; array[i][N - i - 1] = temp; } for (let i = 0; i < N; ++i) { for (let j = 0; j < N; ++j) document.write(\" \" + array[i][j]); document.write(\"<br>\"); }} // Driver Code let array = [[4, 5, 6], [1, 2, 3], [7, 8, 9]]; interchangeDiagonals(array); // This code is contributed by subham348.</script>", "e": 5243, "s": 4548, "text": null }, { "code": null, "e": 5253, "s": 5243, "text": "Output: " }, { "code": null, "e": 5274, "s": 5253, "text": " 6 5 4\n 1 2 3\n 9 8 7" }, { "code": null, "e": 5355, "s": 5274, "text": "Time Complexity: O(N*N), as we are using nested loops for traversing the matrix." }, { "code": null, "e": 5415, "s": 5355, "text": "Auxiliary Space: O(1), as we are not using any extra space." }, { "code": null, "e": 5851, "s": 5415, "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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 5856, "s": 5851, "text": "vt_m" }, { "code": null, "e": 5866, "s": 5856, "text": "Rajput-Ji" }, { "code": null, "e": 5879, "s": 5866, "text": "Akanksha_Rai" }, { "code": null, "e": 5889, "s": 5879, "text": "subham348" }, { "code": null, "e": 5898, "s": 5889, "text": "noob2000" }, { "code": null, "e": 5917, "s": 5898, "text": "rohitkumarsinghcna" }, { "code": null, "e": 5924, "s": 5917, "text": "Matrix" }, { "code": null, "e": 5931, "s": 5924, "text": "Matrix" } ]
Dynamic Arrays and its Operations in Solidity
17 Nov, 2020 The Dynamic arrays are the arrays that are allocated memory at the runtime and the memory is allocated from the heap. Syntax: // declaration of dynamic array int[] private arr; How They Are Different From Fixed Size Arrays? The fixed-size array has a fixed memory size whereas, in dynamic arrays, the size can be randomly updated during the run time which may be considered efficient with respect to the memory complexity of the code. Problem: How to create a dynamic array in solidity and perform its associated operations? Solution: In this article, we will create dynamic arrays in solidity language and will perform the following operations on it: Add data in an arrayGet data of an arrayGet length of an arrayGet sum of elements of an arraySearch a particular element in an array Add data in an array Get data of an array Get length of an array Get sum of elements of an array Search a particular element in an array What is Solidity? Solidity is a high-level language. The structure of smart contracts in solidity is very similar to the structure of classes in object-oriented languages. The solidity file has an extension .sol. What are Smart Contracts? Solidity’s code is encapsulated in contracts which means a contract in Solidity is a collection of code (its functions) and data (its state) that resides at a specific address on the Ethereum blockchain. A contract is a fundamental block of building an application on Ethereum. Step 1: Open Remix-IDE. Step 2: Select File Explorer from the left side icons and select Solidity in the environment. Click on the New option below the Solidity environment. Enter the file name as dynamicArray.sol and Click on the OK button. Step 3: Enter the following Solidity Code. Select the same solidity version as in your code. Solidity // Solidity program to demonstrate// the above approachpragma solidity ^0.6.8;contract DynamicArray{ // Declaring state variable int[] private arr; // Function to add data // in dynamic arrayfunction addData(int num) public{ arr.push(num);} // Function to get data of// dynamic arrayfunction getData() public view returns(int[] memory){ return arr;} // Function to return length // of dynamic arrayfunction getLength() public view returns (uint){ return arr.length;} // Function to return sum of // elements of dynamic arrayfunction getSum() public view returns(int){ uint i; int sum = 0; for(i = 0; i < arr.length; i++) sum = sum + arr[i]; return sum;} // Function to search an // element in dynamic arrayfunction search(int num) public view returns(bool){ uint i; for(i = 0; i < arr.length; i++) { if(arr[i] == num) { return true; } } if(i >= arr.length) return false;}} Step 4: Compile the file dynamicArray.sol from the Solidity Compiler tab. Step 5: Deploy the smart contract from the Deploy and Run Transaction tab. Step 6: Perform various operations on the array under the deployed contracts section. Solidity-Arrays Technical Scripter 2020 Solidity Technical Scripter 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, 2020" }, { "code": null, "e": 147, "s": 28, "text": "The Dynamic arrays are the arrays that are allocated memory at the runtime and the memory is allocated from the heap. " }, { "code": null, "e": 155, "s": 147, "text": "Syntax:" }, { "code": null, "e": 187, "s": 155, "text": "// declaration of dynamic array" }, { "code": null, "e": 210, "s": 187, "text": " int[] private arr; " }, { "code": null, "e": 257, "s": 210, "text": "How They Are Different From Fixed Size Arrays?" }, { "code": null, "e": 469, "s": 257, "text": "The fixed-size array has a fixed memory size whereas, in dynamic arrays, the size can be randomly updated during the run time which may be considered efficient with respect to the memory complexity of the code. " }, { "code": null, "e": 559, "s": 469, "text": "Problem: How to create a dynamic array in solidity and perform its associated operations?" }, { "code": null, "e": 686, "s": 559, "text": "Solution: In this article, we will create dynamic arrays in solidity language and will perform the following operations on it:" }, { "code": null, "e": 819, "s": 686, "text": "Add data in an arrayGet data of an arrayGet length of an arrayGet sum of elements of an arraySearch a particular element in an array" }, { "code": null, "e": 840, "s": 819, "text": "Add data in an array" }, { "code": null, "e": 861, "s": 840, "text": "Get data of an array" }, { "code": null, "e": 884, "s": 861, "text": "Get length of an array" }, { "code": null, "e": 916, "s": 884, "text": "Get sum of elements of an array" }, { "code": null, "e": 956, "s": 916, "text": "Search a particular element in an array" }, { "code": null, "e": 974, "s": 956, "text": "What is Solidity?" }, { "code": null, "e": 1169, "s": 974, "text": "Solidity is a high-level language. The structure of smart contracts in solidity is very similar to the structure of classes in object-oriented languages. The solidity file has an extension .sol." }, { "code": null, "e": 1195, "s": 1169, "text": "What are Smart Contracts?" }, { "code": null, "e": 1473, "s": 1195, "text": "Solidity’s code is encapsulated in contracts which means a contract in Solidity is a collection of code (its functions) and data (its state) that resides at a specific address on the Ethereum blockchain. A contract is a fundamental block of building an application on Ethereum." }, { "code": null, "e": 1497, "s": 1473, "text": "Step 1: Open Remix-IDE." }, { "code": null, "e": 1715, "s": 1497, "text": "Step 2: Select File Explorer from the left side icons and select Solidity in the environment. Click on the New option below the Solidity environment. Enter the file name as dynamicArray.sol and Click on the OK button." }, { "code": null, "e": 1808, "s": 1715, "text": "Step 3: Enter the following Solidity Code. Select the same solidity version as in your code." }, { "code": null, "e": 1817, "s": 1808, "text": "Solidity" }, { "code": "// Solidity program to demonstrate// the above approachpragma solidity ^0.6.8;contract DynamicArray{ // Declaring state variable int[] private arr; // Function to add data // in dynamic arrayfunction addData(int num) public{ arr.push(num);} // Function to get data of// dynamic arrayfunction getData() public view returns(int[] memory){ return arr;} // Function to return length // of dynamic arrayfunction getLength() public view returns (uint){ return arr.length;} // Function to return sum of // elements of dynamic arrayfunction getSum() public view returns(int){ uint i; int sum = 0; for(i = 0; i < arr.length; i++) sum = sum + arr[i]; return sum;} // Function to search an // element in dynamic arrayfunction search(int num) public view returns(bool){ uint i; for(i = 0; i < arr.length; i++) { if(arr[i] == num) { return true; } } if(i >= arr.length) return false;}}", "e": 2760, "s": 1817, "text": null }, { "code": null, "e": 2834, "s": 2760, "text": "Step 4: Compile the file dynamicArray.sol from the Solidity Compiler tab." }, { "code": null, "e": 2909, "s": 2834, "text": "Step 5: Deploy the smart contract from the Deploy and Run Transaction tab." }, { "code": null, "e": 2995, "s": 2909, "text": "Step 6: Perform various operations on the array under the deployed contracts section." }, { "code": null, "e": 3011, "s": 2995, "text": "Solidity-Arrays" }, { "code": null, "e": 3035, "s": 3011, "text": "Technical Scripter 2020" }, { "code": null, "e": 3044, "s": 3035, "text": "Solidity" }, { "code": null, "e": 3063, "s": 3044, "text": "Technical Scripter" } ]
Python - Check if dictionary is empty
During analysis of data sets we may come across situations where we have to deal with empty dictionaries. In tis article we will see how to check if a dictionary is empty or not. The if condition evaluates to true if the dictionary has elements. Otherwise it evaluates to false. So in the below program we will just check the emptiness of a dictionary using only the if condition. Live Demo dict1 = {1:"Mon",2:"Tue",3:"Wed"} dict2 = {} # Given dictionaries print("The original dictionary : " ,(dict1)) print("The original dictionary : " ,(dict2)) # Check if dictionary is empty if dict1: print("dict1 is not empty") else: print("dict1 is empty") if dict2: print("dict2 is not empty") else: print("dict2 is empty") Running the above code gives us the following result − The original dictionary : {1: 'Mon', 2: 'Tue', 3: 'Wed'} The original dictionary : {} dict1 is not empty dict2 is empty The bool method evaluates to true if the dictionary is not empty. Else it evaluates to false. So we use this in expressions to print the result for emptiness of a dictionary. Live Demo dict1 = {1:"Mon",2:"Tue",3:"Wed"} dict2 = {} # Given dictionaries print("The original dictionary : " ,(dict1)) print("The original dictionary : " ,(dict2)) # Check if dictionary is empty print("Is dict1 empty? :",bool(dict1)) print("Is dict2 empty? :",bool(dict2)) Running the above code gives us the following result − The original dictionary : {1: 'Mon', 2: 'Tue', 3: 'Wed'} The original dictionary : {} Is dict1 empty? : True Is dict2 empty? : False
[ { "code": null, "e": 1366, "s": 1187, "text": "During analysis of data sets we may come across situations where we have to deal with empty dictionaries. In tis article we will see how to check if a dictionary is empty or not." }, { "code": null, "e": 1568, "s": 1366, "text": "The if condition evaluates to true if the dictionary has elements. Otherwise it evaluates to false. So in the below program we will just check the emptiness of a dictionary using only the if condition." }, { "code": null, "e": 1579, "s": 1568, "text": " Live Demo" }, { "code": null, "e": 1914, "s": 1579, "text": "dict1 = {1:\"Mon\",2:\"Tue\",3:\"Wed\"}\ndict2 = {}\n# Given dictionaries\nprint(\"The original dictionary : \" ,(dict1))\nprint(\"The original dictionary : \" ,(dict2))\n# Check if dictionary is empty\nif dict1:\n print(\"dict1 is not empty\")\nelse:\n print(\"dict1 is empty\")\nif dict2:\n print(\"dict2 is not empty\")\nelse:\n print(\"dict2 is empty\")" }, { "code": null, "e": 1969, "s": 1914, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2089, "s": 1969, "text": "The original dictionary : {1: 'Mon', 2: 'Tue', 3: 'Wed'}\nThe original dictionary : {}\ndict1 is not empty\ndict2 is empty" }, { "code": null, "e": 2264, "s": 2089, "text": "The bool method evaluates to true if the dictionary is not empty. Else it evaluates to false. So we use this in expressions to print the result for emptiness of a dictionary." }, { "code": null, "e": 2275, "s": 2264, "text": " Live Demo" }, { "code": null, "e": 2540, "s": 2275, "text": "dict1 = {1:\"Mon\",2:\"Tue\",3:\"Wed\"}\ndict2 = {}\n# Given dictionaries\nprint(\"The original dictionary : \" ,(dict1))\nprint(\"The original dictionary : \" ,(dict2))\n# Check if dictionary is empty\nprint(\"Is dict1 empty? :\",bool(dict1))\nprint(\"Is dict2 empty? :\",bool(dict2))" }, { "code": null, "e": 2595, "s": 2540, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2728, "s": 2595, "text": "The original dictionary : {1: 'Mon', 2: 'Tue', 3: 'Wed'}\nThe original dictionary : {}\nIs dict1 empty? : True\nIs dict2 empty? : False" } ]
Type Conversion in C++
Here we will see what are the type conversion techniques present in C++. There are mainly two types of type conversion. The implicit and explicit. Implicit type conversionThis is also known as automatic type conversion. This is done by the compiler without any external trigger from the user. This is done when one expression has more than one datatype is present.All datatypes are upgraded to the datatype of the large variable. Implicit type conversion This is also known as automatic type conversion. This is done by the compiler without any external trigger from the user. This is done when one expression has more than one datatype is present. All datatypes are upgraded to the datatype of the large variable. bool -> char -> short int -> int -> unsigned int -> long -> unsigned -> long long -> float -> double -> long double In the implicit conversion, it may lose some information. The sign can be lost etc. Live Demo #include <iostream> using namespace std; int main() { int a = 10; char b = 'a'; a = b + a; float c = a + 1.0; cout << "a : " << a << "\nb : " << b << "\nc : " << c; } a : 107 b : a c : 108 This is also known as type casting. Here the user can typecast the result to make it to particular datatype. In C++ we can do this in two ways, either using expression in parentheses or using static_cast or dynamic_cast Live Demo #include <iostream> using namespace std; int main() { double x = 1.574; int add = (int)x + 1; cout << "Add: " << add; float y = 3.5; int val = static_cast<int>(y); cout << "\nvalue: " << val; } Add: 2 value: 3
[ { "code": null, "e": 1334, "s": 1187, "text": "Here we will see what are the type conversion techniques present in C++. There are mainly two types of type conversion. The implicit and explicit." }, { "code": null, "e": 1617, "s": 1334, "text": "Implicit type conversionThis is also known as automatic type conversion. This is done by the compiler without any external trigger from the user. This is done when one expression has more than one datatype is present.All datatypes are upgraded to the datatype of the large variable." }, { "code": null, "e": 1642, "s": 1617, "text": "Implicit type conversion" }, { "code": null, "e": 1836, "s": 1642, "text": "This is also known as automatic type conversion. This is done by the compiler without any external trigger from the user. This is done when one expression has more than one datatype is present." }, { "code": null, "e": 1902, "s": 1836, "text": "All datatypes are upgraded to the datatype of the large variable." }, { "code": null, "e": 2018, "s": 1902, "text": "bool -> char -> short int -> int -> unsigned int -> long -> unsigned -> long long -> float -> double -> long double" }, { "code": null, "e": 2102, "s": 2018, "text": "In the implicit conversion, it may lose some information. The sign can be lost etc." }, { "code": null, "e": 2113, "s": 2102, "text": " Live Demo" }, { "code": null, "e": 2295, "s": 2113, "text": "#include <iostream>\nusing namespace std;\nint main() {\n int a = 10;\n char b = 'a';\n a = b + a;\n float c = a + 1.0;\n cout << \"a : \" << a << \"\\nb : \" << b << \"\\nc : \" << c;\n}" }, { "code": null, "e": 2317, "s": 2295, "text": "a : 107\nb : a\nc : 108" }, { "code": null, "e": 2537, "s": 2317, "text": "This is also known as type casting. Here the user can typecast the result to make it to particular datatype. In C++ we can do this in two ways, either using expression in parentheses or using static_cast or dynamic_cast" }, { "code": null, "e": 2548, "s": 2537, "text": " Live Demo" }, { "code": null, "e": 2760, "s": 2548, "text": "#include <iostream>\nusing namespace std;\nint main() {\n double x = 1.574;\n int add = (int)x + 1;\n cout << \"Add: \" << add;\n float y = 3.5;\n int val = static_cast<int>(y);\n cout << \"\\nvalue: \" << val;\n}" }, { "code": null, "e": 2776, "s": 2760, "text": "Add: 2\nvalue: 3" } ]
Matplotlib.axis.Axis.set_major_locator() function in Python
10 Jun, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack. The Axis.set_major_locator() function in axis module of matplotlib library is used to set the locator of the major ticker. Syntax: Axis.set_major_locator(self, locator) Parameters: This method accepts the following parameters. locator: This parameter is the Locator. Return value: This method does not returns any value. Below examples illustrate the matplotlib.axis.Axis.set_major_locator() function in matplotlib.axis:Example 1: Python3 # Implementation of matplotlib function from matplotlib.axis import Axisimport numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib.cbook as cbook years = mdates.YearLocator() months = mdates.MonthLocator() years_fmt = mdates.DateFormatter('% Y') with cbook.get_sample_data('goog.npz') as datafile: data = np.load(datafile)['price_data'].view(np.recarray) fig, ax = plt.subplots() ax.plot('date', 'adj_close', data = data, color ="green") Axis.set_major_locator(ax.xaxis, years) ax.set_ylim((100, 300)) ax.format_xdata = mdates.DateFormatter('% m') ax.grid(True) fig.suptitle("Matplotlib.axis.Axis.set_major_locator()\n\Function Example", fontsize = 12, fontweight ='bold') plt.show() Output: Example 2: Python3 # Implementation of matplotlib function from matplotlib.axis import Axisimport matplotlib.pyplot as plt import matplotlib.ticker as ticker x = [0, 5, 9, 10, 15] y = [0, 1, 2, 3, 4] tick_spacing = 1 fig, ax = plt.subplots(1, 1) ax.plot(x, y) ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing)) fig.suptitle("Matplotlib.axis.Axis.set_major_locator()\n\Function Example", fontsize = 12, fontweight ='bold') plt.show() Output: Matplotlib-Axis Class Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jun, 2020" }, { "code": null, "e": 249, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack." }, { "code": null, "e": 373, "s": 249, "text": "The Axis.set_major_locator() function in axis module of matplotlib library is used to set the locator of the major ticker. " }, { "code": null, "e": 419, "s": 373, "text": "Syntax: Axis.set_major_locator(self, locator)" }, { "code": null, "e": 478, "s": 419, "text": "Parameters: This method accepts the following parameters. " }, { "code": null, "e": 518, "s": 478, "text": "locator: This parameter is the Locator." }, { "code": null, "e": 573, "s": 518, "text": "Return value: This method does not returns any value. " }, { "code": null, "e": 683, "s": 573, "text": "Below examples illustrate the matplotlib.axis.Axis.set_major_locator() function in matplotlib.axis:Example 1:" }, { "code": null, "e": 691, "s": 683, "text": "Python3" }, { "code": "# Implementation of matplotlib function from matplotlib.axis import Axisimport numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib.cbook as cbook years = mdates.YearLocator() months = mdates.MonthLocator() years_fmt = mdates.DateFormatter('% Y') with cbook.get_sample_data('goog.npz') as datafile: data = np.load(datafile)['price_data'].view(np.recarray) fig, ax = plt.subplots() ax.plot('date', 'adj_close', data = data, color =\"green\") Axis.set_major_locator(ax.xaxis, years) ax.set_ylim((100, 300)) ax.format_xdata = mdates.DateFormatter('% m') ax.grid(True) fig.suptitle(\"Matplotlib.axis.Axis.set_major_locator()\\n\\Function Example\", fontsize = 12, fontweight ='bold') plt.show()", "e": 1457, "s": 691, "text": null }, { "code": null, "e": 1466, "s": 1457, "text": "Output: " }, { "code": null, "e": 1477, "s": 1466, "text": "Example 2:" }, { "code": null, "e": 1485, "s": 1477, "text": "Python3" }, { "code": "# Implementation of matplotlib function from matplotlib.axis import Axisimport matplotlib.pyplot as plt import matplotlib.ticker as ticker x = [0, 5, 9, 10, 15] y = [0, 1, 2, 3, 4] tick_spacing = 1 fig, ax = plt.subplots(1, 1) ax.plot(x, y) ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing)) fig.suptitle(\"Matplotlib.axis.Axis.set_major_locator()\\n\\Function Example\", fontsize = 12, fontweight ='bold') plt.show()", "e": 1932, "s": 1485, "text": null }, { "code": null, "e": 1941, "s": 1932, "text": "Output: " }, { "code": null, "e": 1965, "s": 1943, "text": "Matplotlib-Axis Class" }, { "code": null, "e": 1983, "s": 1965, "text": "Python-matplotlib" }, { "code": null, "e": 1990, "s": 1983, "text": "Python" } ]
How to pass an array as a function parameter in JavaScript ?
26 Nov, 2019 Method 1: Using the apply() method: The apply() method is used to call a function with the given arguments as an array or array-like object. It contains two parameters. The this value provides a call to the function and the arguments array contains the array of arguments to be passed. The apply() method is used on the function that has to be passed as the arguments array. The first parameter is specified as ‘null’ and the second parameter is specified with the arguments array. This will call the function with the specified arguments array. Syntax: arrayToPass = [1, "Two", 3]; unmodifiableFunction.apply(null, arrayToPass); Example: <!DOCTYPE html><html> <head> <title> How to pass an array as a function parameter in JavaScript ? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> JavaScript | Passing an array as a function parameter. </b> <p> The arguments passed are '1, "Two", 3' </p> <button onclick="passToFunction()"> Pass to function </button> <script type="text/javascript"> function passToFunction() { arrayToPass = [1, "Two", 3]; unmodifiableFunction.apply(null, arrayToPass); } function unmodifiableFunction(a, b, c) { console.log("First value is: ", a); console.log("Second value is: ", b); console.log("Third value is: ", c); } </script></body> </html> Output: Before clicking the button: After clicking the button: Method 2: Using the spread syntax: The spread syntax is used in place where zero or more arguments are expected. It can be used with iterators that expands in place where there may not be a fixed number of expected arguments (like function parameters). The required function is called as given the arguments array using the spread syntax so that it would fill in the arguments of the function from the array. Syntax: arrayToPass = [1, "Two", 3]; unmodifiableFunction(...arrayToPass); Example: <!DOCTYPE html><html> <head> <title> How to pass an array as a function parameter in JavaScript ? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> JavaScript | Passing an array as a function parameter. </b> <p> The arguments passed are '1, "Two", 3' </p> <button onclick="passToFunction()"> Pass to function </button> <script type="text/javascript"> function passToFunction() { arrayToPass = [1, "Two", 3]; unmodifiableFunction(...arrayToPass); } function unmodifiableFunction(a, b, c) { console.log("First value is: ", a); console.log("Second value is: ", b); console.log("Third value is: ", c); } </script></body> </html> Output: Before clicking the button: After clicking the button: JavaScript-Misc Picked 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 How to append HTML code to a div using JavaScript ? Difference Between PUT and PATCH Request Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 53, "s": 25, "text": "\n26 Nov, 2019" }, { "code": null, "e": 339, "s": 53, "text": "Method 1: Using the apply() method: The apply() method is used to call a function with the given arguments as an array or array-like object. It contains two parameters. The this value provides a call to the function and the arguments array contains the array of arguments to be passed." }, { "code": null, "e": 599, "s": 339, "text": "The apply() method is used on the function that has to be passed as the arguments array. The first parameter is specified as ‘null’ and the second parameter is specified with the arguments array. This will call the function with the specified arguments array." }, { "code": null, "e": 607, "s": 599, "text": "Syntax:" }, { "code": "arrayToPass = [1, \"Two\", 3]; unmodifiableFunction.apply(null, arrayToPass);", "e": 684, "s": 607, "text": null }, { "code": null, "e": 693, "s": 684, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to pass an array as a function parameter in JavaScript ? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> JavaScript | Passing an array as a function parameter. </b> <p> The arguments passed are '1, \"Two\", 3' </p> <button onclick=\"passToFunction()\"> Pass to function </button> <script type=\"text/javascript\"> function passToFunction() { arrayToPass = [1, \"Two\", 3]; unmodifiableFunction.apply(null, arrayToPass); } function unmodifiableFunction(a, b, c) { console.log(\"First value is: \", a); console.log(\"Second value is: \", b); console.log(\"Third value is: \", c); } </script></body> </html>", "e": 1578, "s": 693, "text": null }, { "code": null, "e": 1586, "s": 1578, "text": "Output:" }, { "code": null, "e": 1614, "s": 1586, "text": "Before clicking the button:" }, { "code": null, "e": 1641, "s": 1614, "text": "After clicking the button:" }, { "code": null, "e": 1894, "s": 1641, "text": "Method 2: Using the spread syntax: The spread syntax is used in place where zero or more arguments are expected. It can be used with iterators that expands in place where there may not be a fixed number of expected arguments (like function parameters)." }, { "code": null, "e": 2050, "s": 1894, "text": "The required function is called as given the arguments array using the spread syntax so that it would fill in the arguments of the function from the array." }, { "code": null, "e": 2058, "s": 2050, "text": "Syntax:" }, { "code": "arrayToPass = [1, \"Two\", 3]; unmodifiableFunction(...arrayToPass);", "e": 2126, "s": 2058, "text": null }, { "code": null, "e": 2135, "s": 2126, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to pass an array as a function parameter in JavaScript ? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> JavaScript | Passing an array as a function parameter. </b> <p> The arguments passed are '1, \"Two\", 3' </p> <button onclick=\"passToFunction()\"> Pass to function </button> <script type=\"text/javascript\"> function passToFunction() { arrayToPass = [1, \"Two\", 3]; unmodifiableFunction(...arrayToPass); } function unmodifiableFunction(a, b, c) { console.log(\"First value is: \", a); console.log(\"Second value is: \", b); console.log(\"Third value is: \", c); } </script></body> </html>", "e": 3007, "s": 2135, "text": null }, { "code": null, "e": 3015, "s": 3007, "text": "Output:" }, { "code": null, "e": 3043, "s": 3015, "text": "Before clicking the button:" }, { "code": null, "e": 3070, "s": 3043, "text": "After clicking the button:" }, { "code": null, "e": 3086, "s": 3070, "text": "JavaScript-Misc" }, { "code": null, "e": 3093, "s": 3086, "text": "Picked" }, { "code": null, "e": 3104, "s": 3093, "text": "JavaScript" }, { "code": null, "e": 3121, "s": 3104, "text": "Web Technologies" }, { "code": null, "e": 3148, "s": 3121, "text": "Web technologies Questions" }, { "code": null, "e": 3246, "s": 3148, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3307, "s": 3246, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3379, "s": 3307, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3419, "s": 3379, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3471, "s": 3419, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 3512, "s": 3471, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3574, "s": 3512, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3607, "s": 3574, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3668, "s": 3607, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3718, "s": 3668, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to change the font size in HTML?
15 Mar, 2021 In this article, we will learn how one can change the font size in HTML. This can be used in situations where a text has to be highlighted due to its importance or made smaller for a caption. This can be achieved using the following approaches. Approach 1: The <font> tag in HTML can be used for making changes to the font that is enclosed within the tags. It has various attributes that can be used to specify the size, color, or face of the font. This tag was deprecated in HTML5, therefore this approach may not work in modern browsers. Syntax: <font size="24">Your Text</font> Example: HTML <html><body> <!-- Using <font> tag to set font size --> <font size="6"> Welcome to GeeksforGeeks </font> <font size="24"> Aman Rathod </font></body></html> Output: Approach 2: The <big> tag in HTML can be used for increasing the font size by one level that is enclosed within the tags. It does not have any attributes. This tag was deprecated in HTML5, therefore this approach may not work in modern browsers. Syntax: <big>Your Text</big> Example: HTML <html><body> <p> <!-- Using the <big> tag for increasing the font size --> Welcome to <big>GeeksforGeeks</big> </p> </body></html> Output: Approach 3: Using the inline style attribute to change the font-size of the tag it is used on. The usage of this attribute overrides any style set globally. Syntax: <p style="font-size: 24px;">Your Text</p> Example: HTML <html><body> <!--- Using Inline style attribute to edit font size --> <p style="font-size:20px"> GeeksforGeeks </p> <p style="font-size:25px"> Courses </p> </body></html> Output: Approach 4: Using separate CSS to select the required text and using the font-size property to change the font size. The size value can be set using length units or keywords like x-small, small or large. Syntax: <style> p { font-size: large; } </style> Example: HTML <html><head> <!-- Using CSS to change the font size --> <style> body { font-size: 60px; } p { font-size:xx-large; } </style> </head><body> Perfect Portal for Geeky <p>Welcome to GeeksforGeeks</p> </body></html> Output: HTML-Questions Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS Design a web page using HTML and CSS Angular File Upload Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Mar, 2021" }, { "code": null, "e": 273, "s": 28, "text": "In this article, we will learn how one can change the font size in HTML. This can be used in situations where a text has to be highlighted due to its importance or made smaller for a caption. This can be achieved using the following approaches." }, { "code": null, "e": 568, "s": 273, "text": "Approach 1: The <font> tag in HTML can be used for making changes to the font that is enclosed within the tags. It has various attributes that can be used to specify the size, color, or face of the font. This tag was deprecated in HTML5, therefore this approach may not work in modern browsers." }, { "code": null, "e": 576, "s": 568, "text": "Syntax:" }, { "code": null, "e": 609, "s": 576, "text": "<font size=\"24\">Your Text</font>" }, { "code": null, "e": 618, "s": 609, "text": "Example:" }, { "code": null, "e": 623, "s": 618, "text": "HTML" }, { "code": "<html><body> <!-- Using <font> tag to set font size --> <font size=\"6\"> Welcome to GeeksforGeeks </font> <font size=\"24\"> Aman Rathod </font></body></html>", "e": 790, "s": 623, "text": null }, { "code": null, "e": 798, "s": 790, "text": "Output:" }, { "code": null, "e": 1045, "s": 798, "text": "Approach 2: The <big> tag in HTML can be used for increasing the font size by one level that is enclosed within the tags. It does not have any attributes. This tag was deprecated in HTML5, therefore this approach may not work in modern browsers." }, { "code": null, "e": 1053, "s": 1045, "text": "Syntax:" }, { "code": null, "e": 1074, "s": 1053, "text": "<big>Your Text</big>" }, { "code": null, "e": 1083, "s": 1074, "text": "Example:" }, { "code": null, "e": 1088, "s": 1083, "text": "HTML" }, { "code": "<html><body> <p> <!-- Using the <big> tag for increasing the font size --> Welcome to <big>GeeksforGeeks</big> </p> </body></html>", "e": 1233, "s": 1088, "text": null }, { "code": null, "e": 1241, "s": 1233, "text": "Output:" }, { "code": null, "e": 1398, "s": 1241, "text": "Approach 3: Using the inline style attribute to change the font-size of the tag it is used on. The usage of this attribute overrides any style set globally." }, { "code": null, "e": 1406, "s": 1398, "text": "Syntax:" }, { "code": null, "e": 1448, "s": 1406, "text": "<p style=\"font-size: 24px;\">Your Text</p>" }, { "code": null, "e": 1457, "s": 1448, "text": "Example:" }, { "code": null, "e": 1462, "s": 1457, "text": "HTML" }, { "code": "<html><body> <!--- Using Inline style attribute to edit font size --> <p style=\"font-size:20px\"> GeeksforGeeks </p> <p style=\"font-size:25px\"> Courses </p> </body></html>", "e": 1648, "s": 1462, "text": null }, { "code": null, "e": 1656, "s": 1648, "text": "Output:" }, { "code": null, "e": 1860, "s": 1656, "text": "Approach 4: Using separate CSS to select the required text and using the font-size property to change the font size. The size value can be set using length units or keywords like x-small, small or large." }, { "code": null, "e": 1868, "s": 1860, "text": "Syntax:" }, { "code": null, "e": 1911, "s": 1868, "text": "<style>\np\n{\n font-size: large;\n}\n</style>" }, { "code": null, "e": 1920, "s": 1911, "text": "Example:" }, { "code": null, "e": 1925, "s": 1920, "text": "HTML" }, { "code": "<html><head> <!-- Using CSS to change the font size --> <style> body { font-size: 60px; } p { font-size:xx-large; } </style> </head><body> Perfect Portal for Geeky <p>Welcome to GeeksforGeeks</p> </body></html>", "e": 2178, "s": 1925, "text": null }, { "code": null, "e": 2186, "s": 2178, "text": "Output:" }, { "code": null, "e": 2201, "s": 2186, "text": "HTML-Questions" }, { "code": null, "e": 2208, "s": 2201, "text": "Picked" }, { "code": null, "e": 2213, "s": 2208, "text": "HTML" }, { "code": null, "e": 2230, "s": 2213, "text": "Web Technologies" }, { "code": null, "e": 2235, "s": 2230, "text": "HTML" }, { "code": null, "e": 2333, "s": 2235, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2357, "s": 2333, "text": "REST API (Introduction)" }, { "code": null, "e": 2396, "s": 2357, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 2435, "s": 2396, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 2472, "s": 2435, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 2492, "s": 2472, "text": "Angular File Upload" }, { "code": null, "e": 2525, "s": 2492, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2586, "s": 2525, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2629, "s": 2586, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2701, "s": 2629, "text": "Differences between Functional Components and Class Components in React" } ]
Paytm Interview Experience 2020
11 Nov, 2020 I hope Everyone must have heard about Paytm. To get more information visit https://paytm.com/ Online Coding Round(70 minutes): There were 3 coding problems Based on a simple Number system given an integer, just ou have to change the digit9-->0 8-->1 7-->2 6-->3 5-->4 ......... so on 0 -->9Example: Convert this number to the new number.Input: 420 Output: 579The second problem was similar to https://www.geeksforgeeks.org/a-boolean-matrix-question/.Given two trees, tree1 and tree 2, if tree 1 is a subtree of tree 2, then find the count of the node in tree1. Or if tree 2 is a subtree of tree 1, then find the count of the node in tree2. Based on a simple Number system given an integer, just ou have to change the digit9-->0 8-->1 7-->2 6-->3 5-->4 ......... so on 0 -->9Example: Convert this number to the new number.Input: 420 Output: 579 9-->0 8-->1 7-->2 6-->3 5-->4 ......... so on 0 -->9 Example: Convert this number to the new number. Input: 420 Output: 579 The second problem was similar to https://www.geeksforgeeks.org/a-boolean-matrix-question/. The second problem was similar to https://www.geeksforgeeks.org/a-boolean-matrix-question/. Given two trees, tree1 and tree 2, if tree 1 is a subtree of tree 2, then find the count of the node in tree1. Or if tree 2 is a subtree of tree 1, then find the count of the node in tree2. Given two trees, tree1 and tree 2, if tree 1 is a subtree of tree 2, then find the count of the node in tree1. Or if tree 2 is a subtree of tree 1, then find the count of the node in tree2. I have solved the first two problems completely and in the third one I was about to finish (I was knowing the correct approach and I have written one function for checking the subtree and another function for the counting of nodes. And from the function signature in the problem, I could not finish and time was over.) So the overall online test was medium. Not too hard also not too easy Around 15 students were called for the face to face interview Round 1(Face-To-Face): This round was around 1 hour 10 minutes. The interviewer was very friendly and so cool, supportive, and he made me relaxed also. He asked me to introduce yourself Then he asked me questions. Given a boolean matrix of order mxn which is row-wise sorted. Find the largest length of consecutive 1’s in a row.Eg.00011011110000100111Output: 4, in 2nd row.I have first given the brute force method in O(mn), then he asked me to optimize, after some discussion, I have given the linear time approach by starting the traversal from the top right corner to the bottom left. He was satisfied with my approach and I have written the code on a Google doc.It was on an inorder successor and predecessor of a binary tree. I have given the approach of using an extra array by storing the inorder traversal. Then he told me that do it without using the extra array. He has given me some hint and then I have written the complete code.Then he asked some questions about the Operating system(what is deadlock explain with an example)Then he jumped to the oops conceptIt was like, what is the main advantage of oops and why do we need it.What is inheritance?What is polymorphism? What are the types of it? What is compile-time and runtime polymorphism?What is a virtual function, pure virtual function? Can we create a class that contains the virtual function? The concept of VTABLES was also asked.He has again given me a coding problem and told me that write the code directly. Given a sorted array, and a variable k, print all the pair whose sum is k.I have written the code with two pointer techniques in linear time complexity. Given a boolean matrix of order mxn which is row-wise sorted. Find the largest length of consecutive 1’s in a row.Eg.00011011110000100111Output: 4, in 2nd row.I have first given the brute force method in O(mn), then he asked me to optimize, after some discussion, I have given the linear time approach by starting the traversal from the top right corner to the bottom left. He was satisfied with my approach and I have written the code on a Google doc. Given a boolean matrix of order mxn which is row-wise sorted. Find the largest length of consecutive 1’s in a row. Eg. Output: 4, in 2nd row. I have first given the brute force method in O(mn), then he asked me to optimize, after some discussion, I have given the linear time approach by starting the traversal from the top right corner to the bottom left. He was satisfied with my approach and I have written the code on a Google doc. It was on an inorder successor and predecessor of a binary tree. I have given the approach of using an extra array by storing the inorder traversal. Then he told me that do it without using the extra array. He has given me some hint and then I have written the complete code. It was on an inorder successor and predecessor of a binary tree. I have given the approach of using an extra array by storing the inorder traversal. Then he told me that do it without using the extra array. He has given me some hint and then I have written the complete code. Then he asked some questions about the Operating system(what is deadlock explain with an example) Then he asked some questions about the Operating system(what is deadlock explain with an example) Then he jumped to the oops conceptIt was like, what is the main advantage of oops and why do we need it.What is inheritance?What is polymorphism? What are the types of it? What is compile-time and runtime polymorphism?What is a virtual function, pure virtual function? Can we create a class that contains the virtual function? The concept of VTABLES was also asked. Then he jumped to the oops concept It was like, what is the main advantage of oops and why do we need it. What is inheritance? What is polymorphism? What are the types of it? What is compile-time and runtime polymorphism? What is a virtual function, pure virtual function? Can we create a class that contains the virtual function? The concept of VTABLES was also asked. He has again given me a coding problem and told me that write the code directly. Given a sorted array, and a variable k, print all the pair whose sum is k.I have written the code with two pointer techniques in linear time complexity. He has again given me a coding problem and told me that write the code directly. Given a sorted array, and a variable k, print all the pair whose sum is k. I have written the code with two pointer techniques in linear time complexity. At the end he told me that I am done with the interview, you can ask your doubt Round 2(Face To Face 15minutes): It was again started with an introduction then he asked me to discuss any of the projects from cv(i have 4 projects on ML only). After 10 minutes of discussion on the project he has asked me to write a function to reverse the linked list, Recursively Reversing a linked list (A simple implementation). I have asked him that should I first discuss the logic or I can write the code directly, he told me that first discussed the approach, I have explained the recursive approach thoroughly in O(n^2) and O(n) approach. and he was quite satisfied with the approach that I have discussed. He told me that no need to write the code now, I am pretty sure that you can write easily. He has appreciated and told me that I am recommending to HR Round 3(HR ROUND 15minutes): I am not from CSE. , so he asked me why you want to join the software industry and other HR-related questions, some funny discussion also. I have enjoyed this session a lot. Verdict: selected Suggestion: Be thorough with the OOPS and OS concepts and be confident about the TREES and Linked list. do the problems on Geeksforgeeks from the practice section with company-specific. Also, practice the problems from the Geeksforgeeks list for Amazon. Marketing Paytm Interview Experiences Paytm Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Google SWE Interview Experience (Google Online Coding Challenge) 2022 TCS Digital Interview Questions Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022 Amazon Interview Experience for SDE 1 Google Interview Questions Amazon Interview Experience SDE-2 (3 Years Experienced) TCS Ninja Interview Experience (2020 batch) Write It Up: Share Your Interview Experiences Samsung RnD Coding Round Questions Nagarro Interview Experience
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Nov, 2020" }, { "code": null, "e": 122, "s": 28, "text": "I hope Everyone must have heard about Paytm. To get more information visit https://paytm.com/" }, { "code": null, "e": 185, "s": 122, "text": "Online Coding Round(70 minutes): There were 3 coding problems " }, { "code": null, "e": 670, "s": 185, "text": "Based on a simple Number system given an integer, just ou have to change the digit9-->0\n8-->1\n7-->2\n6-->3\n5-->4 \n......... so on\n0 -->9Example: Convert this number to the new number.Input: 420\nOutput: 579The second problem was similar to https://www.geeksforgeeks.org/a-boolean-matrix-question/.Given two trees, tree1 and tree 2, if tree 1 is a subtree of tree 2, then find the count of the node in tree1. Or if tree 2 is a subtree of tree 1, then find the count of the node in tree2." }, { "code": null, "e": 875, "s": 670, "text": "Based on a simple Number system given an integer, just ou have to change the digit9-->0\n8-->1\n7-->2\n6-->3\n5-->4 \n......... so on\n0 -->9Example: Convert this number to the new number.Input: 420\nOutput: 579" }, { "code": null, "e": 929, "s": 875, "text": "9-->0\n8-->1\n7-->2\n6-->3\n5-->4 \n......... so on\n0 -->9" }, { "code": null, "e": 977, "s": 929, "text": "Example: Convert this number to the new number." }, { "code": null, "e": 1000, "s": 977, "text": "Input: 420\nOutput: 579" }, { "code": null, "e": 1092, "s": 1000, "text": "The second problem was similar to https://www.geeksforgeeks.org/a-boolean-matrix-question/." }, { "code": null, "e": 1184, "s": 1092, "text": "The second problem was similar to https://www.geeksforgeeks.org/a-boolean-matrix-question/." }, { "code": null, "e": 1374, "s": 1184, "text": "Given two trees, tree1 and tree 2, if tree 1 is a subtree of tree 2, then find the count of the node in tree1. Or if tree 2 is a subtree of tree 1, then find the count of the node in tree2." }, { "code": null, "e": 1564, "s": 1374, "text": "Given two trees, tree1 and tree 2, if tree 1 is a subtree of tree 2, then find the count of the node in tree1. Or if tree 2 is a subtree of tree 1, then find the count of the node in tree2." }, { "code": null, "e": 1883, "s": 1564, "text": "I have solved the first two problems completely and in the third one I was about to finish (I was knowing the correct approach and I have written one function for checking the subtree and another function for the counting of nodes. And from the function signature in the problem, I could not finish and time was over.)" }, { "code": null, "e": 1953, "s": 1883, "text": "So the overall online test was medium. Not too hard also not too easy" }, { "code": null, "e": 2015, "s": 1953, "text": "Around 15 students were called for the face to face interview" }, { "code": null, "e": 2202, "s": 2015, "text": "Round 1(Face-To-Face): This round was around 1 hour 10 minutes. The interviewer was very friendly and so cool, supportive, and he made me relaxed also. He asked me to introduce yourself" }, { "code": null, "e": 2230, "s": 2202, "text": "Then he asked me questions." }, { "code": null, "e": 3654, "s": 2230, "text": "Given a boolean matrix of order mxn which is row-wise sorted. Find the largest length of consecutive 1’s in a row.Eg.00011011110000100111Output: 4, in 2nd row.I have first given the brute force method in O(mn), then he asked me to optimize, after some discussion, I have given the linear time approach by starting the traversal from the top right corner to the bottom left. He was satisfied with my approach and I have written the code on a Google doc.It was on an inorder successor and predecessor of a binary tree. I have given the approach of using an extra array by storing the inorder traversal. Then he told me that do it without using the extra array. He has given me some hint and then I have written the complete code.Then he asked some questions about the Operating system(what is deadlock explain with an example)Then he jumped to the oops conceptIt was like, what is the main advantage of oops and why do we need it.What is inheritance?What is polymorphism? What are the types of it? What is compile-time and runtime polymorphism?What is a virtual function, pure virtual function? Can we create a class that contains the virtual function? The concept of VTABLES was also asked.He has again given me a coding problem and told me that write the code directly. Given a sorted array, and a variable k, print all the pair whose sum is k.I have written the code with two pointer techniques in linear time complexity." }, { "code": null, "e": 4108, "s": 3654, "text": "Given a boolean matrix of order mxn which is row-wise sorted. Find the largest length of consecutive 1’s in a row.Eg.00011011110000100111Output: 4, in 2nd row.I have first given the brute force method in O(mn), then he asked me to optimize, after some discussion, I have given the linear time approach by starting the traversal from the top right corner to the bottom left. He was satisfied with my approach and I have written the code on a Google doc." }, { "code": null, "e": 4223, "s": 4108, "text": "Given a boolean matrix of order mxn which is row-wise sorted. Find the largest length of consecutive 1’s in a row." }, { "code": null, "e": 4227, "s": 4223, "text": "Eg." }, { "code": null, "e": 4251, "s": 4227, "text": "Output: 4, in 2nd row." }, { "code": null, "e": 4545, "s": 4251, "text": "I have first given the brute force method in O(mn), then he asked me to optimize, after some discussion, I have given the linear time approach by starting the traversal from the top right corner to the bottom left. He was satisfied with my approach and I have written the code on a Google doc." }, { "code": null, "e": 4821, "s": 4545, "text": "It was on an inorder successor and predecessor of a binary tree. I have given the approach of using an extra array by storing the inorder traversal. Then he told me that do it without using the extra array. He has given me some hint and then I have written the complete code." }, { "code": null, "e": 4887, "s": 4821, "text": "It was on an inorder successor and predecessor of a binary tree. " }, { "code": null, "e": 5098, "s": 4887, "text": "I have given the approach of using an extra array by storing the inorder traversal. Then he told me that do it without using the extra array. He has given me some hint and then I have written the complete code." }, { "code": null, "e": 5196, "s": 5098, "text": "Then he asked some questions about the Operating system(what is deadlock explain with an example)" }, { "code": null, "e": 5294, "s": 5196, "text": "Then he asked some questions about the Operating system(what is deadlock explain with an example)" }, { "code": null, "e": 5660, "s": 5294, "text": "Then he jumped to the oops conceptIt was like, what is the main advantage of oops and why do we need it.What is inheritance?What is polymorphism? What are the types of it? What is compile-time and runtime polymorphism?What is a virtual function, pure virtual function? Can we create a class that contains the virtual function? The concept of VTABLES was also asked." }, { "code": null, "e": 5695, "s": 5660, "text": "Then he jumped to the oops concept" }, { "code": null, "e": 5766, "s": 5695, "text": "It was like, what is the main advantage of oops and why do we need it." }, { "code": null, "e": 5787, "s": 5766, "text": "What is inheritance?" }, { "code": null, "e": 5882, "s": 5787, "text": "What is polymorphism? What are the types of it? What is compile-time and runtime polymorphism?" }, { "code": null, "e": 5992, "s": 5882, "text": "What is a virtual function, pure virtual function? Can we create a class that contains the virtual function? " }, { "code": null, "e": 6031, "s": 5992, "text": "The concept of VTABLES was also asked." }, { "code": null, "e": 6265, "s": 6031, "text": "He has again given me a coding problem and told me that write the code directly. Given a sorted array, and a variable k, print all the pair whose sum is k.I have written the code with two pointer techniques in linear time complexity." }, { "code": null, "e": 6421, "s": 6265, "text": "He has again given me a coding problem and told me that write the code directly. Given a sorted array, and a variable k, print all the pair whose sum is k." }, { "code": null, "e": 6500, "s": 6421, "text": "I have written the code with two pointer techniques in linear time complexity." }, { "code": null, "e": 6580, "s": 6500, "text": "At the end he told me that I am done with the interview, you can ask your doubt" }, { "code": null, "e": 6852, "s": 6580, "text": "Round 2(Face To Face 15minutes): It was again started with an introduction then he asked me to discuss any of the projects from cv(i have 4 projects on ML only). After 10 minutes of discussion on the project he has asked me to write a function to reverse the linked list," }, { "code": null, "e": 6915, "s": 6852, "text": "Recursively Reversing a linked list (A simple implementation)." }, { "code": null, "e": 7290, "s": 6915, "text": "I have asked him that should I first discuss the logic or I can write the code directly, he told me that first discussed the approach, I have explained the recursive approach thoroughly in O(n^2) and O(n) approach. and he was quite satisfied with the approach that I have discussed. He told me that no need to write the code now, I am pretty sure that you can write easily." }, { "code": null, "e": 7350, "s": 7290, "text": "He has appreciated and told me that I am recommending to HR" }, { "code": null, "e": 7553, "s": 7350, "text": "Round 3(HR ROUND 15minutes): I am not from CSE. , so he asked me why you want to join the software industry and other HR-related questions, some funny discussion also. I have enjoyed this session a lot." }, { "code": null, "e": 7571, "s": 7553, "text": "Verdict: selected" }, { "code": null, "e": 7825, "s": 7571, "text": "Suggestion: Be thorough with the OOPS and OS concepts and be confident about the TREES and Linked list. do the problems on Geeksforgeeks from the practice section with company-specific. Also, practice the problems from the Geeksforgeeks list for Amazon." }, { "code": null, "e": 7835, "s": 7825, "text": "Marketing" }, { "code": null, "e": 7841, "s": 7835, "text": "Paytm" }, { "code": null, "e": 7863, "s": 7841, "text": "Interview Experiences" }, { "code": null, "e": 7869, "s": 7863, "text": "Paytm" }, { "code": null, "e": 7967, "s": 7869, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8037, "s": 7967, "text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022" }, { "code": null, "e": 8069, "s": 8037, "text": "TCS Digital Interview Questions" }, { "code": null, "e": 8142, "s": 8069, "text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022" }, { "code": null, "e": 8180, "s": 8142, "text": "Amazon Interview Experience for SDE 1" }, { "code": null, "e": 8207, "s": 8180, "text": "Google Interview Questions" }, { "code": null, "e": 8263, "s": 8207, "text": "Amazon Interview Experience SDE-2 (3 Years Experienced)" }, { "code": null, "e": 8307, "s": 8263, "text": "TCS Ninja Interview Experience (2020 batch)" }, { "code": null, "e": 8353, "s": 8307, "text": "Write It Up: Share Your Interview Experiences" }, { "code": null, "e": 8388, "s": 8353, "text": "Samsung RnD Coding Round Questions" } ]
Regular Expressions in Python – Set 2 (Search, Match and Find All)
14 Dec, 2021 Regular Expression in Python with Examples | Set 1The module re provides support for regular expressions in Python. Below are main methods in this module. Searching an occurrence of pattern re.search() : This method either returns None (if the pattern doesn’t match), or a re.MatchObject that contains information about the matching part of the string. This method stops after the first match, so this is best suited for testing a regular expression more than extracting data. Python3 # A Python program to demonstrate working of re.match(). import re # Lets use a regular expression to match a date string # in the form of Month name followed by day number regex = r"([a-zA-Z]+) (\d+)" match = re.search(regex, "I was born on June 24") if match != None: # We reach here when the expression "([a-zA-Z]+) (\d+)" # matches the date string. # This will print [14, 21), since it matches at index 14 # and ends at 21. print ("Match at index %s, %s" % (match.start(), match.end())) # We us group() method to get all the matches and # captured groups. The groups contain the matched values. # In particular: # match.group(0) always returns the fully matched string # match.group(1) match.group(2), ... return the capture # groups in order from left to right in the input string # match.group() is equivalent to match.group(0) # So this will print "June 24" print ("Full match: %s" % (match.group(0))) # So this will print "June" print ("Month: %s" % (match.group(1))) # So this will print "24" print ("Day: %s" % (match.group(2))) else: print ("The regex pattern does not match.") Output : Match at index 14, 21 Full match: June 24 Month: June Day: 24 Matching a Pattern with Text re.match() : This function attempts to match pattern to whole string. The re.match function returns a match object on success, None on failure. re.match(pattern, string, flags=0) pattern : Regular expression to be matched. string : String where pattern is searched flags : We can specify different flags using bitwise OR (|). Python3 # A Python program to demonstrate working# of re.match().import re # a sample function that uses regular expressions# to find month and day of a date.def findMonthAndDate(string): regex = r"([a-zA-Z]+) (\d+)" match = re.match(regex, string) if match == None: print ("Not a valid date") return print ("Given Data: %s" % (match.group())) print ("Month: %s" % (match.group(1))) print ("Day: %s" % (match.group(2))) # Driver CodefindMonthAndDate("Jun 24")print("")findMonthAndDate("I was born on June 24") Output: Given Data: Jun 24 Month: Jun Day: 24 Not a valid date Finding all occurrences of a pattern re.findall() : Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found (Source : Python Docs). Python3 # A Python program to demonstrate working of# findall()import re # A sample text string where regular expression # is searched.string = """Hello my Number is 123456789 and my friend's number is 987654321""" # A sample regular expression to find digits.regex = '\d+' match = re.findall(regex, string)print(match) # This example is contributed by Ayush Saluja. Output : ['123456789', '987654321'] Regular expression is a vast topic. It’s a complete library. Regular expressions can do a lot of stuff. You can Match, Search, Replace, Extract a lot of data. For example, below small code is so powerful that it can extract email address from a text. So we can make our own Web Crawlers and scrappers in python with easy.Look at the below regex. # extract all email addresses and add them into the resulting set new_emails = set(re.findall(r"[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+", text, re.I)) We will soon be discussing more methods on regular expressions. This article is contributed by Shwetanshu Rohatgi. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above kk9826225 python-regex Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? Iterate over a list in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Dec, 2021" }, { "code": null, "e": 209, "s": 54, "text": "Regular Expression in Python with Examples | Set 1The module re provides support for regular expressions in Python. Below are main methods in this module." }, { "code": null, "e": 245, "s": 209, "text": "Searching an occurrence of pattern " }, { "code": null, "e": 532, "s": 245, "text": "re.search() : This method either returns None (if the pattern doesn’t match), or a re.MatchObject that contains information about the matching part of the string. This method stops after the first match, so this is best suited for testing a regular expression more than extracting data." }, { "code": null, "e": 540, "s": 532, "text": "Python3" }, { "code": "# A Python program to demonstrate working of re.match(). import re # Lets use a regular expression to match a date string # in the form of Month name followed by day number regex = r\"([a-zA-Z]+) (\\d+)\" match = re.search(regex, \"I was born on June 24\") if match != None: # We reach here when the expression \"([a-zA-Z]+) (\\d+)\" # matches the date string. # This will print [14, 21), since it matches at index 14 # and ends at 21. print (\"Match at index %s, %s\" % (match.start(), match.end())) # We us group() method to get all the matches and # captured groups. The groups contain the matched values. # In particular: # match.group(0) always returns the fully matched string # match.group(1) match.group(2), ... return the capture # groups in order from left to right in the input string # match.group() is equivalent to match.group(0) # So this will print \"June 24\" print (\"Full match: %s\" % (match.group(0))) # So this will print \"June\" print (\"Month: %s\" % (match.group(1))) # So this will print \"24\" print (\"Day: %s\" % (match.group(2))) else: print (\"The regex pattern does not match.\")", "e": 1733, "s": 540, "text": null }, { "code": null, "e": 1743, "s": 1733, "text": "Output : " }, { "code": null, "e": 1806, "s": 1743, "text": "Match at index 14, 21\nFull match: June 24\nMonth: June\nDay: 24 " }, { "code": null, "e": 1836, "s": 1806, "text": "Matching a Pattern with Text " }, { "code": null, "e": 1981, "s": 1836, "text": "re.match() : This function attempts to match pattern to whole string. The re.match function returns a match object on success, None on failure. " }, { "code": null, "e": 2174, "s": 1981, "text": "re.match(pattern, string, flags=0)\n\npattern : Regular expression to be matched.\nstring : String where pattern is searched\nflags : We can specify different flags \n using bitwise OR (|). " }, { "code": null, "e": 2182, "s": 2174, "text": "Python3" }, { "code": "# A Python program to demonstrate working# of re.match().import re # a sample function that uses regular expressions# to find month and day of a date.def findMonthAndDate(string): regex = r\"([a-zA-Z]+) (\\d+)\" match = re.match(regex, string) if match == None: print (\"Not a valid date\") return print (\"Given Data: %s\" % (match.group())) print (\"Month: %s\" % (match.group(1))) print (\"Day: %s\" % (match.group(2))) # Driver CodefindMonthAndDate(\"Jun 24\")print(\"\")findMonthAndDate(\"I was born on June 24\")", "e": 2751, "s": 2182, "text": null }, { "code": null, "e": 2760, "s": 2751, "text": "Output: " }, { "code": null, "e": 2816, "s": 2760, "text": "Given Data: Jun 24\nMonth: Jun\nDay: 24\n\nNot a valid date" }, { "code": null, "e": 2854, "s": 2816, "text": "Finding all occurrences of a pattern " }, { "code": null, "e": 3054, "s": 2854, "text": "re.findall() : Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found (Source : Python Docs). " }, { "code": null, "e": 3062, "s": 3054, "text": "Python3" }, { "code": "# A Python program to demonstrate working of# findall()import re # A sample text string where regular expression # is searched.string = \"\"\"Hello my Number is 123456789 and my friend's number is 987654321\"\"\" # A sample regular expression to find digits.regex = '\\d+' match = re.findall(regex, string)print(match) # This example is contributed by Ayush Saluja.", "e": 3454, "s": 3062, "text": null }, { "code": null, "e": 3464, "s": 3454, "text": "Output : " }, { "code": null, "e": 3491, "s": 3464, "text": "['123456789', '987654321']" }, { "code": null, "e": 3838, "s": 3491, "text": "Regular expression is a vast topic. It’s a complete library. Regular expressions can do a lot of stuff. You can Match, Search, Replace, Extract a lot of data. For example, below small code is so powerful that it can extract email address from a text. So we can make our own Web Crawlers and scrappers in python with easy.Look at the below regex. " }, { "code": null, "e": 4017, "s": 3838, "text": "# extract all email addresses and add them into the resulting set\nnew_emails = set(re.findall(r\"[a-z0-9\\.\\-+_]+@[a-z0-9\\.\\-+_]+\\.[a-z]+\", \n text, re.I))" }, { "code": null, "e": 4081, "s": 4017, "text": "We will soon be discussing more methods on regular expressions." }, { "code": null, "e": 4478, "s": 4081, "text": "This article is contributed by Shwetanshu Rohatgi. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 4488, "s": 4478, "text": "kk9826225" }, { "code": null, "e": 4501, "s": 4488, "text": "python-regex" }, { "code": null, "e": 4508, "s": 4501, "text": "Python" }, { "code": null, "e": 4606, "s": 4508, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4634, "s": 4606, "text": "Read JSON file using Python" }, { "code": null, "e": 4684, "s": 4634, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 4706, "s": 4684, "text": "Python map() function" }, { "code": null, "e": 4750, "s": 4706, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 4792, "s": 4750, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4814, "s": 4792, "text": "Enumerate() in Python" }, { "code": null, "e": 4849, "s": 4814, "text": "Read a file line by line in Python" }, { "code": null, "e": 4875, "s": 4849, "text": "Python String | replace()" }, { "code": null, "e": 4907, "s": 4875, "text": "How to Install PIP on Windows ?" } ]
std::replace and std::replace_if in C++
26 Apr, 2022 std::replace Assigns new_value to all the elements in the range [first, last) that compare to old_value. The function use operator == to compare the individual elements to old_value Function Template : void replace (ForwardIterator first, ForwardIterator last, const T& old_value, const T& new_value) first, last : Forward iterators to the initial and final positions in a sequence of elements. old_value : Value to be replaced. new_value : Replacement value. Return Value : This function do not return any value. If elements that needs to be replace is found then element replaced otherwise remain unchanged. Examples: Input : 10 20 30 30 20 10 10 20 Output : 10 99 30 30 99 10 10 99 // Replaced value 20 in vector to 99. Input : 3 5 7 8 9 5 4 Output : 3 5 7 12 9 5 4 // Replaced value 8 by 12. CPP // CPP program to find and replace the value// with another value in array// using std::replace#include <bits/stdc++.h>using namespace std; // Driver codeint main(){ int arr[] = { 10, 20, 30, 30, 20, 10, 10, 20 }; int n = sizeof(arr) / sizeof(arr[0]); // variable containing the old and new values int old_val = 20, new_val = 99; // print old array cout << "Original Array:"; for (int i = 0; i < n; i++) cout << ' ' << arr[i]; cout << '\n'; // Function used to replace the values replace(arr, arr + n, old_val, new_val); // new array after using std::replace cout << "New Array:"; for (int i = 0; i < n; i++) cout << ' ' << arr[i]; cout << '\n'; return 0;} Original Array: 10 20 30 30 20 10 10 20 New Array: 10 99 30 30 99 10 10 99 std::replace_if Assigns new_value to all the elements in range [first, last) for which pred returns true. Function Template : void replace_if (ForwardIterator first, ForwardIterator last, UnaryPredicate pred, const T& new_value) first, last : Forward iterators to the initial and final positions in a sequence of elelments. pred : Unary function that accepts an element in the range as argument, and returns a value convertible to bool.The returned value indicate whether the element is to be replaced (if true, it is replaced). The function shall not modify its argument. old_value : Value to be replaced. new_value : Replacement value. Examples: Input : 1 2 3 4 5 6 7 8 9 10 Output : 0 2 0 4 0 6 0 8 0 10 // Replaced all odd values to 0. Input : 10 20 30 30 20 10 10 20 Output : 10 4 30 30 4 10 10 4 // Replaced all number divisible by 4 to 4. CPP // CPP code to find all the elements that are odd// and replace them with 0.// using std::replace_if#include <bits/stdc++.h>using namespace std; // Function that is used in std::replace_if// If number is odd return 1, else 0// 1 (True) means replace the number// 0 (False) means does not replacebool IsOdd(int i){ return ((i % 2) == 1);} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int n = sizeof(arr) / sizeof(arr[0]); // print old array cout << "Original Array:"; for (int i = 0; i < n; i++) cout << ' ' << arr[i]; cout << '\n'; // replacement value int new_val = 0; // replace_if function replace_if(arr, arr + n, IsOdd, new_val); // new array after using std::replace cout << "New Array:"; for (int i = 0; i < n; i++) cout << ' ' << arr[i]; cout << '\n'; return 0;} Original Array: 1 2 3 4 5 6 7 8 9 10 New Array: 0 2 0 4 0 6 0 8 0 10 Also you can add any kind of function in std::replace_if that can only have one argument only.This article is contributed by Sachin Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. milindverma11 simmytarika5 cpp-algorithm-library STL C++ 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++ Pair in C++ Standard Template Library (STL) Friend class and function in C++ std::string class in C++ Queue in C++ Standard Template Library (STL) std::find in C++ Unordered Sets in C++ Standard Template Library List in C++ Standard Template Library (STL) vector insert() function in C++ STL
[ { "code": null, "e": 52, "s": 24, "text": "\n26 Apr, 2022" }, { "code": null, "e": 65, "s": 52, "text": "std::replace" }, { "code": null, "e": 235, "s": 65, "text": "Assigns new_value to all the elements in the range [first, last) that compare to old_value. The function use operator == to compare the individual elements to old_value " }, { "code": null, "e": 256, "s": 235, "text": "Function Template : " }, { "code": null, "e": 558, "s": 256, "text": "void replace (ForwardIterator first, \n ForwardIterator last,\n const T& old_value,\n const T& new_value)\nfirst, last : \nForward iterators to the initial and final positions\nin a sequence of elements.\nold_value : Value to be replaced.\nnew_value : Replacement value." }, { "code": null, "e": 709, "s": 558, "text": "Return Value : This function do not return any value. If elements that needs to be replace is found then element replaced otherwise remain unchanged. " }, { "code": null, "e": 720, "s": 709, "text": "Examples: " }, { "code": null, "e": 902, "s": 720, "text": "Input : 10 20 30 30 20 10 10 20 \nOutput : 10 99 30 30 99 10 10 99 \n// Replaced value 20 in vector to 99.\n\nInput : 3 5 7 8 9 5 4 \nOutput : 3 5 7 12 9 5 4 \n// Replaced value 8 by 12." }, { "code": null, "e": 906, "s": 902, "text": "CPP" }, { "code": "// CPP program to find and replace the value// with another value in array// using std::replace#include <bits/stdc++.h>using namespace std; // Driver codeint main(){ int arr[] = { 10, 20, 30, 30, 20, 10, 10, 20 }; int n = sizeof(arr) / sizeof(arr[0]); // variable containing the old and new values int old_val = 20, new_val = 99; // print old array cout << \"Original Array:\"; for (int i = 0; i < n; i++) cout << ' ' << arr[i]; cout << '\\n'; // Function used to replace the values replace(arr, arr + n, old_val, new_val); // new array after using std::replace cout << \"New Array:\"; for (int i = 0; i < n; i++) cout << ' ' << arr[i]; cout << '\\n'; return 0;}", "e": 1627, "s": 906, "text": null }, { "code": null, "e": 1702, "s": 1627, "text": "Original Array: 10 20 30 30 20 10 10 20\nNew Array: 10 99 30 30 99 10 10 99" }, { "code": null, "e": 1718, "s": 1702, "text": "std::replace_if" }, { "code": null, "e": 1830, "s": 1718, "text": "Assigns new_value to all the elements in range [first, last) for which pred returns true. Function Template : " }, { "code": null, "e": 2362, "s": 1830, "text": "void replace_if (ForwardIterator first, ForwardIterator last,\n UnaryPredicate pred, const T& new_value)\nfirst, last : Forward iterators to the initial and final positions\nin a sequence of elelments.\npred : Unary function that accepts an element in the range as argument, and\nreturns a value convertible to bool.The returned value indicate whether\nthe element is to be replaced (if true, it is replaced).\nThe function shall not modify its argument.\nold_value : Value to be replaced.\nnew_value : Replacement value. " }, { "code": null, "e": 2373, "s": 2362, "text": "Examples: " }, { "code": null, "e": 2579, "s": 2373, "text": "Input : 1 2 3 4 5 6 7 8 9 10 \nOutput : 0 2 0 4 0 6 0 8 0 10 \n// Replaced all odd values to 0.\n\nInput : 10 20 30 30 20 10 10 20 \nOutput : 10 4 30 30 4 10 10 4 \n// Replaced all number divisible by 4 to 4." }, { "code": null, "e": 2583, "s": 2579, "text": "CPP" }, { "code": "// CPP code to find all the elements that are odd// and replace them with 0.// using std::replace_if#include <bits/stdc++.h>using namespace std; // Function that is used in std::replace_if// If number is odd return 1, else 0// 1 (True) means replace the number// 0 (False) means does not replacebool IsOdd(int i){ return ((i % 2) == 1);} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int n = sizeof(arr) / sizeof(arr[0]); // print old array cout << \"Original Array:\"; for (int i = 0; i < n; i++) cout << ' ' << arr[i]; cout << '\\n'; // replacement value int new_val = 0; // replace_if function replace_if(arr, arr + n, IsOdd, new_val); // new array after using std::replace cout << \"New Array:\"; for (int i = 0; i < n; i++) cout << ' ' << arr[i]; cout << '\\n'; return 0;}", "e": 3447, "s": 2583, "text": null }, { "code": null, "e": 3516, "s": 3447, "text": "Original Array: 1 2 3 4 5 6 7 8 9 10\nNew Array: 0 2 0 4 0 6 0 8 0 10" }, { "code": null, "e": 4031, "s": 3516, "text": "Also you can add any kind of function in std::replace_if that can only have one argument only.This article is contributed by Sachin Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 4045, "s": 4031, "text": "milindverma11" }, { "code": null, "e": 4058, "s": 4045, "text": "simmytarika5" }, { "code": null, "e": 4080, "s": 4058, "text": "cpp-algorithm-library" }, { "code": null, "e": 4084, "s": 4080, "text": "STL" }, { "code": null, "e": 4088, "s": 4084, "text": "C++" }, { "code": null, "e": 4092, "s": 4088, "text": "STL" }, { "code": null, "e": 4096, "s": 4092, "text": "CPP" }, { "code": null, "e": 4194, "s": 4096, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4218, "s": 4194, "text": "Sorting a vector in C++" }, { "code": null, "e": 4238, "s": 4218, "text": "Polymorphism in C++" }, { "code": null, "e": 4282, "s": 4238, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 4315, "s": 4282, "text": "Friend class and function in C++" }, { "code": null, "e": 4340, "s": 4315, "text": "std::string class in C++" }, { "code": null, "e": 4385, "s": 4340, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 4402, "s": 4385, "text": "std::find in C++" }, { "code": null, "e": 4450, "s": 4402, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 4494, "s": 4450, "text": "List in C++ Standard Template Library (STL)" } ]
LINQ | Generation Operator | DefaultIfEmpty
26 May, 2019 The generation operators are used for creating a new sequence of values. The Standard Query Operator supports 4 different types of generation operators: DefaultIfEmptyEmptyRangeRepeat DefaultIfEmpty Empty Range Repeat The DefaultIfEmpty operator is used to replace an empty collection or sequence with a default valued singleton collection or sequence. Or in other words, it returns a collection or sequence with default values if the source is empty, otherwise return the source. This operator is overloaded in two different ways:DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource): This method is used to return the elements of the specified sequence or the specified value in a singleton collection if the sequence is empty.DefaultIfEmpty<TSource>(IEnumerable<TSource>): This method is used to return the elements of the specified sequence or the type parameter’s default value in a singleton collection if the sequence is empty. DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource): This method is used to return the elements of the specified sequence or the specified value in a singleton collection if the sequence is empty. DefaultIfEmpty<TSource>(IEnumerable<TSource>): This method is used to return the elements of the specified sequence or the type parameter’s default value in a singleton collection if the sequence is empty. It does not support query syntax in C# and VB.Net languages. It support method syntax in both C# and VB.Net languages. It present in both the Queryable and Enumerable class. It is implemented by using deferred execution. DefaultIfEmpty<TSource>(IEnumerable<TSource>) will return ArgumentNullException if the given source is null. The default value for the reference types and for the nullable types is null. Example 1: // C# program to illustrate the// use of DefaultIfEmpty operatorusing System;using System.Linq;using System.Collections.Generic; class GFG { static public void Main() { // Data source 1 int[] sequence1 = {}; // The sequence is empty so it // will return the default value // Using DefaultIfEmpty foreach(var val1 in sequence1.DefaultIfEmpty()) { Console.WriteLine(val1); } // Data source 2 string[] sequence2 = {"Geek", "Geeks123", "GeeksforGeeks"}; // The given sequence 2 is non-empty so // it will return the sequence // Using DefaultIfEmpty foreach(var val2 in sequence2.DefaultIfEmpty()) { Console.WriteLine(val2); } }} 0 Geek Geeks123 GeeksforGeeks Example 2: // C# program to illustrate the // use of DefaultIfEmpty operatorusing System;using System.Linq;using System.Collections.Generic; // Employee detailspublic class Employee { public int emp_id { get; set; } public string emp_name { get; set; } public string emp_gender { get; set; } public string emp_hire_date { get; set; } public int emp_salary { get; set; }} class GFG { // Main method static public void Main() { List<Employee> emp = new List<Employee>() { new Employee() {emp_id = 209, emp_name = "Anjita", emp_gender = "Female", emp_hire_date = "12/3/2017", emp_salary = 20000}, new Employee() {emp_id = 210, emp_name = "Soniya", emp_gender = "Female", emp_hire_date = "22/4/2018", emp_salary = 30000}, new Employee() {emp_id = 211, emp_name = "Rohit", emp_gender = "Male", emp_hire_date = "3/5/2016", emp_salary = 40000}, new Employee() {emp_id = 212, emp_name = "Supriya", emp_gender = "Female", emp_hire_date = "4/8/2017", emp_salary = 40000}, new Employee() {emp_id = 213, emp_name = "Anil", emp_gender = "Male", emp_hire_date = "12/1/2016", emp_salary = 40000}, new Employee() {emp_id = 214, emp_name = "Anju", emp_gender = "Female", emp_hire_date = "17/6/2015", emp_salary = 50000}, }; // Using DefaultIfEmpty operator foreach(Employee e in emp.DefaultIfEmpty()) { Console.WriteLine(e.emp_name); } }} Anjita Soniya Rohit Supriya Anil Anju CSharp LINQ C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples Introduction to .NET Framework C# | Delegates C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework C# | Method Overriding C# | Data Types C# | Constructors C# | String.IndexOf( ) Method | Set - 1 C# | Class and Object
[ { "code": null, "e": 28, "s": 0, "text": "\n26 May, 2019" }, { "code": null, "e": 181, "s": 28, "text": "The generation operators are used for creating a new sequence of values. The Standard Query Operator supports 4 different types of generation operators:" }, { "code": null, "e": 212, "s": 181, "text": "DefaultIfEmptyEmptyRangeRepeat" }, { "code": null, "e": 227, "s": 212, "text": "DefaultIfEmpty" }, { "code": null, "e": 233, "s": 227, "text": "Empty" }, { "code": null, "e": 239, "s": 233, "text": "Range" }, { "code": null, "e": 246, "s": 239, "text": "Repeat" }, { "code": null, "e": 509, "s": 246, "text": "The DefaultIfEmpty operator is used to replace an empty collection or sequence with a default valued singleton collection or sequence. Or in other words, it returns a collection or sequence with default values if the source is empty, otherwise return the source." }, { "code": null, "e": 964, "s": 509, "text": "This operator is overloaded in two different ways:DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource): This method is used to return the elements of the specified sequence or the specified value in a singleton collection if the sequence is empty.DefaultIfEmpty<TSource>(IEnumerable<TSource>): This method is used to return the elements of the specified sequence or the type parameter’s default value in a singleton collection if the sequence is empty." }, { "code": null, "e": 1164, "s": 964, "text": "DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource): This method is used to return the elements of the specified sequence or the specified value in a singleton collection if the sequence is empty." }, { "code": null, "e": 1370, "s": 1164, "text": "DefaultIfEmpty<TSource>(IEnumerable<TSource>): This method is used to return the elements of the specified sequence or the type parameter’s default value in a singleton collection if the sequence is empty." }, { "code": null, "e": 1431, "s": 1370, "text": "It does not support query syntax in C# and VB.Net languages." }, { "code": null, "e": 1489, "s": 1431, "text": "It support method syntax in both C# and VB.Net languages." }, { "code": null, "e": 1544, "s": 1489, "text": "It present in both the Queryable and Enumerable class." }, { "code": null, "e": 1591, "s": 1544, "text": "It is implemented by using deferred execution." }, { "code": null, "e": 1700, "s": 1591, "text": "DefaultIfEmpty<TSource>(IEnumerable<TSource>) will return ArgumentNullException if the given source is null." }, { "code": null, "e": 1778, "s": 1700, "text": "The default value for the reference types and for the nullable types is null." }, { "code": null, "e": 1789, "s": 1778, "text": "Example 1:" }, { "code": "// C# program to illustrate the// use of DefaultIfEmpty operatorusing System;using System.Linq;using System.Collections.Generic; class GFG { static public void Main() { // Data source 1 int[] sequence1 = {}; // The sequence is empty so it // will return the default value // Using DefaultIfEmpty foreach(var val1 in sequence1.DefaultIfEmpty()) { Console.WriteLine(val1); } // Data source 2 string[] sequence2 = {\"Geek\", \"Geeks123\", \"GeeksforGeeks\"}; // The given sequence 2 is non-empty so // it will return the sequence // Using DefaultIfEmpty foreach(var val2 in sequence2.DefaultIfEmpty()) { Console.WriteLine(val2); } }}", "e": 2601, "s": 1789, "text": null }, { "code": null, "e": 2632, "s": 2601, "text": "0\nGeek\nGeeks123\nGeeksforGeeks\n" }, { "code": null, "e": 2643, "s": 2632, "text": "Example 2:" }, { "code": "// C# program to illustrate the // use of DefaultIfEmpty operatorusing System;using System.Linq;using System.Collections.Generic; // Employee detailspublic class Employee { public int emp_id { get; set; } public string emp_name { get; set; } public string emp_gender { get; set; } public string emp_hire_date { get; set; } public int emp_salary { get; set; }} class GFG { // Main method static public void Main() { List<Employee> emp = new List<Employee>() { new Employee() {emp_id = 209, emp_name = \"Anjita\", emp_gender = \"Female\", emp_hire_date = \"12/3/2017\", emp_salary = 20000}, new Employee() {emp_id = 210, emp_name = \"Soniya\", emp_gender = \"Female\", emp_hire_date = \"22/4/2018\", emp_salary = 30000}, new Employee() {emp_id = 211, emp_name = \"Rohit\", emp_gender = \"Male\", emp_hire_date = \"3/5/2016\", emp_salary = 40000}, new Employee() {emp_id = 212, emp_name = \"Supriya\", emp_gender = \"Female\", emp_hire_date = \"4/8/2017\", emp_salary = 40000}, new Employee() {emp_id = 213, emp_name = \"Anil\", emp_gender = \"Male\", emp_hire_date = \"12/1/2016\", emp_salary = 40000}, new Employee() {emp_id = 214, emp_name = \"Anju\", emp_gender = \"Female\", emp_hire_date = \"17/6/2015\", emp_salary = 50000}, }; // Using DefaultIfEmpty operator foreach(Employee e in emp.DefaultIfEmpty()) { Console.WriteLine(e.emp_name); } }}", "e": 4432, "s": 2643, "text": null }, { "code": null, "e": 4471, "s": 4432, "text": "Anjita\nSoniya\nRohit\nSupriya\nAnil\nAnju\n" }, { "code": null, "e": 4483, "s": 4471, "text": "CSharp LINQ" }, { "code": null, "e": 4486, "s": 4483, "text": "C#" }, { "code": null, "e": 4584, "s": 4486, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4612, "s": 4584, "text": "C# Dictionary with examples" }, { "code": null, "e": 4643, "s": 4612, "text": "Introduction to .NET Framework" }, { "code": null, "e": 4658, "s": 4643, "text": "C# | Delegates" }, { "code": null, "e": 4701, "s": 4658, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 4750, "s": 4701, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 4773, "s": 4750, "text": "C# | Method Overriding" }, { "code": null, "e": 4789, "s": 4773, "text": "C# | Data Types" }, { "code": null, "e": 4807, "s": 4789, "text": "C# | Constructors" }, { "code": null, "e": 4847, "s": 4807, "text": "C# | String.IndexOf( ) Method | Set - 1" } ]
Java Program to Count Primes in Ranges
13 Jan, 2022 Given a range [L, R], we need to find the count of total numbers of prime numbers in the range [L, R] where 0 <= L <= R < 10000. Consider that there are a large number of queries for different ranges.Examples: Input : Query 1 : L = 1, R = 10 Query 2 : L = 5, R = 10 Output : 4 2 Explanation Primes in the range L = 1 to R = 10 are {2, 3, 5, 7}. Therefore for query, answer is 4 {2, 3, 5, 7}. For the second query, answer is 2 {5, 7}. A simple solution is to do the following for every query [L, R]. Traverse from L to R, check if current number is prime. If yes, increment the count. Finally, return the count.An efficient solution is to use Sieve of Eratosthenes to find all primes up to the given limit. Then we compute a prefix array to store counts till every value before limit. Once we have a prefix array, we can answer queries in O(1) time. We just need to return prefix[R] – prefix[L-1]. Java // Java program to answer queries for // count of primes in given range.import java.util.*; class GFG { static final int MAX = 10000; // prefix[i] is going to store count // of primes till i (including i).static int prefix[] = new int[MAX + 1]; static void buildPrefix() { // Create a boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. boolean prime[] = new boolean[MAX + 1]; Arrays.fill(prime, true); for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } } // Build prefix array prefix[0] = prefix[1] = 0; for (int p = 2; p <= MAX; p++) { prefix[p] = prefix[p - 1]; if (prime[p]) prefix[p]++; }} // Returns count of primes in range // from L to R (both inclusive).static int query(int L, int R){ return prefix[R] - prefix[L - 1]; } // Driver codepublic static void main(String[] args) { buildPrefix(); int L = 5, R = 10; System.out.println(query(L, R)); L = 1; R = 10; System.out.println(query(L, R));}} // This code is contributed by Anant Agarwal. Output: 2 4 Please refer complete article on Count Primes in Ranges for more details! array-range-queries prefix-sum Prime Number sieve Java Java Programs Mathematical prefix-sum Mathematical Prime Number Java sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Jan, 2022" }, { "code": null, "e": 240, "s": 28, "text": "Given a range [L, R], we need to find the count of total numbers of prime numbers in the range [L, R] where 0 <= L <= R < 10000. Consider that there are a large number of queries for different ranges.Examples: " }, { "code": null, "e": 483, "s": 240, "text": "Input : Query 1 : L = 1, R = 10\n Query 2 : L = 5, R = 10\nOutput : 4\n 2\nExplanation\nPrimes in the range L = 1 to R = 10 are \n{2, 3, 5, 7}. Therefore for query, answer \nis 4 {2, 3, 5, 7}.\nFor the second query, answer is 2 {5, 7}." }, { "code": null, "e": 950, "s": 485, "text": "A simple solution is to do the following for every query [L, R]. Traverse from L to R, check if current number is prime. If yes, increment the count. Finally, return the count.An efficient solution is to use Sieve of Eratosthenes to find all primes up to the given limit. Then we compute a prefix array to store counts till every value before limit. Once we have a prefix array, we can answer queries in O(1) time. We just need to return prefix[R] – prefix[L-1]. " }, { "code": null, "e": 955, "s": 950, "text": "Java" }, { "code": "// Java program to answer queries for // count of primes in given range.import java.util.*; class GFG { static final int MAX = 10000; // prefix[i] is going to store count // of primes till i (including i).static int prefix[] = new int[MAX + 1]; static void buildPrefix() { // Create a boolean array \"prime[0..n]\". A // value in prime[i] will finally be false // if i is Not a prime, else true. boolean prime[] = new boolean[MAX + 1]; Arrays.fill(prime, true); for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } } // Build prefix array prefix[0] = prefix[1] = 0; for (int p = 2; p <= MAX; p++) { prefix[p] = prefix[p - 1]; if (prime[p]) prefix[p]++; }} // Returns count of primes in range // from L to R (both inclusive).static int query(int L, int R){ return prefix[R] - prefix[L - 1]; } // Driver codepublic static void main(String[] args) { buildPrefix(); int L = 5, R = 10; System.out.println(query(L, R)); L = 1; R = 10; System.out.println(query(L, R));}} // This code is contributed by Anant Agarwal.", "e": 2241, "s": 955, "text": null }, { "code": null, "e": 2251, "s": 2241, "text": "Output: " }, { "code": null, "e": 2255, "s": 2251, "text": "2\n4" }, { "code": null, "e": 2329, "s": 2255, "text": "Please refer complete article on Count Primes in Ranges for more details!" }, { "code": null, "e": 2349, "s": 2329, "text": "array-range-queries" }, { "code": null, "e": 2360, "s": 2349, "text": "prefix-sum" }, { "code": null, "e": 2373, "s": 2360, "text": "Prime Number" }, { "code": null, "e": 2379, "s": 2373, "text": "sieve" }, { "code": null, "e": 2384, "s": 2379, "text": "Java" }, { "code": null, "e": 2398, "s": 2384, "text": "Java Programs" }, { "code": null, "e": 2411, "s": 2398, "text": "Mathematical" }, { "code": null, "e": 2422, "s": 2411, "text": "prefix-sum" }, { "code": null, "e": 2435, "s": 2422, "text": "Mathematical" }, { "code": null, "e": 2448, "s": 2435, "text": "Prime Number" }, { "code": null, "e": 2453, "s": 2448, "text": "Java" }, { "code": null, "e": 2459, "s": 2453, "text": "sieve" }, { "code": null, "e": 2557, "s": 2459, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2572, "s": 2557, "text": "Stream In Java" }, { "code": null, "e": 2593, "s": 2572, "text": "Introduction to Java" }, { "code": null, "e": 2614, "s": 2593, "text": "Constructors in Java" }, { "code": null, "e": 2633, "s": 2614, "text": "Exceptions in Java" }, { "code": null, "e": 2650, "s": 2633, "text": "Generics in Java" }, { "code": null, "e": 2676, "s": 2650, "text": "Java Programming Examples" }, { "code": null, "e": 2710, "s": 2676, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 2757, "s": 2710, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 2795, "s": 2757, "text": "Factory method design pattern in Java" } ]
How to Create User in Oracle Database ?
28 Oct, 2021 In oracle there are different type of user accounts system, sys, hr and many more. This user accounts is by default created by oracle .If you want to create your own user then you can create it by two different methods. Step 1. Login to your database as normally you would by username and password. Step 2. Use create user command and specify username, password as you want. Syntax: CREATE USER user_name IDENTIFIED BY password ; Here ‘Geeks’ is user_name and ‘Geeks123’ is password for this user_name .create and user both are the keywords followed by username. New user ‘Geeks’ is created and which is identified by password ‘Geeks123’ . Output: Step 3. You can check that user is created or not in your database by simply login as shown. here we logged in successfully with new username and password. Now you can grant the role and privileges to your new user by using grant command. Step 1. Login into your oracle database. Step 2. Go to administration option and then go to database user option now database users is appear as shown. Step 3. Click on the create option present on right side. As you see create database user window now create new user and set password for that user. Step 4. Type username as you want and password for that username. confirm the password and if you want that password is expired after some time so than you can change it so you can check the expire password box .you can also set account status lock/unlock according to privacy and give the role and privileges according to the user. Step 5. After completion click on create option .Now you get a confirmation message that user is created in your database and you can also see that new user ‘Newgeeks’ is added in the list as shown. surindertarika1234 Oracle SQL-basics SQL Oracle SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? Window functions in SQL What is Temporary Table in SQL? SQL using Python SQL | Sub queries in From Clause SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter RANK() Function in SQL Server SQL Query to Convert VARCHAR to INT SQL Query to Compare Two Dates SQL | DROP, TRUNCATE
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Oct, 2021" }, { "code": null, "e": 248, "s": 28, "text": "In oracle there are different type of user accounts system, sys, hr and many more. This user accounts is by default created by oracle .If you want to create your own user then you can create it by two different methods." }, { "code": null, "e": 327, "s": 248, "text": "Step 1. Login to your database as normally you would by username and password." }, { "code": null, "e": 403, "s": 327, "text": "Step 2. Use create user command and specify username, password as you want." }, { "code": null, "e": 411, "s": 403, "text": "Syntax:" }, { "code": null, "e": 458, "s": 411, "text": "CREATE USER user_name IDENTIFIED BY password ;" }, { "code": null, "e": 592, "s": 458, "text": "Here ‘Geeks’ is user_name and ‘Geeks123’ is password for this user_name .create and user both are the keywords followed by username." }, { "code": null, "e": 669, "s": 592, "text": "New user ‘Geeks’ is created and which is identified by password ‘Geeks123’ ." }, { "code": null, "e": 677, "s": 669, "text": "Output:" }, { "code": null, "e": 916, "s": 677, "text": "Step 3. You can check that user is created or not in your database by simply login as shown. here we logged in successfully with new username and password. Now you can grant the role and privileges to your new user by using grant command." }, { "code": null, "e": 957, "s": 916, "text": "Step 1. Login into your oracle database." }, { "code": null, "e": 1068, "s": 957, "text": "Step 2. Go to administration option and then go to database user option now database users is appear as shown." }, { "code": null, "e": 1217, "s": 1068, "text": "Step 3. Click on the create option present on right side. As you see create database user window now create new user and set password for that user." }, { "code": null, "e": 1551, "s": 1217, "text": "Step 4. Type username as you want and password for that username. confirm the password and if you want that password is expired after some time so than you can change it so you can check the expire password box .you can also set account status lock/unlock according to privacy and give the role and privileges according to the user." }, { "code": null, "e": 1750, "s": 1551, "text": "Step 5. After completion click on create option .Now you get a confirmation message that user is created in your database and you can also see that new user ‘Newgeeks’ is added in the list as shown." }, { "code": null, "e": 1769, "s": 1750, "text": "surindertarika1234" }, { "code": null, "e": 1776, "s": 1769, "text": "Oracle" }, { "code": null, "e": 1787, "s": 1776, "text": "SQL-basics" }, { "code": null, "e": 1791, "s": 1787, "text": "SQL" }, { "code": null, "e": 1798, "s": 1791, "text": "Oracle" }, { "code": null, "e": 1802, "s": 1798, "text": "SQL" }, { "code": null, "e": 1900, "s": 1802, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1966, "s": 1900, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 1990, "s": 1966, "text": "Window functions in SQL" }, { "code": null, "e": 2022, "s": 1990, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 2039, "s": 2022, "text": "SQL using Python" }, { "code": null, "e": 2072, "s": 2039, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 2150, "s": 2072, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 2180, "s": 2150, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 2216, "s": 2180, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 2247, "s": 2216, "text": "SQL Query to Compare Two Dates" } ]
How to convert array of strings to array of numbers in JavaScript ?
22 Jun, 2021 In this article, we have given an array of strings and the task is to convert it into an array of numbers in JavaScript. Input: ["1","2","3","4","5"] Output: [1,2,3,4,5] Input: ["10","21","3","14","53"] Output: [10,21,3,14,53] There are two methods to do this, which are given below: Method 1: Array traversal and typecasting: In this method, we traverse an array of strings and add it to a new array of numbers by typecasting it to an integer using the parseInt() function. Javascript <script> // Create an array of string var stringArray = ["1", "2", "3", "4", "5"]; // Create an empty array of number var numberArray = []; // Store length of array of string // in variable length length = stringArray.length; // Iterate through array of string using // for loop // push all elements of array of string // in array of numbers by typecasting // them to integers using parseInt function for (var i = 0; i < length; i++) // Instead of parseInt(), Number() // can also be used numberArray.push(parseInt(stringArray[i])); // Print the array of numbers console.log(numberArray);</script> Output: [1, 2, 3, 4, 5] Method 2: Using map() method of JavaScript: In this method, we use the array map method of JavaScript. Javascript <script> // Create an array of string var stringArray = ["10", "21", "3", "14", "53"]; // Create a numberArray and using // map function iterate over it // and push it by typecasting into // int using Number var numberArray = stringArray.map(Number); // Print the array of numbers console.log(numberArray);</script> Output: [10, 21, 3, 14, 53] JavaScript-Methods JavaScript-Questions Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array 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": 54, "s": 26, "text": "\n22 Jun, 2021" }, { "code": null, "e": 175, "s": 54, "text": "In this article, we have given an array of strings and the task is to convert it into an array of numbers in JavaScript." }, { "code": null, "e": 282, "s": 175, "text": "Input: [\"1\",\"2\",\"3\",\"4\",\"5\"]\nOutput: [1,2,3,4,5]\n\nInput: [\"10\",\"21\",\"3\",\"14\",\"53\"]\nOutput: [10,21,3,14,53]" }, { "code": null, "e": 339, "s": 282, "text": "There are two methods to do this, which are given below:" }, { "code": null, "e": 530, "s": 339, "text": "Method 1: Array traversal and typecasting: In this method, we traverse an array of strings and add it to a new array of numbers by typecasting it to an integer using the parseInt() function." }, { "code": null, "e": 541, "s": 530, "text": "Javascript" }, { "code": "<script> // Create an array of string var stringArray = [\"1\", \"2\", \"3\", \"4\", \"5\"]; // Create an empty array of number var numberArray = []; // Store length of array of string // in variable length length = stringArray.length; // Iterate through array of string using // for loop // push all elements of array of string // in array of numbers by typecasting // them to integers using parseInt function for (var i = 0; i < length; i++) // Instead of parseInt(), Number() // can also be used numberArray.push(parseInt(stringArray[i])); // Print the array of numbers console.log(numberArray);</script>", "e": 1217, "s": 541, "text": null }, { "code": null, "e": 1225, "s": 1217, "text": "Output:" }, { "code": null, "e": 1241, "s": 1225, "text": "[1, 2, 3, 4, 5]" }, { "code": null, "e": 1344, "s": 1241, "text": "Method 2: Using map() method of JavaScript: In this method, we use the array map method of JavaScript." }, { "code": null, "e": 1355, "s": 1344, "text": "Javascript" }, { "code": "<script> // Create an array of string var stringArray = [\"10\", \"21\", \"3\", \"14\", \"53\"]; // Create a numberArray and using // map function iterate over it // and push it by typecasting into // int using Number var numberArray = stringArray.map(Number); // Print the array of numbers console.log(numberArray);</script>", "e": 1702, "s": 1355, "text": null }, { "code": null, "e": 1710, "s": 1702, "text": "Output:" }, { "code": null, "e": 1730, "s": 1710, "text": "[10, 21, 3, 14, 53]" }, { "code": null, "e": 1749, "s": 1730, "text": "JavaScript-Methods" }, { "code": null, "e": 1770, "s": 1749, "text": "JavaScript-Questions" }, { "code": null, "e": 1777, "s": 1770, "text": "Picked" }, { "code": null, "e": 1788, "s": 1777, "text": "JavaScript" }, { "code": null, "e": 1805, "s": 1788, "text": "Web Technologies" }, { "code": null, "e": 1903, "s": 1805, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1964, "s": 1903, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2004, "s": 1964, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2045, "s": 2004, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2087, "s": 2045, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 2109, "s": 2087, "text": "JavaScript | Promises" }, { "code": null, "e": 2142, "s": 2109, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2204, "s": 2142, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2265, "s": 2204, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2315, "s": 2265, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Stack iterator() method in Java with Example
24 Dec, 2018 The Java.util.Stack.iterator() method is used to return an iterator of the same elements as that of the Stack. The elements are returned in random order from what was present in the stack. Syntax: Iterator iterate_value = Stack.iterator(); Parameters: The function does not take any parameter. Return Value: The method iterates over the elements of the stack and returns the values(iterators). Below program illustrates the use of Java.util.Stack.iterator() method: Example 1: // Java code to illustrate iterator() import java.util.*;import java.util.Stack; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<String> stack = new Stack<String>(); // Use add() method to add elements into the Stack stack.add("Welcome"); stack.add("To"); stack.add("Geeks"); stack.add("4"); stack.add("Geeks"); // Displaying the Stack System.out.println("Stack: " + stack); // Creating an iterator Iterator value = stack.iterator(); // Displaying the values // after iterating through the stack System.out.println("The iterator values are: "); while (value.hasNext()) { System.out.println(value.next()); } }} Stack: [Welcome, To, Geeks, 4, Geeks] The iterator values are: Welcome To Geeks 4 Geeks Example 2: // Java code to illustrate hashCode() import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<Integer> stack = new Stack<Integer>(); // Use add() method // to add elements into the Stack stack.add(10); stack.add(20); stack.add(30); stack.add(40); stack.add(50); // Displaying the Stack System.out.println("Stack: " + stack); // Creating an iterator Iterator value = stack.iterator(); // Displaying the values // after iterating through the stack System.out.println("The iterator values are: "); while (value.hasNext()) { System.out.println(value.next()); } }} Stack: [10, 20, 30, 40, 50] The iterator values are: 10 20 30 40 50 Java - util package Java-Collections Java-Functions Java-Stack Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n24 Dec, 2018" }, { "code": null, "e": 242, "s": 53, "text": "The Java.util.Stack.iterator() method is used to return an iterator of the same elements as that of the Stack. The elements are returned in random order from what was present in the stack." }, { "code": null, "e": 250, "s": 242, "text": "Syntax:" }, { "code": null, "e": 294, "s": 250, "text": "Iterator iterate_value = Stack.iterator();\n" }, { "code": null, "e": 348, "s": 294, "text": "Parameters: The function does not take any parameter." }, { "code": null, "e": 448, "s": 348, "text": "Return Value: The method iterates over the elements of the stack and returns the values(iterators)." }, { "code": null, "e": 520, "s": 448, "text": "Below program illustrates the use of Java.util.Stack.iterator() method:" }, { "code": null, "e": 531, "s": 520, "text": "Example 1:" }, { "code": "// Java code to illustrate iterator() import java.util.*;import java.util.Stack; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<String> stack = new Stack<String>(); // Use add() method to add elements into the Stack stack.add(\"Welcome\"); stack.add(\"To\"); stack.add(\"Geeks\"); stack.add(\"4\"); stack.add(\"Geeks\"); // Displaying the Stack System.out.println(\"Stack: \" + stack); // Creating an iterator Iterator value = stack.iterator(); // Displaying the values // after iterating through the stack System.out.println(\"The iterator values are: \"); while (value.hasNext()) { System.out.println(value.next()); } }}", "e": 1341, "s": 531, "text": null }, { "code": null, "e": 1431, "s": 1341, "text": "Stack: [Welcome, To, Geeks, 4, Geeks]\nThe iterator values are: \nWelcome\nTo\nGeeks\n4\nGeeks\n" }, { "code": null, "e": 1442, "s": 1431, "text": "Example 2:" }, { "code": "// Java code to illustrate hashCode() import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<Integer> stack = new Stack<Integer>(); // Use add() method // to add elements into the Stack stack.add(10); stack.add(20); stack.add(30); stack.add(40); stack.add(50); // Displaying the Stack System.out.println(\"Stack: \" + stack); // Creating an iterator Iterator value = stack.iterator(); // Displaying the values // after iterating through the stack System.out.println(\"The iterator values are: \"); while (value.hasNext()) { System.out.println(value.next()); } }}", "e": 2232, "s": 1442, "text": null }, { "code": null, "e": 2302, "s": 2232, "text": "Stack: [10, 20, 30, 40, 50]\nThe iterator values are: \n10\n20\n30\n40\n50\n" }, { "code": null, "e": 2322, "s": 2302, "text": "Java - util package" }, { "code": null, "e": 2339, "s": 2322, "text": "Java-Collections" }, { "code": null, "e": 2354, "s": 2339, "text": "Java-Functions" }, { "code": null, "e": 2365, "s": 2354, "text": "Java-Stack" }, { "code": null, "e": 2370, "s": 2365, "text": "Java" }, { "code": null, "e": 2375, "s": 2370, "text": "Java" }, { "code": null, "e": 2392, "s": 2375, "text": "Java-Collections" } ]
Explain serial execution or transaction with an example(DBMS)
There are three possible ways in which a transaction can be executed. These are as follows − Serial execution − In serial execution, the second transaction can begin its execution only after the first transaction has completed. This is possible on a uniprocessor system. Serial execution − In serial execution, the second transaction can begin its execution only after the first transaction has completed. This is possible on a uniprocessor system. Parallel execution − In parallel execution, two transactions can start their execution at exactly the same instant of time. For this, we require more than one processor. Parallel execution − In parallel execution, two transactions can start their execution at exactly the same instant of time. For this, we require more than one processor. Concurrent execution − In concurrent execution, execution of the second process can begin even before the process has completed its execution. Concurrent execution − In concurrent execution, execution of the second process can begin even before the process has completed its execution. Let us consider two transactions T1 and T2. In concurrent execution, the CPU executes some instructions of transaction T1, then moves to the second transaction and executes its instructions for some time and again it comes back to the first transaction. The cycle is repeated until all the instructions of both the transactions are executed. The process is called context switching. Given below is an example of serial execution − Let us consider two transactions T1 and T2 where T1 performs transfer Rs.150 from account A to account B and similarly T2 transfers 10% of balance from A to B. T1 T2 Read(A) Read(A) A=A-150 temp =0.1 *A Write(A) A=A-temp Read(B) Write(A) B=B+150 Read(B) Write(B) B=B+temp Write(B) The order in which the instructions of transaction T1 and T2 are executed is called a Schedule. The possible serial schedules are as follows − Let A= 200, B=200 Schedule S1 and S2 keeps the database in consistent state. In general if the system consists of n number of transactions, then we can generate n! number of valid serial schedules.
[ { "code": null, "e": 1155, "s": 1062, "text": "There are three possible ways in which a transaction can be executed. These are as follows −" }, { "code": null, "e": 1333, "s": 1155, "text": "Serial execution − In serial execution, the second transaction can begin its execution only after the first transaction has completed. This is possible on a uniprocessor system." }, { "code": null, "e": 1511, "s": 1333, "text": "Serial execution − In serial execution, the second transaction can begin its execution only after the first transaction has completed. This is possible on a uniprocessor system." }, { "code": null, "e": 1681, "s": 1511, "text": "Parallel execution − In parallel execution, two transactions can start their execution at exactly the same instant of time. For this, we require more than one processor." }, { "code": null, "e": 1851, "s": 1681, "text": "Parallel execution − In parallel execution, two transactions can start their execution at exactly the same instant of time. For this, we require more than one processor." }, { "code": null, "e": 1994, "s": 1851, "text": "Concurrent execution − In concurrent execution, execution of the second process can begin even before the process has completed its execution." }, { "code": null, "e": 2137, "s": 1994, "text": "Concurrent execution − In concurrent execution, execution of the second process can begin even before the process has completed its execution." }, { "code": null, "e": 2391, "s": 2137, "text": "Let us consider two transactions T1 and T2. In concurrent execution, the CPU executes some instructions of transaction T1, then moves to the second transaction and executes its instructions for some time and again it comes back to the first transaction." }, { "code": null, "e": 2520, "s": 2391, "text": "The cycle is repeated until all the instructions of both the transactions are executed. The process is called context switching." }, { "code": null, "e": 2568, "s": 2520, "text": "Given below is an example of serial execution −" }, { "code": null, "e": 2728, "s": 2568, "text": "Let us consider two transactions T1 and T2 where T1 performs transfer Rs.150 from account A to account B and similarly T2 transfers 10% of balance from A to B." }, { "code": null, "e": 2933, "s": 2728, "text": " T1 T2\n Read(A) Read(A)\n A=A-150 temp =0.1 *A\n Write(A) A=A-temp\n Read(B) Write(A)\n B=B+150 Read(B)\n Write(B) B=B+temp\n Write(B)" }, { "code": null, "e": 3029, "s": 2933, "text": "The order in which the instructions of transaction T1 and T2 are executed is called a Schedule." }, { "code": null, "e": 3076, "s": 3029, "text": "The possible serial schedules are as follows −" }, { "code": null, "e": 3094, "s": 3076, "text": "Let A= 200, B=200" }, { "code": null, "e": 3153, "s": 3094, "text": "Schedule S1 and S2 keeps the database in consistent state." }, { "code": null, "e": 3274, "s": 3153, "text": "In general if the system consists of n number of transactions, then we can generate n! number of valid serial schedules." } ]
Find multiplication of sums of data of leaves at same levels - GeeksforGeeks
11 Jun, 2021 Given a Binary Tree, return following value for it. 1) For every level, compute sum of all leaves if there are leaves at this level. Otherwise, ignore it. 2) Return multiplication of all sums.Examples: Input: Root of below tree 2 / \ 7 5 \ 9 Output: 63 First levels doesn't have leaves. Second level has one leaf 7 and third level also has one leaf 9. Therefore result is 7*9 = 63 Input: Root of below tree 2 / \ 7 5 / \ \ 8 6 9 / \ / \ 1 11 4 10 Output: 208 First two levels don't have leaves. Third level has single leaf 8. Last level has four leaves 1, 11, 4 and 10. Therefore result is 8 * (1 + 11 + 4 + 10) We strongly recommend you to minimize your browser and try this yourself first.One Simple Solution is to recursively compute leaf sum for all level starting from top to bottom. Then multiply sums of levels which have leaves. Time complexity of this solution would be O(n2).An Efficient Solution is to use Queue based level order traversal. While doing the traversal, process all different levels separately. For every processed level, check if it has leaves. If it has then compute sum of leaf nodes. Finally return product of all sums. C++ Java Python3 C# Javascript /* Iterative C++ program to find sum of data of all leaves of a binary tree on same level and then multiply sums obtained of all levels. */#include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node { int data; struct Node *left, *right;}; // helper function to check if a Node is leaf of treebool isLeaf(Node* root){ return (!root->left && !root->right);} /* Calculate sum of all leaf Nodes at each level and returns multiplication of sums */int sumAndMultiplyLevelData(Node* root){ // Tree is empty if (!root) return 0; int mul = 1; /* To store result */ // Create an empty queue for level order traversal queue<Node*> q; // Enqueue Root and initialize height q.push(root); // Do level order traversal of tree while (1) { // NodeCount (queue size) indicates number of Nodes // at current level. int NodeCount = q.size(); // If there are no Nodes at current level, we are done if (NodeCount == 0) break; // Initialize leaf sum for current level int levelSum = 0; // A boolean variable to indicate if found a leaf // Node at current level or not bool leafFound = false; // Dequeue all Nodes of current level and Enqueue all // Nodes of next level while (NodeCount > 0) { // Process next Node of current level Node* Node = q.front(); /* if Node is a leaf, update sum at the level */ if (isLeaf(Node)) { leafFound = true; levelSum += Node->data; } q.pop(); // Add children of Node if (Node->left != NULL) q.push(Node->left); if (Node->right != NULL) q.push(Node->right); NodeCount--; } // If we found at least one leaf, we multiply // result with level sum. if (leafFound) mul *= levelSum; } return mul; // Return result} // Utility function to create a new tree NodeNode* newNode(int data){ Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // Driver program to test above functionsint main(){ Node* root = newNode(2); root->left = newNode(7); root->right = newNode(5); root->left->right = newNode(6); root->left->left = newNode(8); root->left->right->left = newNode(1); root->left->right->right = newNode(11); root->right->right = newNode(9); root->right->right->left = newNode(4); root->right->right->right = newNode(10); cout << "Final product value = " << sumAndMultiplyLevelData(root) << endl; return 0;} /* Iterative Java program to find sum of data of all leaves of a binary tree on same level and then multiply sums obtained of all levels. */ /* importing the necessary class */import java.util.LinkedList;import java.util.Queue;import java.util.Stack; /* Class containing left and right child of current node and key value*/class Node { int data; Node left, right; public Node(int item) { data = item; left = right = null; }} class BinaryTree { Node root; // helper function to check if a Node is leaf of tree boolean isLeaf(Node node) { return ((node.left == null) && (node.right == null)); } /* Calculate sum of all leaf Nodes at each level and returns multiplication of sums */ int sumAndMultiplyLevelData() { return sumAndMultiplyLevelData(root); } int sumAndMultiplyLevelData(Node node) { // Tree is empty if (node == null) { return 0; } int mul = 1; /* To store result */ // Create an empty queue for level order traversal LinkedList<Node> q = new LinkedList<Node>(); // Enqueue Root and initialize height q.add(node); // Do level order traversal of tree while (true) { // NodeCount (queue size) indicates number of Nodes // at current level. int NodeCount = q.size(); // If there are no Nodes at current level, we are done if (NodeCount == 0) { break; } // Initialize leaf sum for current level int levelSum = 0; // A boolean variable to indicate if found a leaf // Node at current level or not boolean leafFound = false; // Dequeue all Nodes of current level and Enqueue all // Nodes of next level while (NodeCount > 0) { Node node1; node1 = q.poll(); /* if Node is a leaf, update sum at the level */ if (isLeaf(node1)) { leafFound = true; levelSum += node1.data; } // Add children of Node if (node1.left != null) { q.add(node1.left); } if (node1.right != null) { q.add(node1.right); } NodeCount--; } // If we found at least one leaf, we multiply // result with level sum. if (leafFound) { mul *= levelSum; } } return mul; // Return result } public static void main(String args[]) { /* creating a binary tree and entering the nodes */ BinaryTree tree = new BinaryTree(); tree.root = new Node(2); tree.root.left = new Node(7); tree.root.right = new Node(5); tree.root.left.left = new Node(8); tree.root.left.right = new Node(6); tree.root.left.right.left = new Node(1); tree.root.left.right.right = new Node(11); tree.root.right.right = new Node(9); tree.root.right.right.left = new Node(4); tree.root.right.right.right = new Node(10); System.out.println("The final product value : " + tree.sumAndMultiplyLevelData()); }} // This code is contributed by Mayank Jaiswal """Iterative Python3 program to findsum of data of all leaves of a binarytree on same level and then multiplysums obtained of all levels.""" # A Binary Tree Node# Utility function to create a# new tree Nodeclass newNode: def __init__(self, data): self.data = data self.left = self.right = None # helper function to check if a# Node is leaf of treedef isLeaf(root) : return (not root.left and not root.right) """ Calculate sum of all leaf Nodes at eachlevel and returns multiplication of sums """def sumAndMultiplyLevelData( root) : # Tree is empty if (not root) : return 0 mul = 1 """ To store result """ # Create an empty queue for level # order traversal q = [] # Enqueue Root and initialize height q.append(root) # Do level order traversal of tree while (1): # NodeCount (queue size) indicates # number of Nodes at current level. NodeCount = len(q) # If there are no Nodes at current # level, we are done if (NodeCount == 0) : break # Initialize leaf sum for # current level levelSum = 0 # A boolean variable to indicate # if found a leaf Node at current # level or not leafFound = False # Dequeue all Nodes of current level # and Enqueue all Nodes of next level while (NodeCount > 0) : # Process next Node of current level Node = q[0] """ if Node is a leaf, update sum at the level """ if (isLeaf(Node)) : leafFound = True levelSum += Node.data q.pop(0) # Add children of Node if (Node.left != None) : q.append(Node.left) if (Node.right != None) : q.append(Node.right) NodeCount-=1 # If we found at least one leaf, # we multiply result with level sum. if (leafFound) : mul *= levelSum return mul # Return result # Driver Codeif __name__ == '__main__': root = newNode(2) root.left = newNode(7) root.right = newNode(5) root.left.right = newNode(6) root.left.left = newNode(8) root.left.right.left = newNode(1) root.left.right.right = newNode(11) root.right.right = newNode(9) root.right.right.left = newNode(4) root.right.right.right = newNode(10) print("Final product value = ", sumAndMultiplyLevelData(root)) # This code is contributed# by SHUBHAMSINGH10 /* Iterative C# program to find sumof data of all leaves of a binary treeon same level and then multiply sumsobtained of all levels. */ /* importing the necessary class */using System;using System.Collections.Generic; /* Class containing left and right child of current node and key value*/public class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ Node root; // helper function to check if // a Node is leaf of tree bool isLeaf(Node node) { return ((node.left == null) && (node.right == null)); } /* Calculate sum of all leaf Nodes at each level and returns multiplication of sums */ int sumAndMultiplyLevelData() { return sumAndMultiplyLevelData(root); } int sumAndMultiplyLevelData(Node node) { // Tree is empty if (node == null) { return 0; } int mul = 1; /* To store result */ // Create an empty queue for level order traversal Queue<Node> q = new Queue<Node>(); // Enqueue Root and initialize height q.Enqueue(node); // Do level order traversal of tree while (true) { // NodeCount (queue size) indicates // number of Nodes at current level. int NodeCount = q.Count; // If there are no Nodes at current // level, we are done if (NodeCount == 0) { break; } // Initialize leaf sum for current level int levelSum = 0; // A boolean variable to indicate if found a leaf // Node at current level or not bool leafFound = false; // Dequeue all Nodes of current level and // Enqueue all Nodes of next level while (NodeCount > 0) { Node node1; node1 = q.Dequeue(); /* if Node is a leaf, update sum at the level */ if (isLeaf(node1)) { leafFound = true; levelSum += node1.data; } // Add children of Node if (node1.left != null) { q.Enqueue(node1.left); } if (node1.right != null) { q.Enqueue(node1.right); } NodeCount--; } // If we found at least one leaf, we multiply // result with level sum. if (leafFound) { mul *= levelSum; } } return mul; // Return result } // Driver code public static void Main(String []args) { /* creating a binary tree and entering the nodes */ BinaryTree tree = new BinaryTree(); tree.root = new Node(2); tree.root.left = new Node(7); tree.root.right = new Node(5); tree.root.left.left = new Node(8); tree.root.left.right = new Node(6); tree.root.left.right.left = new Node(1); tree.root.left.right.right = new Node(11); tree.root.right.right = new Node(9); tree.root.right.right.left = new Node(4); tree.root.right.right.right = new Node(10); Console.WriteLine("The final product value : " + tree.sumAndMultiplyLevelData()); }} // This code has been contributed by 29AjayKumar <script> /* Iterative Javascript program to find sum of data of all leaves of a binary tree on same level and then multiply sums obtained of all levels. */ /* importing the necessary class */ /* Class containing left and right child of current node and key value*/class Node{ constructor(data) { this.data=data; this.left = this.right = null; }} let root;// helper function to check if a Node is leaf of treefunction isLeaf(node){ return ((node.left == null) && (node.right == null));} /* Calculate sum of all leaf Nodes at each level and returns multiplication of sums */ function sumAndMultiplyLevelData(node){ // Tree is empty if (node == null) { return 0; } let mul = 1; /* To store result */ // Create an empty queue for level order traversal let q = []; // Enqueue Root and initialize height q.push(node); // Do level order traversal of tree while (true) { // NodeCount (queue size) indicates number of Nodes // at current level. let NodeCount = q.length; // If there are no Nodes at current level, we are done if (NodeCount == 0) { break; } // Initialize leaf sum for current level let levelSum = 0; // A boolean variable to indicate if found a leaf // Node at current level or not let leafFound = false; // Dequeue all Nodes of current level and Enqueue all // Nodes of next level while (NodeCount > 0) { let node1= q.shift(); /* if Node is a leaf, update sum at the level */ if (isLeaf(node1)) { leafFound = true; levelSum += node1.data; } // Add children of Node if (node1.left != null) { q.push(node1.left); } if (node1.right != null) { q.push(node1.right); } NodeCount--; } // If we found at least one leaf, we multiply // result with level sum. if (leafFound) { mul *= levelSum; } } return mul; // Return result} /* creating a binary tree and entering the nodes */root = new Node(2);root.left = new Node(7);root.right = new Node(5);root.left.left = new Node(8);root.left.right = new Node(6);root.left.right.left = new Node(1);root.left.right.right = new Node(11);root.right.right = new Node(9);root.right.right.left = new Node(4);root.right.right.right = new Node(10);document.write("The final product value : " + sumAndMultiplyLevelData(root)); // This code is contributed by rag2127 </script> Output: Final product value = 208 YouTubeGeeksforGeeks502K subscribersFind multiplication of sums of data of leaves at same levels | 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 / 6:47•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=oG1LqvQbnzQ" 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 Mohammed Raqeeb. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above SHUBHAMSINGH10 29AjayKumar sweetyty rag2127 Microsoft tree-level-order Tree Microsoft Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inorder Tree Traversal without Recursion Binary Tree | Set 3 (Types of Binary Tree) Binary Tree | Set 2 (Properties) A program to check if a binary tree is BST or not Decision Tree Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Construct Tree from given Inorder and Preorder traversals Introduction to Tree Data Structure Lowest Common Ancestor in a Binary Tree | Set 1 BFS vs DFS for Binary Tree
[ { "code": null, "e": 24830, "s": 24802, "text": "\n11 Jun, 2021" }, { "code": null, "e": 25034, "s": 24830, "text": "Given a Binary Tree, return following value for it. 1) For every level, compute sum of all leaves if there are leaves at this level. Otherwise, ignore it. 2) Return multiplication of all sums.Examples: " }, { "code": null, "e": 25575, "s": 25034, "text": "Input: Root of below tree\n 2\n / \\\n 7 5\n \\\n 9\nOutput: 63\nFirst levels doesn't have leaves. Second level\nhas one leaf 7 and third level also has one \nleaf 9. Therefore result is 7*9 = 63\n\n\nInput: Root of below tree\n 2\n / \\\n 7 5\n / \\ \\\n 8 6 9\n / \\ / \\\n 1 11 4 10 \n\nOutput: 208\nFirst two levels don't have leaves. Third\nlevel has single leaf 8. Last level has four\nleaves 1, 11, 4 and 10. Therefore result is \n8 * (1 + 11 + 4 + 10) " }, { "code": null, "e": 26113, "s": 25575, "text": "We strongly recommend you to minimize your browser and try this yourself first.One Simple Solution is to recursively compute leaf sum for all level starting from top to bottom. Then multiply sums of levels which have leaves. Time complexity of this solution would be O(n2).An Efficient Solution is to use Queue based level order traversal. While doing the traversal, process all different levels separately. For every processed level, check if it has leaves. If it has then compute sum of leaf nodes. Finally return product of all sums. " }, { "code": null, "e": 26117, "s": 26113, "text": "C++" }, { "code": null, "e": 26122, "s": 26117, "text": "Java" }, { "code": null, "e": 26130, "s": 26122, "text": "Python3" }, { "code": null, "e": 26133, "s": 26130, "text": "C#" }, { "code": null, "e": 26144, "s": 26133, "text": "Javascript" }, { "code": "/* Iterative C++ program to find sum of data of all leaves of a binary tree on same level and then multiply sums obtained of all levels. */#include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node { int data; struct Node *left, *right;}; // helper function to check if a Node is leaf of treebool isLeaf(Node* root){ return (!root->left && !root->right);} /* Calculate sum of all leaf Nodes at each level and returns multiplication of sums */int sumAndMultiplyLevelData(Node* root){ // Tree is empty if (!root) return 0; int mul = 1; /* To store result */ // Create an empty queue for level order traversal queue<Node*> q; // Enqueue Root and initialize height q.push(root); // Do level order traversal of tree while (1) { // NodeCount (queue size) indicates number of Nodes // at current level. int NodeCount = q.size(); // If there are no Nodes at current level, we are done if (NodeCount == 0) break; // Initialize leaf sum for current level int levelSum = 0; // A boolean variable to indicate if found a leaf // Node at current level or not bool leafFound = false; // Dequeue all Nodes of current level and Enqueue all // Nodes of next level while (NodeCount > 0) { // Process next Node of current level Node* Node = q.front(); /* if Node is a leaf, update sum at the level */ if (isLeaf(Node)) { leafFound = true; levelSum += Node->data; } q.pop(); // Add children of Node if (Node->left != NULL) q.push(Node->left); if (Node->right != NULL) q.push(Node->right); NodeCount--; } // If we found at least one leaf, we multiply // result with level sum. if (leafFound) mul *= levelSum; } return mul; // Return result} // Utility function to create a new tree NodeNode* newNode(int data){ Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // Driver program to test above functionsint main(){ Node* root = newNode(2); root->left = newNode(7); root->right = newNode(5); root->left->right = newNode(6); root->left->left = newNode(8); root->left->right->left = newNode(1); root->left->right->right = newNode(11); root->right->right = newNode(9); root->right->right->left = newNode(4); root->right->right->right = newNode(10); cout << \"Final product value = \" << sumAndMultiplyLevelData(root) << endl; return 0;}", "e": 28847, "s": 26144, "text": null }, { "code": "/* Iterative Java program to find sum of data of all leaves of a binary tree on same level and then multiply sums obtained of all levels. */ /* importing the necessary class */import java.util.LinkedList;import java.util.Queue;import java.util.Stack; /* Class containing left and right child of current node and key value*/class Node { int data; Node left, right; public Node(int item) { data = item; left = right = null; }} class BinaryTree { Node root; // helper function to check if a Node is leaf of tree boolean isLeaf(Node node) { return ((node.left == null) && (node.right == null)); } /* Calculate sum of all leaf Nodes at each level and returns multiplication of sums */ int sumAndMultiplyLevelData() { return sumAndMultiplyLevelData(root); } int sumAndMultiplyLevelData(Node node) { // Tree is empty if (node == null) { return 0; } int mul = 1; /* To store result */ // Create an empty queue for level order traversal LinkedList<Node> q = new LinkedList<Node>(); // Enqueue Root and initialize height q.add(node); // Do level order traversal of tree while (true) { // NodeCount (queue size) indicates number of Nodes // at current level. int NodeCount = q.size(); // If there are no Nodes at current level, we are done if (NodeCount == 0) { break; } // Initialize leaf sum for current level int levelSum = 0; // A boolean variable to indicate if found a leaf // Node at current level or not boolean leafFound = false; // Dequeue all Nodes of current level and Enqueue all // Nodes of next level while (NodeCount > 0) { Node node1; node1 = q.poll(); /* if Node is a leaf, update sum at the level */ if (isLeaf(node1)) { leafFound = true; levelSum += node1.data; } // Add children of Node if (node1.left != null) { q.add(node1.left); } if (node1.right != null) { q.add(node1.right); } NodeCount--; } // If we found at least one leaf, we multiply // result with level sum. if (leafFound) { mul *= levelSum; } } return mul; // Return result } public static void main(String args[]) { /* creating a binary tree and entering the nodes */ BinaryTree tree = new BinaryTree(); tree.root = new Node(2); tree.root.left = new Node(7); tree.root.right = new Node(5); tree.root.left.left = new Node(8); tree.root.left.right = new Node(6); tree.root.left.right.left = new Node(1); tree.root.left.right.right = new Node(11); tree.root.right.right = new Node(9); tree.root.right.right.left = new Node(4); tree.root.right.right.right = new Node(10); System.out.println(\"The final product value : \" + tree.sumAndMultiplyLevelData()); }} // This code is contributed by Mayank Jaiswal", "e": 32237, "s": 28847, "text": null }, { "code": "\"\"\"Iterative Python3 program to findsum of data of all leaves of a binarytree on same level and then multiplysums obtained of all levels.\"\"\" # A Binary Tree Node# Utility function to create a# new tree Nodeclass newNode: def __init__(self, data): self.data = data self.left = self.right = None # helper function to check if a# Node is leaf of treedef isLeaf(root) : return (not root.left and not root.right) \"\"\" Calculate sum of all leaf Nodes at eachlevel and returns multiplication of sums \"\"\"def sumAndMultiplyLevelData( root) : # Tree is empty if (not root) : return 0 mul = 1 \"\"\" To store result \"\"\" # Create an empty queue for level # order traversal q = [] # Enqueue Root and initialize height q.append(root) # Do level order traversal of tree while (1): # NodeCount (queue size) indicates # number of Nodes at current level. NodeCount = len(q) # If there are no Nodes at current # level, we are done if (NodeCount == 0) : break # Initialize leaf sum for # current level levelSum = 0 # A boolean variable to indicate # if found a leaf Node at current # level or not leafFound = False # Dequeue all Nodes of current level # and Enqueue all Nodes of next level while (NodeCount > 0) : # Process next Node of current level Node = q[0] \"\"\" if Node is a leaf, update sum at the level \"\"\" if (isLeaf(Node)) : leafFound = True levelSum += Node.data q.pop(0) # Add children of Node if (Node.left != None) : q.append(Node.left) if (Node.right != None) : q.append(Node.right) NodeCount-=1 # If we found at least one leaf, # we multiply result with level sum. if (leafFound) : mul *= levelSum return mul # Return result # Driver Codeif __name__ == '__main__': root = newNode(2) root.left = newNode(7) root.right = newNode(5) root.left.right = newNode(6) root.left.left = newNode(8) root.left.right.left = newNode(1) root.left.right.right = newNode(11) root.right.right = newNode(9) root.right.right.left = newNode(4) root.right.right.right = newNode(10) print(\"Final product value = \", sumAndMultiplyLevelData(root)) # This code is contributed# by SHUBHAMSINGH10", "e": 34812, "s": 32237, "text": null }, { "code": "/* Iterative C# program to find sumof data of all leaves of a binary treeon same level and then multiply sumsobtained of all levels. */ /* importing the necessary class */using System;using System.Collections.Generic; /* Class containing left and right child of current node and key value*/public class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ Node root; // helper function to check if // a Node is leaf of tree bool isLeaf(Node node) { return ((node.left == null) && (node.right == null)); } /* Calculate sum of all leaf Nodes at each level and returns multiplication of sums */ int sumAndMultiplyLevelData() { return sumAndMultiplyLevelData(root); } int sumAndMultiplyLevelData(Node node) { // Tree is empty if (node == null) { return 0; } int mul = 1; /* To store result */ // Create an empty queue for level order traversal Queue<Node> q = new Queue<Node>(); // Enqueue Root and initialize height q.Enqueue(node); // Do level order traversal of tree while (true) { // NodeCount (queue size) indicates // number of Nodes at current level. int NodeCount = q.Count; // If there are no Nodes at current // level, we are done if (NodeCount == 0) { break; } // Initialize leaf sum for current level int levelSum = 0; // A boolean variable to indicate if found a leaf // Node at current level or not bool leafFound = false; // Dequeue all Nodes of current level and // Enqueue all Nodes of next level while (NodeCount > 0) { Node node1; node1 = q.Dequeue(); /* if Node is a leaf, update sum at the level */ if (isLeaf(node1)) { leafFound = true; levelSum += node1.data; } // Add children of Node if (node1.left != null) { q.Enqueue(node1.left); } if (node1.right != null) { q.Enqueue(node1.right); } NodeCount--; } // If we found at least one leaf, we multiply // result with level sum. if (leafFound) { mul *= levelSum; } } return mul; // Return result } // Driver code public static void Main(String []args) { /* creating a binary tree and entering the nodes */ BinaryTree tree = new BinaryTree(); tree.root = new Node(2); tree.root.left = new Node(7); tree.root.right = new Node(5); tree.root.left.left = new Node(8); tree.root.left.right = new Node(6); tree.root.left.right.left = new Node(1); tree.root.left.right.right = new Node(11); tree.root.right.right = new Node(9); tree.root.right.right.left = new Node(4); tree.root.right.right.right = new Node(10); Console.WriteLine(\"The final product value : \" + tree.sumAndMultiplyLevelData()); }} // This code has been contributed by 29AjayKumar", "e": 38320, "s": 34812, "text": null }, { "code": "<script> /* Iterative Javascript program to find sum of data of all leaves of a binary tree on same level and then multiply sums obtained of all levels. */ /* importing the necessary class */ /* Class containing left and right child of current node and key value*/class Node{ constructor(data) { this.data=data; this.left = this.right = null; }} let root;// helper function to check if a Node is leaf of treefunction isLeaf(node){ return ((node.left == null) && (node.right == null));} /* Calculate sum of all leaf Nodes at each level and returns multiplication of sums */ function sumAndMultiplyLevelData(node){ // Tree is empty if (node == null) { return 0; } let mul = 1; /* To store result */ // Create an empty queue for level order traversal let q = []; // Enqueue Root and initialize height q.push(node); // Do level order traversal of tree while (true) { // NodeCount (queue size) indicates number of Nodes // at current level. let NodeCount = q.length; // If there are no Nodes at current level, we are done if (NodeCount == 0) { break; } // Initialize leaf sum for current level let levelSum = 0; // A boolean variable to indicate if found a leaf // Node at current level or not let leafFound = false; // Dequeue all Nodes of current level and Enqueue all // Nodes of next level while (NodeCount > 0) { let node1= q.shift(); /* if Node is a leaf, update sum at the level */ if (isLeaf(node1)) { leafFound = true; levelSum += node1.data; } // Add children of Node if (node1.left != null) { q.push(node1.left); } if (node1.right != null) { q.push(node1.right); } NodeCount--; } // If we found at least one leaf, we multiply // result with level sum. if (leafFound) { mul *= levelSum; } } return mul; // Return result} /* creating a binary tree and entering the nodes */root = new Node(2);root.left = new Node(7);root.right = new Node(5);root.left.left = new Node(8);root.left.right = new Node(6);root.left.right.left = new Node(1);root.left.right.right = new Node(11);root.right.right = new Node(9);root.right.right.left = new Node(4);root.right.right.right = new Node(10);document.write(\"The final product value : \" + sumAndMultiplyLevelData(root)); // This code is contributed by rag2127 </script>", "e": 41199, "s": 38320, "text": null }, { "code": null, "e": 41209, "s": 41199, "text": "Output: " }, { "code": null, "e": 41235, "s": 41209, "text": "Final product value = 208" }, { "code": null, "e": 42096, "s": 41237, "text": "YouTubeGeeksforGeeks502K subscribersFind multiplication of sums of data of leaves at same levels | 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 / 6:47•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=oG1LqvQbnzQ\" 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": 42269, "s": 42096, "text": "This article is contributed by Mohammed Raqeeb. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 42284, "s": 42269, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 42296, "s": 42284, "text": "29AjayKumar" }, { "code": null, "e": 42305, "s": 42296, "text": "sweetyty" }, { "code": null, "e": 42313, "s": 42305, "text": "rag2127" }, { "code": null, "e": 42323, "s": 42313, "text": "Microsoft" }, { "code": null, "e": 42340, "s": 42323, "text": "tree-level-order" }, { "code": null, "e": 42345, "s": 42340, "text": "Tree" }, { "code": null, "e": 42355, "s": 42345, "text": "Microsoft" }, { "code": null, "e": 42360, "s": 42355, "text": "Tree" }, { "code": null, "e": 42458, "s": 42360, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42499, "s": 42458, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 42542, "s": 42499, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 42575, "s": 42542, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 42625, "s": 42575, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 42639, "s": 42625, "text": "Decision Tree" }, { "code": null, "e": 42722, "s": 42639, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 42780, "s": 42722, "text": "Construct Tree from given Inorder and Preorder traversals" }, { "code": null, "e": 42816, "s": 42780, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 42864, "s": 42816, "text": "Lowest Common Ancestor in a Binary Tree | Set 1" } ]
How to Build a Web Scraper in Python | by Roman Paolucci | Towards Data Science
Web scraping is an awesome tool for analysts to sift through and collect large amounts of public data. Using keywords relevant to the topic in question, a good web scraper can gather large amounts of data very quickly and aggregate it into a dataset. There are several libraries in Python that make this extremely easy to accomplish. In this article, I will illustrate an architecture that I have been using for web scraping and summarizing search engine data. The article will be broken up into the following sections... Link Scraping Content Scraping Content Summarizing Building a Pipeline All of the code will be provided herein. First, we need a way to gather URLs relevant to the topic we are scraping data for. Fortunately, the Python library googlesearch makes it easy to gather URLs in response to an initial google search. Let’s build a class that uses this library to search our keywords and append a fixed number of URLs to a list for further analysis... This is arguably the most important part of the web scraper as it determines what data on a webpage will be gathered. Using a combination of urllib and beautiful soup (bs4) we are able to retrieve and parse the HTML for each URL in our Link Scraper class. Beautiful soup lets us specify the tags we want to extract data from. In the case below I am establishing a URL request and parsing the HTML response with bs4 and storing all the information found in the paragraph (<p></p>) tags... This is where we create a summary of the text extracted from each page’s HTML residing in our Content Scraper. To do this we will be using a combination of libraries, mainly NLTK. The way in which we are generating the summary is relatively elementary and there are many ways to improve this method — but it's a great start. After some formatting and voiding of filler words, words get tokenized and ranked by frequency generating a few sentences that aim to accurately summarize the article... This is the part where we put everything together. One class will instantiate an instance of each other component as needed to build and implement our web scraper. The WebScraper class takes a few parameters... search — String, Search engine query n — Integer, Number of URL sources to analyze sl —Integer, Sentence length of the summary fall_through — Boolean, Multithread the process or not Write_file —Boolean, Write the summaries to a file Let’s now instantiate and run an instance of this WebScraper class... Analyst(‘AAPL’, 10, 3, False, False) Running the previous code results in the following output... Analyzing: http://t1.gstatic.com/images?q=tbn:ANd9GcSjoU2lZ2eJX3aCMfiFDt39uRNcDu9W7pTKcyZymE2iKa7IOVaIAnalyzing: https://en.wikipedia.org/wiki/Apple_Inc.Analyzing: https://www.bloomberg.com/news/articles/2020-08-26/apple-plans-augmented-reality-content-to-boost-tv-video-serviceAnalyzing: https://www.marketwatch.com/story/apple-stock-rises-after-wedbush-hikes-target-to-new-street-high-of-600-2020-08-26Analyzing: https://www.marketwatch.com/story/tesla-and-apple-have-had-a-great-run-heres-why-theyre-poised-to-rocket-even-higher-in-the-next-year-2020-08-26Analyzing: https://finance.yahoo.com/quote/AAPL/Analyzing: https://seekingalpha.com/article/4370830-apple-sees-extreme-bullishnessAnalyzing: https://seekingalpha.com/news/3608898-apples-newest-street-high-price-target-700-bull-caseAnalyzing: https://www.marketwatch.com/investing/stock/aaplAnalyzing: https://stocktwits.com/symbol/AAPLencoding error : input conversion failed due to input error, bytes 0x9D 0x09 0x96 0xA3encoding error : input conversion failed due to input error, bytes 0x9D 0x09 0x96 0xA3Value Error***For more information you can review our Terms of Service and Cookie Policy.For inquiries related to this message please contact our support team and provide the reference ID below.***URL ErrorValue Error"China remains a key ingredient in Apple's recipe for success as we estimate roughly 20% of iPhone upgrades will be coming from this region over the coming year."Ives points to recent signs of momentum in China, which he expects will continue for the next six to nine months.Real-time last sale data for U.S. stock quotes reflect trades reported through Nasdaq only.***By comparison, Amazon AMZN, +0.58% has split its stock three times, rallying an average of 209% the following year.Apple�s history isn�t quite as stellar as all those, with its four previous splits resulting in an average gain of 10.4% in the following year.Real-time last sale data for U.S. stock quotes reflect trades reported through Nasdaq only.***The truck and fuel cell maker �could be a major horse in the EV race,� wrote the analyst, while voicing concerns about the stock�s valuation.stocks edged lower Wednesday, a day after the S&P 500 set its first record close since February, after Federal Reserve officials highlighted the uncertainties facing the economy.stock-market benchmarks mostly opened higher on Wednesday, pushing the key benchmarks to further records after an economic report came in better than expected.***Apple is the world's largest information technology company by revenue, the world's largest technology company by total assets, and the world's second-largest mobile phone manufacturer after Samsung.Two million iPhones were sold in the first twenty-four hours of pre-ordering and over five million handsets were sold in the first three days of its launch.The same year, Apple introduced System 7, a major upgrade to the operating system which added color to the interface and introduced new networking capabilities.***Howley also weighs in on Nintendo potentially releasing an upgraded Switch in 2021.***[Finished in 5.443s] We have successfully extracted a few summaries from top search results about AAPL. Some sites have this type of request blocked as seen in the console output. Nevertheless, this has been a comprehensive starter guide to web scraping in Python.
[ { "code": null, "e": 694, "s": 172, "text": "Web scraping is an awesome tool for analysts to sift through and collect large amounts of public data. Using keywords relevant to the topic in question, a good web scraper can gather large amounts of data very quickly and aggregate it into a dataset. There are several libraries in Python that make this extremely easy to accomplish. In this article, I will illustrate an architecture that I have been using for web scraping and summarizing search engine data. The article will be broken up into the following sections..." }, { "code": null, "e": 708, "s": 694, "text": "Link Scraping" }, { "code": null, "e": 725, "s": 708, "text": "Content Scraping" }, { "code": null, "e": 745, "s": 725, "text": "Content Summarizing" }, { "code": null, "e": 765, "s": 745, "text": "Building a Pipeline" }, { "code": null, "e": 806, "s": 765, "text": "All of the code will be provided herein." }, { "code": null, "e": 1139, "s": 806, "text": "First, we need a way to gather URLs relevant to the topic we are scraping data for. Fortunately, the Python library googlesearch makes it easy to gather URLs in response to an initial google search. Let’s build a class that uses this library to search our keywords and append a fixed number of URLs to a list for further analysis..." }, { "code": null, "e": 1627, "s": 1139, "text": "This is arguably the most important part of the web scraper as it determines what data on a webpage will be gathered. Using a combination of urllib and beautiful soup (bs4) we are able to retrieve and parse the HTML for each URL in our Link Scraper class. Beautiful soup lets us specify the tags we want to extract data from. In the case below I am establishing a URL request and parsing the HTML response with bs4 and storing all the information found in the paragraph (<p></p>) tags..." }, { "code": null, "e": 2122, "s": 1627, "text": "This is where we create a summary of the text extracted from each page’s HTML residing in our Content Scraper. To do this we will be using a combination of libraries, mainly NLTK. The way in which we are generating the summary is relatively elementary and there are many ways to improve this method — but it's a great start. After some formatting and voiding of filler words, words get tokenized and ranked by frequency generating a few sentences that aim to accurately summarize the article..." }, { "code": null, "e": 2333, "s": 2122, "text": "This is the part where we put everything together. One class will instantiate an instance of each other component as needed to build and implement our web scraper. The WebScraper class takes a few parameters..." }, { "code": null, "e": 2370, "s": 2333, "text": "search — String, Search engine query" }, { "code": null, "e": 2416, "s": 2370, "text": "n — Integer, Number of URL sources to analyze" }, { "code": null, "e": 2460, "s": 2416, "text": "sl —Integer, Sentence length of the summary" }, { "code": null, "e": 2515, "s": 2460, "text": "fall_through — Boolean, Multithread the process or not" }, { "code": null, "e": 2566, "s": 2515, "text": "Write_file —Boolean, Write the summaries to a file" }, { "code": null, "e": 2636, "s": 2566, "text": "Let’s now instantiate and run an instance of this WebScraper class..." }, { "code": null, "e": 2673, "s": 2636, "text": "Analyst(‘AAPL’, 10, 3, False, False)" }, { "code": null, "e": 2734, "s": 2673, "text": "Running the previous code results in the following output..." }, { "code": null, "e": 5854, "s": 2734, "text": "Analyzing: http://t1.gstatic.com/images?q=tbn:ANd9GcSjoU2lZ2eJX3aCMfiFDt39uRNcDu9W7pTKcyZymE2iKa7IOVaIAnalyzing: https://en.wikipedia.org/wiki/Apple_Inc.Analyzing: https://www.bloomberg.com/news/articles/2020-08-26/apple-plans-augmented-reality-content-to-boost-tv-video-serviceAnalyzing: https://www.marketwatch.com/story/apple-stock-rises-after-wedbush-hikes-target-to-new-street-high-of-600-2020-08-26Analyzing: https://www.marketwatch.com/story/tesla-and-apple-have-had-a-great-run-heres-why-theyre-poised-to-rocket-even-higher-in-the-next-year-2020-08-26Analyzing: https://finance.yahoo.com/quote/AAPL/Analyzing: https://seekingalpha.com/article/4370830-apple-sees-extreme-bullishnessAnalyzing: https://seekingalpha.com/news/3608898-apples-newest-street-high-price-target-700-bull-caseAnalyzing: https://www.marketwatch.com/investing/stock/aaplAnalyzing: https://stocktwits.com/symbol/AAPLencoding error : input conversion failed due to input error, bytes 0x9D 0x09 0x96 0xA3encoding error : input conversion failed due to input error, bytes 0x9D 0x09 0x96 0xA3Value Error***For more information you can review our Terms of Service and Cookie Policy.For inquiries related to this message please contact our support team and provide the reference ID below.***URL ErrorValue Error\"China remains a key ingredient in Apple's recipe for success as we estimate roughly 20% of iPhone upgrades will be coming from this region over the coming year.\"Ives points to recent signs of momentum in China, which he expects will continue for the next six to nine months.Real-time last sale data for U.S. stock quotes reflect trades reported through Nasdaq only.***By comparison, Amazon AMZN, +0.58% has split its stock three times, rallying an average of 209% the following year.Apple�s history isn�t quite as stellar as all those, with its four previous splits resulting in an average gain of 10.4% in the following year.Real-time last sale data for U.S. stock quotes reflect trades reported through Nasdaq only.***The truck and fuel cell maker �could be a major horse in the EV race,� wrote the analyst, while voicing concerns about the stock�s valuation.stocks edged lower Wednesday, a day after the S&P 500 set its first record close since February, after Federal Reserve officials highlighted the uncertainties facing the economy.stock-market benchmarks mostly opened higher on Wednesday, pushing the key benchmarks to further records after an economic report came in better than expected.***Apple is the world's largest information technology company by revenue, the world's largest technology company by total assets, and the world's second-largest mobile phone manufacturer after Samsung.Two million iPhones were sold in the first twenty-four hours of pre-ordering and over five million handsets were sold in the first three days of its launch.The same year, Apple introduced System 7, a major upgrade to the operating system which added color to the interface and introduced new networking capabilities.***Howley also weighs in on Nintendo potentially releasing an upgraded Switch in 2021.***[Finished in 5.443s]" } ]
Getting Started with Plotly-Python - GeeksforGeeks
15 Jul, 2021 The Plotly Python library is an interactive open-source library. This can be a very helpful tool for data visualization and understanding the data simply and easily. plotly graph objects are a high-level interface to plotly which are easy to use. It can plot various types of graphs and charts like scatter plots, line charts, bar charts, box plots, histograms, pie charts, etc. So you all must be wondering why plotly over other visualization tools or libraries? Here’s the answer – Plotly has hover tool capabilities that allow us to detect any outliers or anomalies in a large number of data points. It is visually attractive that can be accepted by a wide range of audiences. It allows us for the endless customization of our graphs that makes our plot more meaningful and understandable for others. Ok, enough theory let’s start. Installation: To install this module type the below command in the terminal. pip install plotly Let’s create various plots using this module Scatter Plot: Scatter plot represent values for two different numeric variables. They are mainly used for the representation of the relationship between two variables. Python3 # import all required librariesimport numpy as npimport plotlyimport plotly.graph_objects as goimport plotly.offline as pyofrom plotly.offline import init_notebook_mode init_notebook_mode(connected=True) # generating 150 random integers# from 1 to 50x = np.random.randint(low=1, high=50, size=150)*0.1 # generating 150 random integers# from 1 to 50y = np.random.randint(low=1, high=50, size=150)*0.1 # plotting scatter plotfig = go.Figure(data=go.Scatter(x=x, y=y, mode='markers')) fig.show() Output: Bar charts: Bar charts are used when we want to compare different groups of data and make inferences of which groups are highest and which groups are common and compare how one group is performing compared to others. Python3 # import all required librariesimport numpy as npimport plotlyimport plotly.graph_objects as goimport plotly.offline as pyofrom plotly.offline import init_notebook_mode init_notebook_mode(connected = True) # countries on x-axiscountries=['India', 'canada', 'Australia','Brazil', 'Mexico','Russia', 'Germany','Switzerland', 'Texas'] # plotting corresponding y for each# country in xfig = go.Figure([go.Bar(x=countries, y=[80,70,60,50, 40,50,60,70,80])]) fig.show() Output: Pie chart: A pie chart represents the distribution of different variables among total. In the pie chart each slice shows its contribution to the total amount. Python3 # import all required librariesimport numpy as npimport plotlyimport plotly.graph_objects as goimport plotly.offline as pyofrom plotly.offline import init_notebook_mode init_notebook_mode(connected = True) # different individual parts in# total chartcountries=['India', 'canada', 'Australia','Brazil', 'Mexico','Russia', 'Germany','Switzerland', 'Texas'] # values corresponding to each# individual country present in# countriesvalues = [4500, 2500, 1053, 500, 3200, 1500, 1253, 600, 3500] # plotting pie chartfig = go.Figure(data=[go.Pie(labels=countries, values=values)]) fig.show() Output: Histogram: A histogram plots the continuous distribution of variable as series of bars and each bar indicates the frequency of the occurring value in a variable. In order to use a histogram, we simply require a variable that takes continuous numeric values Python3 # import all required librariesimport numpy as npimport plotlyimport plotly.graph_objects as goimport plotly.offline as pyofrom plotly.offline import init_notebook_mode init_notebook_mode(connected = True) # save the state of randomnp.random.seed(42) # generating 250 random numbersx = np.random.randn(250) # plotting histogram for xfig = go.Figure(data=[go.Histogram(x=x)]) fig.show() Output: Box plot: A box plot is the representation of a statistical summary. Minimum, First Quartile, Median, Third Quartile, Maximum. Python3 # import all required librariesimport numpy as npimport plotlyimport plotly.graph_objects as goimport plotly.offline as pyofrom plotly.offline import init_notebook_mode init_notebook_mode(connected = True) np.random.seed(42) # generating 50 random numbersy = np.random.randn(50) # generating 50 random numbersy1 = np.random.randn(50)fig = go.Figure() # updating the figure with yfig.add_trace(go.Box(y=y)) # updating the figure with y1fig.add_trace(go.Box(y=y1)) fig.show() Output: nidhi_biet sooda367 python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Defaultdict in Python Python | os.path.join() method Selecting rows in pandas DataFrame based on conditions Python | Get unique values from a list Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24316, "s": 24288, "text": "\n15 Jul, 2021" }, { "code": null, "e": 24696, "s": 24316, "text": "The Plotly Python library is an interactive open-source library. This can be a very helpful tool for data visualization and understanding the data simply and easily. plotly graph objects are a high-level interface to plotly which are easy to use. It can plot various types of graphs and charts like scatter plots, line charts, bar charts, box plots, histograms, pie charts, etc. " }, { "code": null, "e": 24802, "s": 24696, "text": "So you all must be wondering why plotly over other visualization tools or libraries? Here’s the answer – " }, { "code": null, "e": 24921, "s": 24802, "text": "Plotly has hover tool capabilities that allow us to detect any outliers or anomalies in a large number of data points." }, { "code": null, "e": 24998, "s": 24921, "text": "It is visually attractive that can be accepted by a wide range of audiences." }, { "code": null, "e": 25122, "s": 24998, "text": "It allows us for the endless customization of our graphs that makes our plot more meaningful and understandable for others." }, { "code": null, "e": 25153, "s": 25122, "text": "Ok, enough theory let’s start." }, { "code": null, "e": 25167, "s": 25153, "text": "Installation:" }, { "code": null, "e": 25230, "s": 25167, "text": "To install this module type the below command in the terminal." }, { "code": null, "e": 25249, "s": 25230, "text": "pip install plotly" }, { "code": null, "e": 25294, "s": 25249, "text": "Let’s create various plots using this module" }, { "code": null, "e": 25463, "s": 25294, "text": "Scatter Plot: Scatter plot represent values for two different numeric variables. They are mainly used for the representation of the relationship between two variables." }, { "code": null, "e": 25471, "s": 25463, "text": "Python3" }, { "code": "# import all required librariesimport numpy as npimport plotlyimport plotly.graph_objects as goimport plotly.offline as pyofrom plotly.offline import init_notebook_mode init_notebook_mode(connected=True) # generating 150 random integers# from 1 to 50x = np.random.randint(low=1, high=50, size=150)*0.1 # generating 150 random integers# from 1 to 50y = np.random.randint(low=1, high=50, size=150)*0.1 # plotting scatter plotfig = go.Figure(data=go.Scatter(x=x, y=y, mode='markers')) fig.show()", "e": 25964, "s": 25471, "text": null }, { "code": null, "e": 25976, "s": 25964, "text": "Output: " }, { "code": null, "e": 26193, "s": 25976, "text": "Bar charts: Bar charts are used when we want to compare different groups of data and make inferences of which groups are highest and which groups are common and compare how one group is performing compared to others." }, { "code": null, "e": 26201, "s": 26193, "text": "Python3" }, { "code": "# import all required librariesimport numpy as npimport plotlyimport plotly.graph_objects as goimport plotly.offline as pyofrom plotly.offline import init_notebook_mode init_notebook_mode(connected = True) # countries on x-axiscountries=['India', 'canada', 'Australia','Brazil', 'Mexico','Russia', 'Germany','Switzerland', 'Texas'] # plotting corresponding y for each# country in xfig = go.Figure([go.Bar(x=countries, y=[80,70,60,50, 40,50,60,70,80])]) fig.show()", "e": 26754, "s": 26201, "text": null }, { "code": null, "e": 26762, "s": 26754, "text": "Output:" }, { "code": null, "e": 26921, "s": 26762, "text": "Pie chart: A pie chart represents the distribution of different variables among total. In the pie chart each slice shows its contribution to the total amount." }, { "code": null, "e": 26929, "s": 26921, "text": "Python3" }, { "code": "# import all required librariesimport numpy as npimport plotlyimport plotly.graph_objects as goimport plotly.offline as pyofrom plotly.offline import init_notebook_mode init_notebook_mode(connected = True) # different individual parts in# total chartcountries=['India', 'canada', 'Australia','Brazil', 'Mexico','Russia', 'Germany','Switzerland', 'Texas'] # values corresponding to each# individual country present in# countriesvalues = [4500, 2500, 1053, 500, 3200, 1500, 1253, 600, 3500] # plotting pie chartfig = go.Figure(data=[go.Pie(labels=countries, values=values)]) fig.show()", "e": 27583, "s": 26929, "text": null }, { "code": null, "e": 27592, "s": 27583, "text": "Output: " }, { "code": null, "e": 27849, "s": 27592, "text": "Histogram: A histogram plots the continuous distribution of variable as series of bars and each bar indicates the frequency of the occurring value in a variable. In order to use a histogram, we simply require a variable that takes continuous numeric values" }, { "code": null, "e": 27857, "s": 27849, "text": "Python3" }, { "code": "# import all required librariesimport numpy as npimport plotlyimport plotly.graph_objects as goimport plotly.offline as pyofrom plotly.offline import init_notebook_mode init_notebook_mode(connected = True) # save the state of randomnp.random.seed(42) # generating 250 random numbersx = np.random.randn(250) # plotting histogram for xfig = go.Figure(data=[go.Histogram(x=x)]) fig.show()", "e": 28244, "s": 27857, "text": null }, { "code": null, "e": 28253, "s": 28244, "text": "Output: " }, { "code": null, "e": 28380, "s": 28253, "text": "Box plot: A box plot is the representation of a statistical summary. Minimum, First Quartile, Median, Third Quartile, Maximum." }, { "code": null, "e": 28388, "s": 28380, "text": "Python3" }, { "code": "# import all required librariesimport numpy as npimport plotlyimport plotly.graph_objects as goimport plotly.offline as pyofrom plotly.offline import init_notebook_mode init_notebook_mode(connected = True) np.random.seed(42) # generating 50 random numbersy = np.random.randn(50) # generating 50 random numbersy1 = np.random.randn(50)fig = go.Figure() # updating the figure with yfig.add_trace(go.Box(y=y)) # updating the figure with y1fig.add_trace(go.Box(y=y1)) fig.show()", "e": 28863, "s": 28388, "text": null }, { "code": null, "e": 28872, "s": 28863, "text": "Output: " }, { "code": null, "e": 28885, "s": 28874, "text": "nidhi_biet" }, { "code": null, "e": 28894, "s": 28885, "text": "sooda367" }, { "code": null, "e": 28909, "s": 28894, "text": "python-modules" }, { "code": null, "e": 28916, "s": 28909, "text": "Python" }, { "code": null, "e": 29014, "s": 28916, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29046, "s": 29014, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29088, "s": 29046, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29144, "s": 29088, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29186, "s": 29144, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29208, "s": 29186, "text": "Defaultdict in Python" }, { "code": null, "e": 29239, "s": 29208, "text": "Python | os.path.join() method" }, { "code": null, "e": 29294, "s": 29239, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 29333, "s": 29294, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29362, "s": 29333, "text": "Create a directory in Python" } ]
Sentiment classification in Python | by Zolzaya Luvsandorj | Towards Data Science
This post is the last of the three sequential posts on steps to build a sentiment classifier. Having done some exploratory text analysis and preprocessed the text, it’s time to classify reviews to sentiments. In this post, we will first look at 2 ways to get sentiments without building a model then build a custom model. Before we dive in, let’s take a step back and look at the bigger picture really quickly. CRISP-DM methodology outlines the process flow for a successful data science project. In this post, we will do some of the tasks that a data scientist would go through during the modelling stage. This post assumes that the reader (👀 yes, you!) has access to and is familiar with Python including installing packages, defining functions and other basic tasks. If you are new to Python, this is a good place to get started. I have tested the scripts in Python 3.7.1 in Jupyter Notebook. Let’s make sure you have the following libraries installed before we start:◼️ Data manipulation/analysis: numpy, pandas◼️ Data partitioning: sklearn◼️ Text preprocessing/analysis: nltk, textblob◼️ Visualisation: matplotlib, seaborn Once you have nltk installed, please make sure you have downloaded ‘stopwords’ , ‘wordnet’ and ‘vader_lexicon’ from nltk with the script below: import nltknltk.download('stopwords') nltk.download('wordnet')nltk.download('vader_lexicon') If you have already downloaded, running this will notify you so. Now, we are ready to import the packages: # Set random seedseed = 123# Data manipulation/analysisimport numpy as npimport pandas as pd# Text preprocessing/analysisimport refrom nltk.corpus import stopwordsfrom nltk.stem import WordNetLemmatizerfrom nltk.tokenize import RegexpTokenizerfrom nltk.sentiment.vader import SentimentIntensityAnalyzerfrom textblob import TextBlobfrom scipy.sparse import hstack, csr_matrixfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.preprocessing import MinMaxScaler# Modellingfrom sklearn.model_selection import train_test_split, cross_validate, GridSearchCV, RandomizedSearchCVfrom sklearn.linear_model import LogisticRegression, SGDClassifierfrom sklearn.naive_bayes import MultinomialNBfrom sklearn.metrics import classification_report, confusion_matrixfrom sklearn.pipeline import Pipeline# Visualisationimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inlinesns.set(style="whitegrid", context='talk') We will use IMDB movie reviews dataset. You can download the dataset here and save it in your working directory. Once saved, let’s import it to Python: sample = pd.read_csv('IMDB Dataset.csv')print(f"{sample.shape[0]} rows and {sample.shape[1]} columns")sample.head() Let’s look at the split between sentiments: sample['sentiment'].value_counts() Sentiment is evenly split in the sample data. Let’s encode the target into numeric values where positive is 1 and negative is 0: # Encode to numericsample['target'] = np.where(sample['sentiment']=='positive', 1, 0)# Check valuessample.groupby(['sentiment', 'target']).count().unstack() Let’s set aside 5000 cases for testing: # Split data into train & testX_train, X_test, y_train, y_test = train_test_split(sample['review'], sample['sentiment'], test_size=5000, random_state=seed, stratify=sample['sentiment'])# Append sentiment back using indicestrain = pd.concat([X_train, y_train], axis=1)test = pd.concat([X_test, y_test], axis=1)# Check dimensionsprint(f"Train: {train.shape[0]} rows and {train.shape[1]} columns")print(f"{train['sentiment'].value_counts()}\n")print(f"Test: {test.shape[0]} rows and {test.shape[1]} columns")print(test['sentiment'].value_counts()) We will quickly inspect the head of the training dataset: train.head() Alright, let’s dive in! 🐳 In this section, I want to show you two very simple methods to get sentiments without building a custom model. We will extract polarity intensity scores with VADER and TextBlob. ‘VADER (Valence Aware Dictionary and sEntiment Reasoner) is a lexicon and rule-based sentiment analysis tool that is specifically attuned to sentiments expressed in social media.’ Let’s start with a simple example and see how we extract sentiment intensity scores using VADER sentiment analyser: example = 'The movie was awesome.'sid = SentimentIntensityAnalyzer()sid.polarity_scores(example) neg, neu, pos: These three scores sum up to 1. These scores show the proportion of text falling in the category.compound: This score ranges from -1 (the most negative) to 1 (the most positive. Although not all reviews would be as simple as our example at hand, it’s good to see that scores for the example review looks mostly positive. Now, let’s add the intensity scores to the training data: train[['neg', 'neu', 'pos', 'compound']] = train['review'].apply(sid.polarity_scores).apply(pd.Series)train.head() All it takes to get sentiment scores is a single line of code once we initialise the analyser object. Shall we inspect the scores further? Let’s start with peaking at 5 records with the highest pos scores: train.nlargest(5, ['pos']) It’s great to see that all of them are indeed positive reviews. Let’s do the same for neg: train.nlargest(5, ['neg']) This looks good too. But we could be looking at the extreme ends of the data where the sentiment is more obvious. Let’s visualise the scores with histograms to understand better: for var in ['pos', 'neg', 'neu', 'compound']: plt.figure(figsize=(12,4)) sns.distplot(train.query("target==1")[var], bins=30, kde=False, color='green', label='Positive') sns.distplot(train.query("target==0")[var], bins=30, kde=False, color='red', label='Negative') plt.legend() plt.title(f'Histogram of {var} by true sentiment'); From the histograms, it appears that pos, neg and potentially compound columns are useful in classifying positive and negative sentiments. We can quickly classify each review into either positive or negative classes using these scores. Let’s see how well it will do: train['vader_polarity'] = np.where(train['pos']>train['neg'], 1, 0)target_names=['negative', 'positive']print(classification_report(train['target'], train['vader_polarity'], target_names=target_names)) With very little effort, we can get about 69% accuracy using VADER. The performance on positive and negative reviews look different though. We have higher recall and lower precision of positive reviews — meaning that we have more false positives (See what I did there? Do you see why I encoded positive reviews as 1? 🙊). Let’s see confusion matrix: # Create function so that we could reuse laterdef plot_cm(y_test, y_pred, target_names=['negative', 'positive'], figsize=(5,3)): """Create a labelled confusion matrix plot.""" cm = confusion_matrix(y_test, y_pred) fig, ax = plt.subplots(figsize=figsize) sns.heatmap(cm, annot=True, fmt='g', cmap='BuGn', cbar=False, ax=ax) ax.set_title('Confusion matrix') ax.set_xlabel('Predicted') ax.set_xticklabels(target_names) ax.set_ylabel('Actual') ax.set_yticklabels(target_names, fontdict={'verticalalignment': 'center'});# Plot confusion matrixplot_cm(train['target'], train['vader_polarity']) As we can see, we have many true positives and false positives. In fact, about 67% of our predictions are positive. Let’s see whether performance improves if we use the compound score. train['vader_compound'] = np.where(train['compound']>0, 1, 0)print(classification_report(train['target'], train['vader_compound'], target_names=target_names)) plot_cm(train['target'], train['vader_compound']) Performance looks pretty similar. I used training dataset to assess because we are not training a model here. However, if you do the same on the test data, the results should be very similar. 🔗 More information on VADER and VADER in nltk. Another way to get sentiment score is to leverage TextBlob library. Using sentiment property from the TextBlob object, we can also extract similar scores. Here’s how we can extract using our previous example: TextBlob(example).sentiment polarity: ranges from -1 (the most negative) to 1 (the most positive)subjectivity: ranges from 0 (very objective) to 1 (very subjective) Our example was analysed to be a very subjective positive statement. It’s true, isn’t it? Of these two scores, polarity is more relevant for us. Let’s add the intensity scores to the training data and inspect 5 records with the highest polarity scores: train[['polarity', 'subjectivity']] = train['review'].apply(lambda x:TextBlob(x).sentiment).to_list()columns = ['review', 'target', 'polarity', 'subjectivity']train[columns].nlargest(5, ['polarity']) As you saw, adding sentiment intensity score with TextBlob is also quite simple. Let’s look at 5 records with the lowest polarity scores: train[columns].nsmallest(5, ['polarity']) Time to plot some histograms to understand the scores better: for var in ['polarity', 'subjectivity']: plt.figure(figsize=(12,4)) sns.distplot(train.query("target==1")[var], bins=30, kde=False, color='green', label='Positive') sns.distplot(train.query("target==0")[var], bins=30, kde=False, color='red', label='Negative') plt.legend() plt.title(f'Histogram of {var} by true sentiment'); As expected, polarity score looks possibly useful in classifying positive and negative sentiments. Let’s classify using the polarity score and see performance: train['blob_polarity'] = np.where(train['polarity']>0, 1, 0)print(classification_report(train['target'], train['blob_polarity'], target_names=target_names)) With very little effort, we can get about 69% accuracy using TextBlob. Again, we have many false positives, in fact, even more than before. Let’s look at confusion matrix: plot_cm(train['target'], train['blob_polarity']) This time, the number of false positives are higher than the number of true negatives. Predictions are skewed to positive sentiment as 76% of predictions are positive. 🔗 More information on TextBlob. Let’s compare how similar the scores from VADER and TextBlob are: pd.crosstab(train['vader_polarity'], train['blob_polarity']) There is about 79% overlap in their classifications with majority in positive sentiments. Let’s visualise the polarity scores: plt.figure(figsize=(12,12))sns.scatterplot(data=train, x='polarity', y='compound', hue='target', palette=['red', 'green'], alpha=.3)plt.axhline(0, linestyle='--', color='k')plt.axvline(0, linestyle='--', color='k')plt.title('Scatterplot between polarity intensity scores'); This plot shows a little bit more information than the previous table. In the bottom left quadrant, we see mainly red circles since negative classifications in both methods were more precise. In the top right quadrant, there is a higher volume of circles that are mostly green but the color mix is not as pure as before. The remaining two quadrants show where the two scores disagree with each other. Overall, the colour is more mixed than the left half in the right half of the plot. We get very similar overall accuracy of 69% from both; however, when we look at the predictions closely, the performance differs between the approaches. Now you know how to get sentiment polarity scores with VADER or TextBlob. If you have unlabeled data, these two provide a great starting point to label your data automatically. It’s time to build a model! ✨ In this section, we will: choose a suitable preprocessing approach and algorithmexplore whether adding VADER and TextBlob sentiment scores as features improves the predictive power of the modelbuild a pipeline and tune its hyperparameterstest the final pipeline on unseen data choose a suitable preprocessing approach and algorithm explore whether adding VADER and TextBlob sentiment scores as features improves the predictive power of the model build a pipeline and tune its hyperparameters test the final pipeline on unseen data The sentiment classification is one application of supervised classification model .Therefore, the approach we are taking here can be generalised to any supervised classification tasks. In my previous post, we have explored three different ways to preprocess text and shortlisted two of them: simpler approach and simple approach. Of these two, we will now test if there is any difference in model performance between the two options and choose one of them to use moving forward. To make things easier, we will create two functions (the idea of these functions is inspired from here): # Define functionsdef create_baseline_models(): """Create list of baseline models.""" models = [] models.append(('log', LogisticRegression(random_state=seed, max_iter=1000))) models.append(('sgd', SGDClassifier(random_state=seed))) models.append(('mnb', MultinomialNB())) return modelsdef assess(X, y, models, cv=5, scoring=['roc_auc', 'accuracy', 'f1']): """Provide summary of cross validation results for models.""" results = pd.DataFrame() for name, model in models: result = pd.DataFrame(cross_validate(model, X, y, cv=cv, scoring=scoring)) mean = result.mean().rename('{}_mean'.format) std = result.std().rename('{}_std'.format) results[name] = pd.concat([mean, std], axis=0) return results.sort_index() I have picked three algorithms to try: Logistic Regression Classifier, Stochastic Gradient Descent Classifier and Multinomial Naive Bayes Classifier. Let’s initiate the models: models = create_baseline_models()models Now, let’s inspect model performance when using simpler approach: # Preprocess the datavectoriser = TfidfVectorizer(token_pattern=r'[a-z]+', stop_words='english', min_df=30, max_df=.7)X_train_simpler = vectoriser.fit_transform(X_train)# Assess the modelassess(X_train_simpler, y_train, models) Great to see we get much better performance: 86–89% accuracy with baseline models compared to using only the sentiment scores. Since the classes are pretty balanced, we will mainly focus on accuracy. But we will ensure to inspect the predictions closer later to evaluate the model. Performance metrics look pretty close between Logistic Regression and Stochastic Gradient Descent with the latter being faster in training (see fit_time). Naive Bayes is the fastest of the three in training but performs slightly worse than the other two. Now let’s assess simple approach: # Define functiondef preprocess_text(text): # 1. Tokenise to alphabetic tokens tokeniser = RegexpTokenizer(r'[A-Za-z]+') tokens = tokeniser.tokenize(text) # 2. Lowercase and lemmatise lemmatiser = WordNetLemmatizer() tokens = [lemmatiser.lemmatize(t.lower(), pos='v') for t in tokens] return tokens# Preprocess the datavectoriser = TfidfVectorizer(analyzer=preprocess_text, min_df=30, max_df=.7)X_train_simple = vectoriser.fit_transform(X_train)# Assess modelsassess(X_train_simple, y_train, models) The performance looks similar to before. Therefore, we will favour the simpler approach and use it moving forward. Of the three algorithms, we will choose Stochastic Gradient Descent because it balances both speed and predictive power the most. In this section, we will explore whether adding VADER and TextBlob sentiment scores as features improves the predictive power of the model. Let’s quickly check if there are any highly correlated features: plt.figure(figsize = (14,5))columns = ['target', 'neg', 'neu', 'pos', 'compound', 'polarity', 'subjectivity']sns.heatmap(train[columns].corr(), annot=True, cmap='seismic_r'); The most correlated features are compound and neg. Let’s run a quick model to see which scores are more useful to use: # Initialise a modelsgd = SGDClassifier(random_state=seed)# Initialise a scalerscaler = MinMaxScaler()# Assess the model using scoresscores = train[['neg', 'neu', 'pos', 'compound', 'polarity', 'subjectivity']]assess(scaler.fit_transform(scores), y_train, [('sgd', sgd)]) We get about 77% accuracy using the scores. Now let’s inspect coefficients: # Fit to training datasgd.fit(scores, y_train)# Get coefficientscoefs = pd.DataFrame(data=sgd.coef_, columns=scores.columns).Tcoefs.rename(columns={0: 'coef'}, inplace=True)# Plotplt.figure(figsize=(10,5))sns.barplot(x=coefs.index, y='coef', data=coefs)plt.title('Coefficients'); Seems like we could only use neg, pos and polarity because they are the most dominant features among the scores. Let’s see if model results can be improved by adding these selected scores to the previously preprocessed data. # Add features to sparse matrixselected_scores = train[['neg', 'pos', 'polarity']]X_train_extended = hstack([X_train_simpler, csr_matrix(scaler.fit_transform(selected_scores))])# Assessassess(X_train_extended, y_train, [('sgd', sgd)]) Since adding these scores didn’t improve the model, it is unnecessary to add them as features. That will keep our pipeline simple too! It’s time to build a small pipeline that puts together the preprocessor and the model. We will fine tune its hyperparameters to see if we can improve the model. Firstly, let’s try to understand the impact of three hyperparameters: min_df, max_df for the vectoriser and loss for the model with random search: # Create a pipelinepipe = Pipeline([('vectoriser', TfidfVectorizer(token_pattern=r'[a-z]+')), ('model', SGDClassifier(random_state=seed))])# Prepare a random searchparam_distributions = {'vectoriser__min_df': np.arange(10, 1000, 10), 'vectoriser__max_df': np.linspace(.2, 1, 40), 'model__loss': ['log', 'hinge']}r_search = RandomizedSearchCV(estimator=pipe, param_distributions=param_distributions, n_iter=30, cv=5, n_jobs=-1, random_state=seed)r_search.fit(X_train, y_train)# Save results to a dataframer_search_results = pd.DataFrame(r_search.cv_results_).sort_values(by='rank_test_score') Here, we are trying 30 different random combinations of hyperparameter space specified. This will take a while to run. The output of the random search will be saved in a dataframe called r_search_results. Let’s create another dataframe containing a few columns that are more interesting to us: columns = [col for col in r_search_results.columns if re.search(r"split|param_", col)]r_summary = r_search_results[columns].copy()r_summary.columns = [re.sub(r'_test_score|param_', '', col) for col in r_summary.columns]columns = [col.split('__')[1] if '__' in col else col for col in r_summary.columns ]r_summary.columns = columnsr_summary.head() Let’s visualise the output to understand the impact of hyperparameters better: # Create a long dataframer_summary_long = pd.melt(r_summary, id_vars=['min_df', 'max_df', 'loss'], value_vars=['split0', 'split1', 'split2', 'split3', 'split4'])# Plot hyperparameter 'loss'plt.figure(figsize=(8,4))plt.title('Performance by loss')sns.boxplot(x='value', y='loss', data=r_summary_long, orient='h')plt.xlim(.8, .9); It looks loss='hinge' results in slightly better performance. Let’s look at the numerical hyperparameters: for param in ['min_df', 'max_df']: plt.figure(figsize=(8,4)) sns.scatterplot(x=param, y="value", data=r_summary_long, x_jitter=True, alpha=0.5) plt.ylim(.8, .9); As there seems to be a negative relationship between min_df and accuracy, we will keep min_df under 200. There isn’t a clear trend in max_df probably because the performance was more impacted by min_df and loss. Although this is true for all three of them, it’s more obvious for max_df. Now we have some idea on how these hyperparameters impact the model, let’s define the pipeline more precisely (max_df=.6 and loss=’hinge') and try to further tune it with grid search: # Create a pipelinepipe = Pipeline([('vectoriser', TfidfVectorizer(token_pattern=r'[a-z]+', max_df=.6)), ('model', SGDClassifier(random_state=seed, loss='hinge'))])# Prepare a grid searchparam_grid = {'vectoriser__min_df': [30, 90, 150], 'vectoriser__ngram_range': [(1,1), (1,2)], 'vectoriser__stop_words': [None, 'english'], 'model__fit_intercept': [True, False]}g_search = GridSearchCV(estimator=pipe, param_grid=param_grid, cv=5, n_jobs=-1)g_search.fit(X_train, y_train)# Save results to a dataframeg_search_results = pd.DataFrame(g_search.cv_results_).sort_values(by='rank_test_score') Grid searching will also take a bit of time because we have 24 different combinations of hyperparameters to try. Like before, the output will be saved to a dataframe called g_search_results. Let’s extract more relevant columns to another dataframe: columns = [col for col in g_search_results.columns if re.search(r"split|param_", col)]g_summary = g_search_results[columns+['mean_test_score']].copy()g_summary.columns = [re.sub(r'_test_score|param_', '', col) for col in g_summary.columns]columns = [col.split('__')[1] if '__' in col else col for col in g_summary.columns ]g_summary.columns = columnsg_summary.head() With any of these combinations, we reach a cross validated accuracy of ~0.9. It’s nice to see a marginal increase. # Create a long dataframeg_summary_long = pd.melt(g_summary, id_vars=['min_df', 'ngram_range', 'stop_words', 'fit_intercept'], value_vars=['split0', 'split1', 'split2', 'split3', 'split4'])g_summary_long.replace({None: 'None'}, inplace=True)# Plot performancefor param in ['ngram_range', 'stop_words', 'fit_intercept']: plt.figure(figsize=(8,4)) plt.title(f'Performance by {param}') sns.boxplot(x='value', y=param, data=g_summary_long, orient='h') plt.xlim(.85, .95); We can see that by changing to ngram_range=(1,2), model performs better. The same is true for stop_words=None. On the other hand, whether we fit intercept or not doesn’t have much impact, which means we can leave this hyperparameter to its default. I think this is good enough, we can now define the final pipeline. Using the top combination from grid search, this is how our final pipeline looks like: pipe = Pipeline([('vectoriser', TfidfVectorizer(token_pattern=r'[a-z]+', min_df=30, max_df=.6, ngram_range=(1,2))), ('model', SGDClassifier(random_state=seed, loss='hinge'))])pipe.fit(X_train, y_train) Our pipeline is very small and simple. Let’s see its coefficients: coefs = pd.DataFrame(pipe['model'].coef_, columns=pipe['vectoriser'].get_feature_names())coefs = coefs.T.rename(columns={0:'coef'}).sort_values('coef')coefs Features with the highest or lowest coefficients look intuitive. But look at the number of features we have: 49,577! This is mainly due to having relaxed min_df, adding bigrams and not removing stop words. If we were keen to reduce the number of features, we could change these hyperparamaters in the pipeline. If we start cutting down features, we will notice a tradeoff between number of features and the model accuracy. What an optimal balance looks like depends on the context. Let’s evaluate the pipeline: train_pred = pipe.predict(X_train)print(classification_report(train_pred, y_train, target_names=target_names)) test_pred = pipe.predict(X_test)print(classification_report(test_pred, y_test, target_names=target_names)) Accuracy on train and test set is about 0.94 and 0.92 respectively. Precision and recall by both sentiments look pretty similar. We have slightly more false negatives. Let’s plot confusion matrix: plot_cm(test_pred, y_test, target_names=target_names) Looks good. Yay 🎊, now we have a pipeline that classifies about 9 in 10 reviews into the correct sentiment. Let’s see how long it takes to make a single prediction. We will use Jupyter Notebook’s magic command %timeit: for i in range(10): lead = X_test.sample(1) %timeit pipe.predict(lead) Although %timeit runs multiple loops and gives us mean and standard deviation of run time, I notice that I get slightly different output every time. Hence, we are looking at 10 loops of %timeit to observe the range. A single prediction takes about 1.5 to 4 milliseconds. This needs to be evaluated in the context of production environment for the use case. Alright, that was it for this post. 💫 Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me. Thank you for reading my post. Hopefully, you have learned a few different practical ways to classify text into sentiments with or without building a custom model. Here are links to the other two posts of the series:◼️ Exploratory text analysis in Python◼️ Preprocessing text in Python Here are links to the my other NLP-related posts:◼️ Simple wordcloud in Python(Below lists a series of posts on Introduction to NLP)◼️ Part 1: Preprocessing text in Python◼️ Part 2: Difference between lemmatisation and stemming◼️ Part 3: TF-IDF explained◼️ Part 4: Supervised text classification model in Python◼️ Part 5A: Unsupervised topic model in Python (sklearn)◼️ Part 5B: Unsupervised topic model in Python (gensim) Bye for now 🏃💨
[ { "code": null, "e": 494, "s": 172, "text": "This post is the last of the three sequential posts on steps to build a sentiment classifier. Having done some exploratory text analysis and preprocessed the text, it’s time to classify reviews to sentiments. In this post, we will first look at 2 ways to get sentiments without building a model then build a custom model." }, { "code": null, "e": 779, "s": 494, "text": "Before we dive in, let’s take a step back and look at the bigger picture really quickly. CRISP-DM methodology outlines the process flow for a successful data science project. In this post, we will do some of the tasks that a data scientist would go through during the modelling stage." }, { "code": null, "e": 1005, "s": 779, "text": "This post assumes that the reader (👀 yes, you!) has access to and is familiar with Python including installing packages, defining functions and other basic tasks. If you are new to Python, this is a good place to get started." }, { "code": null, "e": 1068, "s": 1005, "text": "I have tested the scripts in Python 3.7.1 in Jupyter Notebook." }, { "code": null, "e": 1300, "s": 1068, "text": "Let’s make sure you have the following libraries installed before we start:◼️ Data manipulation/analysis: numpy, pandas◼️ Data partitioning: sklearn◼️ Text preprocessing/analysis: nltk, textblob◼️ Visualisation: matplotlib, seaborn" }, { "code": null, "e": 1444, "s": 1300, "text": "Once you have nltk installed, please make sure you have downloaded ‘stopwords’ , ‘wordnet’ and ‘vader_lexicon’ from nltk with the script below:" }, { "code": null, "e": 1537, "s": 1444, "text": "import nltknltk.download('stopwords') nltk.download('wordnet')nltk.download('vader_lexicon')" }, { "code": null, "e": 1602, "s": 1537, "text": "If you have already downloaded, running this will notify you so." }, { "code": null, "e": 1644, "s": 1602, "text": "Now, we are ready to import the packages:" }, { "code": null, "e": 2579, "s": 1644, "text": "# Set random seedseed = 123# Data manipulation/analysisimport numpy as npimport pandas as pd# Text preprocessing/analysisimport refrom nltk.corpus import stopwordsfrom nltk.stem import WordNetLemmatizerfrom nltk.tokenize import RegexpTokenizerfrom nltk.sentiment.vader import SentimentIntensityAnalyzerfrom textblob import TextBlobfrom scipy.sparse import hstack, csr_matrixfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.preprocessing import MinMaxScaler# Modellingfrom sklearn.model_selection import train_test_split, cross_validate, GridSearchCV, RandomizedSearchCVfrom sklearn.linear_model import LogisticRegression, SGDClassifierfrom sklearn.naive_bayes import MultinomialNBfrom sklearn.metrics import classification_report, confusion_matrixfrom sklearn.pipeline import Pipeline# Visualisationimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inlinesns.set(style=\"whitegrid\", context='talk')" }, { "code": null, "e": 2731, "s": 2579, "text": "We will use IMDB movie reviews dataset. You can download the dataset here and save it in your working directory. Once saved, let’s import it to Python:" }, { "code": null, "e": 2847, "s": 2731, "text": "sample = pd.read_csv('IMDB Dataset.csv')print(f\"{sample.shape[0]} rows and {sample.shape[1]} columns\")sample.head()" }, { "code": null, "e": 2891, "s": 2847, "text": "Let’s look at the split between sentiments:" }, { "code": null, "e": 2926, "s": 2891, "text": "sample['sentiment'].value_counts()" }, { "code": null, "e": 3055, "s": 2926, "text": "Sentiment is evenly split in the sample data. Let’s encode the target into numeric values where positive is 1 and negative is 0:" }, { "code": null, "e": 3212, "s": 3055, "text": "# Encode to numericsample['target'] = np.where(sample['sentiment']=='positive', 1, 0)# Check valuessample.groupby(['sentiment', 'target']).count().unstack()" }, { "code": null, "e": 3252, "s": 3212, "text": "Let’s set aside 5000 cases for testing:" }, { "code": null, "e": 3849, "s": 3252, "text": "# Split data into train & testX_train, X_test, y_train, y_test = train_test_split(sample['review'], sample['sentiment'], test_size=5000, random_state=seed, stratify=sample['sentiment'])# Append sentiment back using indicestrain = pd.concat([X_train, y_train], axis=1)test = pd.concat([X_test, y_test], axis=1)# Check dimensionsprint(f\"Train: {train.shape[0]} rows and {train.shape[1]} columns\")print(f\"{train['sentiment'].value_counts()}\\n\")print(f\"Test: {test.shape[0]} rows and {test.shape[1]} columns\")print(test['sentiment'].value_counts())" }, { "code": null, "e": 3907, "s": 3849, "text": "We will quickly inspect the head of the training dataset:" }, { "code": null, "e": 3920, "s": 3907, "text": "train.head()" }, { "code": null, "e": 3946, "s": 3920, "text": "Alright, let’s dive in! 🐳" }, { "code": null, "e": 4124, "s": 3946, "text": "In this section, I want to show you two very simple methods to get sentiments without building a custom model. We will extract polarity intensity scores with VADER and TextBlob." }, { "code": null, "e": 4304, "s": 4124, "text": "‘VADER (Valence Aware Dictionary and sEntiment Reasoner) is a lexicon and rule-based sentiment analysis tool that is specifically attuned to sentiments expressed in social media.’" }, { "code": null, "e": 4420, "s": 4304, "text": "Let’s start with a simple example and see how we extract sentiment intensity scores using VADER sentiment analyser:" }, { "code": null, "e": 4517, "s": 4420, "text": "example = 'The movie was awesome.'sid = SentimentIntensityAnalyzer()sid.polarity_scores(example)" }, { "code": null, "e": 4710, "s": 4517, "text": "neg, neu, pos: These three scores sum up to 1. These scores show the proportion of text falling in the category.compound: This score ranges from -1 (the most negative) to 1 (the most positive." }, { "code": null, "e": 4911, "s": 4710, "text": "Although not all reviews would be as simple as our example at hand, it’s good to see that scores for the example review looks mostly positive. Now, let’s add the intensity scores to the training data:" }, { "code": null, "e": 5026, "s": 4911, "text": "train[['neg', 'neu', 'pos', 'compound']] = train['review'].apply(sid.polarity_scores).apply(pd.Series)train.head()" }, { "code": null, "e": 5232, "s": 5026, "text": "All it takes to get sentiment scores is a single line of code once we initialise the analyser object. Shall we inspect the scores further? Let’s start with peaking at 5 records with the highest pos scores:" }, { "code": null, "e": 5259, "s": 5232, "text": "train.nlargest(5, ['pos'])" }, { "code": null, "e": 5350, "s": 5259, "text": "It’s great to see that all of them are indeed positive reviews. Let’s do the same for neg:" }, { "code": null, "e": 5377, "s": 5350, "text": "train.nlargest(5, ['neg'])" }, { "code": null, "e": 5556, "s": 5377, "text": "This looks good too. But we could be looking at the extreme ends of the data where the sentiment is more obvious. Let’s visualise the scores with histograms to understand better:" }, { "code": null, "e": 5935, "s": 5556, "text": "for var in ['pos', 'neg', 'neu', 'compound']: plt.figure(figsize=(12,4)) sns.distplot(train.query(\"target==1\")[var], bins=30, kde=False, color='green', label='Positive') sns.distplot(train.query(\"target==0\")[var], bins=30, kde=False, color='red', label='Negative') plt.legend() plt.title(f'Histogram of {var} by true sentiment');" }, { "code": null, "e": 6202, "s": 5935, "text": "From the histograms, it appears that pos, neg and potentially compound columns are useful in classifying positive and negative sentiments. We can quickly classify each review into either positive or negative classes using these scores. Let’s see how well it will do:" }, { "code": null, "e": 6460, "s": 6202, "text": "train['vader_polarity'] = np.where(train['pos']>train['neg'], 1, 0)target_names=['negative', 'positive']print(classification_report(train['target'], train['vader_polarity'], target_names=target_names))" }, { "code": null, "e": 6809, "s": 6460, "text": "With very little effort, we can get about 69% accuracy using VADER. The performance on positive and negative reviews look different though. We have higher recall and lower precision of positive reviews — meaning that we have more false positives (See what I did there? Do you see why I encoded positive reviews as 1? 🙊). Let’s see confusion matrix:" }, { "code": null, "e": 7475, "s": 6809, "text": "# Create function so that we could reuse laterdef plot_cm(y_test, y_pred, target_names=['negative', 'positive'], figsize=(5,3)): \"\"\"Create a labelled confusion matrix plot.\"\"\" cm = confusion_matrix(y_test, y_pred) fig, ax = plt.subplots(figsize=figsize) sns.heatmap(cm, annot=True, fmt='g', cmap='BuGn', cbar=False, ax=ax) ax.set_title('Confusion matrix') ax.set_xlabel('Predicted') ax.set_xticklabels(target_names) ax.set_ylabel('Actual') ax.set_yticklabels(target_names, fontdict={'verticalalignment': 'center'});# Plot confusion matrixplot_cm(train['target'], train['vader_polarity'])" }, { "code": null, "e": 7660, "s": 7475, "text": "As we can see, we have many true positives and false positives. In fact, about 67% of our predictions are positive. Let’s see whether performance improves if we use the compound score." }, { "code": null, "e": 7875, "s": 7660, "text": "train['vader_compound'] = np.where(train['compound']>0, 1, 0)print(classification_report(train['target'], train['vader_compound'], target_names=target_names))" }, { "code": null, "e": 7925, "s": 7875, "text": "plot_cm(train['target'], train['vader_compound'])" }, { "code": null, "e": 8117, "s": 7925, "text": "Performance looks pretty similar. I used training dataset to assess because we are not training a model here. However, if you do the same on the test data, the results should be very similar." }, { "code": null, "e": 8164, "s": 8117, "text": "🔗 More information on VADER and VADER in nltk." }, { "code": null, "e": 8373, "s": 8164, "text": "Another way to get sentiment score is to leverage TextBlob library. Using sentiment property from the TextBlob object, we can also extract similar scores. Here’s how we can extract using our previous example:" }, { "code": null, "e": 8401, "s": 8373, "text": "TextBlob(example).sentiment" }, { "code": null, "e": 8538, "s": 8401, "text": "polarity: ranges from -1 (the most negative) to 1 (the most positive)subjectivity: ranges from 0 (very objective) to 1 (very subjective)" }, { "code": null, "e": 8791, "s": 8538, "text": "Our example was analysed to be a very subjective positive statement. It’s true, isn’t it? Of these two scores, polarity is more relevant for us. Let’s add the intensity scores to the training data and inspect 5 records with the highest polarity scores:" }, { "code": null, "e": 8991, "s": 8791, "text": "train[['polarity', 'subjectivity']] = train['review'].apply(lambda x:TextBlob(x).sentiment).to_list()columns = ['review', 'target', 'polarity', 'subjectivity']train[columns].nlargest(5, ['polarity'])" }, { "code": null, "e": 9129, "s": 8991, "text": "As you saw, adding sentiment intensity score with TextBlob is also quite simple. Let’s look at 5 records with the lowest polarity scores:" }, { "code": null, "e": 9171, "s": 9129, "text": "train[columns].nsmallest(5, ['polarity'])" }, { "code": null, "e": 9233, "s": 9171, "text": "Time to plot some histograms to understand the scores better:" }, { "code": null, "e": 9607, "s": 9233, "text": "for var in ['polarity', 'subjectivity']: plt.figure(figsize=(12,4)) sns.distplot(train.query(\"target==1\")[var], bins=30, kde=False, color='green', label='Positive') sns.distplot(train.query(\"target==0\")[var], bins=30, kde=False, color='red', label='Negative') plt.legend() plt.title(f'Histogram of {var} by true sentiment');" }, { "code": null, "e": 9767, "s": 9607, "text": "As expected, polarity score looks possibly useful in classifying positive and negative sentiments. Let’s classify using the polarity score and see performance:" }, { "code": null, "e": 9980, "s": 9767, "text": "train['blob_polarity'] = np.where(train['polarity']>0, 1, 0)print(classification_report(train['target'], train['blob_polarity'], target_names=target_names))" }, { "code": null, "e": 10152, "s": 9980, "text": "With very little effort, we can get about 69% accuracy using TextBlob. Again, we have many false positives, in fact, even more than before. Let’s look at confusion matrix:" }, { "code": null, "e": 10201, "s": 10152, "text": "plot_cm(train['target'], train['blob_polarity'])" }, { "code": null, "e": 10369, "s": 10201, "text": "This time, the number of false positives are higher than the number of true negatives. Predictions are skewed to positive sentiment as 76% of predictions are positive." }, { "code": null, "e": 10401, "s": 10369, "text": "🔗 More information on TextBlob." }, { "code": null, "e": 10467, "s": 10401, "text": "Let’s compare how similar the scores from VADER and TextBlob are:" }, { "code": null, "e": 10528, "s": 10467, "text": "pd.crosstab(train['vader_polarity'], train['blob_polarity'])" }, { "code": null, "e": 10655, "s": 10528, "text": "There is about 79% overlap in their classifications with majority in positive sentiments. Let’s visualise the polarity scores:" }, { "code": null, "e": 10960, "s": 10655, "text": "plt.figure(figsize=(12,12))sns.scatterplot(data=train, x='polarity', y='compound', hue='target', palette=['red', 'green'], alpha=.3)plt.axhline(0, linestyle='--', color='k')plt.axvline(0, linestyle='--', color='k')plt.title('Scatterplot between polarity intensity scores');" }, { "code": null, "e": 11445, "s": 10960, "text": "This plot shows a little bit more information than the previous table. In the bottom left quadrant, we see mainly red circles since negative classifications in both methods were more precise. In the top right quadrant, there is a higher volume of circles that are mostly green but the color mix is not as pure as before. The remaining two quadrants show where the two scores disagree with each other. Overall, the colour is more mixed than the left half in the right half of the plot." }, { "code": null, "e": 11598, "s": 11445, "text": "We get very similar overall accuracy of 69% from both; however, when we look at the predictions closely, the performance differs between the approaches." }, { "code": null, "e": 11805, "s": 11598, "text": "Now you know how to get sentiment polarity scores with VADER or TextBlob. If you have unlabeled data, these two provide a great starting point to label your data automatically. It’s time to build a model! ✨" }, { "code": null, "e": 11831, "s": 11805, "text": "In this section, we will:" }, { "code": null, "e": 12082, "s": 11831, "text": "choose a suitable preprocessing approach and algorithmexplore whether adding VADER and TextBlob sentiment scores as features improves the predictive power of the modelbuild a pipeline and tune its hyperparameterstest the final pipeline on unseen data" }, { "code": null, "e": 12137, "s": 12082, "text": "choose a suitable preprocessing approach and algorithm" }, { "code": null, "e": 12251, "s": 12137, "text": "explore whether adding VADER and TextBlob sentiment scores as features improves the predictive power of the model" }, { "code": null, "e": 12297, "s": 12251, "text": "build a pipeline and tune its hyperparameters" }, { "code": null, "e": 12336, "s": 12297, "text": "test the final pipeline on unseen data" }, { "code": null, "e": 12522, "s": 12336, "text": "The sentiment classification is one application of supervised classification model .Therefore, the approach we are taking here can be generalised to any supervised classification tasks." }, { "code": null, "e": 12921, "s": 12522, "text": "In my previous post, we have explored three different ways to preprocess text and shortlisted two of them: simpler approach and simple approach. Of these two, we will now test if there is any difference in model performance between the two options and choose one of them to use moving forward. To make things easier, we will create two functions (the idea of these functions is inspired from here):" }, { "code": null, "e": 13858, "s": 12921, "text": "# Define functionsdef create_baseline_models(): \"\"\"Create list of baseline models.\"\"\" models = [] models.append(('log', LogisticRegression(random_state=seed, max_iter=1000))) models.append(('sgd', SGDClassifier(random_state=seed))) models.append(('mnb', MultinomialNB())) return modelsdef assess(X, y, models, cv=5, scoring=['roc_auc', 'accuracy', 'f1']): \"\"\"Provide summary of cross validation results for models.\"\"\" results = pd.DataFrame() for name, model in models: result = pd.DataFrame(cross_validate(model, X, y, cv=cv, scoring=scoring)) mean = result.mean().rename('{}_mean'.format) std = result.std().rename('{}_std'.format) results[name] = pd.concat([mean, std], axis=0) return results.sort_index()" }, { "code": null, "e": 14035, "s": 13858, "text": "I have picked three algorithms to try: Logistic Regression Classifier, Stochastic Gradient Descent Classifier and Multinomial Naive Bayes Classifier. Let’s initiate the models:" }, { "code": null, "e": 14075, "s": 14035, "text": "models = create_baseline_models()models" }, { "code": null, "e": 14141, "s": 14075, "text": "Now, let’s inspect model performance when using simpler approach:" }, { "code": null, "e": 14456, "s": 14141, "text": "# Preprocess the datavectoriser = TfidfVectorizer(token_pattern=r'[a-z]+', stop_words='english', min_df=30, max_df=.7)X_train_simpler = vectoriser.fit_transform(X_train)# Assess the modelassess(X_train_simpler, y_train, models)" }, { "code": null, "e": 15027, "s": 14456, "text": "Great to see we get much better performance: 86–89% accuracy with baseline models compared to using only the sentiment scores. Since the classes are pretty balanced, we will mainly focus on accuracy. But we will ensure to inspect the predictions closer later to evaluate the model. Performance metrics look pretty close between Logistic Regression and Stochastic Gradient Descent with the latter being faster in training (see fit_time). Naive Bayes is the fastest of the three in training but performs slightly worse than the other two. Now let’s assess simple approach:" }, { "code": null, "e": 15625, "s": 15027, "text": "# Define functiondef preprocess_text(text): # 1. Tokenise to alphabetic tokens tokeniser = RegexpTokenizer(r'[A-Za-z]+') tokens = tokeniser.tokenize(text) # 2. Lowercase and lemmatise lemmatiser = WordNetLemmatizer() tokens = [lemmatiser.lemmatize(t.lower(), pos='v') for t in tokens] return tokens# Preprocess the datavectoriser = TfidfVectorizer(analyzer=preprocess_text, min_df=30, max_df=.7)X_train_simple = vectoriser.fit_transform(X_train)# Assess modelsassess(X_train_simple, y_train, models)" }, { "code": null, "e": 15870, "s": 15625, "text": "The performance looks similar to before. Therefore, we will favour the simpler approach and use it moving forward. Of the three algorithms, we will choose Stochastic Gradient Descent because it balances both speed and predictive power the most." }, { "code": null, "e": 16075, "s": 15870, "text": "In this section, we will explore whether adding VADER and TextBlob sentiment scores as features improves the predictive power of the model. Let’s quickly check if there are any highly correlated features:" }, { "code": null, "e": 16261, "s": 16075, "text": "plt.figure(figsize = (14,5))columns = ['target', 'neg', 'neu', 'pos', 'compound', 'polarity', 'subjectivity']sns.heatmap(train[columns].corr(), annot=True, cmap='seismic_r');" }, { "code": null, "e": 16380, "s": 16261, "text": "The most correlated features are compound and neg. Let’s run a quick model to see which scores are more useful to use:" }, { "code": null, "e": 16668, "s": 16380, "text": "# Initialise a modelsgd = SGDClassifier(random_state=seed)# Initialise a scalerscaler = MinMaxScaler()# Assess the model using scoresscores = train[['neg', 'neu', 'pos', 'compound', 'polarity', 'subjectivity']]assess(scaler.fit_transform(scores), y_train, [('sgd', sgd)])" }, { "code": null, "e": 16744, "s": 16668, "text": "We get about 77% accuracy using the scores. Now let’s inspect coefficients:" }, { "code": null, "e": 17024, "s": 16744, "text": "# Fit to training datasgd.fit(scores, y_train)# Get coefficientscoefs = pd.DataFrame(data=sgd.coef_, columns=scores.columns).Tcoefs.rename(columns={0: 'coef'}, inplace=True)# Plotplt.figure(figsize=(10,5))sns.barplot(x=coefs.index, y='coef', data=coefs)plt.title('Coefficients');" }, { "code": null, "e": 17249, "s": 17024, "text": "Seems like we could only use neg, pos and polarity because they are the most dominant features among the scores. Let’s see if model results can be improved by adding these selected scores to the previously preprocessed data." }, { "code": null, "e": 17484, "s": 17249, "text": "# Add features to sparse matrixselected_scores = train[['neg', 'pos', 'polarity']]X_train_extended = hstack([X_train_simpler, csr_matrix(scaler.fit_transform(selected_scores))])# Assessassess(X_train_extended, y_train, [('sgd', sgd)])" }, { "code": null, "e": 17619, "s": 17484, "text": "Since adding these scores didn’t improve the model, it is unnecessary to add them as features. That will keep our pipeline simple too!" }, { "code": null, "e": 17927, "s": 17619, "text": "It’s time to build a small pipeline that puts together the preprocessor and the model. We will fine tune its hyperparameters to see if we can improve the model. Firstly, let’s try to understand the impact of three hyperparameters: min_df, max_df for the vectoriser and loss for the model with random search:" }, { "code": null, "e": 18609, "s": 17927, "text": "# Create a pipelinepipe = Pipeline([('vectoriser', TfidfVectorizer(token_pattern=r'[a-z]+')), ('model', SGDClassifier(random_state=seed))])# Prepare a random searchparam_distributions = {'vectoriser__min_df': np.arange(10, 1000, 10), 'vectoriser__max_df': np.linspace(.2, 1, 40), 'model__loss': ['log', 'hinge']}r_search = RandomizedSearchCV(estimator=pipe, param_distributions=param_distributions, n_iter=30, cv=5, n_jobs=-1, random_state=seed)r_search.fit(X_train, y_train)# Save results to a dataframer_search_results = pd.DataFrame(r_search.cv_results_).sort_values(by='rank_test_score')" }, { "code": null, "e": 18903, "s": 18609, "text": "Here, we are trying 30 different random combinations of hyperparameter space specified. This will take a while to run. The output of the random search will be saved in a dataframe called r_search_results. Let’s create another dataframe containing a few columns that are more interesting to us:" }, { "code": null, "e": 19293, "s": 18903, "text": "columns = [col for col in r_search_results.columns if re.search(r\"split|param_\", col)]r_summary = r_search_results[columns].copy()r_summary.columns = [re.sub(r'_test_score|param_', '', col) for col in r_summary.columns]columns = [col.split('__')[1] if '__' in col else col for col in r_summary.columns ]r_summary.columns = columnsr_summary.head()" }, { "code": null, "e": 19372, "s": 19293, "text": "Let’s visualise the output to understand the impact of hyperparameters better:" }, { "code": null, "e": 19979, "s": 19372, "text": "# Create a long dataframer_summary_long = pd.melt(r_summary, id_vars=['min_df', 'max_df', 'loss'], value_vars=['split0', 'split1', 'split2', 'split3', 'split4'])# Plot hyperparameter 'loss'plt.figure(figsize=(8,4))plt.title('Performance by loss')sns.boxplot(x='value', y='loss', data=r_summary_long, orient='h')plt.xlim(.8, .9);" }, { "code": null, "e": 20086, "s": 19979, "text": "It looks loss='hinge' results in slightly better performance. Let’s look at the numerical hyperparameters:" }, { "code": null, "e": 20277, "s": 20086, "text": "for param in ['min_df', 'max_df']: plt.figure(figsize=(8,4)) sns.scatterplot(x=param, y=\"value\", data=r_summary_long, x_jitter=True, alpha=0.5) plt.ylim(.8, .9);" }, { "code": null, "e": 20748, "s": 20277, "text": "As there seems to be a negative relationship between min_df and accuracy, we will keep min_df under 200. There isn’t a clear trend in max_df probably because the performance was more impacted by min_df and loss. Although this is true for all three of them, it’s more obvious for max_df. Now we have some idea on how these hyperparameters impact the model, let’s define the pipeline more precisely (max_df=.6 and loss=’hinge') and try to further tune it with grid search:" }, { "code": null, "e": 21393, "s": 20748, "text": "# Create a pipelinepipe = Pipeline([('vectoriser', TfidfVectorizer(token_pattern=r'[a-z]+', max_df=.6)), ('model', SGDClassifier(random_state=seed, loss='hinge'))])# Prepare a grid searchparam_grid = {'vectoriser__min_df': [30, 90, 150], 'vectoriser__ngram_range': [(1,1), (1,2)], 'vectoriser__stop_words': [None, 'english'], 'model__fit_intercept': [True, False]}g_search = GridSearchCV(estimator=pipe, param_grid=param_grid, cv=5, n_jobs=-1)g_search.fit(X_train, y_train)# Save results to a dataframeg_search_results = pd.DataFrame(g_search.cv_results_).sort_values(by='rank_test_score')" }, { "code": null, "e": 21642, "s": 21393, "text": "Grid searching will also take a bit of time because we have 24 different combinations of hyperparameters to try. Like before, the output will be saved to a dataframe called g_search_results. Let’s extract more relevant columns to another dataframe:" }, { "code": null, "e": 22052, "s": 21642, "text": "columns = [col for col in g_search_results.columns if re.search(r\"split|param_\", col)]g_summary = g_search_results[columns+['mean_test_score']].copy()g_summary.columns = [re.sub(r'_test_score|param_', '', col) for col in g_summary.columns]columns = [col.split('__')[1] if '__' in col else col for col in g_summary.columns ]g_summary.columns = columnsg_summary.head()" }, { "code": null, "e": 22167, "s": 22052, "text": "With any of these combinations, we reach a cross validated accuracy of ~0.9. It’s nice to see a marginal increase." }, { "code": null, "e": 22947, "s": 22167, "text": "# Create a long dataframeg_summary_long = pd.melt(g_summary, id_vars=['min_df', 'ngram_range', 'stop_words', 'fit_intercept'], value_vars=['split0', 'split1', 'split2', 'split3', 'split4'])g_summary_long.replace({None: 'None'}, inplace=True)# Plot performancefor param in ['ngram_range', 'stop_words', 'fit_intercept']: plt.figure(figsize=(8,4)) plt.title(f'Performance by {param}') sns.boxplot(x='value', y=param, data=g_summary_long, orient='h') plt.xlim(.85, .95);" }, { "code": null, "e": 23263, "s": 22947, "text": "We can see that by changing to ngram_range=(1,2), model performs better. The same is true for stop_words=None. On the other hand, whether we fit intercept or not doesn’t have much impact, which means we can leave this hyperparameter to its default. I think this is good enough, we can now define the final pipeline." }, { "code": null, "e": 23350, "s": 23263, "text": "Using the top combination from grid search, this is how our final pipeline looks like:" }, { "code": null, "e": 23568, "s": 23350, "text": "pipe = Pipeline([('vectoriser', TfidfVectorizer(token_pattern=r'[a-z]+', min_df=30, max_df=.6, ngram_range=(1,2))), ('model', SGDClassifier(random_state=seed, loss='hinge'))])pipe.fit(X_train, y_train)" }, { "code": null, "e": 23635, "s": 23568, "text": "Our pipeline is very small and simple. Let’s see its coefficients:" }, { "code": null, "e": 23813, "s": 23635, "text": "coefs = pd.DataFrame(pipe['model'].coef_, columns=pipe['vectoriser'].get_feature_names())coefs = coefs.T.rename(columns={0:'coef'}).sort_values('coef')coefs" }, { "code": null, "e": 24324, "s": 23813, "text": "Features with the highest or lowest coefficients look intuitive. But look at the number of features we have: 49,577! This is mainly due to having relaxed min_df, adding bigrams and not removing stop words. If we were keen to reduce the number of features, we could change these hyperparamaters in the pipeline. If we start cutting down features, we will notice a tradeoff between number of features and the model accuracy. What an optimal balance looks like depends on the context. Let’s evaluate the pipeline:" }, { "code": null, "e": 24491, "s": 24324, "text": "train_pred = pipe.predict(X_train)print(classification_report(train_pred, y_train, target_names=target_names))" }, { "code": null, "e": 24654, "s": 24491, "text": "test_pred = pipe.predict(X_test)print(classification_report(test_pred, y_test, target_names=target_names))" }, { "code": null, "e": 24851, "s": 24654, "text": "Accuracy on train and test set is about 0.94 and 0.92 respectively. Precision and recall by both sentiments look pretty similar. We have slightly more false negatives. Let’s plot confusion matrix:" }, { "code": null, "e": 24905, "s": 24851, "text": "plot_cm(test_pred, y_test, target_names=target_names)" }, { "code": null, "e": 25124, "s": 24905, "text": "Looks good. Yay 🎊, now we have a pipeline that classifies about 9 in 10 reviews into the correct sentiment. Let’s see how long it takes to make a single prediction. We will use Jupyter Notebook’s magic command %timeit:" }, { "code": null, "e": 25201, "s": 25124, "text": "for i in range(10): lead = X_test.sample(1) %timeit pipe.predict(lead)" }, { "code": null, "e": 25417, "s": 25201, "text": "Although %timeit runs multiple loops and gives us mean and standard deviation of run time, I notice that I get slightly different output every time. Hence, we are looking at 10 loops of %timeit to observe the range." }, { "code": null, "e": 25558, "s": 25417, "text": "A single prediction takes about 1.5 to 4 milliseconds. This needs to be evaluated in the context of production environment for the use case." }, { "code": null, "e": 25596, "s": 25558, "text": "Alright, that was it for this post. 💫" }, { "code": null, "e": 25820, "s": 25596, "text": "Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me." }, { "code": null, "e": 26106, "s": 25820, "text": "Thank you for reading my post. Hopefully, you have learned a few different practical ways to classify text into sentiments with or without building a custom model. Here are links to the other two posts of the series:◼️ Exploratory text analysis in Python◼️ Preprocessing text in Python" }, { "code": null, "e": 26529, "s": 26106, "text": "Here are links to the my other NLP-related posts:◼️ Simple wordcloud in Python(Below lists a series of posts on Introduction to NLP)◼️ Part 1: Preprocessing text in Python◼️ Part 2: Difference between lemmatisation and stemming◼️ Part 3: TF-IDF explained◼️ Part 4: Supervised text classification model in Python◼️ Part 5A: Unsupervised topic model in Python (sklearn)◼️ Part 5B: Unsupervised topic model in Python (gensim)" } ]
Spring AOP - Annotation Based PointCut
A JoinPoint represents a point in your application where you can plug-in AOP aspect. You can also say, it is the actual place in the application where an action will be taken using Spring AOP framework. Consider the following examples − All methods classes contained in a package(s). All methods classes contained in a package(s). A particular methods of a class. A particular methods of a class. Pointcut is a set of one or more JoinPoint where an advice should be executed. You can specify Pointcuts using expressions or patterns as we will see in our AOP examples. In Spring, Pointcut helps to use specific JoinPoints to apply the advice. Consider the following examples − @Pointcut("execution(* com.tutorialspoint.*.*(..))") @Pointcut("execution(* com.tutorialspoint.*.*(..))") @Pointcut("execution(* com.tutorialspoint.Student.getName(..))") @Pointcut("execution(* com.tutorialspoint.Student.getName(..))") @Aspect public class Logging { @Pointcut("execution(* com.tutorialspoint.*.*(..))") private void selectAll(){} } Where, @Aspect − Mark a class as a class containing advice methods. @Aspect − Mark a class as a class containing advice methods. @Pointcut − Mark a function as a Pointcut @Pointcut − Mark a function as a Pointcut execution( expression ) − Expression covering methods on which advice is to be applied. execution( expression ) − Expression covering methods on which advice is to be applied. To understand the above-mentioned concepts related to JoinPoint and PointCut, let us write an example which will implement few of the PointCuts. To write our example with few advices, let us have a working Eclipse IDE in place and use the following steps to create a Spring application − Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points. package com.tutorialspoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.annotation.Before; @Aspect public class Logging { /** Following is the definition for a PointCut to select * all the methods available. So advice will be called * for all the methods. */ @Pointcut("execution(* com.tutorialspoint.*.*(..))") private void selectAll(){} /** * This is the method which I would like to execute * before a selected method execution. */ @Before("selectAll()") public void beforeAdvice(){ System.out.println("Going to setup student profile."); } } Following is the content of the Student.java file. package com.tutorialspoint; public class Student { private Integer age; private String name; public void setAge(Integer age) { this.age = age; } public Integer getAge() { System.out.println("Age : " + age ); return age; } public void setName(String name) { this.name = name; } public String getName() { System.out.println("Name : " + name ); return name; } public void printThrowException(){ System.out.println("Exception raised"); throw new IllegalArgumentException(); } } Following is the content of the MainApp.java file. package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); Student student = (Student) context.getBean("student"); student.getName(); student.getAge(); } } Following is the configuration file Beans.xml. <?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:aop = "http://www.springframework.org/schema/aop" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd "> <aop:aspectj-autoproxy/> <!-- Definition for student bean --> <bean id = "student" class = "com.tutorialspoint.Student"> <property name = "name" value = "Zara" /> <property name = "age" value = "11"/> </bean> <!-- Definition for logging aspect --> <bean id = "logging" class = "com.tutorialspoint.Logging"/> </beans> Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message. Going to setup student profile. Name : Zara Going to setup student profile. Age : 11 The above-defined @Pointcut uses an expression to select all the methods defined under the package com.tutorialspoint. @Before advice uses the above-defined Pointcut as a parameter. Effectively beforeAdvice() method will be called before every method covered by above Pointcut. Print Add Notes Bookmark this page
[ { "code": null, "e": 2506, "s": 2269, "text": "A JoinPoint represents a point in your application where you can plug-in AOP aspect. You can also say, it is the actual place in the application where an action will be taken using Spring AOP framework. Consider the following examples −" }, { "code": null, "e": 2553, "s": 2506, "text": "All methods classes contained in a package(s)." }, { "code": null, "e": 2600, "s": 2553, "text": "All methods classes contained in a package(s)." }, { "code": null, "e": 2633, "s": 2600, "text": "A particular methods of a class." }, { "code": null, "e": 2666, "s": 2633, "text": "A particular methods of a class." }, { "code": null, "e": 2945, "s": 2666, "text": "Pointcut is a set of one or more JoinPoint where an advice should be executed. You can specify Pointcuts using expressions or patterns as we will see in our AOP examples. In Spring, Pointcut helps to use specific JoinPoints to apply the advice. Consider the following examples −" }, { "code": null, "e": 2998, "s": 2945, "text": "@Pointcut(\"execution(* com.tutorialspoint.*.*(..))\")" }, { "code": null, "e": 3051, "s": 2998, "text": "@Pointcut(\"execution(* com.tutorialspoint.*.*(..))\")" }, { "code": null, "e": 3116, "s": 3051, "text": "@Pointcut(\"execution(* com.tutorialspoint.Student.getName(..))\")" }, { "code": null, "e": 3181, "s": 3116, "text": "@Pointcut(\"execution(* com.tutorialspoint.Student.getName(..))\")" }, { "code": null, "e": 3300, "s": 3181, "text": "@Aspect\npublic class Logging {\n @Pointcut(\"execution(* com.tutorialspoint.*.*(..))\")\n private void selectAll(){}\n}" }, { "code": null, "e": 3307, "s": 3300, "text": "Where," }, { "code": null, "e": 3368, "s": 3307, "text": "@Aspect − Mark a class as a class containing advice methods." }, { "code": null, "e": 3429, "s": 3368, "text": "@Aspect − Mark a class as a class containing advice methods." }, { "code": null, "e": 3471, "s": 3429, "text": "@Pointcut − Mark a function as a Pointcut" }, { "code": null, "e": 3513, "s": 3471, "text": "@Pointcut − Mark a function as a Pointcut" }, { "code": null, "e": 3601, "s": 3513, "text": "execution( expression ) − Expression covering methods on which advice is to be applied." }, { "code": null, "e": 3689, "s": 3601, "text": "execution( expression ) − Expression covering methods on which advice is to be applied." }, { "code": null, "e": 3977, "s": 3689, "text": "To understand the above-mentioned concepts related to JoinPoint and PointCut, let us write an example which will implement few of the PointCuts. To write our example with few advices, let us have a working Eclipse IDE in place and use the following steps to create a Spring application −" }, { "code": null, "e": 4126, "s": 3977, "text": "Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points." }, { "code": null, "e": 4804, "s": 4126, "text": "package com.tutorialspoint;\n\nimport org.aspectj.lang.annotation.Aspect;\nimport org.aspectj.lang.annotation.Pointcut;\nimport org.aspectj.lang.annotation.Before;\n\n@Aspect\npublic class Logging {\n /** Following is the definition for a PointCut to select\n * all the methods available. So advice will be called\n * for all the methods.\n */\n @Pointcut(\"execution(* com.tutorialspoint.*.*(..))\")\n private void selectAll(){}\n\n /** \n * This is the method which I would like to execute\n * before a selected method execution.\n */\n @Before(\"selectAll()\")\n public void beforeAdvice(){\n System.out.println(\"Going to setup student profile.\");\n } \n}" }, { "code": null, "e": 4855, "s": 4804, "text": "Following is the content of the Student.java file." }, { "code": null, "e": 5415, "s": 4855, "text": "package com.tutorialspoint;\n\npublic class Student {\n private Integer age;\n private String name;\n\n public void setAge(Integer age) {\n this.age = age;\n }\n public Integer getAge() {\n System.out.println(\"Age : \" + age );\n return age;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getName() {\n System.out.println(\"Name : \" + name );\n return name;\n }\n public void printThrowException(){\n System.out.println(\"Exception raised\");\n throw new IllegalArgumentException();\n }\n}" }, { "code": null, "e": 5466, "s": 5415, "text": "Following is the content of the MainApp.java file." }, { "code": null, "e": 5901, "s": 5466, "text": "package com.tutorialspoint;\n\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\npublic class MainApp {\n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n\n Student student = (Student) context.getBean(\"student\");\n student.getName();\n student.getAge(); \n }\n}" }, { "code": null, "e": 5948, "s": 5901, "text": "Following is the configuration file Beans.xml." }, { "code": null, "e": 6788, "s": 5948, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xmlns:aop = \"http://www.springframework.org/schema/aop\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd \n http://www.springframework.org/schema/aop \n http://www.springframework.org/schema/aop/spring-aop-3.0.xsd \">\n\n <aop:aspectj-autoproxy/>\n\n <!-- Definition for student bean -->\n <bean id = \"student\" class = \"com.tutorialspoint.Student\">\n <property name = \"name\" value = \"Zara\" />\n <property name = \"age\" value = \"11\"/> \n </bean>\n\n <!-- Definition for logging aspect -->\n <bean id = \"logging\" class = \"com.tutorialspoint.Logging\"/> \n \n</beans>" }, { "code": null, "e": 7043, "s": 6788, "text": "Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message." }, { "code": null, "e": 7129, "s": 7043, "text": "Going to setup student profile.\nName : Zara\nGoing to setup student profile.\nAge : 11\n" }, { "code": null, "e": 7407, "s": 7129, "text": "The above-defined @Pointcut uses an expression to select all the methods defined under the package com.tutorialspoint. @Before advice uses the above-defined Pointcut as a parameter. Effectively beforeAdvice() method will be called before every method covered by above Pointcut." }, { "code": null, "e": 7414, "s": 7407, "text": " Print" }, { "code": null, "e": 7425, "s": 7414, "text": " Add Notes" } ]
Decode String in C++
Suppose we have an encoded string; we have to return its decoded string. The rule for encoding is: k[encoded_string], this indicates where the encoded_string inside the square brackets is being repeated exactly k times. We can assume that the original data does not contain any numeric characters and that digits are only for those repeat numbers, k. So if the input is like “1[ba]2[na]”, then the output will be “banana”. To solve this, we will follow these steps − create one empty stack, set i := 0 while i < size of a stringif s[i] is ‘]’res := delete element from the stack and take only the string that is inside the square brackets.n := 0while stack is not empty, and stack top is one numeric character, then accommodate the numbers and form the actual integer as nfor j in range 1 to nfor x in range 0 to size of resinsert res[x] into the stackotherwise insert s[i] into the stackincrease i by 1 if s[i] is ‘]’res := delete element from the stack and take only the string that is inside the square brackets.n := 0while stack is not empty, and stack top is one numeric character, then accommodate the numbers and form the actual integer as nfor j in range 1 to nfor x in range 0 to size of resinsert res[x] into the stack res := delete element from the stack and take only the string that is inside the square brackets. n := 0 while stack is not empty, and stack top is one numeric character, then accommodate the numbers and form the actual integer as n for j in range 1 to nfor x in range 0 to size of resinsert res[x] into the stack for x in range 0 to size of resinsert res[x] into the stack insert res[x] into the stack otherwise insert s[i] into the stack increase i by 1 ans := an empty string while stack is not emptyans := stack top element + anspop from stack ans := stack top element + ans pop from stack return ans Let us see the following implementation to get a better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: string decodeString(string s) { stack <char> st; int i = 0; while(i<s.size()){ if(s[i] == ']'){ string res = ""; while(st.top()!='['){ res = st.top() + res; st.pop(); } st.pop(); int n = 0; int x = 1; while(!st.empty() && st.top()>='0' && st.top()<='9'){ n = n + (st.top()-'0')*x; x*=10; st.pop(); } for(int j = 1; j <= n; j++){ for(int x = 0; x < res.size();x++){ st.push(res[x]); } } } else{ st.push(s[i]); } i++; } string ans =""; while(!st.empty()){ ans = st.top() + ans; st.pop(); } return ans; } }; main(){ Solution ob; cout << ob.decodeString("1[ba]2[na]"); } "1[ba]2[na]" "banana"
[ { "code": null, "e": 1485, "s": 1062, "text": "Suppose we have an encoded string; we have to return its decoded string. The rule for encoding is: k[encoded_string], this indicates where the encoded_string inside the square brackets is being repeated exactly k times. We can assume that the original data does not contain any numeric characters and that digits are only for those repeat numbers, k. So if the input is like “1[ba]2[na]”, then the output will be “banana”." }, { "code": null, "e": 1529, "s": 1485, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1564, "s": 1529, "text": "create one empty stack, set i := 0" }, { "code": null, "e": 1966, "s": 1564, "text": "while i < size of a stringif s[i] is ‘]’res := delete element from the stack and take only the string that is inside the square brackets.n := 0while stack is not empty, and stack top is one numeric character, then accommodate the numbers and form the actual integer as nfor j in range 1 to nfor x in range 0 to size of resinsert res[x] into the stackotherwise insert s[i] into the stackincrease i by 1" }, { "code": null, "e": 2291, "s": 1966, "text": "if s[i] is ‘]’res := delete element from the stack and take only the string that is inside the square brackets.n := 0while stack is not empty, and stack top is one numeric character, then accommodate the numbers and form the actual integer as nfor j in range 1 to nfor x in range 0 to size of resinsert res[x] into the stack" }, { "code": null, "e": 2389, "s": 2291, "text": "res := delete element from the stack and take only the string that is inside the square brackets." }, { "code": null, "e": 2396, "s": 2389, "text": "n := 0" }, { "code": null, "e": 2524, "s": 2396, "text": "while stack is not empty, and stack top is one numeric character, then accommodate the numbers and form the actual integer as n" }, { "code": null, "e": 2605, "s": 2524, "text": "for j in range 1 to nfor x in range 0 to size of resinsert res[x] into the stack" }, { "code": null, "e": 2665, "s": 2605, "text": "for x in range 0 to size of resinsert res[x] into the stack" }, { "code": null, "e": 2694, "s": 2665, "text": "insert res[x] into the stack" }, { "code": null, "e": 2731, "s": 2694, "text": "otherwise insert s[i] into the stack" }, { "code": null, "e": 2747, "s": 2731, "text": "increase i by 1" }, { "code": null, "e": 2770, "s": 2747, "text": "ans := an empty string" }, { "code": null, "e": 2839, "s": 2770, "text": "while stack is not emptyans := stack top element + anspop from stack" }, { "code": null, "e": 2870, "s": 2839, "text": "ans := stack top element + ans" }, { "code": null, "e": 2885, "s": 2870, "text": "pop from stack" }, { "code": null, "e": 2896, "s": 2885, "text": "return ans" }, { "code": null, "e": 2968, "s": 2896, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 2979, "s": 2968, "text": " Live Demo" }, { "code": null, "e": 3995, "s": 2979, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n string decodeString(string s) {\n stack <char> st;\n int i = 0;\n while(i<s.size()){\n if(s[i] == ']'){\n string res = \"\";\n while(st.top()!='['){\n res = st.top() + res;\n st.pop();\n }\n st.pop();\n int n = 0;\n int x = 1;\n while(!st.empty() && st.top()>='0' && st.top()<='9'){\n n = n + (st.top()-'0')*x;\n x*=10;\n st.pop();\n }\n for(int j = 1; j <= n; j++){\n for(int x = 0; x < res.size();x++){\n st.push(res[x]);\n }\n }\n }\n else{\n st.push(s[i]);\n }\n i++;\n }\n string ans =\"\";\n while(!st.empty()){\n ans = st.top() + ans;\n st.pop();\n }\n return ans;\n }\n};\nmain(){\n Solution ob;\n cout << ob.decodeString(\"1[ba]2[na]\");\n}" }, { "code": null, "e": 4008, "s": 3995, "text": "\"1[ba]2[na]\"" }, { "code": null, "e": 4017, "s": 4008, "text": "\"banana\"" } ]
How To Downfill Null Values In SQL | Towards Data Science
When it comes to data analysis, you often don’t realize what you’re missing until you visualize it. Huge gaps or downward spikes in visualizations will show you exactly where the data is missing, but that’s not a story you want to communicate to your stakeholders. While some visualization tools can cover these gaps with ease, it’s often best to handle for this at the data source, and relying on your viz tool to do the work for you won’t come in handy if you need to do further analysis outside of tool. So how do we fill in null or missing values at the source? Let’s suppose we have a table that looks like the one below called inventory_log that keeps track of how many widgets your company has in its inventory at the end of each: Since your store is closed on the weekends, there would have been no change of inventory from Friday to Monday, but that also means there was no one to count the inventory and to input that value into the table. It would be safe to assume that the inventory number didn’t change from Friday to Monday, so correct values for Saturday and Sunday would be whatever the value for Friday is. To accomplish this, we apply a tool called filling down. Filling down is exactly what it sounds like: whenever there is a null value, we simply grab the most recent non-null value from above it to replace the null value. There are many features in Python (including the pandas.DataFrame.ffill() function) that accomplish this, but they are almost always slower than performing the operation directly on the database server. Now that we’ve fully examined the problem, let’s understand how to do it in SQL. Using the same table above as our sample data, we can replace the null values utilizing both nested queries and window functions. The first thing we want to do is to group the rows with null values with the first non-null value above it. We can do that by utilizing a window function to count the inventory column over the date: select date, day_of_week, inventory, count(inventory) over (order by date) as _grpfrom inventory_log This query will return us a table that looks like this: Okay! That gives us a new column that allows us to group together the null values with the first non-null value preceding them. Now the next step is to return that first value for every row that shares a grouping. Luckily, the first_value window function allows us to do just that. Applying this function to what we already have gives us this query: with grouped_table as ( select date, day_of_week, inventory, count(inventory) over (order by date) as _grp from inventory_log)select date, day_of_week, inventory, _grp, first_value() over (partition by _grp order by date) as filled_inventoryfrom grouped_table If you want to dive deep into the first_value function, you can check out the documentation here, but the function simply returns the first value for the partition according to the order. The above query gives us the following table: That’s it! We now have a column with the null values replaced with the preceding value. So let’s put our query all together: with grouped_table as ( select date, day_of_week, inventory, count(inventory) over (order by date) as _grp from inventory_log), final_table as( select date, day_of_week, inventory, _grp, first_value() over (partition by _grp order by date) as new_inventory from grouped_table)select date, day_of_week, new_inventoryfrom final_table output: NOTE: If you have a query where you have multiple dimensions/columns that you need to take into consideration (maybe different store locations in this example), simply add those to the partition clause in the count() window function in the grouped_table sub-query. Happy coding! If you want to see other data science tips and tricks, check out my article on How To Load Your Pandas DataFrame To Your Database 10x Faster. Let me know what you’re working on in the comments below!
[ { "code": null, "e": 437, "s": 172, "text": "When it comes to data analysis, you often don’t realize what you’re missing until you visualize it. Huge gaps or downward spikes in visualizations will show you exactly where the data is missing, but that’s not a story you want to communicate to your stakeholders." }, { "code": null, "e": 738, "s": 437, "text": "While some visualization tools can cover these gaps with ease, it’s often best to handle for this at the data source, and relying on your viz tool to do the work for you won’t come in handy if you need to do further analysis outside of tool. So how do we fill in null or missing values at the source?" }, { "code": null, "e": 910, "s": 738, "text": "Let’s suppose we have a table that looks like the one below called inventory_log that keeps track of how many widgets your company has in its inventory at the end of each:" }, { "code": null, "e": 1122, "s": 910, "text": "Since your store is closed on the weekends, there would have been no change of inventory from Friday to Monday, but that also means there was no one to count the inventory and to input that value into the table." }, { "code": null, "e": 1518, "s": 1122, "text": "It would be safe to assume that the inventory number didn’t change from Friday to Monday, so correct values for Saturday and Sunday would be whatever the value for Friday is. To accomplish this, we apply a tool called filling down. Filling down is exactly what it sounds like: whenever there is a null value, we simply grab the most recent non-null value from above it to replace the null value." }, { "code": null, "e": 1721, "s": 1518, "text": "There are many features in Python (including the pandas.DataFrame.ffill() function) that accomplish this, but they are almost always slower than performing the operation directly on the database server." }, { "code": null, "e": 1802, "s": 1721, "text": "Now that we’ve fully examined the problem, let’s understand how to do it in SQL." }, { "code": null, "e": 1932, "s": 1802, "text": "Using the same table above as our sample data, we can replace the null values utilizing both nested queries and window functions." }, { "code": null, "e": 2131, "s": 1932, "text": "The first thing we want to do is to group the rows with null values with the first non-null value above it. We can do that by utilizing a window function to count the inventory column over the date:" }, { "code": null, "e": 2250, "s": 2131, "text": "select date, day_of_week, inventory, count(inventory) over (order by date) as _grpfrom inventory_log" }, { "code": null, "e": 2306, "s": 2250, "text": "This query will return us a table that looks like this:" }, { "code": null, "e": 2588, "s": 2306, "text": "Okay! That gives us a new column that allows us to group together the null values with the first non-null value preceding them. Now the next step is to return that first value for every row that shares a grouping. Luckily, the first_value window function allows us to do just that." }, { "code": null, "e": 2656, "s": 2588, "text": "Applying this function to what we already have gives us this query:" }, { "code": null, "e": 2971, "s": 2656, "text": "with grouped_table as ( select date, day_of_week, inventory, count(inventory) over (order by date) as _grp from inventory_log)select date, day_of_week, inventory, _grp, first_value() over (partition by _grp order by date) as filled_inventoryfrom grouped_table" }, { "code": null, "e": 3159, "s": 2971, "text": "If you want to dive deep into the first_value function, you can check out the documentation here, but the function simply returns the first value for the partition according to the order." }, { "code": null, "e": 3205, "s": 3159, "text": "The above query gives us the following table:" }, { "code": null, "e": 3293, "s": 3205, "text": "That’s it! We now have a column with the null values replaced with the preceding value." }, { "code": null, "e": 3330, "s": 3293, "text": "So let’s put our query all together:" }, { "code": null, "e": 3759, "s": 3330, "text": "with grouped_table as ( select date, day_of_week, inventory, count(inventory) over (order by date) as _grp from inventory_log), final_table as( select date, day_of_week, inventory, _grp, first_value() over (partition by _grp order by date) as new_inventory from grouped_table)select date, day_of_week, new_inventoryfrom final_table" }, { "code": null, "e": 3767, "s": 3759, "text": "output:" }, { "code": null, "e": 4032, "s": 3767, "text": "NOTE: If you have a query where you have multiple dimensions/columns that you need to take into consideration (maybe different store locations in this example), simply add those to the partition clause in the count() window function in the grouped_table sub-query." }, { "code": null, "e": 4046, "s": 4032, "text": "Happy coding!" } ]
Arduino - Fading LED
This example demonstrates the use of the analogWrite() function in fading an LED off. AnalogWrite uses pulse width modulation (PWM), turning a digital pin on and off very quickly with different ratios between on and off, to create a fading effect. You will need the following components − 1 × Breadboard 1 × Arduino Uno R3 1 × LED 1 × 330Ω Resistor 2 × Jumper Follow the circuit diagram and hook up the components on the breadboard as shown in the image given below. Note − To find out the polarity of an LED, look at it closely. The shorter of the two legs, towards the flat edge of the bulb indicates the negative terminal. Components like resistors need to have their terminals bent into 90° angles in order to fit the breadboard sockets properly. You can also cut the terminals shorter. Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the new sketch File by clicking New. /* Fade This example shows how to fade an LED on pin 9 using the analogWrite() function. The analogWrite() function uses PWM, so if you want to change the pin you're using, be sure to use another PWM capable pin. On most Arduino, the PWM pins are identified with a "~" sign, like ~3, ~5, ~6, ~9, ~10 and ~11. */ int led = 9; // the PWM pin the LED is attached to int brightness = 0; // how bright the LED is int fadeAmount = 5; // how many points to fade the LED by // the setup routine runs once when you press reset: void setup() { // declare pin 9 to be an output: pinMode(led, OUTPUT); } // the loop routine runs over and over again forever: void loop() { // set the brightness of pin 9: analogWrite(led, brightness); // change the brightness for next time through the loop: brightness = brightness + fadeAmount; // reverse the direction of the fading at the ends of the fade: if (brightness == 0 || brightness == 255) { fadeAmount = -fadeAmount ; } // wait for 30 milliseconds to see the dimming effect delay(300); } After declaring pin 9 as your LED pin, there is nothing to do in the setup() function of your code. The analogWrite() function that you will be using in the main loop of your code requires two arguments: One, telling the function which pin to write to and the other indicating what PWM value to write. In order to fade the LED off and on, gradually increase the PWM values from 0 (all the way off) to 255 (all the way on), and then back to 0, to complete the cycle. In the sketch given above, the PWM value is set using a variable called brightness. Each time through the loop, it increases by the value of the variable fadeAmount. If brightness is at either extreme of its value (either 0 or 255), then fadeAmount is changed to its negative. In other words, if fadeAmount is 5, then it is set to -5. If it is -5, then it is set to 5. The next time through the loop, this change causes brightness to change direction as well. analogWrite() can change the PWM value very fast, so the delay at the end of the sketch controls the speed of the fade. Try changing the value of the delay and see how it changes the fading effect. You should see your LED brightness change gradually. 65 Lectures 6.5 hours Amit Rana 43 Lectures 3 hours Amit Rana 20 Lectures 2 hours Ashraf Said 19 Lectures 1.5 hours Ashraf Said 11 Lectures 47 mins Ashraf Said 9 Lectures 41 mins Ashraf Said Print Add Notes Bookmark this page
[ { "code": null, "e": 3118, "s": 2870, "text": "This example demonstrates the use of the analogWrite() function in fading an LED off. AnalogWrite uses pulse width modulation (PWM), turning a digital pin on and off very quickly with different ratios between on and off, to create a fading effect." }, { "code": null, "e": 3159, "s": 3118, "text": "You will need the following components −" }, { "code": null, "e": 3174, "s": 3159, "text": "1 × Breadboard" }, { "code": null, "e": 3193, "s": 3174, "text": "1 × Arduino Uno R3" }, { "code": null, "e": 3201, "s": 3193, "text": "1 × LED" }, { "code": null, "e": 3219, "s": 3201, "text": "1 × 330Ω Resistor" }, { "code": null, "e": 3230, "s": 3219, "text": "2 × Jumper" }, { "code": null, "e": 3337, "s": 3230, "text": "Follow the circuit diagram and hook up the components on the breadboard as shown in the image given below." }, { "code": null, "e": 3496, "s": 3337, "text": "Note − To find out the polarity of an LED, look at it closely. The shorter of the two legs, towards the flat edge of the bulb indicates the negative terminal." }, { "code": null, "e": 3661, "s": 3496, "text": "Components like resistors need to have their terminals bent into 90° angles in order to fit the breadboard sockets properly. You can also cut the terminals shorter." }, { "code": null, "e": 3809, "s": 3661, "text": "Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the new sketch File by clicking New." }, { "code": null, "e": 4890, "s": 3809, "text": "/*\n Fade\n This example shows how to fade an LED on pin 9 using the analogWrite() function.\n\n The analogWrite() function uses PWM, so if you want to change the pin you're using, be\n sure to use another PWM capable pin. On most Arduino, the PWM pins are identified with\n a \"~\" sign, like ~3, ~5, ~6, ~9, ~10 and ~11.\n*/\n\nint led = 9; // the PWM pin the LED is attached to\nint brightness = 0; // how bright the LED is\nint fadeAmount = 5; // how many points to fade the LED by\n// the setup routine runs once when you press reset:\n\nvoid setup() {\n // declare pin 9 to be an output:\n pinMode(led, OUTPUT);\n}\n\n// the loop routine runs over and over again forever:\n\nvoid loop() {\n // set the brightness of pin 9:\n analogWrite(led, brightness);\n // change the brightness for next time through the loop:\n brightness = brightness + fadeAmount;\n // reverse the direction of the fading at the ends of the fade:\n if (brightness == 0 || brightness == 255) {\n fadeAmount = -fadeAmount ;\n }\n // wait for 30 milliseconds to see the dimming effect\n delay(300);\n}" }, { "code": null, "e": 5192, "s": 4890, "text": "After declaring pin 9 as your LED pin, there is nothing to do in the setup() function of your code. The analogWrite() function that you will be using in the main loop of your code requires two arguments: One, telling the function which pin to write to and the other indicating what PWM value to write." }, { "code": null, "e": 5522, "s": 5192, "text": "In order to fade the LED off and on, gradually increase the PWM values from 0 (all the way off) to 255 (all the way on), and then back to 0, to complete the cycle. In the sketch given above, the PWM value is set using a variable called brightness. Each time through the loop, it increases by the value of the variable fadeAmount." }, { "code": null, "e": 5816, "s": 5522, "text": "If brightness is at either extreme of its value (either 0 or 255), then fadeAmount is changed to its negative. In other words, if fadeAmount is 5, then it is set to -5. If it is -5, then it is set to 5. The next time through the loop, this change causes brightness to change direction as well." }, { "code": null, "e": 6014, "s": 5816, "text": "analogWrite() can change the PWM value very fast, so the delay at the end of the sketch controls the speed of the fade. Try changing the value of the delay and see how it changes the fading effect." }, { "code": null, "e": 6067, "s": 6014, "text": "You should see your LED brightness change gradually." }, { "code": null, "e": 6102, "s": 6067, "text": "\n 65 Lectures \n 6.5 hours \n" }, { "code": null, "e": 6113, "s": 6102, "text": " Amit Rana" }, { "code": null, "e": 6146, "s": 6113, "text": "\n 43 Lectures \n 3 hours \n" }, { "code": null, "e": 6157, "s": 6146, "text": " Amit Rana" }, { "code": null, "e": 6190, "s": 6157, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 6203, "s": 6190, "text": " Ashraf Said" }, { "code": null, "e": 6238, "s": 6203, "text": "\n 19 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6251, "s": 6238, "text": " Ashraf Said" }, { "code": null, "e": 6283, "s": 6251, "text": "\n 11 Lectures \n 47 mins\n" }, { "code": null, "e": 6296, "s": 6283, "text": " Ashraf Said" }, { "code": null, "e": 6327, "s": 6296, "text": "\n 9 Lectures \n 41 mins\n" }, { "code": null, "e": 6340, "s": 6327, "text": " Ashraf Said" }, { "code": null, "e": 6347, "s": 6340, "text": " Print" }, { "code": null, "e": 6358, "s": 6347, "text": " Add Notes" } ]
Simple and Multiple Linear Regression in Python | by Adi Bronshtein | Towards Data Science
Quick introduction to linear regression in Python Hi everyone! After briefly introducing the “Pandas” library as well as the NumPy library, I wanted to provide a quick introduction to building models in Python, and what better place to start than one of the very basic models, linear regression? This will be the first post about machine learning and I plan to write about more complex models in the future. Stay tuned! But for right now, let’s focus on linear regression. In this blog post, I want to focus on the concept of linear regression and mainly on the implementation of it in Python. Linear regression is a statistical model that examines the linear relationship between two (Simple Linear Regression ) or more (Multiple Linear Regression) variables — a dependent variable and independent variable(s). Linear relationship basically means that when one (or more) independent variables increases (or decreases), the dependent variable increases (or decreases) too: As you can see, a linear relationship can be positive (independent variable goes up, dependent variable goes up) or negative (independent variable goes up, dependent variable goes down). Like I said, I will focus on the implementation of regression models in Python, so I don’t want to delve too much into the math under the regression hood, but I will write a little bit about it. If you’d like a blog post about that, please don’t hesitate to write me in the responses! A relationship between variables Y and X is represented by this equation: Y`i = mX + b In this equation, Y is the dependent variable — or the variable we are trying to predict or estimate; X is the independent variable — the variable we are using to make predictions; m is the slope of the regression line — it represent the effect X has on Y. In other words, if X increases by 1 unit, Y will increase by exactly m units. (“Full disclosure”: this is true only if we know that X and Y have a linear relationship. In almost all linear regression cases, this will not be true!) b is a constant, also known as the Y-intercept. If X equals 0, Y would be equal to b (Caveat: see full disclosure from earlier!). This is not necessarily applicable in real life — we won’t always know the exact relationship between X and Y or have an exact linear relationship. These caveats lead us to a Simple Linear Regression (SLR). In a SLR model, we build a model based on data — the slope and Y-intercept derive from the data; furthermore, we don’t need the relationship between X and Y to be exactly linear. SLR models also include the errors in the data (also known as residuals). I won’t go too much into it now, maybe in a later post, but residuals are basically the differences between the true value of Y and the predicted/estimated value of Y. It is important to note that in a linear regression, we are trying to predict a continuous variable. In a regression model, we are trying to minimize these errors by finding the “line of best fit” — the regression line from the errors would be minimal. We are trying to minimize the length of the black lines (or more accurately, the distance of the blue dots) from the red line — as close to zero as possible. It is related to (or equivalent to) minimizing the mean squared error (MSE) or the sum of squares of error (SSE), also called the “residual sum of squares.” (RSS) but this might be beyond the scope of this blog post :-) In most cases, we will have more than one independent variable — we’ll have multiple variables; it can be as little as two independent variables and up to hundreds (or theoretically even thousands) of variables. in those cases we will use a Multiple Linear Regression model (MLR). The regression equation is pretty much the same as the simple regression equation, just with more variables: Y’i = b0 + b1X1i + b2X2i This concludes the math portion of this post :) Ready to get to implementing it in Python? There are two main ways to perform linear regression in Python — with Statsmodels and scikit-learn. It is also possible to use the Scipy library, but I feel this is not as common as the two other libraries I’ve mentioned. Let’s look into doing linear regression in both of them: Statsmodels is “a Python module that provides classes and functions for the estimation of many different statistical models, as well as for conducting statistical tests, and statistical data exploration.” (from the documentation) As in with Pandas and NumPy, the easiest way to get or install Statsmodels is through the Anaconda package. If, for some reason you are interested in installing in another way, check out this link. After installing it, you will need to import it every time you want to use it: import statsmodels.api as sm Let’s see how to actually use Statsmodels for linear regression. I’ll use an example from the data science class I took at General Assembly DC: First, we import a dataset from sklearn (the other library I’ve mentioned): from sklearn import datasets ## imports datasets from scikit-learndata = datasets.load_boston() ## loads Boston dataset from datasets library This is a dataset of the Boston house prices (link to the description). Because it is a dataset designated for testing and learning machine learning tools, it comes with a description of the dataset, and we can see it by using the command print data.DESCR (this is only true for sklearn datasets, not every dataset! Would have been cool though...). I’m adding the beginning of the description, for better understanding of the variables: Boston House Prices dataset===========================Notes------Data Set Characteristics: :Number of Instances: 506 :Number of Attributes: 13 numeric/categorical predictive :Median Value (attribute 14) is usually the target :Attribute Information (in order): - CRIM per capita crime rate by town - ZN proportion of residential land zoned for lots over 25,000 sq.ft. - INDUS proportion of non-retail business acres per town - CHAS Charles River dummy variable (= 1 if tract bounds river; 0 otherwise) - NOX nitric oxides concentration (parts per 10 million) - RM average number of rooms per dwelling - AGE proportion of owner-occupied units built prior to 1940 - DIS weighted distances to five Boston employment centres - RAD index of accessibility to radial highways - TAX full-value property-tax rate per $10,000 - PTRATIO pupil-teacher ratio by town - B 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town - LSTAT % lower status of the population - MEDV Median value of owner-occupied homes in $1000's :Missing Attribute Values: None :Creator: Harrison, D. and Rubinfeld, D.L.This is a copy of UCI ML housing dataset.http://archive.ics.uci.edu/ml/datasets/HousingThis dataset was taken from the StatLib library which is maintained at Carnegie Mellon University. Running data.feature_names and data.target would print the column names of the independent variables and the dependent variable, respectively. Meaning, Scikit-learn has already set the house value/price data as a target variable and 13 other variables are set as predictors. Let’s see how to run a linear regression on this dataset. First, we should load the data as a pandas data frame for easier analysis and set the median home value as our target variable: import numpy as npimport pandas as pd# define the data/predictors as the pre-set feature names df = pd.DataFrame(data.data, columns=data.feature_names)# Put the target (housing value -- MEDV) in another DataFrametarget = pd.DataFrame(data.target, columns=["MEDV"]) What we’ve done here is to take the dataset and load it as a pandas data frame; after that, we’re setting the predictors (as df) — the independent variables that are pre-set in the dataset. We’re also setting the target — the dependent variable, or the variable we’re trying to predict/estimate. Next we’ll want to fit a linear regression model. We need to choose variables that we think we’ll be good predictors for the dependent variable — that can be done by checking the correlation(s) between variables, by plotting the data and searching visually for relationship, by conducting preliminary research on what variables are good predictors of y etc. For this first example, let’s take RM — the average number of rooms and LSTAT — percentage of lower status of the population. It’s important to note that Statsmodels does not add a constant by default. Let’s see it first without a constant in our regression model: ## Without a constantimport statsmodels.api as smX = df["RM"]y = target["MEDV"]# Note the difference in argument ordermodel = sm.OLS(y, X).fit()predictions = model.predict(X) # make the predictions by the model# Print out the statisticsmodel.summary() The output: Interpreting the Table —This is a very long table, isn’t it? First we have what’s the dependent variable and the model and the method. OLS stands for Ordinary Least Squares and the method “Least Squares” means that we’re trying to fit a regression line that would minimize the square of distance from the regression line (see the previous section of this post). Date and Time are pretty self-explanatory :) So as number of observations. Df of residuals and models relates to the degrees of freedom — “the number of values in the final calculation of a statistic that are free to vary.” The coefficient of 3.6534 means that as the RM variable increases by 1, the predicted value of MDEV increases by 3.6534. A few other important values are the R-squared — the percentage of variance our model explains; the standard error (is the standard deviation of the sampling distribution of a statistic, most commonly of the mean); the t scores and p-values, for hypothesis test — the RM has statistically significant p-value; there is a 95% confidence intervals for the RM (meaning we predict at a 95% percent confidence that the value of RM is between 3.548 to 3.759). If we do want to add a constant to our model — we have to set it by using the command X = sm.add_constant(X) where X is the name of your data frame containing your input (independent) variables. import statsmodels.api as sm # import statsmodels X = df["RM"] ## X usually means our input variables (or independent variables)y = target["MEDV"] ## Y usually means our output/dependent variableX = sm.add_constant(X) ## let's add an intercept (beta_0) to our model# Note the difference in argument ordermodel = sm.OLS(y, X).fit() ## sm.OLS(output, input)predictions = model.predict(X)# Print out the statisticsmodel.summary() The output: Interpreting the Table — With the constant term the coefficients are different. Without a constant we are forcing our model to go through the origin, but now we have a y-intercept at -34.67. We also changed the slope of the RM predictor from 3.634 to 9.1021. Now let’s try fitting a regression model with more than one variable — we’ll be using RM and LSTAT I’ve mentioned before. Model fitting is the same: X = df[[“RM”, “LSTAT”]]y = target[“MEDV”]model = sm.OLS(y, X).fit()predictions = model.predict(X)model.summary() And the output: Interpreting the Output — We can see here that this model has a much higher R-squared value — 0.948, meaning that this model explains 94.8% of the variance in our dependent variable. Whenever we add variables to a regression model, R2 will be higher, but this is a pretty high R2. We can see that both RM and LSTAT are statistically significant in predicting (or estimating) the median house value; not surprisingly , we see that as RM increases by 1, MEDV will increase by 4.9069 and when LSTAT increases by 1, MEDV will decrease by -0.6557. As you may remember, LSTAT is the percentage of lower status of the population, and unfortunately we can expect that it will lower the median value of houses. With this same logic, the more rooms in a house, usually the higher its value will be. This was the example of both single and multiple linear regression in Statsmodels. We could have used as little or as many variables we wanted in our regression model(s) — up to all the 13! Next, I will demonstrate how to run linear regression models in SKLearn. SKLearn is pretty much the golden standard when it comes to machine learning in Python. It has many learning algorithms, for regression, classification, clustering and dimensionality reduction. Check out my post on the KNN algorithm for a map of the different algorithms and more links to SKLearn. In order to use linear regression, we need to import it: from sklearn import linear_model Let’s use the same dataset we used before, the Boston housing prices. The process would be the same in the beginning — importing the datasets from SKLearn and loading in the Boston dataset: from sklearn import datasets ## imports datasets from scikit-learndata = datasets.load_boston() ## loads Boston dataset from datasets library Next, we’ll load the data to Pandas (same as before): # define the data/predictors as the pre-set feature names df = pd.DataFrame(data.data, columns=data.feature_names)# Put the target (housing value -- MEDV) in another DataFrametarget = pd.DataFrame(data.target, columns=["MEDV"]) So now, as before, we have the data frame that contains the independent variables (marked as “df”) and the data frame with the dependent variable (marked as “target”). Let’s fit a regression model using SKLearn. First we’ll define our X and y — this time I’ll use all the variables in the data frame to predict the housing price: X = dfy = target[“MEDV”] And then I’ll fit a model: lm = linear_model.LinearRegression()model = lm.fit(X,y) The lm.fit() function fits a linear model. We want to use the model to make predictions (that’s what we’re here for!), so we’ll use lm.predict(): predictions = lm.predict(X)print(predictions)[0:5] The print function would print the first 5 predictions for y (I didn’t print the entire list to “save room”. Removing [0:5] would print the entire list): [ 30.00821269 25.0298606 30.5702317 28.60814055 27.94288232] Remember, lm.predict() predicts the y (dependent variable) using the linear model we fitted. You must have noticed that when we run a linear regression with SKLearn, we don’t get a pretty table (okay, it’s not that pretty... but it’s pretty useful) like in Statsmodels. What we can do is use built-in functions to return the score, the coefficients and the estimated intercepts. Let’s see how it works: lm.score(X,y) Would give this output: 0.7406077428649428 This is the R2 score of our model. As you probably remember, this the percentage of explained variance of the predictions. If you’re interested, read more here. Next, let’s check out the coefficients for the predictors: lm.coef_ will give this output: array([ -1.07170557e-01, 4.63952195e-02, 2.08602395e-02, 2.68856140e+00, -1.77957587e+01, 3.80475246e+00, 7.51061703e-04, -1.47575880e+00, 3.05655038e-01, -1.23293463e-02, -9.53463555e-01, 9.39251272e-03, -5.25466633e-01]) and the intercept: lm.intercept_ that will give this output: 36.491103280363134 These are all (estimated/predicted) parts of the multiple regression equation I’ve mentioned earlier. Check out the documentation to read more about coef_ and intercept_. So, this is has a been a quick (but rather long!) introduction on how to conduct linear regression in Python. In practice, you would not use the entire dataset, but you will split your data into a training data to train your model on, and a test data — to, you guessed it, test your model/predictions on. If you would like to read about it, please check out my next blog post. In the meanwhile, I hope you enjoyed this post and that I’ll “see” you on the next one. Thank you for reading!
[ { "code": null, "e": 221, "s": 171, "text": "Quick introduction to linear regression in Python" }, { "code": null, "e": 644, "s": 221, "text": "Hi everyone! After briefly introducing the “Pandas” library as well as the NumPy library, I wanted to provide a quick introduction to building models in Python, and what better place to start than one of the very basic models, linear regression? This will be the first post about machine learning and I plan to write about more complex models in the future. Stay tuned! But for right now, let’s focus on linear regression." }, { "code": null, "e": 1144, "s": 644, "text": "In this blog post, I want to focus on the concept of linear regression and mainly on the implementation of it in Python. Linear regression is a statistical model that examines the linear relationship between two (Simple Linear Regression ) or more (Multiple Linear Regression) variables — a dependent variable and independent variable(s). Linear relationship basically means that when one (or more) independent variables increases (or decreases), the dependent variable increases (or decreases) too:" }, { "code": null, "e": 1616, "s": 1144, "text": "As you can see, a linear relationship can be positive (independent variable goes up, dependent variable goes up) or negative (independent variable goes up, dependent variable goes down). Like I said, I will focus on the implementation of regression models in Python, so I don’t want to delve too much into the math under the regression hood, but I will write a little bit about it. If you’d like a blog post about that, please don’t hesitate to write me in the responses!" }, { "code": null, "e": 1690, "s": 1616, "text": "A relationship between variables Y and X is represented by this equation:" }, { "code": null, "e": 1703, "s": 1690, "text": "Y`i = mX + b" }, { "code": null, "e": 2469, "s": 1703, "text": "In this equation, Y is the dependent variable — or the variable we are trying to predict or estimate; X is the independent variable — the variable we are using to make predictions; m is the slope of the regression line — it represent the effect X has on Y. In other words, if X increases by 1 unit, Y will increase by exactly m units. (“Full disclosure”: this is true only if we know that X and Y have a linear relationship. In almost all linear regression cases, this will not be true!) b is a constant, also known as the Y-intercept. If X equals 0, Y would be equal to b (Caveat: see full disclosure from earlier!). This is not necessarily applicable in real life — we won’t always know the exact relationship between X and Y or have an exact linear relationship." }, { "code": null, "e": 3580, "s": 2469, "text": "These caveats lead us to a Simple Linear Regression (SLR). In a SLR model, we build a model based on data — the slope and Y-intercept derive from the data; furthermore, we don’t need the relationship between X and Y to be exactly linear. SLR models also include the errors in the data (also known as residuals). I won’t go too much into it now, maybe in a later post, but residuals are basically the differences between the true value of Y and the predicted/estimated value of Y. It is important to note that in a linear regression, we are trying to predict a continuous variable. In a regression model, we are trying to minimize these errors by finding the “line of best fit” — the regression line from the errors would be minimal. We are trying to minimize the length of the black lines (or more accurately, the distance of the blue dots) from the red line — as close to zero as possible. It is related to (or equivalent to) minimizing the mean squared error (MSE) or the sum of squares of error (SSE), also called the “residual sum of squares.” (RSS) but this might be beyond the scope of this blog post :-)" }, { "code": null, "e": 3970, "s": 3580, "text": "In most cases, we will have more than one independent variable — we’ll have multiple variables; it can be as little as two independent variables and up to hundreds (or theoretically even thousands) of variables. in those cases we will use a Multiple Linear Regression model (MLR). The regression equation is pretty much the same as the simple regression equation, just with more variables:" }, { "code": null, "e": 3995, "s": 3970, "text": "Y’i = b0 + b1X1i + b2X2i" }, { "code": null, "e": 4086, "s": 3995, "text": "This concludes the math portion of this post :) Ready to get to implementing it in Python?" }, { "code": null, "e": 4365, "s": 4086, "text": "There are two main ways to perform linear regression in Python — with Statsmodels and scikit-learn. It is also possible to use the Scipy library, but I feel this is not as common as the two other libraries I’ve mentioned. Let’s look into doing linear regression in both of them:" }, { "code": null, "e": 4595, "s": 4365, "text": "Statsmodels is “a Python module that provides classes and functions for the estimation of many different statistical models, as well as for conducting statistical tests, and statistical data exploration.” (from the documentation)" }, { "code": null, "e": 4872, "s": 4595, "text": "As in with Pandas and NumPy, the easiest way to get or install Statsmodels is through the Anaconda package. If, for some reason you are interested in installing in another way, check out this link. After installing it, you will need to import it every time you want to use it:" }, { "code": null, "e": 4901, "s": 4872, "text": "import statsmodels.api as sm" }, { "code": null, "e": 5045, "s": 4901, "text": "Let’s see how to actually use Statsmodels for linear regression. I’ll use an example from the data science class I took at General Assembly DC:" }, { "code": null, "e": 5121, "s": 5045, "text": "First, we import a dataset from sklearn (the other library I’ve mentioned):" }, { "code": null, "e": 5264, "s": 5121, "text": "from sklearn import datasets ## imports datasets from scikit-learndata = datasets.load_boston() ## loads Boston dataset from datasets library " }, { "code": null, "e": 5701, "s": 5264, "text": "This is a dataset of the Boston house prices (link to the description). Because it is a dataset designated for testing and learning machine learning tools, it comes with a description of the dataset, and we can see it by using the command print data.DESCR (this is only true for sklearn datasets, not every dataset! Would have been cool though...). I’m adding the beginning of the description, for better understanding of the variables:" }, { "code": null, "e": 7163, "s": 5701, "text": "Boston House Prices dataset===========================Notes------Data Set Characteristics: :Number of Instances: 506 :Number of Attributes: 13 numeric/categorical predictive :Median Value (attribute 14) is usually the target :Attribute Information (in order): - CRIM per capita crime rate by town - ZN proportion of residential land zoned for lots over 25,000 sq.ft. - INDUS proportion of non-retail business acres per town - CHAS Charles River dummy variable (= 1 if tract bounds river; 0 otherwise) - NOX nitric oxides concentration (parts per 10 million) - RM average number of rooms per dwelling - AGE proportion of owner-occupied units built prior to 1940 - DIS weighted distances to five Boston employment centres - RAD index of accessibility to radial highways - TAX full-value property-tax rate per $10,000 - PTRATIO pupil-teacher ratio by town - B 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town - LSTAT % lower status of the population - MEDV Median value of owner-occupied homes in $1000's :Missing Attribute Values: None :Creator: Harrison, D. and Rubinfeld, D.L.This is a copy of UCI ML housing dataset.http://archive.ics.uci.edu/ml/datasets/HousingThis dataset was taken from the StatLib library which is maintained at Carnegie Mellon University." }, { "code": null, "e": 7496, "s": 7163, "text": "Running data.feature_names and data.target would print the column names of the independent variables and the dependent variable, respectively. Meaning, Scikit-learn has already set the house value/price data as a target variable and 13 other variables are set as predictors. Let’s see how to run a linear regression on this dataset." }, { "code": null, "e": 7624, "s": 7496, "text": "First, we should load the data as a pandas data frame for easier analysis and set the median home value as our target variable:" }, { "code": null, "e": 7890, "s": 7624, "text": "import numpy as npimport pandas as pd# define the data/predictors as the pre-set feature names df = pd.DataFrame(data.data, columns=data.feature_names)# Put the target (housing value -- MEDV) in another DataFrametarget = pd.DataFrame(data.target, columns=[\"MEDV\"])" }, { "code": null, "e": 8186, "s": 7890, "text": "What we’ve done here is to take the dataset and load it as a pandas data frame; after that, we’re setting the predictors (as df) — the independent variables that are pre-set in the dataset. We’re also setting the target — the dependent variable, or the variable we’re trying to predict/estimate." }, { "code": null, "e": 8809, "s": 8186, "text": "Next we’ll want to fit a linear regression model. We need to choose variables that we think we’ll be good predictors for the dependent variable — that can be done by checking the correlation(s) between variables, by plotting the data and searching visually for relationship, by conducting preliminary research on what variables are good predictors of y etc. For this first example, let’s take RM — the average number of rooms and LSTAT — percentage of lower status of the population. It’s important to note that Statsmodels does not add a constant by default. Let’s see it first without a constant in our regression model:" }, { "code": null, "e": 9061, "s": 8809, "text": "## Without a constantimport statsmodels.api as smX = df[\"RM\"]y = target[\"MEDV\"]# Note the difference in argument ordermodel = sm.OLS(y, X).fit()predictions = model.predict(X) # make the predictions by the model# Print out the statisticsmodel.summary()" }, { "code": null, "e": 9073, "s": 9061, "text": "The output:" }, { "code": null, "e": 9659, "s": 9073, "text": "Interpreting the Table —This is a very long table, isn’t it? First we have what’s the dependent variable and the model and the method. OLS stands for Ordinary Least Squares and the method “Least Squares” means that we’re trying to fit a regression line that would minimize the square of distance from the regression line (see the previous section of this post). Date and Time are pretty self-explanatory :) So as number of observations. Df of residuals and models relates to the degrees of freedom — “the number of values in the final calculation of a statistic that are free to vary.”" }, { "code": null, "e": 10234, "s": 9659, "text": "The coefficient of 3.6534 means that as the RM variable increases by 1, the predicted value of MDEV increases by 3.6534. A few other important values are the R-squared — the percentage of variance our model explains; the standard error (is the standard deviation of the sampling distribution of a statistic, most commonly of the mean); the t scores and p-values, for hypothesis test — the RM has statistically significant p-value; there is a 95% confidence intervals for the RM (meaning we predict at a 95% percent confidence that the value of RM is between 3.548 to 3.759)." }, { "code": null, "e": 10429, "s": 10234, "text": "If we do want to add a constant to our model — we have to set it by using the command X = sm.add_constant(X) where X is the name of your data frame containing your input (independent) variables." }, { "code": null, "e": 10856, "s": 10429, "text": "import statsmodels.api as sm # import statsmodels X = df[\"RM\"] ## X usually means our input variables (or independent variables)y = target[\"MEDV\"] ## Y usually means our output/dependent variableX = sm.add_constant(X) ## let's add an intercept (beta_0) to our model# Note the difference in argument ordermodel = sm.OLS(y, X).fit() ## sm.OLS(output, input)predictions = model.predict(X)# Print out the statisticsmodel.summary()" }, { "code": null, "e": 10868, "s": 10856, "text": "The output:" }, { "code": null, "e": 11127, "s": 10868, "text": "Interpreting the Table — With the constant term the coefficients are different. Without a constant we are forcing our model to go through the origin, but now we have a y-intercept at -34.67. We also changed the slope of the RM predictor from 3.634 to 9.1021." }, { "code": null, "e": 11276, "s": 11127, "text": "Now let’s try fitting a regression model with more than one variable — we’ll be using RM and LSTAT I’ve mentioned before. Model fitting is the same:" }, { "code": null, "e": 11389, "s": 11276, "text": "X = df[[“RM”, “LSTAT”]]y = target[“MEDV”]model = sm.OLS(y, X).fit()predictions = model.predict(X)model.summary()" }, { "code": null, "e": 11405, "s": 11389, "text": "And the output:" }, { "code": null, "e": 12194, "s": 11405, "text": "Interpreting the Output — We can see here that this model has a much higher R-squared value — 0.948, meaning that this model explains 94.8% of the variance in our dependent variable. Whenever we add variables to a regression model, R2 will be higher, but this is a pretty high R2. We can see that both RM and LSTAT are statistically significant in predicting (or estimating) the median house value; not surprisingly , we see that as RM increases by 1, MEDV will increase by 4.9069 and when LSTAT increases by 1, MEDV will decrease by -0.6557. As you may remember, LSTAT is the percentage of lower status of the population, and unfortunately we can expect that it will lower the median value of houses. With this same logic, the more rooms in a house, usually the higher its value will be." }, { "code": null, "e": 12457, "s": 12194, "text": "This was the example of both single and multiple linear regression in Statsmodels. We could have used as little or as many variables we wanted in our regression model(s) — up to all the 13! Next, I will demonstrate how to run linear regression models in SKLearn." }, { "code": null, "e": 12812, "s": 12457, "text": "SKLearn is pretty much the golden standard when it comes to machine learning in Python. It has many learning algorithms, for regression, classification, clustering and dimensionality reduction. Check out my post on the KNN algorithm for a map of the different algorithms and more links to SKLearn. In order to use linear regression, we need to import it:" }, { "code": null, "e": 12845, "s": 12812, "text": "from sklearn import linear_model" }, { "code": null, "e": 13035, "s": 12845, "text": "Let’s use the same dataset we used before, the Boston housing prices. The process would be the same in the beginning — importing the datasets from SKLearn and loading in the Boston dataset:" }, { "code": null, "e": 13177, "s": 13035, "text": "from sklearn import datasets ## imports datasets from scikit-learndata = datasets.load_boston() ## loads Boston dataset from datasets library" }, { "code": null, "e": 13231, "s": 13177, "text": "Next, we’ll load the data to Pandas (same as before):" }, { "code": null, "e": 13460, "s": 13231, "text": "# define the data/predictors as the pre-set feature names df = pd.DataFrame(data.data, columns=data.feature_names)# Put the target (housing value -- MEDV) in another DataFrametarget = pd.DataFrame(data.target, columns=[\"MEDV\"])" }, { "code": null, "e": 13790, "s": 13460, "text": "So now, as before, we have the data frame that contains the independent variables (marked as “df”) and the data frame with the dependent variable (marked as “target”). Let’s fit a regression model using SKLearn. First we’ll define our X and y — this time I’ll use all the variables in the data frame to predict the housing price:" }, { "code": null, "e": 13815, "s": 13790, "text": "X = dfy = target[“MEDV”]" }, { "code": null, "e": 13842, "s": 13815, "text": "And then I’ll fit a model:" }, { "code": null, "e": 13898, "s": 13842, "text": "lm = linear_model.LinearRegression()model = lm.fit(X,y)" }, { "code": null, "e": 14044, "s": 13898, "text": "The lm.fit() function fits a linear model. We want to use the model to make predictions (that’s what we’re here for!), so we’ll use lm.predict():" }, { "code": null, "e": 14095, "s": 14044, "text": "predictions = lm.predict(X)print(predictions)[0:5]" }, { "code": null, "e": 14249, "s": 14095, "text": "The print function would print the first 5 predictions for y (I didn’t print the entire list to “save room”. Removing [0:5] would print the entire list):" }, { "code": null, "e": 14316, "s": 14249, "text": "[ 30.00821269 25.0298606 30.5702317 28.60814055 27.94288232]" }, { "code": null, "e": 14719, "s": 14316, "text": "Remember, lm.predict() predicts the y (dependent variable) using the linear model we fitted. You must have noticed that when we run a linear regression with SKLearn, we don’t get a pretty table (okay, it’s not that pretty... but it’s pretty useful) like in Statsmodels. What we can do is use built-in functions to return the score, the coefficients and the estimated intercepts. Let’s see how it works:" }, { "code": null, "e": 14733, "s": 14719, "text": "lm.score(X,y)" }, { "code": null, "e": 14757, "s": 14733, "text": "Would give this output:" }, { "code": null, "e": 14776, "s": 14757, "text": "0.7406077428649428" }, { "code": null, "e": 14996, "s": 14776, "text": "This is the R2 score of our model. As you probably remember, this the percentage of explained variance of the predictions. If you’re interested, read more here. Next, let’s check out the coefficients for the predictors:" }, { "code": null, "e": 15005, "s": 14996, "text": "lm.coef_" }, { "code": null, "e": 15028, "s": 15005, "text": "will give this output:" }, { "code": null, "e": 15294, "s": 15028, "text": "array([ -1.07170557e-01, 4.63952195e-02, 2.08602395e-02, 2.68856140e+00, -1.77957587e+01, 3.80475246e+00, 7.51061703e-04, -1.47575880e+00, 3.05655038e-01, -1.23293463e-02, -9.53463555e-01, 9.39251272e-03, -5.25466633e-01])" }, { "code": null, "e": 15313, "s": 15294, "text": "and the intercept:" }, { "code": null, "e": 15327, "s": 15313, "text": "lm.intercept_" }, { "code": null, "e": 15355, "s": 15327, "text": "that will give this output:" }, { "code": null, "e": 15374, "s": 15355, "text": "36.491103280363134" }, { "code": null, "e": 15545, "s": 15374, "text": "These are all (estimated/predicted) parts of the multiple regression equation I’ve mentioned earlier. Check out the documentation to read more about coef_ and intercept_." }, { "code": null, "e": 16010, "s": 15545, "text": "So, this is has a been a quick (but rather long!) introduction on how to conduct linear regression in Python. In practice, you would not use the entire dataset, but you will split your data into a training data to train your model on, and a test data — to, you guessed it, test your model/predictions on. If you would like to read about it, please check out my next blog post. In the meanwhile, I hope you enjoyed this post and that I’ll “see” you on the next one." } ]
LISP - Bitwise Operators
Bitwise operators work on bits and perform bit-by-bit operation. The truth tables for bitwise and, or, and xor operations are as follows − Assume if A = 60; and B = 13; now in binary format they will be as follows: A = 0011 1100 B = 0000 1101 ----------------- A and B = 0000 1100 A or B = 0011 1101 A xor B = 0011 0001 not A = 1100 0011 The Bitwise operators supported by LISP are listed in the following table. Assume variable A holds 60 and variable B holds 13, then − Create a new source code file named main.lisp and type the following code in it. (setq a 60) (setq b 13) (format t "~% BITWISE AND of a and b is ~a" (logand a b)) (format t "~% BITWISE INCLUSIVE OR of a and b is ~a" (logior a b)) (format t "~% BITWISE EXCLUSIVE OR of a and b is ~a" (logxor a b)) (format t "~% A NOT B is ~a" (lognor a b)) (format t "~% A EQUIVALANCE B is ~a" (logeqv a b)) (terpri) (terpri) (setq a 10) (setq b 0) (setq c 30) (setq d 40) (format t "~% Result of bitwise and operation on 10, 0, 30, 40 is ~a" (logand a b c d)) (format t "~% Result of bitwise or operation on 10, 0, 30, 40 is ~a" (logior a b c d)) (format t "~% Result of bitwise xor operation on 10, 0, 30, 40 is ~a" (logxor a b c d)) (format t "~% Result of bitwise eqivalance operation on 10, 0, 30, 40 is ~a" (logeqv a b c d)) When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is − BITWISE AND of a and b is 12 BITWISE INCLUSIVE OR of a and b is 61 BITWISE EXCLUSIVE OR of a and b is 49 A NOT B is -62 A EQUIVALANCE B is -50 Result of bitwise and operation on 10, 0, 30, 40 is 0 Result of bitwise or operation on 10, 0, 30, 40 is 62 Result of bitwise xor operation on 10, 0, 30, 40 is 60 Result of bitwise eqivalance operation on 10, 0, 30, 40 is -61 79 Lectures 7 hours Arnold Higuit Print Add Notes Bookmark this page
[ { "code": null, "e": 2199, "s": 2060, "text": "Bitwise operators work on bits and perform bit-by-bit operation. The truth tables for bitwise and, or, and xor operations are as follows −" }, { "code": null, "e": 2399, "s": 2199, "text": "Assume if A = 60; and B = 13; now in binary format they will be as follows:\nA = 0011 1100\nB = 0000 1101\n-----------------\nA and B = 0000 1100\nA or B = 0011 1101\nA xor B = 0011 0001\nnot A = 1100 0011" }, { "code": null, "e": 2533, "s": 2399, "text": "The Bitwise operators supported by LISP are listed in the following table. Assume variable A holds 60 and variable B holds 13, then −" }, { "code": null, "e": 2614, "s": 2533, "text": "Create a new source code file named main.lisp and type the following code in it." }, { "code": null, "e": 3351, "s": 2614, "text": "(setq a 60)\n(setq b 13)\n\n(format t \"~% BITWISE AND of a and b is ~a\" (logand a b))\n(format t \"~% BITWISE INCLUSIVE OR of a and b is ~a\" (logior a b))\n(format t \"~% BITWISE EXCLUSIVE OR of a and b is ~a\" (logxor a b))\n(format t \"~% A NOT B is ~a\" (lognor a b))\n(format t \"~% A EQUIVALANCE B is ~a\" (logeqv a b))\n\n(terpri)\n(terpri)\n\n(setq a 10)\n(setq b 0)\n(setq c 30)\n(setq d 40)\n\n(format t \"~% Result of bitwise and operation on 10, 0, 30, 40 is ~a\" (logand a b c d))\n(format t \"~% Result of bitwise or operation on 10, 0, 30, 40 is ~a\" (logior a b c d))\n(format t \"~% Result of bitwise xor operation on 10, 0, 30, 40 is ~a\" (logxor a b c d))\n(format t \"~% Result of bitwise eqivalance operation on 10, 0, 30, 40 is ~a\" (logeqv a b c d))" }, { "code": null, "e": 3460, "s": 3351, "text": "When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −" }, { "code": null, "e": 3831, "s": 3460, "text": "BITWISE AND of a and b is 12\nBITWISE INCLUSIVE OR of a and b is 61\nBITWISE EXCLUSIVE OR of a and b is 49\nA NOT B is -62\nA EQUIVALANCE B is -50\n\nResult of bitwise and operation on 10, 0, 30, 40 is 0\nResult of bitwise or operation on 10, 0, 30, 40 is 62\nResult of bitwise xor operation on 10, 0, 30, 40 is 60\nResult of bitwise eqivalance operation on 10, 0, 30, 40 is -61\n" }, { "code": null, "e": 3864, "s": 3831, "text": "\n 79 Lectures \n 7 hours \n" }, { "code": null, "e": 3879, "s": 3864, "text": " Arnold Higuit" }, { "code": null, "e": 3886, "s": 3879, "text": " Print" }, { "code": null, "e": 3897, "s": 3886, "text": " Add Notes" } ]
Exception and Exception Classes
In general, an exception is any unusual condition. Exception usually indicates errors but sometimes they intentionally puts in the program, in cases like terminating a procedure early or recovering from a resource shortage. There are number of built-in exceptions, which indicate conditions like reading past the end of a file, or dividing by zero. We can define our own exceptions called custom exception. Exception handling enables you handle errors gracefully and do something meaningful about it. Exception handling has two components: “throwing” and ‘catching’. Every error occurs in Python result an exception which will an error condition identified by its error type. >>> #Exception >>> 1/0 Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> 1/0 ZeroDivisionError: division by zero >>> >>> var = 20 >>> print(ver) Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> print(ver) NameError: name 'ver' is not defined >>> #Above as we have misspelled a variable name so we get an NameError. >>> >>> print('hello) SyntaxError: EOL while scanning string literal >>> #Above we have not closed the quote in a string, so we get SyntaxError. >>> >>> #Below we are asking for a key, that doen't exists. >>> mydict = {} >>> mydict['x'] Traceback (most recent call last): File "<pyshell#15>", line 1, in <module> mydict['x'] KeyError: 'x' >>> #Above keyError >>> >>> #Below asking for a index that didn't exist in a list. >>> mylist = [1,2,3,4] >>> mylist[5] Traceback (most recent call last): File "<pyshell#20>", line 1, in <module> mylist[5] IndexError: list index out of range >>> #Above, index out of range, raised IndexError. When something unusual occurs in your program and you wish to handle it using the exception mechanism, you ‘throw an exception’. The keywords try and except are used to catch exceptions. Whenever an error occurs within a try block, Python looks for a matching except block to handle it. If there is one, execution jumps there. try: #write some code #that might throw some exception except <ExceptionType>: # Exception handler, alert the user The code within the try clause will be executed statement by statement. If an exception occurs, the rest of the try block will be skipped and the except clause will be executed. try: some statement here except: exception handling Let’s write some code to see what happens when you not use any error handling mechanism in your program. number = int(input('Please enter the number between 1 & 10: ')) print('You have entered number',number) Above programme will work correctly as long as the user enters a number, but what happens if the users try to puts some other data type(like a string or a list). Please enter the number between 1 > 10: 'Hi' Traceback (most recent call last): File "C:/Python/Python361/exception2.py", line 1, in <module> number = int(input('Please enter the number between 1 & 10: ')) ValueError: invalid literal for int() with base 10: "'Hi'" Now ValueError is an exception type. Let’s try to rewrite the above code with exception handling. import sys print('Previous code with exception handling') try: number = int(input('Enter number between 1 > 10: ')) except(ValueError): print('Error..numbers only') sys.exit() print('You have entered number: ',number) If we run the program, and enter a string (instead of a number), we can see that we get a different result. Previous code with exception handling Enter number between 1 > 10: 'Hi' Error..numbers only To raise your exceptions from your own methods you need to use raise keyword like this raise ExceptionClass(‘Some Text Here’) Let’s take an example def enterAge(age): if age<0: raise ValueError('Only positive integers are allowed') if age % 2 ==0: print('Entered Age is even') else: print('Entered Age is odd') try: num = int(input('Enter your age: ')) enterAge(num) except ValueError: print('Only positive integers are allowed') Run the program and enter positive integer. Enter your age: 12 Entered Age is even But when we try to enter a negative number we get, Enter your age: -2 Only positive integers are allowed You can create a custom exception class by Extending BaseException class or subclass of BaseException. From above diagram we can see most of the exception classes in Python extends from the BaseException class. You can derive your own exception class from BaseException class or from its subclass. Create a new file called NegativeNumberException.py and write the following code. class NegativeNumberException(RuntimeError): def __init__(self, age): super().__init__() self.age = age Above code creates a new exception class named NegativeNumberException, which consists of only constructor which call parent class constructor using super()__init__() and sets the age. Now to create your own custom exception class, will write some code and import the new exception class. from NegativeNumberException import NegativeNumberException def enterage(age): if age < 0: raise NegativeNumberException('Only positive integers are allowed') if age % 2 == 0: print('Age is Even') else: print('Age is Odd') try: num = int(input('Enter your age: ')) enterage(num) except NegativeNumberException: print('Only positive integers are allowed') except: print('Something is wrong') Enter your age: -2 Only positive integers are allowed Another way to create a custom Exception class. class customException(Exception): def __init__(self, value): self.parameter = value def __str__(self): return repr(self.parameter) try: raise customException('My Useful Error Message!') except customException as instance: print('Caught: ' + instance.parameter) Caught: My Useful Error Message! The class hierarchy for built-in exceptions is − +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- StopIteration +-- StopAsyncIteration +-- ArithmeticError | +-- FloatingPointError | +-- OverflowError | +-- ZeroDivisionError +-- AssertionError +-- AttributeError +-- BufferError +-- EOFError +-- ImportError +-- LookupError | +-- IndexError | +-- KeyError +-- MemoryError +-- NameError | +-- UnboundLocalError +-- OSError | +-- BlockingIOError | +-- ChildProcessError | +-- ConnectionError | | +-- BrokenPipeError | | +-- ConnectionAbortedError | | +-- ConnectionRefusedError | | +-- ConnectionResetError | +-- FileExistsError | +-- FileNotFoundError | +-- InterruptedError | +-- IsADirectoryError | +-- NotADirectoryError | +-- PermissionError | +-- ProcessLookupError | +-- TimeoutError +-- ReferenceError +-- RuntimeError | +-- NotImplementedError | +-- RecursionError +-- SyntaxError | +-- IndentationError | +-- TabError +-- SystemError +-- TypeError +-- ValueError | +-- UnicodeError | +-- UnicodeDecodeError | +-- UnicodeEncodeError | +-- UnicodeTranslateError +-- Warning +-- DeprecationWarning +-- PendingDeprecationWarning +-- RuntimeWarning +-- SyntaxWarning +-- UserWarning +-- FutureWarning +-- ImportWarning +-- UnicodeWarning +-- BytesWarning +-- ResourceWarning 14 Lectures 1.5 hours Harshit Srivastava 60 Lectures 8 hours DigiFisk (Programming Is Fun) 11 Lectures 35 mins Sandip Bhattacharya 21 Lectures 2 hours Pranjal Srivastava 6 Lectures 43 mins Frahaan Hussain 49 Lectures 4.5 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2217, "s": 1810, "text": "In general, an exception is any unusual condition. Exception usually indicates errors but sometimes they intentionally puts in the program, in cases like terminating a procedure early or recovering from a resource shortage. There are number of built-in exceptions, which indicate conditions like reading past the end of a file, or dividing by zero. We can define our own exceptions called custom exception." }, { "code": null, "e": 2377, "s": 2217, "text": "Exception handling enables you handle errors gracefully and do something meaningful about it. Exception handling has two components: “throwing” and ‘catching’." }, { "code": null, "e": 2486, "s": 2377, "text": "Every error occurs in Python result an exception which will an error condition identified by its error type." }, { "code": null, "e": 3521, "s": 2486, "text": ">>> #Exception\n>>> 1/0\nTraceback (most recent call last):\n File \"<pyshell#2>\", line 1, in <module>\n 1/0\nZeroDivisionError: division by zero\n>>>\n>>> var = 20\n>>> print(ver)\nTraceback (most recent call last):\n File \"<pyshell#5>\", line 1, in <module>\n print(ver)\nNameError: name 'ver' is not defined\n>>> #Above as we have misspelled a variable name so we get an NameError.\n>>>\n>>> print('hello)\n\nSyntaxError: EOL while scanning string literal\n>>> #Above we have not closed the quote in a string, so we get SyntaxError.\n>>>\n>>> #Below we are asking for a key, that doen't exists.\n>>> mydict = {}\n>>> mydict['x']\nTraceback (most recent call last):\n File \"<pyshell#15>\", line 1, in <module>\n mydict['x']\nKeyError: 'x'\n>>> #Above keyError\n>>>\n>>> #Below asking for a index that didn't exist in a list.\n>>> mylist = [1,2,3,4]\n>>> mylist[5]\nTraceback (most recent call last):\n File \"<pyshell#20>\", line 1, in <module>\n mylist[5]\nIndexError: list index out of range\n>>> #Above, index out of range, raised IndexError." }, { "code": null, "e": 3848, "s": 3521, "text": "When something unusual occurs in your program and you wish to handle it using the exception mechanism, you ‘throw an exception’. The keywords try and except are used to catch exceptions. Whenever an error occurs within a try block, Python looks for a matching except block to handle it. If there is one, execution jumps there." }, { "code": null, "e": 3973, "s": 3848, "text": "try:\n #write some code\n #that might throw some exception\nexcept <ExceptionType>:\n # Exception handler, alert the user\n" }, { "code": null, "e": 4045, "s": 3973, "text": "The code within the try clause will be executed statement by statement." }, { "code": null, "e": 4151, "s": 4045, "text": "If an exception occurs, the rest of the try block will be skipped and the except clause will be executed." }, { "code": null, "e": 4209, "s": 4151, "text": "try:\n some statement here\nexcept:\n exception handling" }, { "code": null, "e": 4314, "s": 4209, "text": "Let’s write some code to see what happens when you not use any error handling mechanism in your program." }, { "code": null, "e": 4418, "s": 4314, "text": "number = int(input('Please enter the number between 1 & 10: '))\nprint('You have entered number',number)" }, { "code": null, "e": 4580, "s": 4418, "text": "Above programme will work correctly as long as the user enters a number, but what happens if the users try to puts some other data type(like a string or a list)." }, { "code": null, "e": 4854, "s": 4580, "text": "Please enter the number between 1 > 10: 'Hi'\nTraceback (most recent call last):\n File \"C:/Python/Python361/exception2.py\", line 1, in <module>\n number = int(input('Please enter the number between 1 & 10: '))\nValueError: invalid literal for int() with base 10: \"'Hi'\"" }, { "code": null, "e": 4952, "s": 4854, "text": "Now ValueError is an exception type. Let’s try to rewrite the above code with exception handling." }, { "code": null, "e": 5183, "s": 4952, "text": "import sys\n\nprint('Previous code with exception handling')\n\ntry:\n number = int(input('Enter number between 1 > 10: '))\n\nexcept(ValueError):\n print('Error..numbers only')\n sys.exit()\n\nprint('You have entered number: ',number)" }, { "code": null, "e": 5291, "s": 5183, "text": "If we run the program, and enter a string (instead of a number), we can see that we get a different result." }, { "code": null, "e": 5383, "s": 5291, "text": "Previous code with exception handling\nEnter number between 1 > 10: 'Hi'\nError..numbers only" }, { "code": null, "e": 5470, "s": 5383, "text": "To raise your exceptions from your own methods you need to use raise keyword like this" }, { "code": null, "e": 5509, "s": 5470, "text": "raise ExceptionClass(‘Some Text Here’)" }, { "code": null, "e": 5531, "s": 5509, "text": "Let’s take an example" }, { "code": null, "e": 5850, "s": 5531, "text": "def enterAge(age):\n if age<0:\n raise ValueError('Only positive integers are allowed')\n if age % 2 ==0:\n print('Entered Age is even')\n else:\n print('Entered Age is odd')\n\ntry:\n num = int(input('Enter your age: '))\n enterAge(num)\nexcept ValueError:\n print('Only positive integers are allowed')" }, { "code": null, "e": 5894, "s": 5850, "text": "Run the program and enter positive integer." }, { "code": null, "e": 5934, "s": 5894, "text": "Enter your age: 12\nEntered Age is even\n" }, { "code": null, "e": 5985, "s": 5934, "text": "But when we try to enter a negative number we get," }, { "code": null, "e": 6040, "s": 5985, "text": "Enter your age: -2\nOnly positive integers are allowed\n" }, { "code": null, "e": 6143, "s": 6040, "text": "You can create a custom exception class by Extending BaseException class or subclass of BaseException." }, { "code": null, "e": 6338, "s": 6143, "text": "From above diagram we can see most of the exception classes in Python extends from the BaseException class. You can derive your own exception class from BaseException class or from its subclass." }, { "code": null, "e": 6420, "s": 6338, "text": "Create a new file called NegativeNumberException.py and write the following code." }, { "code": null, "e": 6539, "s": 6420, "text": "class NegativeNumberException(RuntimeError):\n def __init__(self, age):\n super().__init__()\n self.age = age" }, { "code": null, "e": 6724, "s": 6539, "text": "Above code creates a new exception class named NegativeNumberException, which consists of only constructor which call parent class constructor using super()__init__() and sets the age." }, { "code": null, "e": 6828, "s": 6724, "text": "Now to create your own custom exception class, will write some code and import the new exception class." }, { "code": null, "e": 7261, "s": 6828, "text": "from NegativeNumberException import NegativeNumberException\ndef enterage(age):\n if age < 0:\n raise NegativeNumberException('Only positive integers are allowed')\n\n if age % 2 == 0:\n print('Age is Even')\n\n else:\n print('Age is Odd')\n\ntry:\n num = int(input('Enter your age: '))\n enterage(num)\nexcept NegativeNumberException:\n print('Only positive integers are allowed')\nexcept:\n print('Something is wrong')" }, { "code": null, "e": 7316, "s": 7261, "text": "Enter your age: -2\nOnly positive integers are allowed\n" }, { "code": null, "e": 7364, "s": 7316, "text": "Another way to create a custom Exception class." }, { "code": null, "e": 7650, "s": 7364, "text": "class customException(Exception):\n def __init__(self, value):\n self.parameter = value\n\n def __str__(self):\n return repr(self.parameter)\ntry:\n raise customException('My Useful Error Message!')\nexcept customException as instance:\n print('Caught: ' + instance.parameter)" }, { "code": null, "e": 7684, "s": 7650, "text": "Caught: My Useful Error Message!\n" }, { "code": null, "e": 7733, "s": 7684, "text": "The class hierarchy for built-in exceptions is −" }, { "code": null, "e": 9046, "s": 7733, "text": "+-- SystemExit \n+-- KeyboardInterrupt \n+-- GeneratorExit \n+-- Exception \n+-- StopIteration \n+-- StopAsyncIteration \n+-- ArithmeticError \n| +-- FloatingPointError \n| +-- OverflowError \n| +-- ZeroDivisionError \n+-- AssertionError \n+-- AttributeError \n+-- BufferError \n+-- EOFError \n+-- ImportError \n+-- LookupError \n| +-- IndexError \n| +-- KeyError \n+-- MemoryError \n+-- NameError \n| +-- UnboundLocalError \n+-- OSError \n| +-- BlockingIOError \n| +-- ChildProcessError \n| +-- ConnectionError \n| | +-- BrokenPipeError \n| | +-- ConnectionAbortedError \n| | +-- ConnectionRefusedError \n| | +-- ConnectionResetError \n| +-- FileExistsError \n| +-- FileNotFoundError \n| +-- InterruptedError \n| +-- IsADirectoryError \n| +-- NotADirectoryError \n| +-- PermissionError \n| +-- ProcessLookupError \n| +-- TimeoutError \n+-- ReferenceError \n+-- RuntimeError \n| +-- NotImplementedError \n| +-- RecursionError \n+-- SyntaxError \n| +-- IndentationError\n| +-- TabError \n+-- SystemError \n+-- TypeError \n+-- ValueError \n| +-- UnicodeError \n| +-- UnicodeDecodeError \n| +-- UnicodeEncodeError \n| +-- UnicodeTranslateError \n+-- Warning \n+-- DeprecationWarning \n+-- PendingDeprecationWarning \n+-- RuntimeWarning \n+-- SyntaxWarning \n+-- UserWarning \n+-- FutureWarning \n+-- ImportWarning \n+-- UnicodeWarning \n+-- BytesWarning \n+-- ResourceWarning\n" }, { "code": null, "e": 9081, "s": 9046, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9101, "s": 9081, "text": " Harshit Srivastava" }, { "code": null, "e": 9134, "s": 9101, "text": "\n 60 Lectures \n 8 hours \n" }, { "code": null, "e": 9165, "s": 9134, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 9197, "s": 9165, "text": "\n 11 Lectures \n 35 mins\n" }, { "code": null, "e": 9218, "s": 9197, "text": " Sandip Bhattacharya" }, { "code": null, "e": 9251, "s": 9218, "text": "\n 21 Lectures \n 2 hours \n" }, { "code": null, "e": 9271, "s": 9251, "text": " Pranjal Srivastava" }, { "code": null, "e": 9302, "s": 9271, "text": "\n 6 Lectures \n 43 mins\n" }, { "code": null, "e": 9319, "s": 9302, "text": " Frahaan Hussain" }, { "code": null, "e": 9354, "s": 9319, "text": "\n 49 Lectures \n 4.5 hours \n" }, { "code": null, "e": 9371, "s": 9354, "text": " Abhilash Nelson" }, { "code": null, "e": 9378, "s": 9371, "text": " Print" }, { "code": null, "e": 9389, "s": 9378, "text": " Add Notes" } ]
How to Analyze Emotions and Words of the Lyrics From your Favorite Music Artist | by Cristóbal Veas | Towards Data Science
Music is a powerful language to express our feelings and in many cases is used as a therapy to deal with tough moments in our lives. The different sounds, rhythms, and effects used in music are capable to modify our emotions for a moment, but there’s a component that sometimes goes unnoticed when we are listening to music; The Lyrics of the songs. Lyrics are powerful texts who share the ideas that came from the mind of the author when the song was been created. That’s why I decided to analyze the lyrics of one of my favorite bands; Metallica. Metallica has had a noticeable change of concepts and ideas on their song lyrics throughout their music career and considering they started playing music in the ’80s until now, this band is a good option to study. In this article, I will expose and explain how I could achieve this idea using Word Clouds, a Statistics Table, Frequency Comparision Plot of Words, VADER Sentiment Analysis, and a cool Dataset provided by Genius. So with no more to say, let’s start working!. Pandas and Numpy for data analysis. Re and String for data cleaning. Matplotlib and Wordcloud to plot nice graphs. NLTK for Sentiment Analysis, Tokenization, and Lemmatization. Sklearn to count words frequency. Lyricsgenius to extract the data of lyrics. Genius Credentials to access their Apis and Data acquisition (click here for more info). Script Helpers.py that stores the functions used to extract, clean, and transform the data (this script was created by me, and is located on my GitHub repository) #libraries used to extract, clean and manipulate the datafrom helpers import *import pandas as pdimport numpy as npimport string#To plot the graphsfrom wordcloud import WordCloudimport matplotlib.pyplot as pltplt.style.use('seaborn')#library used to count the frequency of wordsfrom sklearn.feature_extraction.text import CountVectorizer#To create the sentiment analysis model, tokenization and lemmatizationimport nltkfrom nltk.sentiment.vader import SentimentIntensityAnalyzerfrom nltk import word_tokenizeimport nltk.datanltk.download('vader_lexicon')nltk.download('punkt') Full code, scripts, notebooks, and data are on my Github Repository (click here) The first step is to obtain information on the most popular songs by the artist. to do that, I created a function called search_data() that helps to automatize the process to collect the attributes of each song. This function uses the library lyricsgenius to obtain the data and you must pass the parameters of the artist name, max number of songs to extract, and your client access token: #Extracting the information of the 50 most popular songs of Metallica using function created on helpers scriptaccess_token = "your_genius_access_token"df0 = search_data('Metallica',50,access_token) As you may notice, the lyric column has a lot of words and symbols that are not important to study because they are used to explain the structure of the song, so I cleaned this information using the function clean_data() and also creating a new column to group songs by decade. This new column will help us to have a better understanding when analyzing the data. Finally, I filtered the information to just use songs that have lyrics because some artists have instrumental songs. #cleaning and transforming the data using functions created on helpers scriptdf = clean_lyrics(df0,'lyric')#Create the decades columndf = create_decades(df)#Filter data to use songs that have lyrics.df = df[df['lyric'].notnull()]#Save the data into a csv filedf.to_csv('lyrics.csv',index=False)df.head(10) Now we have a clean data frame to start creating our data frame of words. You can access the CSV file of this data clicking here. To have a complete analysis of Metallica lyrics I wanted to take a look at how they tend to use words on different decades. So I had to create a Dataframe of words based on the lyrics of each song. To do that, first I considered unique words by lyrics due to some of the songs repeat the same words on the chorus part. I defined a function called unique to do this process, the parameter corresponds to a list of words def unique(list1): # intilize a null list unique_list = [] # traverse for all elements for x in list1: # check if exists in unique_list or not if x not in unique_list: unique_list.append(x) return unique_list Then I use the following code to store the unique words of lyrics with the function defined above and another function called lyrics_to_words that you can find on the helpers script. I saved this information on a new column called words on the data frame of lyrics. #Stores unique words of each lyrics song into a new column called words#list used to store the wordswords = []#iterate trought each lyric and split unique words appending the result into the words listdf = df.reset_index(drop=True)for word in df['lyric'].tolist(): words.append(unique(lyrics_to_words(word).split()))#create the new column with the information of words listsdf['words'] = wordsdf.head() As you may notice now we have a column that stores the unique words for each song used in lyrics. But this is the first step to create our data frame of words. The next step is to use this new words column, count how many times a unique word is used on songs lyrics by decade, and store all these results into a new data frame of 5 columns, one for words and the others for the frequency of occurrence by decade. It’s important to consider remove your own stopwords depending on each data in case the clean function does not remove all of them. Stopwords are natural language words that have very little meaning, such as “and”, “the”, “a”, “an”, and similar words. #Create a new dataframe of all the words used in lyrics and its decades#list used to store the informationset_words = []set_decades = []#Iterate trought each word and decade and stores them into the new listsfor i in df.index: for word in df['words'].iloc[i]: set_words.append(word) set_decades.append(df['decade'].iloc[i])#create the new data frame with the information of words and decade listswords_df = pd.DataFrame({'words':set_words,'decade':set_decades})#Defined your own Stopwords in case the clean data function does not remove all of themstop_words =['verse','im','get','1000','58','60','80','youre','youve', 'guitar','solo','instrumental','intro','pre',"3"]# count the frequency of each word that aren't on the stop_words listscv = CountVectorizer(stop_words=stop_words)#Create a dataframe called data_cv to store the the number of times the word was used in a lyric based their decadestext_cv = cv.fit_transform(words_df['words'].iloc[:])data_cv = pd.DataFrame(text_cv.toarray(),columns=cv.get_feature_names())data_cv['decade'] = words_df['decade']#created a dataframe that Sums the ocurrence frequency of each word and group the result by decadevect_words = data_cv.groupby('decade').sum().Tvect_words = vect_words.reset_index(level=0).rename(columns ={'index':'words'})vect_words = vect_words.rename_axis(columns='')#Save the data into a csv filevect_words.to_csv('words.csv',index=False)#change the order of columns to order from the oldest to actual decadevect_words = vect_words[['words','80s','90s','00s','10s']]vect_words you can access to look the code clicking here. This Data Frame is interesting and useful because it shows us how many times Metallica used a word on the lyrics of their songs depending on the decade the song was released. For instance, the word young was used in 1 song in the 1980s, 2 songs in the 1990s, and 0 times in the 2000s, and 2010s. You can access the CSV file of this data clicking here. To start analyzing the words used by Metallica to create their song lyrics, I wanted to answer a lot of questions that I had in mind. These questions are: Which are the most frequent words used on their song lyrics by decade? How many words are used per song? Which are the total of words and unique words used by decade? How is the comparison of the most frequent words used in a specific decade to the other decades? Cited by Google a Word Cloud is “an image composed of words used in a particular text or subject, in which the size of each word indicates its frequency or importance”. For this purpose, the Word Cloud is grouped by decade and will show us which are the most frequent words used in song lyrics of Metallica during the different decades. I used the libraries Matplotlib and Wordcloud to create this graph with a function where you must pass the data frame, the number of rows, and columns of the figure depending on the decades you want to plot. In my case, I have 4 decades (80s, 90s, 00s, 10s) and I want the graph in a 2x2 format. def plot_wordcloud(df,row,col): wc = WordCloud(background_color="white",colormap="Dark2", max_font_size=100,random_state=15) fig = plt.figure(figsize=(20,10)) for index, value in enumerate(df.columns[1:]): top_dict = dict(zip(df['words'].tolist(),df[value].tolist())) wc.generate_from_frequencies(top_dict) plt.subplot(row,col,index+1) plt.imshow(wc,interpolation="bilinear") plt.axis("off") plt.title(f"{value}",fontsize=15)plt.subplots_adjust(wspace=0.1, hspace=0.1) plt.show()#Plot the word cloudplot_wordcloud(vect_words,2,2) It’s cool to observe the differences among the words used during the different decades of Metallica musical career. During the 80s words are focused on concepts related yo death and life and in the 10s words are about more deep concepts about feelings. I also defined a function to calculate some Stats for the number of words in the different periods of decades. You must pass as parameters, the data frame of lyrics, and the data frame of words. I used the following code to create the table: def words_stats(df,main_df): unique_words = [] total_words = [] total_news = [] years = [] for value in df.columns[1:]: unique_words.append(np.count_nonzero(df[value])) total_words.append(sum(df[value])) years.append(str(value)) total_news.append(main_df['decade' [main_df['decade']==value].count())data = pd.DataFrame({'decade':years, 'unique words':unique_words, 'total words':total_words, 'total songs':total_news})data['words per songs'] = round(data['total words'] / data['total songs'],0)data['words per songs'] = data['words per songs'].astype('int')return data#display the table of statisticswords_stats(vect_words,df) With this table, we can show a lot of information about the songs and the Lyrics of Metallica. For instance, the 1980s have more number of words and songs, and that’s because the most famous songs were released during this decade. Word per song of the 2000s is less than the rest of the decades, maybe we can infer that during the 2000s songs are shorter in time than the other decades. Another cool analysis that can help us to understand this data is taking a look at the tendency among the most frequent words used in a decade compared to the frequency of the same words in other decades. Using the function below you can create a line plot to look the tendency for a set of common words in a specific decade. for instance, if I want to compare the 10 most common words of the 1980s to the other decades I must pass this information and the data frame of words as parameters to the function: def plot_freq_words(df,decade,n_words): top_words_2020 = df.sort_values([decade],ascending=False).head(n_words)fig = plt.figure(figsize=(15,8))plt.plot(top_words_2020['words'],top_words_2020[df.columns[1]]) plt.plot(top_words_2020['words'],top_words_2020[df.columns[2]]) plt.plot(top_words_2020['words'],top_words_2020[df.columns[3]]) plt.plot(top_words_2020['words'],top_words_2020[df.columns[4]])plt.legend(df.columns[1:].tolist()) plt.title(f"Most frequent words in {decade} compared with other decades",fontsize=14) plt.xlabel(f'Most Frequent Words of {decade}',fontsize=12) plt.ylabel('Frecuency',fontsize=12) plt.xticks(fontsize=12,rotation=20) plt.yticks(fontsize=12) plt.show()#Ploting the comparision plotplot_freq_words(vect_words,'80s',10) As you may notice during the 1980s the first 2 most common words used in lyrics of Metallica are Life and Death with a frequency of 12 for both words. But during the 1990s just life was used only in 6 lyrics and Death in just 1 for the rest of the decades. VADER (Valence Aware Dictionary and sEntiment Reasoner) of the NLKT Python Library is a lexicon and rule-based sentiment analysis tool. VADER uses a combination of A sentiment lexicon is a list of lexical features (e.g., words) which are generally labeled according to their semantic orientation as either positive or negative. VADER model uses 4 different Sentiment Metrics. Negative, Neutral, and Positive metrics represent the proportion of text that falls in these categories. Compound Metric calculates the sum of all the lexicon rating, which is normalizer between -1(max limit of negativity) and 1(max limit of positivity). If you want to read more information about the VADER metrics, click here. I used the following code to calculate the 4 metrics for the Songs Lyrics of the Data Frame. #Create lists to store the different scores for each wordnegative = []neutral = []positive = []compound = []#Initialize the modelsid = SentimentIntensityAnalyzer()#Iterate for each row of lyrics and append the scoresfor i in df.index: scores = sid.polarity_scores(df['lyric'].iloc[i]) negative.append(scores['neg']) neutral.append(scores['neu']) positive.append(scores['pos']) compound.append(scores['compound'])#Create 4 columns to the main data frame for each scoredf['negative'] = negativedf['neutral'] = neutraldf['positive'] = positivedf['compound'] = compounddf.head() Now a good way to vizualize the results are plotting the songs and their respectives Sentiment Metrics on a Scatter Plot using Matplotlib Library. In this case I plotted the Negative Score and the Positive Score for each lyric grouped by decade. for name, group in df.groupby('decade'): plt.scatter(group['positive'],group['negative'],label=name) plt.legend(fontsize=10)plt.xlim([-0.05,0.7])plt.ylim([-0.05,0.7])plt.title("Lyrics Sentiments by Decade")plt.xlabel('Positive Valence')plt.ylabel('Negative Valence')plt.show() Analyzing this plot I can inferred that the Lyrics of Metallica’s songs tends to have more Negative Valence, so for leading to generate a little more of negative feelings. I also wanted to analyze the sentiment but using the mean of scores by decade. so I just group by decade the main Data frame having this result. means_df = df.groupby(['decade']).mean()means_df for name, group in means_df.groupby('decade'): plt.scatter(group['positive'],group['negative'],label=name) plt.legend()plt.xlim([-0.05,0.7])plt.ylim([-0.05,0.7])plt.title("Lyrics Sentiments by Decade")plt.xlabel('Positive Valence')plt.ylabel('Negative Valence')plt.show() I realized that the 90s Songs Lyrics of Metallica tends to have more positive valence than the other decades. That’s really insteresting considering the most famous exposition of Metallica in the mainstream music was during the 90s. Most Famous songs of Metallica were released during the 1980s. The first lyrics of Metallica Songs used words related death, live hell and kill topics and over the years this lyrics were changed to deepest human feelings using words like fear, pain and rise. The lyrics of the songs released in the 1990s have a little more of positive feelings rather the other decades. In the 2010s Metallica used 323 unique words to create the lyrics of 6 songs. The number of words per lyrics are in a range between 50 and 70. To conclude this article we learnt how to use a new technique to analyze words and text sentiments applied to Music. The advantage that people have living in this modern decade rather the past decades are astonishing. I mean, using simple techniques in the comfort of your home to create amazing researchs and projects, it allows us keep growing as society and taking advantage of the technology to achieve our goals and enjoy the time doing interesting things. This article will have a second part where I will try to find which are the main Topics, Concepts and Ideas that Metallica expose on their songs lyrics.
[ { "code": null, "e": 522, "s": 172, "text": "Music is a powerful language to express our feelings and in many cases is used as a therapy to deal with tough moments in our lives. The different sounds, rhythms, and effects used in music are capable to modify our emotions for a moment, but there’s a component that sometimes goes unnoticed when we are listening to music; The Lyrics of the songs." }, { "code": null, "e": 721, "s": 522, "text": "Lyrics are powerful texts who share the ideas that came from the mind of the author when the song was been created. That’s why I decided to analyze the lyrics of one of my favorite bands; Metallica." }, { "code": null, "e": 935, "s": 721, "text": "Metallica has had a noticeable change of concepts and ideas on their song lyrics throughout their music career and considering they started playing music in the ’80s until now, this band is a good option to study." }, { "code": null, "e": 1195, "s": 935, "text": "In this article, I will expose and explain how I could achieve this idea using Word Clouds, a Statistics Table, Frequency Comparision Plot of Words, VADER Sentiment Analysis, and a cool Dataset provided by Genius. So with no more to say, let’s start working!." }, { "code": null, "e": 1231, "s": 1195, "text": "Pandas and Numpy for data analysis." }, { "code": null, "e": 1264, "s": 1231, "text": "Re and String for data cleaning." }, { "code": null, "e": 1310, "s": 1264, "text": "Matplotlib and Wordcloud to plot nice graphs." }, { "code": null, "e": 1372, "s": 1310, "text": "NLTK for Sentiment Analysis, Tokenization, and Lemmatization." }, { "code": null, "e": 1406, "s": 1372, "text": "Sklearn to count words frequency." }, { "code": null, "e": 1450, "s": 1406, "text": "Lyricsgenius to extract the data of lyrics." }, { "code": null, "e": 1539, "s": 1450, "text": "Genius Credentials to access their Apis and Data acquisition (click here for more info)." }, { "code": null, "e": 1702, "s": 1539, "text": "Script Helpers.py that stores the functions used to extract, clean, and transform the data (this script was created by me, and is located on my GitHub repository)" }, { "code": null, "e": 2279, "s": 1702, "text": "#libraries used to extract, clean and manipulate the datafrom helpers import *import pandas as pdimport numpy as npimport string#To plot the graphsfrom wordcloud import WordCloudimport matplotlib.pyplot as pltplt.style.use('seaborn')#library used to count the frequency of wordsfrom sklearn.feature_extraction.text import CountVectorizer#To create the sentiment analysis model, tokenization and lemmatizationimport nltkfrom nltk.sentiment.vader import SentimentIntensityAnalyzerfrom nltk import word_tokenizeimport nltk.datanltk.download('vader_lexicon')nltk.download('punkt')" }, { "code": null, "e": 2347, "s": 2279, "text": "Full code, scripts, notebooks, and data are on my Github Repository" }, { "code": null, "e": 2360, "s": 2347, "text": "(click here)" }, { "code": null, "e": 2750, "s": 2360, "text": "The first step is to obtain information on the most popular songs by the artist. to do that, I created a function called search_data() that helps to automatize the process to collect the attributes of each song. This function uses the library lyricsgenius to obtain the data and you must pass the parameters of the artist name, max number of songs to extract, and your client access token:" }, { "code": null, "e": 2948, "s": 2750, "text": "#Extracting the information of the 50 most popular songs of Metallica using function created on helpers scriptaccess_token = \"your_genius_access_token\"df0 = search_data('Metallica',50,access_token)" }, { "code": null, "e": 3428, "s": 2948, "text": "As you may notice, the lyric column has a lot of words and symbols that are not important to study because they are used to explain the structure of the song, so I cleaned this information using the function clean_data() and also creating a new column to group songs by decade. This new column will help us to have a better understanding when analyzing the data. Finally, I filtered the information to just use songs that have lyrics because some artists have instrumental songs." }, { "code": null, "e": 3735, "s": 3428, "text": "#cleaning and transforming the data using functions created on helpers scriptdf = clean_lyrics(df0,'lyric')#Create the decades columndf = create_decades(df)#Filter data to use songs that have lyrics.df = df[df['lyric'].notnull()]#Save the data into a csv filedf.to_csv('lyrics.csv',index=False)df.head(10)" }, { "code": null, "e": 3865, "s": 3735, "text": "Now we have a clean data frame to start creating our data frame of words. You can access the CSV file of this data clicking here." }, { "code": null, "e": 4284, "s": 3865, "text": "To have a complete analysis of Metallica lyrics I wanted to take a look at how they tend to use words on different decades. So I had to create a Dataframe of words based on the lyrics of each song. To do that, first I considered unique words by lyrics due to some of the songs repeat the same words on the chorus part. I defined a function called unique to do this process, the parameter corresponds to a list of words" }, { "code": null, "e": 4538, "s": 4284, "text": "def unique(list1): # intilize a null list unique_list = [] # traverse for all elements for x in list1: # check if exists in unique_list or not if x not in unique_list: unique_list.append(x) return unique_list" }, { "code": null, "e": 4804, "s": 4538, "text": "Then I use the following code to store the unique words of lyrics with the function defined above and another function called lyrics_to_words that you can find on the helpers script. I saved this information on a new column called words on the data frame of lyrics." }, { "code": null, "e": 5210, "s": 4804, "text": "#Stores unique words of each lyrics song into a new column called words#list used to store the wordswords = []#iterate trought each lyric and split unique words appending the result into the words listdf = df.reset_index(drop=True)for word in df['lyric'].tolist(): words.append(unique(lyrics_to_words(word).split()))#create the new column with the information of words listsdf['words'] = wordsdf.head()" }, { "code": null, "e": 5308, "s": 5210, "text": "As you may notice now we have a column that stores the unique words for each song used in lyrics." }, { "code": null, "e": 5623, "s": 5308, "text": "But this is the first step to create our data frame of words. The next step is to use this new words column, count how many times a unique word is used on songs lyrics by decade, and store all these results into a new data frame of 5 columns, one for words and the others for the frequency of occurrence by decade." }, { "code": null, "e": 5875, "s": 5623, "text": "It’s important to consider remove your own stopwords depending on each data in case the clean function does not remove all of them. Stopwords are natural language words that have very little meaning, such as “and”, “the”, “a”, “an”, and similar words." }, { "code": null, "e": 7435, "s": 5875, "text": "#Create a new dataframe of all the words used in lyrics and its decades#list used to store the informationset_words = []set_decades = []#Iterate trought each word and decade and stores them into the new listsfor i in df.index: for word in df['words'].iloc[i]: set_words.append(word) set_decades.append(df['decade'].iloc[i])#create the new data frame with the information of words and decade listswords_df = pd.DataFrame({'words':set_words,'decade':set_decades})#Defined your own Stopwords in case the clean data function does not remove all of themstop_words =['verse','im','get','1000','58','60','80','youre','youve', 'guitar','solo','instrumental','intro','pre',\"3\"]# count the frequency of each word that aren't on the stop_words listscv = CountVectorizer(stop_words=stop_words)#Create a dataframe called data_cv to store the the number of times the word was used in a lyric based their decadestext_cv = cv.fit_transform(words_df['words'].iloc[:])data_cv = pd.DataFrame(text_cv.toarray(),columns=cv.get_feature_names())data_cv['decade'] = words_df['decade']#created a dataframe that Sums the ocurrence frequency of each word and group the result by decadevect_words = data_cv.groupby('decade').sum().Tvect_words = vect_words.reset_index(level=0).rename(columns ={'index':'words'})vect_words = vect_words.rename_axis(columns='')#Save the data into a csv filevect_words.to_csv('words.csv',index=False)#change the order of columns to order from the oldest to actual decadevect_words = vect_words[['words','80s','90s','00s','10s']]vect_words" }, { "code": null, "e": 7482, "s": 7435, "text": "you can access to look the code clicking here." }, { "code": null, "e": 7778, "s": 7482, "text": "This Data Frame is interesting and useful because it shows us how many times Metallica used a word on the lyrics of their songs depending on the decade the song was released. For instance, the word young was used in 1 song in the 1980s, 2 songs in the 1990s, and 0 times in the 2000s, and 2010s." }, { "code": null, "e": 7834, "s": 7778, "text": "You can access the CSV file of this data clicking here." }, { "code": null, "e": 7989, "s": 7834, "text": "To start analyzing the words used by Metallica to create their song lyrics, I wanted to answer a lot of questions that I had in mind. These questions are:" }, { "code": null, "e": 8060, "s": 7989, "text": "Which are the most frequent words used on their song lyrics by decade?" }, { "code": null, "e": 8094, "s": 8060, "text": "How many words are used per song?" }, { "code": null, "e": 8156, "s": 8094, "text": "Which are the total of words and unique words used by decade?" }, { "code": null, "e": 8253, "s": 8156, "text": "How is the comparison of the most frequent words used in a specific decade to the other decades?" }, { "code": null, "e": 8590, "s": 8253, "text": "Cited by Google a Word Cloud is “an image composed of words used in a particular text or subject, in which the size of each word indicates its frequency or importance”. For this purpose, the Word Cloud is grouped by decade and will show us which are the most frequent words used in song lyrics of Metallica during the different decades." }, { "code": null, "e": 8886, "s": 8590, "text": "I used the libraries Matplotlib and Wordcloud to create this graph with a function where you must pass the data frame, the number of rows, and columns of the figure depending on the decades you want to plot. In my case, I have 4 decades (80s, 90s, 00s, 10s) and I want the graph in a 2x2 format." }, { "code": null, "e": 9492, "s": 8886, "text": "def plot_wordcloud(df,row,col): wc = WordCloud(background_color=\"white\",colormap=\"Dark2\", max_font_size=100,random_state=15) fig = plt.figure(figsize=(20,10)) for index, value in enumerate(df.columns[1:]): top_dict = dict(zip(df['words'].tolist(),df[value].tolist())) wc.generate_from_frequencies(top_dict) plt.subplot(row,col,index+1) plt.imshow(wc,interpolation=\"bilinear\") plt.axis(\"off\") plt.title(f\"{value}\",fontsize=15)plt.subplots_adjust(wspace=0.1, hspace=0.1) plt.show()#Plot the word cloudplot_wordcloud(vect_words,2,2)" }, { "code": null, "e": 9745, "s": 9492, "text": "It’s cool to observe the differences among the words used during the different decades of Metallica musical career. During the 80s words are focused on concepts related yo death and life and in the 10s words are about more deep concepts about feelings." }, { "code": null, "e": 9987, "s": 9745, "text": "I also defined a function to calculate some Stats for the number of words in the different periods of decades. You must pass as parameters, the data frame of lyrics, and the data frame of words. I used the following code to create the table:" }, { "code": null, "e": 10757, "s": 9987, "text": "def words_stats(df,main_df): unique_words = [] total_words = [] total_news = [] years = [] for value in df.columns[1:]: unique_words.append(np.count_nonzero(df[value])) total_words.append(sum(df[value])) years.append(str(value)) total_news.append(main_df['decade' [main_df['decade']==value].count())data = pd.DataFrame({'decade':years, 'unique words':unique_words, 'total words':total_words, 'total songs':total_news})data['words per songs'] = round(data['total words'] / data['total songs'],0)data['words per songs'] = data['words per songs'].astype('int')return data#display the table of statisticswords_stats(vect_words,df)" }, { "code": null, "e": 11144, "s": 10757, "text": "With this table, we can show a lot of information about the songs and the Lyrics of Metallica. For instance, the 1980s have more number of words and songs, and that’s because the most famous songs were released during this decade. Word per song of the 2000s is less than the rest of the decades, maybe we can infer that during the 2000s songs are shorter in time than the other decades." }, { "code": null, "e": 11349, "s": 11144, "text": "Another cool analysis that can help us to understand this data is taking a look at the tendency among the most frequent words used in a decade compared to the frequency of the same words in other decades." }, { "code": null, "e": 11652, "s": 11349, "text": "Using the function below you can create a line plot to look the tendency for a set of common words in a specific decade. for instance, if I want to compare the 10 most common words of the 1980s to the other decades I must pass this information and the data frame of words as parameters to the function:" }, { "code": null, "e": 12445, "s": 11652, "text": "def plot_freq_words(df,decade,n_words): top_words_2020 = df.sort_values([decade],ascending=False).head(n_words)fig = plt.figure(figsize=(15,8))plt.plot(top_words_2020['words'],top_words_2020[df.columns[1]]) plt.plot(top_words_2020['words'],top_words_2020[df.columns[2]]) plt.plot(top_words_2020['words'],top_words_2020[df.columns[3]]) plt.plot(top_words_2020['words'],top_words_2020[df.columns[4]])plt.legend(df.columns[1:].tolist()) plt.title(f\"Most frequent words in {decade} compared with other decades\",fontsize=14) plt.xlabel(f'Most Frequent Words of {decade}',fontsize=12) plt.ylabel('Frecuency',fontsize=12) plt.xticks(fontsize=12,rotation=20) plt.yticks(fontsize=12) plt.show()#Ploting the comparision plotplot_freq_words(vect_words,'80s',10)" }, { "code": null, "e": 12702, "s": 12445, "text": "As you may notice during the 1980s the first 2 most common words used in lyrics of Metallica are Life and Death with a frequency of 12 for both words. But during the 1990s just life was used only in 6 lyrics and Death in just 1 for the rest of the decades." }, { "code": null, "e": 13078, "s": 12702, "text": "VADER (Valence Aware Dictionary and sEntiment Reasoner) of the NLKT Python Library is a lexicon and rule-based sentiment analysis tool. VADER uses a combination of A sentiment lexicon is a list of lexical features (e.g., words) which are generally labeled according to their semantic orientation as either positive or negative. VADER model uses 4 different Sentiment Metrics." }, { "code": null, "e": 13183, "s": 13078, "text": "Negative, Neutral, and Positive metrics represent the proportion of text that falls in these categories." }, { "code": null, "e": 13333, "s": 13183, "text": "Compound Metric calculates the sum of all the lexicon rating, which is normalizer between -1(max limit of negativity) and 1(max limit of positivity)." }, { "code": null, "e": 13407, "s": 13333, "text": "If you want to read more information about the VADER metrics, click here." }, { "code": null, "e": 13500, "s": 13407, "text": "I used the following code to calculate the 4 metrics for the Songs Lyrics of the Data Frame." }, { "code": null, "e": 14091, "s": 13500, "text": "#Create lists to store the different scores for each wordnegative = []neutral = []positive = []compound = []#Initialize the modelsid = SentimentIntensityAnalyzer()#Iterate for each row of lyrics and append the scoresfor i in df.index: scores = sid.polarity_scores(df['lyric'].iloc[i]) negative.append(scores['neg']) neutral.append(scores['neu']) positive.append(scores['pos']) compound.append(scores['compound'])#Create 4 columns to the main data frame for each scoredf['negative'] = negativedf['neutral'] = neutraldf['positive'] = positivedf['compound'] = compounddf.head()" }, { "code": null, "e": 14337, "s": 14091, "text": "Now a good way to vizualize the results are plotting the songs and their respectives Sentiment Metrics on a Scatter Plot using Matplotlib Library. In this case I plotted the Negative Score and the Positive Score for each lyric grouped by decade." }, { "code": null, "e": 14621, "s": 14337, "text": "for name, group in df.groupby('decade'): plt.scatter(group['positive'],group['negative'],label=name) plt.legend(fontsize=10)plt.xlim([-0.05,0.7])plt.ylim([-0.05,0.7])plt.title(\"Lyrics Sentiments by Decade\")plt.xlabel('Positive Valence')plt.ylabel('Negative Valence')plt.show()" }, { "code": null, "e": 14793, "s": 14621, "text": "Analyzing this plot I can inferred that the Lyrics of Metallica’s songs tends to have more Negative Valence, so for leading to generate a little more of negative feelings." }, { "code": null, "e": 14938, "s": 14793, "text": "I also wanted to analyze the sentiment but using the mean of scores by decade. so I just group by decade the main Data frame having this result." }, { "code": null, "e": 14987, "s": 14938, "text": "means_df = df.groupby(['decade']).mean()means_df" }, { "code": null, "e": 15266, "s": 14987, "text": "for name, group in means_df.groupby('decade'): plt.scatter(group['positive'],group['negative'],label=name) plt.legend()plt.xlim([-0.05,0.7])plt.ylim([-0.05,0.7])plt.title(\"Lyrics Sentiments by Decade\")plt.xlabel('Positive Valence')plt.ylabel('Negative Valence')plt.show()" }, { "code": null, "e": 15499, "s": 15266, "text": "I realized that the 90s Songs Lyrics of Metallica tends to have more positive valence than the other decades. That’s really insteresting considering the most famous exposition of Metallica in the mainstream music was during the 90s." }, { "code": null, "e": 15562, "s": 15499, "text": "Most Famous songs of Metallica were released during the 1980s." }, { "code": null, "e": 15758, "s": 15562, "text": "The first lyrics of Metallica Songs used words related death, live hell and kill topics and over the years this lyrics were changed to deepest human feelings using words like fear, pain and rise." }, { "code": null, "e": 15870, "s": 15758, "text": "The lyrics of the songs released in the 1990s have a little more of positive feelings rather the other decades." }, { "code": null, "e": 15948, "s": 15870, "text": "In the 2010s Metallica used 323 unique words to create the lyrics of 6 songs." }, { "code": null, "e": 16013, "s": 15948, "text": "The number of words per lyrics are in a range between 50 and 70." }, { "code": null, "e": 16475, "s": 16013, "text": "To conclude this article we learnt how to use a new technique to analyze words and text sentiments applied to Music. The advantage that people have living in this modern decade rather the past decades are astonishing. I mean, using simple techniques in the comfort of your home to create amazing researchs and projects, it allows us keep growing as society and taking advantage of the technology to achieve our goals and enjoy the time doing interesting things." } ]
Group with multiple fields and get the count of duplicate field values grouped together in MongoDB
For this, use MongoDB aggregate and within that, use $cond. The $cond evaluates a boolean expression to return one of the two specified return expressions. Let us first create a collection with documents − > db.demo536.insertOne({"Name1":"Chris","Name2":"David"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8c843eef4dcbee04fbbc01") } > db.demo536.insertOne({"Name1":"David","Name2":"Chris"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8c843fef4dcbee04fbbc02") } > db.demo536.insertOne({"Name1":"Bob","Name2":"Sam"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8c843fef4dcbee04fbbc03") } > db.demo536.insertOne({"Name1":"Chris","Name2":"David"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8c843fef4dcbee04fbbc04") } Display all documents from a collection with the help of find() method − > db.demo536.find(); This will produce the following output − { "_id" : ObjectId("5e8c843eef4dcbee04fbbc01"), "Name1" : "Chris", "Name2" : "David" } { "_id" : ObjectId("5e8c843fef4dcbee04fbbc02"), "Name1" : "David", "Name2" : "Chris" } { "_id" : ObjectId("5e8c843fef4dcbee04fbbc03"), "Name1" : "Bob", "Name2" : "Sam" } { "_id" : ObjectId("5e8c843fef4dcbee04fbbc04"), "Name1" : "Chris", "Name2" : "David" } Following is the query to group with multiple fields − > db.demo536.aggregate([ ... { ... $project: ... { ... FirstName1: ... { ... $cond: { if: { $gte: [ "$Name1", "$Name2" ] }, then: "$Name2", else: "$Name1" } ... }, ... FirstName2: ... { ... $cond: { if: { $lt: [ "$Name1", "$Name2" ] }, then: "$Name2", else: "$Name1" } ... } ... } ... } ... ,{ ... $group: ... { ... _id: ... { ... Name1: "$FirstName1", ... Name2: "$FirstName2" ... } ... ,count: { $sum: 1} ... } ... } ... ]) This will produce the following output &imnus; { "_id" : { "Name1" : "Bob", "Name2" : "Sam" }, "count" : 1 } { "_id" : { "Name1" : "Chris", "Name2" : "David" }, "count" : 3 }
[ { "code": null, "e": 1218, "s": 1062, "text": "For this, use MongoDB aggregate and within that, use $cond. The $cond evaluates a boolean expression to return one of the two specified return expressions." }, { "code": null, "e": 1268, "s": 1218, "text": "Let us first create a collection with documents −" }, { "code": null, "e": 1836, "s": 1268, "text": "> db.demo536.insertOne({\"Name1\":\"Chris\",\"Name2\":\"David\"});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e8c843eef4dcbee04fbbc01\")\n}\n> db.demo536.insertOne({\"Name1\":\"David\",\"Name2\":\"Chris\"});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e8c843fef4dcbee04fbbc02\")\n}\n> db.demo536.insertOne({\"Name1\":\"Bob\",\"Name2\":\"Sam\"});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e8c843fef4dcbee04fbbc03\")\n}\n> db.demo536.insertOne({\"Name1\":\"Chris\",\"Name2\":\"David\"});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e8c843fef4dcbee04fbbc04\")\n}" }, { "code": null, "e": 1909, "s": 1836, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1930, "s": 1909, "text": "> db.demo536.find();" }, { "code": null, "e": 1971, "s": 1930, "text": "This will produce the following output −" }, { "code": null, "e": 2315, "s": 1971, "text": "{ \"_id\" : ObjectId(\"5e8c843eef4dcbee04fbbc01\"), \"Name1\" : \"Chris\", \"Name2\" : \"David\" }\n{ \"_id\" : ObjectId(\"5e8c843fef4dcbee04fbbc02\"), \"Name1\" : \"David\", \"Name2\" : \"Chris\" }\n{ \"_id\" : ObjectId(\"5e8c843fef4dcbee04fbbc03\"), \"Name1\" : \"Bob\", \"Name2\" : \"Sam\" }\n{ \"_id\" : ObjectId(\"5e8c843fef4dcbee04fbbc04\"), \"Name1\" : \"Chris\", \"Name2\" : \"David\" }" }, { "code": null, "e": 2370, "s": 2315, "text": "Following is the query to group with multiple fields −" }, { "code": null, "e": 2910, "s": 2370, "text": "> db.demo536.aggregate([\n... {\n... $project:\n... {\n... FirstName1:\n... {\n... $cond: { if: { $gte: [ \"$Name1\", \"$Name2\" ] }, then: \"$Name2\", else: \"$Name1\" }\n... },\n... FirstName2:\n... {\n... $cond: { if: { $lt: [ \"$Name1\", \"$Name2\" ] }, then: \"$Name2\", else: \"$Name1\" }\n... }\n... }\n... }\n... ,{\n... $group:\n... {\n... _id:\n... {\n... Name1: \"$FirstName1\",\n... Name2: \"$FirstName2\"\n... }\n... ,count: { $sum: 1}\n... }\n... }\n... ])" }, { "code": null, "e": 2957, "s": 2910, "text": "This will produce the following output &imnus;" }, { "code": null, "e": 3085, "s": 2957, "text": "{ \"_id\" : { \"Name1\" : \"Bob\", \"Name2\" : \"Sam\" }, \"count\" : 1 }\n{ \"_id\" : { \"Name1\" : \"Chris\", \"Name2\" : \"David\" }, \"count\" : 3 }" } ]
Elixir - Case Statement
Case statement can be considered as a replacement for the switch statement in imperative languages. Case takes a variable/literal and applies pattern matching to it with different cases. If any case matches, Elixir executes the code associated with that case and exits the case statement. If no match is found, it exits the statement with an CaseClauseError that displays no matching clauses were found. You should always have a case with _ which matches all values. This helps in prevention of the above mentioned error. Also this is comparable to the default case in switch-case statements. The syntax of an if statement is as follows − case value do matcher_1 -> #code to execute if value matches matcher_1 matcher_2 -> #code to execute if value matches matcher_2 matcher_3 -> #code to execute if value matches matcher_3 ... _ -> #code to execute if value does not match any of the above end case 3 do 1 -> IO.puts("Hi, I'm one") 2 -> IO.puts("Hi, I'm two") 3 -> IO.puts("Hi, I'm three") _ -> IO.puts("Oops, you dont match!") end The above program generates the following result. Hi, I'm three Note that the case selection is done using pattern matching, so you can use the standard pattern matching techniques. 35 Lectures 3 hours Pranjal Srivastava 54 Lectures 6 hours Pranjal Srivastava, Harshit Srivastava 80 Lectures 9.5 hours Pranjal Srivastava 43 Lectures 4 hours Mohammad Nauman Print Add Notes Bookmark this page
[ { "code": null, "e": 2775, "s": 2182, "text": "Case statement can be considered as a replacement for the switch statement in imperative languages. Case takes a variable/literal and applies pattern matching to it with different cases. If any case matches, Elixir executes the code associated with that case and exits the case statement. If no match is found, it exits the statement with an CaseClauseError that displays no matching clauses were found. You should always have a case with _ which matches all values. This helps in prevention of the above mentioned error. Also this is comparable to the default case in switch-case statements." }, { "code": null, "e": 2821, "s": 2775, "text": "The syntax of an if statement is as follows −" }, { "code": null, "e": 3088, "s": 2821, "text": "case value do\n matcher_1 -> #code to execute if value matches matcher_1\n\tmatcher_2 -> #code to execute if value matches matcher_2\n\tmatcher_3 -> #code to execute if value matches matcher_3\n\t...\n\t_ -> #code to execute if value does not match any of the above\nend\n" }, { "code": null, "e": 3238, "s": 3088, "text": "case 3 do\n 1 -> IO.puts(\"Hi, I'm one\")\n 2 -> IO.puts(\"Hi, I'm two\")\n 3 -> IO.puts(\"Hi, I'm three\")\n _ -> IO.puts(\"Oops, you dont match!\")\nend" }, { "code": null, "e": 3288, "s": 3238, "text": "The above program generates the following result." }, { "code": null, "e": 3303, "s": 3288, "text": "Hi, I'm three\n" }, { "code": null, "e": 3421, "s": 3303, "text": "Note that the case selection is done using pattern matching, so you can use the standard pattern matching techniques." }, { "code": null, "e": 3454, "s": 3421, "text": "\n 35 Lectures \n 3 hours \n" }, { "code": null, "e": 3474, "s": 3454, "text": " Pranjal Srivastava" }, { "code": null, "e": 3507, "s": 3474, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 3547, "s": 3507, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 3582, "s": 3547, "text": "\n 80 Lectures \n 9.5 hours \n" }, { "code": null, "e": 3602, "s": 3582, "text": " Pranjal Srivastava" }, { "code": null, "e": 3635, "s": 3602, "text": "\n 43 Lectures \n 4 hours \n" }, { "code": null, "e": 3652, "s": 3635, "text": " Mohammad Nauman" }, { "code": null, "e": 3659, "s": 3652, "text": " Print" }, { "code": null, "e": 3670, "s": 3659, "text": " Add Notes" } ]
How to change Tkinter label text on button press?
Most often, Tkinter Label widgets are used in the application to display the text or images. We can configure the label widget such as its text property, color, background or foreground color using the config(**options) method. If you need to modify or change the label widget dynamically, then you can use a button and a function to change the text of the label widget. # Import the required libraries from tkinter import * # Create an instance of tkinter frame or window win = Tk() # Set the size of the tkinter window win.geometry("700x350") # Define a function update the label text def on_click(): label["text"] = "Python" b["state"] = "disabled" # Create a label widget label = Label(win, text="Click the Button to update this Text", font=('Calibri 15 bold')) label.pack(pady=20) # Create a button to update the label widget b = Button(win, text="Update Label", command=on_click) b.pack(pady=20) win.mainloop() When you run the above code, it will show a label text and a button in the window. When you click the button, it will just update the label text.
[ { "code": null, "e": 1290, "s": 1062, "text": "Most often, Tkinter Label widgets are used in the application to display the text or images. We can configure the label widget such as its text property, color, background or foreground color using the config(**options) method." }, { "code": null, "e": 1433, "s": 1290, "text": "If you need to modify or change the label widget dynamically, then you can use a button and a function to change the text of the label widget." }, { "code": null, "e": 1991, "s": 1433, "text": "# Import the required libraries\nfrom tkinter import *\n\n# Create an instance of tkinter frame or window\nwin = Tk()\n\n# Set the size of the tkinter window\nwin.geometry(\"700x350\")\n\n# Define a function update the label text\ndef on_click():\n label[\"text\"] = \"Python\"\n b[\"state\"] = \"disabled\"\n\n# Create a label widget\nlabel = Label(win, text=\"Click the Button to update this Text\",\nfont=('Calibri 15 bold'))\nlabel.pack(pady=20)\n\n# Create a button to update the label widget\nb = Button(win, text=\"Update Label\", command=on_click)\nb.pack(pady=20)\n\nwin.mainloop()" }, { "code": null, "e": 2074, "s": 1991, "text": "When you run the above code, it will show a label text and a button in the window." }, { "code": null, "e": 2137, "s": 2074, "text": "When you click the button, it will just update the label text." } ]
How to compare two slices of bytes in Golang? - GeeksforGeeks
26 Aug, 2019 In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice, you are allowed to compare two slices of the byte type with each other using Compare() function. This function returns an integer value which represents that these slices are equal or not and the values are: If the result is 0, then slice_1 == slice_2. If the result is -1, then slice_1 < slice_2. If the result is +1, then slice_1 > slice_2. This function is defined under the bytes package so, you have to import bytes package in your program for accessing Compare function. Syntax: func Compare(slice_1, slice_2 []byte) int Let us discuss this concept with the help of the examples: Example 1: // Go program to illustrate how to// compare two slices of bytespackage main import ( "bytes" "fmt") // Main functionfunc main() { // Creating and initializing // slices of bytes // Using shorthand declaration slice_1 := []byte{'G', 'E', 'E', 'K', 'S'} slice_2 := []byte{'G', 'E', 'e', 'K', 'S'} // Comparing slice // Using Compare function res := bytes.Compare(slice_1, slice_2) if res == 0 { fmt.Println("!..Slices are equal..!") } else { fmt.Println("!..Slice are not equal..!") }} Output: !..Slice are not equal..! Example 2: // Go program to illustrate how// to compare two slices of bytepackage main import ( "bytes" "fmt") func main() { // Creating and initializing // slices of bytes // Using shorthand declaration slice_1 := []byte{'A', 'N', 'M', 'O', 'P', 'Q'} slice_2 := []byte{'a', 'g', 't', 'e', 'q', 'm'} slice_3 := []byte{'A', 'N', 'M', 'O', 'P', 'Q'} slice_4 := []byte{'A', 'n', 'M', 'o', 'p', 'Q'} // Displaying slices fmt.Println("Slice 1: ", slice_1) fmt.Println("Slice 2: ", slice_2) fmt.Println("Slice 3: ", slice_3) fmt.Println("Slice 4: ", slice_4) // Comparing slices // Using Compare function res1 := bytes.Compare(slice_1, slice_2) res2 := bytes.Compare(slice_1, slice_3) res3 := bytes.Compare(slice_1, slice_4) res4 := bytes.Compare(slice_2, slice_3) res5 := bytes.Compare(slice_2, slice_4) res6 := bytes.Compare(slice_2, slice_1) res7 := bytes.Compare(slice_3, slice_1) res8 := bytes.Compare(slice_3, slice_2) res9 := bytes.Compare(slice_3, slice_4) res10 := bytes.Compare(slice_4, slice_1) res11 := bytes.Compare(slice_4, slice_2) res12 := bytes.Compare(slice_4, slice_3) res13 := bytes.Compare(slice_4, slice_4) // Displaying results fmt.Println("\nResult 1:", res1) fmt.Println("Result 2:", res2) fmt.Println("Result 3:", res3) fmt.Println("Result 4:", res4) fmt.Println("Result 5:", res5) fmt.Println("Result 6:", res6) fmt.Println("Result 7:", res7) fmt.Println("Result 8:", res8) fmt.Println("Result 9:", res9) fmt.Println("Result 10:", res10) fmt.Println("Result 11:", res11) fmt.Println("Result 12:", res12) fmt.Println("Result 13:", res13)} Output: Slice 1: [65 78 77 79 80 81] Slice 2: [97 103 116 101 113 109] Slice 3: [65 78 77 79 80 81] Slice 4: [65 110 77 111 112 81] Result 1: -1 Result 2: 0 Result 3: -1 Result 4: 1 Result 5: 1 Result 6: 1 Result 7: 0 Result 8: -1 Result 9: -1 Result 10: 1 Result 11: -1 Result 12: 1 Result 13: 0 Golang Golang-Slices Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. strings.Replace() Function in Golang With Examples How to Split a String in Golang? Arrays in Go Golang Maps Slices in Golang How to compare times in Golang? How to Trim a String in Golang? Inheritance in GoLang Different Ways to Find the Type of Variable in Golang How to Parse JSON in Golang?
[ { "code": null, "e": 24436, "s": 24408, "text": "\n26 Aug, 2019" }, { "code": null, "e": 24929, "s": 24436, "text": "In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice, you are allowed to compare two slices of the byte type with each other using Compare() function. This function returns an integer value which represents that these slices are equal or not and the values are:" }, { "code": null, "e": 24974, "s": 24929, "text": "If the result is 0, then slice_1 == slice_2." }, { "code": null, "e": 25019, "s": 24974, "text": "If the result is -1, then slice_1 < slice_2." }, { "code": null, "e": 25064, "s": 25019, "text": "If the result is +1, then slice_1 > slice_2." }, { "code": null, "e": 25198, "s": 25064, "text": "This function is defined under the bytes package so, you have to import bytes package in your program for accessing Compare function." }, { "code": null, "e": 25206, "s": 25198, "text": "Syntax:" }, { "code": null, "e": 25248, "s": 25206, "text": "func Compare(slice_1, slice_2 []byte) int" }, { "code": null, "e": 25307, "s": 25248, "text": "Let us discuss this concept with the help of the examples:" }, { "code": null, "e": 25318, "s": 25307, "text": "Example 1:" }, { "code": "// Go program to illustrate how to// compare two slices of bytespackage main import ( \"bytes\" \"fmt\") // Main functionfunc main() { // Creating and initializing // slices of bytes // Using shorthand declaration slice_1 := []byte{'G', 'E', 'E', 'K', 'S'} slice_2 := []byte{'G', 'E', 'e', 'K', 'S'} // Comparing slice // Using Compare function res := bytes.Compare(slice_1, slice_2) if res == 0 { fmt.Println(\"!..Slices are equal..!\") } else { fmt.Println(\"!..Slice are not equal..!\") }}", "e": 25866, "s": 25318, "text": null }, { "code": null, "e": 25874, "s": 25866, "text": "Output:" }, { "code": null, "e": 25900, "s": 25874, "text": "!..Slice are not equal..!" }, { "code": null, "e": 25911, "s": 25900, "text": "Example 2:" }, { "code": "// Go program to illustrate how// to compare two slices of bytepackage main import ( \"bytes\" \"fmt\") func main() { // Creating and initializing // slices of bytes // Using shorthand declaration slice_1 := []byte{'A', 'N', 'M', 'O', 'P', 'Q'} slice_2 := []byte{'a', 'g', 't', 'e', 'q', 'm'} slice_3 := []byte{'A', 'N', 'M', 'O', 'P', 'Q'} slice_4 := []byte{'A', 'n', 'M', 'o', 'p', 'Q'} // Displaying slices fmt.Println(\"Slice 1: \", slice_1) fmt.Println(\"Slice 2: \", slice_2) fmt.Println(\"Slice 3: \", slice_3) fmt.Println(\"Slice 4: \", slice_4) // Comparing slices // Using Compare function res1 := bytes.Compare(slice_1, slice_2) res2 := bytes.Compare(slice_1, slice_3) res3 := bytes.Compare(slice_1, slice_4) res4 := bytes.Compare(slice_2, slice_3) res5 := bytes.Compare(slice_2, slice_4) res6 := bytes.Compare(slice_2, slice_1) res7 := bytes.Compare(slice_3, slice_1) res8 := bytes.Compare(slice_3, slice_2) res9 := bytes.Compare(slice_3, slice_4) res10 := bytes.Compare(slice_4, slice_1) res11 := bytes.Compare(slice_4, slice_2) res12 := bytes.Compare(slice_4, slice_3) res13 := bytes.Compare(slice_4, slice_4) // Displaying results fmt.Println(\"\\nResult 1:\", res1) fmt.Println(\"Result 2:\", res2) fmt.Println(\"Result 3:\", res3) fmt.Println(\"Result 4:\", res4) fmt.Println(\"Result 5:\", res5) fmt.Println(\"Result 6:\", res6) fmt.Println(\"Result 7:\", res7) fmt.Println(\"Result 8:\", res8) fmt.Println(\"Result 9:\", res9) fmt.Println(\"Result 10:\", res10) fmt.Println(\"Result 11:\", res11) fmt.Println(\"Result 12:\", res12) fmt.Println(\"Result 13:\", res13)}", "e": 27598, "s": 25911, "text": null }, { "code": null, "e": 27606, "s": 27598, "text": "Output:" }, { "code": null, "e": 27901, "s": 27606, "text": "Slice 1: [65 78 77 79 80 81]\nSlice 2: [97 103 116 101 113 109]\nSlice 3: [65 78 77 79 80 81]\nSlice 4: [65 110 77 111 112 81]\n\nResult 1: -1\nResult 2: 0\nResult 3: -1\nResult 4: 1\nResult 5: 1\nResult 6: 1\nResult 7: 0\nResult 8: -1\nResult 9: -1\nResult 10: 1\nResult 11: -1\nResult 12: 1\nResult 13: 0\n" }, { "code": null, "e": 27908, "s": 27901, "text": "Golang" }, { "code": null, "e": 27922, "s": 27908, "text": "Golang-Slices" }, { "code": null, "e": 27934, "s": 27922, "text": "Go Language" }, { "code": null, "e": 28032, "s": 27934, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28083, "s": 28032, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 28116, "s": 28083, "text": "How to Split a String in Golang?" }, { "code": null, "e": 28129, "s": 28116, "text": "Arrays in Go" }, { "code": null, "e": 28141, "s": 28129, "text": "Golang Maps" }, { "code": null, "e": 28158, "s": 28141, "text": "Slices in Golang" }, { "code": null, "e": 28190, "s": 28158, "text": "How to compare times in Golang?" }, { "code": null, "e": 28222, "s": 28190, "text": "How to Trim a String in Golang?" }, { "code": null, "e": 28244, "s": 28222, "text": "Inheritance in GoLang" }, { "code": null, "e": 28298, "s": 28244, "text": "Different Ways to Find the Type of Variable in Golang" } ]
How to show a bar and line graph on the same plot in Matplotlib?
To show a bar and line graph on the same plot in matplotlib, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Set the figure size and adjust the padding between and around the subplots. Make a two-dimensional, size-mutable, potentially heterogeneous tabular data. Make a two-dimensional, size-mutable, potentially heterogeneous tabular data. Create a figure and a set of subplots. Create a figure and a set of subplots. Plot the bar and line with the dataframe obtained from Step 2. Plot the bar and line with the dataframe obtained from Step 2. To display the figure, use show() method. To display the figure, use show() method. import pandas as pd import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True df = pd.DataFrame(dict(data=[2, 4, 1, 5, 9, 6, 0, 7])) fig, ax = plt.subplots() df['data'].plot(kind='bar', color='red') df['data'].plot(kind='line', marker='*', color='black', ms=10) plt.show()
[ { "code": null, "e": 1157, "s": 1062, "text": "To show a bar and line graph on the same plot in matplotlib, we can take the following steps −" }, { "code": null, "e": 1233, "s": 1157, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1309, "s": 1233, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1387, "s": 1309, "text": "Make a two-dimensional, size-mutable, potentially heterogeneous tabular data." }, { "code": null, "e": 1465, "s": 1387, "text": "Make a two-dimensional, size-mutable, potentially heterogeneous tabular data." }, { "code": null, "e": 1504, "s": 1465, "text": "Create a figure and a set of subplots." }, { "code": null, "e": 1543, "s": 1504, "text": "Create a figure and a set of subplots." }, { "code": null, "e": 1606, "s": 1543, "text": "Plot the bar and line with the dataframe obtained from Step 2." }, { "code": null, "e": 1669, "s": 1606, "text": "Plot the bar and line with the dataframe obtained from Step 2." }, { "code": null, "e": 1711, "s": 1669, "text": "To display the figure, use show() method." }, { "code": null, "e": 1753, "s": 1711, "text": "To display the figure, use show() method." }, { "code": null, "e": 2091, "s": 1753, "text": "import pandas as pd\nimport matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ndf = pd.DataFrame(dict(data=[2, 4, 1, 5, 9, 6, 0, 7]))\nfig, ax = plt.subplots()\n\ndf['data'].plot(kind='bar', color='red')\ndf['data'].plot(kind='line', marker='*', color='black', ms=10)\n\nplt.show()" } ]
Exploratory Data Analysis(EDA) with PySpark on Databricks | by Cao YI | Towards Data Science
bye-bye, Pandas... EDA with spark means saying bye-bye to Pandas. Due to the large scale of data, every calculation must be parallelized, instead of Pandas, pyspark.sql.functions are the right tools you can use. It is, for sure, struggling to change your old data-wrangling habit. I hope this post can give you a jump start to perform EDA with Spark. There are two kinds of variables, continuous and categorical. Each of them has different EDA requirements: Continuous variables EDA list: missing values statistic values: mean, min, max, stddev, quantiles binning & distribution correlation Categorical variables EDA list: missing values frequency table I will also show how to generate charts on Databricks without any plot libraries like seaborn or matplotlib. Now first, Let’s load the data. The data I used is from a Kaggle competition, Santander Customer Transaction Prediction. # It's always best to manually write the Schema, I am lazy heredf = (spark .read .option("inferSchema","true") .option("header","true") .csv("/FileStore/tables/train.csv")) The built-in function describe() is extremely helpful. It computes count, mean, stddev, min and max for the selected variables. For example: df.select('var_0').describe().show() However, when you calculate statistic values for multiple variables, this data frame showed will not be neat to check, like below: Remember we talked about not using Pandas to do calculations before. However, we can still use it to display the result. Here, the describe() function which is built in the spark data frame has done the statistic values calculation. The computed summary table is not large in size. So we can use pandas to display it. df.select('var_0','var_1','var_2','var_3','var_4','var_5','var_6','var_7','var_8','var_9','var_10','var_11','var_12','var_13','var_14').describe().toPandas() Get the quantiles: quantile = df.approxQuantile(['var_0'], [0.25, 0.5, 0.75], 0)quantile_25 = quantile[0][0]quantile_50 = quantile[0][1]quantile_75 = quantile[0][2]print('quantile_25: '+str(quantile_25))print('quantile_50: '+str(quantile_50))print('quantile_75: '+str(quantile_75))'''quantile_25: 8.4537 quantile_50: 10.5247 quantile_75: 12.7582''' Check the missings: Introduce two functions to do the filter # wheredf.where(col("var_0").isNull()).count()# filterdf.filter(col("var_0").isNull()).count() These two are the same. According to spark documentation, “where” is an alias of “filter”. Binning: For continuous variables, sometimes we want to bin them and check those bins distribution. For example, in financial related data, we can bin FICO scores(normally range 650 to 850) into buckets. Each bucket has an interval of 25. like 650–675, 675–700, 700–725,...And check how many people in each bucket. Now let’s use “var_0” to give an example for binning. From previous statistic values, we know “var_0” range from 0.41 to 20.31. So we create a list of 0 to 21, with an interval of 0.5. Correlation: To check missing values, it’s the same as continuous variables. To check the frequency table: freq_table = df.select(col("target").cast("string")).groupBy("target").count().toPandas() Databricks actually provide a “Tableau-like” visualization solution. The display() function gives you a friendly UI to generate any plots you like. For example: Choose the chart type you want. You can also create charts with multiple variables. Click on the “Plot Options” button. You can modify the plot as you need: If you like to discuss more, find me on LinkedIn.
[ { "code": null, "e": 66, "s": 47, "text": "bye-bye, Pandas..." }, { "code": null, "e": 398, "s": 66, "text": "EDA with spark means saying bye-bye to Pandas. Due to the large scale of data, every calculation must be parallelized, instead of Pandas, pyspark.sql.functions are the right tools you can use. It is, for sure, struggling to change your old data-wrangling habit. I hope this post can give you a jump start to perform EDA with Spark." }, { "code": null, "e": 505, "s": 398, "text": "There are two kinds of variables, continuous and categorical. Each of them has different EDA requirements:" }, { "code": null, "e": 536, "s": 505, "text": "Continuous variables EDA list:" }, { "code": null, "e": 551, "s": 536, "text": "missing values" }, { "code": null, "e": 603, "s": 551, "text": "statistic values: mean, min, max, stddev, quantiles" }, { "code": null, "e": 626, "s": 603, "text": "binning & distribution" }, { "code": null, "e": 638, "s": 626, "text": "correlation" }, { "code": null, "e": 670, "s": 638, "text": "Categorical variables EDA list:" }, { "code": null, "e": 685, "s": 670, "text": "missing values" }, { "code": null, "e": 701, "s": 685, "text": "frequency table" }, { "code": null, "e": 810, "s": 701, "text": "I will also show how to generate charts on Databricks without any plot libraries like seaborn or matplotlib." }, { "code": null, "e": 931, "s": 810, "text": "Now first, Let’s load the data. The data I used is from a Kaggle competition, Santander Customer Transaction Prediction." }, { "code": null, "e": 1198, "s": 931, "text": "# It's always best to manually write the Schema, I am lazy heredf = (spark .read .option(\"inferSchema\",\"true\") .option(\"header\",\"true\") .csv(\"/FileStore/tables/train.csv\"))" }, { "code": null, "e": 1339, "s": 1198, "text": "The built-in function describe() is extremely helpful. It computes count, mean, stddev, min and max for the selected variables. For example:" }, { "code": null, "e": 1376, "s": 1339, "text": "df.select('var_0').describe().show()" }, { "code": null, "e": 1507, "s": 1376, "text": "However, when you calculate statistic values for multiple variables, this data frame showed will not be neat to check, like below:" }, { "code": null, "e": 1825, "s": 1507, "text": "Remember we talked about not using Pandas to do calculations before. However, we can still use it to display the result. Here, the describe() function which is built in the spark data frame has done the statistic values calculation. The computed summary table is not large in size. So we can use pandas to display it." }, { "code": null, "e": 1983, "s": 1825, "text": "df.select('var_0','var_1','var_2','var_3','var_4','var_5','var_6','var_7','var_8','var_9','var_10','var_11','var_12','var_13','var_14').describe().toPandas()" }, { "code": null, "e": 2002, "s": 1983, "text": "Get the quantiles:" }, { "code": null, "e": 2332, "s": 2002, "text": "quantile = df.approxQuantile(['var_0'], [0.25, 0.5, 0.75], 0)quantile_25 = quantile[0][0]quantile_50 = quantile[0][1]quantile_75 = quantile[0][2]print('quantile_25: '+str(quantile_25))print('quantile_50: '+str(quantile_50))print('quantile_75: '+str(quantile_75))'''quantile_25: 8.4537 quantile_50: 10.5247 quantile_75: 12.7582'''" }, { "code": null, "e": 2352, "s": 2332, "text": "Check the missings:" }, { "code": null, "e": 2393, "s": 2352, "text": "Introduce two functions to do the filter" }, { "code": null, "e": 2488, "s": 2393, "text": "# wheredf.where(col(\"var_0\").isNull()).count()# filterdf.filter(col(\"var_0\").isNull()).count()" }, { "code": null, "e": 2579, "s": 2488, "text": "These two are the same. According to spark documentation, “where” is an alias of “filter”." }, { "code": null, "e": 2588, "s": 2579, "text": "Binning:" }, { "code": null, "e": 2894, "s": 2588, "text": "For continuous variables, sometimes we want to bin them and check those bins distribution. For example, in financial related data, we can bin FICO scores(normally range 650 to 850) into buckets. Each bucket has an interval of 25. like 650–675, 675–700, 700–725,...And check how many people in each bucket." }, { "code": null, "e": 3079, "s": 2894, "text": "Now let’s use “var_0” to give an example for binning. From previous statistic values, we know “var_0” range from 0.41 to 20.31. So we create a list of 0 to 21, with an interval of 0.5." }, { "code": null, "e": 3092, "s": 3079, "text": "Correlation:" }, { "code": null, "e": 3156, "s": 3092, "text": "To check missing values, it’s the same as continuous variables." }, { "code": null, "e": 3186, "s": 3156, "text": "To check the frequency table:" }, { "code": null, "e": 3276, "s": 3186, "text": "freq_table = df.select(col(\"target\").cast(\"string\")).groupBy(\"target\").count().toPandas()" }, { "code": null, "e": 3424, "s": 3276, "text": "Databricks actually provide a “Tableau-like” visualization solution. The display() function gives you a friendly UI to generate any plots you like." }, { "code": null, "e": 3437, "s": 3424, "text": "For example:" }, { "code": null, "e": 3469, "s": 3437, "text": "Choose the chart type you want." }, { "code": null, "e": 3594, "s": 3469, "text": "You can also create charts with multiple variables. Click on the “Plot Options” button. You can modify the plot as you need:" } ]
Python - Text Translation
Text translation from one language to another is increasingly becoming common for various websites as they cater to an international audience. The python package which helps us do this is called translate. This package can be installed by the following way. It provides translation for major languages. pip install translate Below is an example of translating a simple sentence from English to German. The default from language being English. from translate import Translator translator= Translator(to_lang="German") translation = translator.translate("Good Morning!") print translation When we run the above program, we get the following output − Guten Morgen! If we have the need specify the from-language and the to-language, then we can specify it as in the below program. from translate import Translator translator= Translator(from_lang="german",to_lang="spanish") translation = translator.translate("Guten Morgen") print translation When we run the above program, we get the following output − Buenos días 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": 2793, "s": 2587, "text": "Text translation from one language to another is increasingly becoming common for various websites as they cater to an international audience. The python package which helps us do this is called translate." }, { "code": null, "e": 2890, "s": 2793, "text": "This package can be installed by the following way. It provides translation for major languages." }, { "code": null, "e": 2912, "s": 2890, "text": "pip install translate" }, { "code": null, "e": 3030, "s": 2912, "text": "Below is an example of translating a simple sentence from English to German. The default from language being English." }, { "code": null, "e": 3174, "s": 3030, "text": "from translate import Translator\ntranslator= Translator(to_lang=\"German\")\ntranslation = translator.translate(\"Good Morning!\")\nprint translation" }, { "code": null, "e": 3235, "s": 3174, "text": "When we run the above program, we get the following output −" }, { "code": null, "e": 3250, "s": 3235, "text": "Guten Morgen!\n" }, { "code": null, "e": 3365, "s": 3250, "text": "If we have the need specify the from-language and the to-language, then we can specify it as in the below program." }, { "code": null, "e": 3528, "s": 3365, "text": "from translate import Translator\ntranslator= Translator(from_lang=\"german\",to_lang=\"spanish\")\ntranslation = translator.translate(\"Guten Morgen\")\nprint translation" }, { "code": null, "e": 3589, "s": 3528, "text": "When we run the above program, we get the following output −" }, { "code": null, "e": 3603, "s": 3589, "text": "Buenos días\n" }, { "code": null, "e": 3640, "s": 3603, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3656, "s": 3640, "text": " Malhar Lathkar" }, { "code": null, "e": 3689, "s": 3656, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3708, "s": 3689, "text": " Arnab Chakraborty" }, { "code": null, "e": 3743, "s": 3708, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3765, "s": 3743, "text": " In28Minutes Official" }, { "code": null, "e": 3799, "s": 3765, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3827, "s": 3799, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3862, "s": 3827, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3876, "s": 3862, "text": " Lets Kode It" }, { "code": null, "e": 3909, "s": 3876, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3926, "s": 3909, "text": " Abhilash Nelson" }, { "code": null, "e": 3933, "s": 3926, "text": " Print" }, { "code": null, "e": 3944, "s": 3933, "text": " Add Notes" } ]
getpagesize() - Unix, Linux System Call
Unix - Home Unix - Getting Started Unix - File Management Unix - Directories Unix - File Permission Unix - Environment Unix - Basic Utilities Unix - Pipes & Filters Unix - Processes Unix - Communication Unix - The vi Editor Unix - What is Shell? Unix - Using Variables Unix - Special Variables Unix - Using Arrays Unix - Basic Operators Unix - Decision Making Unix - Shell Loops Unix - Loop Control Unix - Shell Substitutions Unix - Quoting Mechanisms Unix - IO Redirections Unix - Shell Functions Unix - Manpage Help Unix - Regular Expressions Unix - File System Basics Unix - User Administration Unix - System Performance Unix - System Logging Unix - Signals and Traps Unix - Useful Commands Unix - Quick Guide Unix - Builtin Functions Unix - System Calls Unix - Commands List Unix Useful Resources Computer Glossary Who is Who Copyright © 2014 by tutorialspoint int getpagesize(void); The size of the kind of pages that mmap() uses, is found using #include <unistd.h> long sz = sysconf(_SC_PAGESIZE); (where some systems also allow the synonym _SC_PAGE_SIZE for _SC_PAGESIZE), or #include <unistd.h> int sz = getpagesize(); mmap (2) mmap (2) 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": 1466, "s": 1454, "text": "Unix - Home" }, { "code": null, "e": 1489, "s": 1466, "text": "Unix - Getting Started" }, { "code": null, "e": 1512, "s": 1489, "text": "Unix - File Management" }, { "code": null, "e": 1531, "s": 1512, "text": "Unix - Directories" }, { "code": null, "e": 1554, "s": 1531, "text": "Unix - File Permission" }, { "code": null, "e": 1573, "s": 1554, "text": "Unix - Environment" }, { "code": null, "e": 1596, "s": 1573, "text": "Unix - Basic Utilities" }, { "code": null, "e": 1619, "s": 1596, "text": "Unix - Pipes & Filters" }, { "code": null, "e": 1636, "s": 1619, "text": "Unix - Processes" }, { "code": null, "e": 1657, "s": 1636, "text": "Unix - Communication" }, { "code": null, "e": 1678, "s": 1657, "text": "Unix - The vi Editor" }, { "code": null, "e": 1700, "s": 1678, "text": "Unix - What is Shell?" }, { "code": null, "e": 1723, "s": 1700, "text": "Unix - Using Variables" }, { "code": null, "e": 1748, "s": 1723, "text": "Unix - Special Variables" }, { "code": null, "e": 1768, "s": 1748, "text": "Unix - Using Arrays" }, { "code": null, "e": 1791, "s": 1768, "text": "Unix - Basic Operators" }, { "code": null, "e": 1814, "s": 1791, "text": "Unix - Decision Making" }, { "code": null, "e": 1833, "s": 1814, "text": "Unix - Shell Loops" }, { "code": null, "e": 1853, "s": 1833, "text": "Unix - Loop Control" }, { "code": null, "e": 1880, "s": 1853, "text": "Unix - Shell Substitutions" }, { "code": null, "e": 1906, "s": 1880, "text": "Unix - Quoting Mechanisms" }, { "code": null, "e": 1929, "s": 1906, "text": "Unix - IO Redirections" }, { "code": null, "e": 1952, "s": 1929, "text": "Unix - Shell Functions" }, { "code": null, "e": 1972, "s": 1952, "text": "Unix - Manpage Help" }, { "code": null, "e": 1999, "s": 1972, "text": "Unix - Regular Expressions" }, { "code": null, "e": 2025, "s": 1999, "text": "Unix - File System Basics" }, { "code": null, "e": 2052, "s": 2025, "text": "Unix - User Administration" }, { "code": null, "e": 2078, "s": 2052, "text": "Unix - System Performance" }, { "code": null, "e": 2100, "s": 2078, "text": "Unix - System Logging" }, { "code": null, "e": 2125, "s": 2100, "text": "Unix - Signals and Traps" }, { "code": null, "e": 2148, "s": 2125, "text": "Unix - Useful Commands" }, { "code": null, "e": 2167, "s": 2148, "text": "Unix - Quick Guide" }, { "code": null, "e": 2192, "s": 2167, "text": "Unix - Builtin Functions" }, { "code": null, "e": 2212, "s": 2192, "text": "Unix - System Calls" }, { "code": null, "e": 2233, "s": 2212, "text": "Unix - Commands List" }, { "code": null, "e": 2255, "s": 2233, "text": "Unix Useful Resources" }, { "code": null, "e": 2273, "s": 2255, "text": "Computer Glossary" }, { "code": null, "e": 2284, "s": 2273, "text": "Who is Who" }, { "code": null, "e": 2319, "s": 2284, "text": "Copyright © 2014 by tutorialspoint" }, { "code": null, "e": 2344, "s": 2319, "text": "\nint getpagesize(void); " }, { "code": null, "e": 2409, "s": 2344, "text": "\nThe size of the kind of pages that\nmmap() uses, is found using\n" }, { "code": null, "e": 2465, "s": 2411, "text": "#include <unistd.h>\nlong sz = sysconf(_SC_PAGESIZE);\n" }, { "code": null, "e": 2546, "s": 2465, "text": "\n(where some systems also allow the synonym _SC_PAGE_SIZE for _SC_PAGESIZE),\nor\n" }, { "code": null, "e": 2593, "s": 2548, "text": "#include <unistd.h>\nint sz = getpagesize();\n" }, { "code": null, "e": 2602, "s": 2593, "text": "mmap (2)" }, { "code": null, "e": 2611, "s": 2602, "text": "mmap (2)" }, { "code": null, "e": 2628, "s": 2611, "text": "\nAdvertisements\n" }, { "code": null, "e": 2663, "s": 2628, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 2691, "s": 2663, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 2725, "s": 2691, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 2742, "s": 2725, "text": " Frahaan Hussain" }, { "code": null, "e": 2775, "s": 2742, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 2786, "s": 2775, "text": " Pradeep D" }, { "code": null, "e": 2821, "s": 2786, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2837, "s": 2821, "text": " Musab Zayadneh" }, { "code": null, "e": 2870, "s": 2837, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 2882, "s": 2870, "text": " GUHARAJANM" }, { "code": null, "e": 2914, "s": 2882, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 2922, "s": 2914, "text": " Uplatz" }, { "code": null, "e": 2929, "s": 2922, "text": " Print" }, { "code": null, "e": 2940, "s": 2929, "text": " Add Notes" } ]
Broadcast Receiver in Android With Example - GeeksforGeeks
18 Jan, 2022 Broadcast in android is the system-wide events that can occur when the device starts, when a message is received on the device or when incoming calls are received, or when a device goes to airplane mode, etc. Broadcast Receivers are used to respond to these system-wide events. Broadcast Receivers allow us to register for the system and application events, and when that event happens, then the register receivers get notified. There are mainly two types of Broadcast Receivers: Static Broadcast Receivers: These types of Receivers are declared in the manifest file and works even if the app is closed. Dynamic Broadcast Receivers: These types of receivers work only if the app is active or minimized. Since from API Level 26, most of the broadcast can only be caught by the dynamic receiver, so we have implemented dynamic receivers in our sample project given below. There are some static fields defined in the Intent class which can be used to broadcast different events. We have taken a change of airplane mode as a broadcast event, but there are many events for which broadcast register can be used. Following are some of the important system-wide generated intents:- Intent Description Of Event The two main things that we have to do in order to use the broadcast receiver in our application are: Creating the Broadcast Receiver: class AirplaneModeChangeReceiver:BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { // logic of the code needs to be written here } } Registering a BroadcastReceiver: IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED).also { // receiver is the broadcast receiver that we have registered // and it is the intent filter that we have created registerReceiver(receiver,it) } Below is the sample project showing how to create the broadcast Receiver and how to register them for a particular event and how to use them in the application. 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. Step 2: Working with the activity_main.xml file Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout 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"></androidx.constraintlayout.widget.ConstraintLayout> Step 3: Working with the MainActivity file Go to the MainActivity file and refer to the following code. Below is the code for the MainActivity file. Comments are added inside the code to understand the code in more detail. Kotlin Java import android.content.Intentimport android.content.IntentFilterimport android.os.Bundleimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { // register the receiver in the main activity in order // to receive updates of broadcasts events if they occur lateinit var receiver: AirplaneModeChangeReceiver override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) receiver = AirplaneModeChangeReceiver() // Intent Filter is useful to determine which apps wants to receive // which intents,since here we want to respond to change of // airplane mode IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED).also { // registering the receiver // it parameter which is passed in registerReceiver() function // is the intent filter that we have just created registerReceiver(receiver, it) } } // since AirplaneModeChangeReceiver class holds a instance of Context // and that context is actually the activity context in which // the receiver has been created override fun onStop() { super.onStop() unregisterReceiver(receiver) }} import androidx.appcompat.app.AppCompatActivity; import android.content.Intent;import android.content.IntentFilter;import android.os.Bundle; public class MainActivity extends AppCompatActivity { AirplaneModeChangeReceiver airplaneModeChangeReceiver = new AirplaneModeChangeReceiver(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override protected void onStart() { super.onStart(); IntentFilter filter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED); registerReceiver(airplaneModeChangeReceiver, filter); } @Override protected void onStop() { super.onStop(); unregisterReceiver(airplaneModeChangeReceiver); }} Step 4: Create a new class Go to app > java > your package name(in which the MainActicity is present) > right-click > New > Kotlin File/Class and name the files as AirplaneModeChangeReceiver. Below is the code for the AirplaneModeChangeReceiver file. Comments are added inside the code to understand the code in more detail. Kotlin Java import android.content.BroadcastReceiverimport android.content.Contextimport android.content.Intentimport android.widget.Toast // AirplaneModeChangeReceiver class extending BroadcastReceiver classclass AirplaneModeChangeReceiver : BroadcastReceiver() { // this function will be executed when the user changes his // airplane mode override fun onReceive(context: Context?, intent: Intent?) { // intent contains the information about the broadcast // in our case broadcast is change of airplane mode // if getBooleanExtra contains null value,it will directly return back val isAirplaneModeEnabled = intent?.getBooleanExtra("state", false) ?: return // checking whether airplane mode is enabled or not if (isAirplaneModeEnabled) { // showing the toast message if airplane mode is enabled Toast.makeText(context, "Airplane Mode Enabled", Toast.LENGTH_LONG).show() } else { // showing the toast message if airplane mode is disabled Toast.makeText(context, "Airplane Mode Disabled", Toast.LENGTH_LONG).show() } }} import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.provider.Settings;import android.widget.Toast; public class AirplaneModeChangeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (isAirplaneModeOn(context.getApplicationContext())) { Toast.makeText(context, "AirPlane mode is on", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(context, "AirPlane mode is off", Toast.LENGTH_SHORT).show(); } } private static boolean isAirplaneModeOn(Context context) { return Settings.System.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0; }} Output: meetpatel2220 sumitgumber28 android Technical Scripter 2020 Android Kotlin Technical Scripter Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Create and Add Data to SQLite Database in Android? Android RecyclerView in Kotlin CardView in Android With Example Content Providers in Android with Example Navigation Drawer in Android Android UI Layouts Android RecyclerView in Kotlin Kotlin Array Content Providers in Android with Example Retrofit with Kotlin Coroutine in Android
[ { "code": null, "e": 24585, "s": 24557, "text": "\n18 Jan, 2022" }, { "code": null, "e": 25065, "s": 24585, "text": "Broadcast in android is the system-wide events that can occur when the device starts, when a message is received on the device or when incoming calls are received, or when a device goes to airplane mode, etc. Broadcast Receivers are used to respond to these system-wide events. Broadcast Receivers allow us to register for the system and application events, and when that event happens, then the register receivers get notified. There are mainly two types of Broadcast Receivers:" }, { "code": null, "e": 25189, "s": 25065, "text": "Static Broadcast Receivers: These types of Receivers are declared in the manifest file and works even if the app is closed." }, { "code": null, "e": 25288, "s": 25189, "text": "Dynamic Broadcast Receivers: These types of receivers work only if the app is active or minimized." }, { "code": null, "e": 25759, "s": 25288, "text": "Since from API Level 26, most of the broadcast can only be caught by the dynamic receiver, so we have implemented dynamic receivers in our sample project given below. There are some static fields defined in the Intent class which can be used to broadcast different events. We have taken a change of airplane mode as a broadcast event, but there are many events for which broadcast register can be used. Following are some of the important system-wide generated intents:-" }, { "code": null, "e": 25789, "s": 25759, "text": " Intent" }, { "code": null, "e": 25810, "s": 25789, "text": "Description Of Event" }, { "code": null, "e": 25912, "s": 25810, "text": "The two main things that we have to do in order to use the broadcast receiver in our application are:" }, { "code": null, "e": 25945, "s": 25912, "text": "Creating the Broadcast Receiver:" }, { "code": null, "e": 26000, "s": 25945, "text": "class AirplaneModeChangeReceiver:BroadcastReceiver() {" }, { "code": null, "e": 26068, "s": 26000, "text": " override fun onReceive(context: Context?, intent: Intent?) {" }, { "code": null, "e": 26126, "s": 26068, "text": " // logic of the code needs to be written here" }, { "code": null, "e": 26134, "s": 26126, "text": " }" }, { "code": null, "e": 26137, "s": 26134, "text": "} " }, { "code": null, "e": 26170, "s": 26137, "text": "Registering a BroadcastReceiver:" }, { "code": null, "e": 26227, "s": 26170, "text": "IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED).also {" }, { "code": null, "e": 26310, "s": 26227, "text": " // receiver is the broadcast receiver that we have registered" }, { "code": null, "e": 26382, "s": 26310, "text": " // and it is the intent filter that we have created" }, { "code": null, "e": 26432, "s": 26382, "text": " registerReceiver(receiver,it)" }, { "code": null, "e": 26441, "s": 26432, "text": " } " }, { "code": null, "e": 26602, "s": 26441, "text": "Below is the sample project showing how to create the broadcast Receiver and how to register them for a particular event and how to use them in the application." }, { "code": null, "e": 26631, "s": 26602, "text": "Step 1: Create a New Project" }, { "code": null, "e": 26742, "s": 26631, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio." }, { "code": null, "e": 26790, "s": 26742, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 26906, "s": 26790, "text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file." }, { "code": null, "e": 26910, "s": 26906, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout 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\"></androidx.constraintlayout.widget.ConstraintLayout>", "e": 27276, "s": 26910, "text": null }, { "code": null, "e": 27320, "s": 27276, "text": "Step 3: Working with the MainActivity file " }, { "code": null, "e": 27501, "s": 27320, "text": "Go to the MainActivity file and refer to the following code. Below is the code for the MainActivity file. Comments are added inside the code to understand the code in more detail. " }, { "code": null, "e": 27508, "s": 27501, "text": "Kotlin" }, { "code": null, "e": 27513, "s": 27508, "text": "Java" }, { "code": "import android.content.Intentimport android.content.IntentFilterimport android.os.Bundleimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { // register the receiver in the main activity in order // to receive updates of broadcasts events if they occur lateinit var receiver: AirplaneModeChangeReceiver override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) receiver = AirplaneModeChangeReceiver() // Intent Filter is useful to determine which apps wants to receive // which intents,since here we want to respond to change of // airplane mode IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED).also { // registering the receiver // it parameter which is passed in registerReceiver() function // is the intent filter that we have just created registerReceiver(receiver, it) } } // since AirplaneModeChangeReceiver class holds a instance of Context // and that context is actually the activity context in which // the receiver has been created override fun onStop() { super.onStop() unregisterReceiver(receiver) }}", "e": 28784, "s": 27513, "text": null }, { "code": "import androidx.appcompat.app.AppCompatActivity; import android.content.Intent;import android.content.IntentFilter;import android.os.Bundle; public class MainActivity extends AppCompatActivity { AirplaneModeChangeReceiver airplaneModeChangeReceiver = new AirplaneModeChangeReceiver(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override protected void onStart() { super.onStart(); IntentFilter filter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED); registerReceiver(airplaneModeChangeReceiver, filter); } @Override protected void onStop() { super.onStop(); unregisterReceiver(airplaneModeChangeReceiver); }}", "e": 29583, "s": 28784, "text": null }, { "code": null, "e": 29611, "s": 29583, "text": "Step 4: Create a new class " }, { "code": null, "e": 29910, "s": 29611, "text": "Go to app > java > your package name(in which the MainActicity is present) > right-click > New > Kotlin File/Class and name the files as AirplaneModeChangeReceiver. Below is the code for the AirplaneModeChangeReceiver file. Comments are added inside the code to understand the code in more detail. " }, { "code": null, "e": 29917, "s": 29910, "text": "Kotlin" }, { "code": null, "e": 29922, "s": 29917, "text": "Java" }, { "code": "import android.content.BroadcastReceiverimport android.content.Contextimport android.content.Intentimport android.widget.Toast // AirplaneModeChangeReceiver class extending BroadcastReceiver classclass AirplaneModeChangeReceiver : BroadcastReceiver() { // this function will be executed when the user changes his // airplane mode override fun onReceive(context: Context?, intent: Intent?) { // intent contains the information about the broadcast // in our case broadcast is change of airplane mode // if getBooleanExtra contains null value,it will directly return back val isAirplaneModeEnabled = intent?.getBooleanExtra(\"state\", false) ?: return // checking whether airplane mode is enabled or not if (isAirplaneModeEnabled) { // showing the toast message if airplane mode is enabled Toast.makeText(context, \"Airplane Mode Enabled\", Toast.LENGTH_LONG).show() } else { // showing the toast message if airplane mode is disabled Toast.makeText(context, \"Airplane Mode Disabled\", Toast.LENGTH_LONG).show() } }}", "e": 31062, "s": 29922, "text": null }, { "code": "import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.provider.Settings;import android.widget.Toast; public class AirplaneModeChangeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (isAirplaneModeOn(context.getApplicationContext())) { Toast.makeText(context, \"AirPlane mode is on\", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(context, \"AirPlane mode is off\", Toast.LENGTH_SHORT).show(); } } private static boolean isAirplaneModeOn(Context context) { return Settings.System.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0; }}", "e": 31814, "s": 31062, "text": null }, { "code": null, "e": 31822, "s": 31814, "text": "Output:" }, { "code": null, "e": 31836, "s": 31822, "text": "meetpatel2220" }, { "code": null, "e": 31850, "s": 31836, "text": "sumitgumber28" }, { "code": null, "e": 31858, "s": 31850, "text": "android" }, { "code": null, "e": 31882, "s": 31858, "text": "Technical Scripter 2020" }, { "code": null, "e": 31890, "s": 31882, "text": "Android" }, { "code": null, "e": 31897, "s": 31890, "text": "Kotlin" }, { "code": null, "e": 31916, "s": 31897, "text": "Technical Scripter" }, { "code": null, "e": 31924, "s": 31916, "text": "Android" }, { "code": null, "e": 32022, "s": 31924, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32031, "s": 32022, "text": "Comments" }, { "code": null, "e": 32044, "s": 32031, "text": "Old Comments" }, { "code": null, "e": 32102, "s": 32044, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 32133, "s": 32102, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 32166, "s": 32133, "text": "CardView in Android With Example" }, { "code": null, "e": 32208, "s": 32166, "text": "Content Providers in Android with Example" }, { "code": null, "e": 32237, "s": 32208, "text": "Navigation Drawer in Android" }, { "code": null, "e": 32256, "s": 32237, "text": "Android UI Layouts" }, { "code": null, "e": 32287, "s": 32256, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 32300, "s": 32287, "text": "Kotlin Array" }, { "code": null, "e": 32342, "s": 32300, "text": "Content Providers in Android with Example" } ]
Explain PowerShell Profile.
When you open PowerShell, it loads the profile just like the Windows operating system. When you log in to windows OS you are logged into your profile and every user has their individual profile. It is called the current profile for the current host. To check your profile, type $Profile command in the PowerShell console. PS C:\Users\Administrator> $profile C:\Users\Administrator\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.p s1 This was for Powershell console but let's check if Powershell uses the same profile for ISE. PS C:\> $profile C:\Users\Administrator\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profil e.ps1 So the ISE has its own profile too and both are stored in the $Home directory. What if we use the $profile for VSCode. PS C:\> $profile C:\Users\Administrator\Documents\PowerShell\Microsoft.VSCode_profile.ps1 This means each editor has its own profile for the current user and current host. You might have noticed, whenever you start the PowerShell, you can access the commands and modules created by different users on the systems from the Module path because simply starting PowerShell also loads the modules which are stored on $PSHome location. Apart from the current users PS C:\> $pshome C:\Windows\System32\WindowsPowerShell\v1.0 The above example suggests that there could be also a profile that exists for all users. Let see how many total profiles exist for PowerShell ISE version. PS C:\> $profile | fl * -Force AllUsersAllHosts : C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1 AllUsersCurrentHost : C:\Windows\System32\WindowsPowerShell\v1.0\Microsoft.Pow erShellISE_profile.ps1 CurrentUserAllHosts : C:\Users\Administrator\Documents\WindowsPowerShell\profi le.ps1 CurrentUserCurrentHost : C:\Users\Administrator\Documents\WindowsPowerShell\Micro soft.PowerShellISE_profile.ps1 Length : 86 The above command is executed from ISE, we will now check the same command in PowerShell Console, PS C:\Users\Administrator> $PROFILE | fl * -Force AllUsersAllHosts : C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1 AllUsersCurrentHost : C:\Windows\System32\WindowsPowerShell\v1.0\Microsoft.Pow erShell_profile.ps1 CurrentUserAllHosts : C:\Users\Administrator\Documents\WindowsPowerShell\profi le.ps1 CurrentUserCurrentHost : C:\Users\Administrator\Documents\WindowsPowerShell\Micro soft.PowerShell_profile.ps1 Length : 83 When you compare the above two output, you can notice that the current Host (All Users and current user) profile depends on the editor you use. If you use PowerShell console, the profile name would contain PowerShell profile, If you use ISE or VSCode the current Host profile would contain name accordingly. By comparing we come to know that basically profiles are stored at two locations. 1) $Home (C:\Users\<UserName>) and 2) $PSHome (C:\Windows\System32\WindowsPowerShell). So there are total 6 profiles. Current User, Current Host – PowerShell Console Current User, Current Host – PowerShell Console Current User, All Hosts Current User, All Hosts All Users, Current Host - PowerShell Console All Users, Current Host - PowerShell Console All Users, All Hosts All Users, All Hosts Current User, Current Host – Depends on Editor Current User, Current Host – Depends on Editor All Users, Current Host – Depends on Editor. All Users, Current Host – Depends on Editor.
[ { "code": null, "e": 1312, "s": 1062, "text": "When you open PowerShell, it loads the profile just like the Windows operating system. When you log in to windows OS you are logged into your profile and every user has their individual profile. It is called the current profile for the current host." }, { "code": null, "e": 1384, "s": 1312, "text": "To check your profile, type $Profile command in the PowerShell console." }, { "code": null, "e": 1505, "s": 1384, "text": "PS C:\\Users\\Administrator> $profile\nC:\\Users\\Administrator\\Documents\\WindowsPowerShell\\Microsoft.PowerShell_profile.p\ns1" }, { "code": null, "e": 1598, "s": 1505, "text": "This was for Powershell console but let's check if Powershell uses the same profile for ISE." }, { "code": null, "e": 1703, "s": 1598, "text": "PS C:\\> $profile\nC:\\Users\\Administrator\\Documents\\WindowsPowerShell\\Microsoft.PowerShellISE_profil\ne.ps1" }, { "code": null, "e": 1822, "s": 1703, "text": "So the ISE has its own profile too and both are stored in the $Home directory. What if we use the $profile for VSCode." }, { "code": null, "e": 1912, "s": 1822, "text": "PS C:\\> $profile\nC:\\Users\\Administrator\\Documents\\PowerShell\\Microsoft.VSCode_profile.ps1" }, { "code": null, "e": 1994, "s": 1912, "text": "This means each editor has its own profile for the current user and current host." }, { "code": null, "e": 2281, "s": 1994, "text": "You might have noticed, whenever you start the PowerShell, you can access the commands and modules created by different users on the systems from the Module path because simply starting PowerShell also loads the modules which are stored on $PSHome location. Apart from the current users" }, { "code": null, "e": 2340, "s": 2281, "text": "PS C:\\> $pshome\nC:\\Windows\\System32\\WindowsPowerShell\\v1.0" }, { "code": null, "e": 2495, "s": 2340, "text": "The above example suggests that there could be also a profile that exists for all users. Let see how many total profiles exist for PowerShell ISE version." }, { "code": null, "e": 2956, "s": 2495, "text": "PS C:\\> $profile | fl * -Force\nAllUsersAllHosts : C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\profile.ps1\nAllUsersCurrentHost : C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\Microsoft.Pow\nerShellISE_profile.ps1\nCurrentUserAllHosts : C:\\Users\\Administrator\\Documents\\WindowsPowerShell\\profi\nle.ps1\nCurrentUserCurrentHost : C:\\Users\\Administrator\\Documents\\WindowsPowerShell\\Micro\nsoft.PowerShellISE_profile.ps1\nLength : 86" }, { "code": null, "e": 3054, "s": 2956, "text": "The above command is executed from ISE, we will now check the same command in PowerShell Console," }, { "code": null, "e": 3528, "s": 3054, "text": "PS C:\\Users\\Administrator> $PROFILE | fl * -Force\nAllUsersAllHosts : C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\profile.ps1\nAllUsersCurrentHost : C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\Microsoft.Pow\nerShell_profile.ps1\nCurrentUserAllHosts : C:\\Users\\Administrator\\Documents\\WindowsPowerShell\\profi\nle.ps1\nCurrentUserCurrentHost : C:\\Users\\Administrator\\Documents\\WindowsPowerShell\\Micro\nsoft.PowerShell_profile.ps1\nLength : 83" }, { "code": null, "e": 3836, "s": 3528, "text": "When you compare the above two output, you can notice that the current Host (All Users and current user) profile depends on the editor you use. If you use PowerShell console, the profile name would contain PowerShell profile, If you use ISE or VSCode the current Host profile would contain name accordingly." }, { "code": null, "e": 4005, "s": 3836, "text": "By comparing we come to know that basically profiles are stored at two locations. 1) $Home (C:\\Users\\<UserName>) and 2) $PSHome (C:\\Windows\\System32\\WindowsPowerShell)." }, { "code": null, "e": 4036, "s": 4005, "text": "So there are total 6 profiles." }, { "code": null, "e": 4084, "s": 4036, "text": "Current User, Current Host – PowerShell Console" }, { "code": null, "e": 4132, "s": 4084, "text": "Current User, Current Host – PowerShell Console" }, { "code": null, "e": 4156, "s": 4132, "text": "Current User, All Hosts" }, { "code": null, "e": 4180, "s": 4156, "text": "Current User, All Hosts" }, { "code": null, "e": 4225, "s": 4180, "text": "All Users, Current Host - PowerShell Console" }, { "code": null, "e": 4270, "s": 4225, "text": "All Users, Current Host - PowerShell Console" }, { "code": null, "e": 4291, "s": 4270, "text": "All Users, All Hosts" }, { "code": null, "e": 4312, "s": 4291, "text": "All Users, All Hosts" }, { "code": null, "e": 4359, "s": 4312, "text": "Current User, Current Host – Depends on Editor" }, { "code": null, "e": 4406, "s": 4359, "text": "Current User, Current Host – Depends on Editor" }, { "code": null, "e": 4451, "s": 4406, "text": "All Users, Current Host – Depends on Editor." }, { "code": null, "e": 4496, "s": 4451, "text": "All Users, Current Host – Depends on Editor." } ]
false command in Linux with examples - GeeksforGeeks
05 Mar, 2019 false command is used to return an exit status code (“1” by default) that indicates failure. It is useful when the user wants a conditional expression or an argument to always be unsuccessful. When no argument is passed to the false command, it fails with no output and exit status as 1. Syntax: false [argument] Example: We can see that no output is returned but we can check the exit status value by checking the value of the special shell variable i.e. ?, that contain the exit status of the false command. Since ? is a variable, we need to prefix it with $ for the reference. Syntax: "$?" Example: To print the exit status of the previous command. Options: –help : It is used to show this help information and exit. –version: It gives the version information and exit. Implementing false command in an if statement: We can use the false command in if statement when we want to execute a statement/command if the condition becomes false. Syntax: if false; then [Executable statements]; else [Executable statement]; fi Example: if false; then echo "It's false"; else echo "It's True"; fi linux-command Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Thread functions in C/C++ nohup Command in Linux with Examples scp command in Linux with Examples chown command in Linux with Examples Array Basics in Shell Scripting | Set 1 mv command in Linux with examples Basic Operators in Shell Scripting SED command in Linux | Set 2 Docker - COPY Instruction Named Pipe or FIFO with example C program
[ { "code": null, "e": 24406, "s": 24378, "text": "\n05 Mar, 2019" }, { "code": null, "e": 24694, "s": 24406, "text": "false command is used to return an exit status code (“1” by default) that indicates failure. It is useful when the user wants a conditional expression or an argument to always be unsuccessful. When no argument is passed to the false command, it fails with no output and exit status as 1." }, { "code": null, "e": 24702, "s": 24694, "text": "Syntax:" }, { "code": null, "e": 24719, "s": 24702, "text": "false [argument]" }, { "code": null, "e": 24728, "s": 24719, "text": "Example:" }, { "code": null, "e": 24986, "s": 24728, "text": "We can see that no output is returned but we can check the exit status value by checking the value of the special shell variable i.e. ?, that contain the exit status of the false command. Since ? is a variable, we need to prefix it with $ for the reference." }, { "code": null, "e": 24994, "s": 24986, "text": "Syntax:" }, { "code": null, "e": 24999, "s": 24994, "text": "\"$?\"" }, { "code": null, "e": 25058, "s": 24999, "text": "Example: To print the exit status of the previous command." }, { "code": null, "e": 25067, "s": 25058, "text": "Options:" }, { "code": null, "e": 25126, "s": 25067, "text": "–help : It is used to show this help information and exit." }, { "code": null, "e": 25179, "s": 25126, "text": "–version: It gives the version information and exit." }, { "code": null, "e": 25347, "s": 25179, "text": "Implementing false command in an if statement: We can use the false command in if statement when we want to execute a statement/command if the condition becomes false." }, { "code": null, "e": 25355, "s": 25347, "text": "Syntax:" }, { "code": null, "e": 25427, "s": 25355, "text": "if false; then [Executable statements]; else [Executable statement]; fi" }, { "code": null, "e": 25436, "s": 25427, "text": "Example:" }, { "code": null, "e": 25496, "s": 25436, "text": "if false; then echo \"It's false\"; else echo \"It's True\"; fi" }, { "code": null, "e": 25510, "s": 25496, "text": "linux-command" }, { "code": null, "e": 25517, "s": 25510, "text": "Picked" }, { "code": null, "e": 25528, "s": 25517, "text": "Linux-Unix" }, { "code": null, "e": 25626, "s": 25528, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25635, "s": 25626, "text": "Comments" }, { "code": null, "e": 25648, "s": 25635, "text": "Old Comments" }, { "code": null, "e": 25674, "s": 25648, "text": "Thread functions in C/C++" }, { "code": null, "e": 25711, "s": 25674, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 25746, "s": 25711, "text": "scp command in Linux with Examples" }, { "code": null, "e": 25783, "s": 25746, "text": "chown command in Linux with Examples" }, { "code": null, "e": 25823, "s": 25783, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 25857, "s": 25823, "text": "mv command in Linux with examples" }, { "code": null, "e": 25892, "s": 25857, "text": "Basic Operators in Shell Scripting" }, { "code": null, "e": 25921, "s": 25892, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 25947, "s": 25921, "text": "Docker - COPY Instruction" } ]
An Introduction to Dimensionality Reduction | by Peter Grant | Towards Data Science
High dimensional data sets provide one of the largest challenges in all of data science. The challenge is quite straightforward. Machine learning algorithms require the data set to be dense in order to make accurate predictions. Data spaces get extremely vast as more and more dimensions are added. Vast data spaces require extremely large data sets to maintain density. This challenge can either result in inaccurate predictions from models (For instance, I described how the k-nearest neighbors algorithm can be rendered useless with high dimension data spaces in k-Nearest Neighbors and the Curse of Dimensionality) or data sets that are too large for computers to reasonably handle. Fortunately data scientists have identified a solution to this problem. It’s called dimensionality reduction. The essence of dimensionality reduction is simple: You search the data set for trends that imply the data set is acting along a different dimension than your original assumption, then you transform your data accordingly. In this way you can reduce the number of dimensions in your data set. Dimensionality reduction works by identifying the dimensions that truly matter in your data set. Once the really important dimensions have been identified, you can transform your data set so that the points are represented along these dimensions instead of the dimensions that they were originally presented with. Let’s discuss this in terms of an example. In k-Nearest Neighbors and the Curse of Dimensionality I presented the somewhat tongue in cheek example of the Garden Gnome Demarcation Line. In this example pretend that you’re studying the locations of garden gnomes in a city, and plotting them. You start off by identifying the latitude and longitude of each garden gnome in the city, then plot them in a 2 dimensional graph. The two dimensions are North-South and East-West, represented in miles from the center of the city. This is a perfectly reasonable way to present the data and, with only two dimensions, would suffice perfectly. However, pretend that you’re a perfectionist and want to present the data using as few dimensions as possible. You also notice that the garden gnomes, for some odd reason, form a nearly perfect line running from the North-East corner of the city to the South-West corner of the city. The data set isn’t a cloud of garden gnome locations, it’s a line. Noticing this, you realize that you could plot the location of each garden gnome in terms of distance from the city center in the NorthEast-SouthWest direction. And this representation would only require one dimension. The next step is then to perform the transformation. You need to calculate the distance of each point from the center of the city along the new axis, and declare that your new data set. The new distance can be done algebraically. And once that’s done, the resulting profile can be plotted showing your data set in a single dimension. We’ll walk through this process using the prior example of the Garden Gnome Demarcation Line. I’ll do all of this work in python, using the capabilities of pandas and numpy. For detailed instructions on how to use those tools, I highly recommend reading Python for Data Analysis by Wes McKinney (Wes is the creator of pandas, so you can bet he knows what he’s talking about. I’ll be generating plots using the python package bokeh. A useful introduction to that package can be found in Hands on Data Visualization with Bokeh. I’ve constructed my data set in a pandas dataframe called GardenGnomeLocations. It has an index for 31 entries, and columns representing the location of each garden gnome along the North-South and East-West axis. The columns are named ‘NorthSouth (mi)’ and ‘EastWest (mi)’. Figure 1 presents the original data set, showing the location of each garden gnome in the city along the North-South and East-West axes. Each circle represents the location of a garden gnome relative to the city center. Notice the previously described trend presented in the data; the location of the garden gnomes is, for some mysterious reason, a straight line running from the North-East corner of the city to the South-West corner of the city. Upon noticing that trend it becomes clear that the location of garden gnomes can really be presented using a single dimension, a single axis. We can use this knowledge to create a new axis, the NorthEast-SouthWest axis (Or, as I enjoy calling it, the Garden Gnome Demarcation Line). Then the data can be presented in a single dimension, as the distance from the city center along that axis. To perform this translation, we use the pythagorean theorem on each data point. To calculate the distance of each garden gnome from the city center along our new axis, we need to use a for loop, the pandas.loc function, the math.sqrt function, and some algebraic expressions. The code calculating the new distance and adding it to the ‘Distance (mi)’ column in the data frame is as follows: for i in GardenGnomeLocations.index: GardenGnomeLocations.loc[i, 'Distance (mi)'] = math.sqrt(GardenGnomeLocations.loc[i, 'NorthSouth (mi)'] ** 2 + GardenGnomeLocations.loc[i, 'EastWest (mi)'] ** 2) if GardenGnomeLocations.loc[i, 'NorthSouth (mi)'] < 0: GardenGnomeLocations.loc[i, 'Distance (mi)'] = -1 * GardenGnomeLocations.loc[i, 'Distance (mi)'] The for loop at the top of the code block tells the script to perform this calculation for each row in the GardenGnomeLocations dataframe, and to use the variable i to keep track of it’s location in the dataframe. The second line performs the actual calculation and stores the data in the appropriate location in the dataframe. You’ll note that the equation boils down to c = sqrt(a2 + b2), which is the common form of the pythagorean theorem. The first term, GardenGnomeLocations.loc[i, ‘Distance (mi)’] tells python that the value we’re about to calculate should be placed in row i of column ‘Distance (mi)’ in the GardenGnomeLocations dataframe. The other side of the equation uses the corresponding data from the ‘NorthSouth (mi)’ and ‘EastWest (mi)’ columns to calculate the result. Keep in mind that the pythagorean theorem will only return absolute values of the distance. To overcome that, we add the final two lines of code. The first determines whether the values of the original data point were positive or negative. The second then multiplies the distance by -1, to make it negative, if the original values were negative. Plotting this data results in Figure 2. The data looks very similar, because this plot presents it in 2 dimensions, but notice the axes in this case. Instead of presenting each plot using the location in the North-South and East-West axes, Figure 2 shows the location of each gnome only in terms of the distance from the city center. In one dimension. This reduction to a single dimension makes the data set much easier to use. Fewer points are needed to ensure that the data set is dense enough to return accurate predictions. Fewer data points means reduced computational time for the same quality results. And some algorithms, like the k-nearest neighbors algorithm, are much more likely to return useful results than with higher dimensions. This transformation does make it harder to interpret the data, however. Originally the data was easily understood; each data point referred to the location of the garden gnome in terms we commonly use. We could fine the distance North/South, and the distance East/West and simple use that. Now instead we have a distance from the city center, but the data doesn’t clearly state the direction. In order to make sense of this data, we must retain all prior data sets and algorithms. In that way we can later translate the data from the new axis back to the original axis, so it can be easily understood and used. Unfortunately, no it isn’t really that simple. This was an overly simplified, somewhat comical, example meant to demonstrate the fundamental concepts. In reality no data set will operate along a perfectly shaped line like this data set did, and it won’t be possible to transform the data by simply using the pythagorean theorem. Real data sets will look more like clouds of data with vague trends hidden in them, and you’ll need to use a technique called principal component analysis to transform the data. This technique is beyond the scope of this introductory article, but Joel Gros does an excellent job of demonstrating how to implement it in Data Science from Scratch. Highly dimensional data sets provide a serious challenge for data scientists. As the number of dimensions increases, so does the data space. As more and more dimensions are added, the space becomes extremely large. This large space makes it hard for most machine learning algorithms to function because gaps in the data set present areas that the models cannot match. Some algorithms, such as the k-nearest neighbors algorithm, are especially sensitive because they require data points to be close in every dimension which gets very rare when there are many dimensions. The obvious solution to the dimensionality problem is larger data sets. This can be used to maintain data density; however, very large data spaces require very large data sets. These data sets can get too large, overwhelming the ability of computers to perform the necessary calculations. In that case, the solution is to apply dimensionality reduction. Dimensionality reduction is the practice of noticing when data points align along different axes from the ones that are originally used, and transforming the data sets to present them along those axes instead. We demonstrated this using the example of garden gnomes spread throughout the city. Originally they were plotted on the intuitive North-South and East-West axes. However, after inspecting the data, it became clear that they were oriented along a separate axis running from the North-East corner of the city to the South-West corner. Translating the data set accordingly reduced the data set from one dimension to two. While this is a small example, the principal can be applied to much larger data sets.
[ { "code": null, "e": 859, "s": 172, "text": "High dimensional data sets provide one of the largest challenges in all of data science. The challenge is quite straightforward. Machine learning algorithms require the data set to be dense in order to make accurate predictions. Data spaces get extremely vast as more and more dimensions are added. Vast data spaces require extremely large data sets to maintain density. This challenge can either result in inaccurate predictions from models (For instance, I described how the k-nearest neighbors algorithm can be rendered useless with high dimension data spaces in k-Nearest Neighbors and the Curse of Dimensionality) or data sets that are too large for computers to reasonably handle." }, { "code": null, "e": 1260, "s": 859, "text": "Fortunately data scientists have identified a solution to this problem. It’s called dimensionality reduction. The essence of dimensionality reduction is simple: You search the data set for trends that imply the data set is acting along a different dimension than your original assumption, then you transform your data accordingly. In this way you can reduce the number of dimensions in your data set." }, { "code": null, "e": 1574, "s": 1260, "text": "Dimensionality reduction works by identifying the dimensions that truly matter in your data set. Once the really important dimensions have been identified, you can transform your data set so that the points are represented along these dimensions instead of the dimensions that they were originally presented with." }, { "code": null, "e": 2207, "s": 1574, "text": "Let’s discuss this in terms of an example. In k-Nearest Neighbors and the Curse of Dimensionality I presented the somewhat tongue in cheek example of the Garden Gnome Demarcation Line. In this example pretend that you’re studying the locations of garden gnomes in a city, and plotting them. You start off by identifying the latitude and longitude of each garden gnome in the city, then plot them in a 2 dimensional graph. The two dimensions are North-South and East-West, represented in miles from the center of the city. This is a perfectly reasonable way to present the data and, with only two dimensions, would suffice perfectly." }, { "code": null, "e": 2777, "s": 2207, "text": "However, pretend that you’re a perfectionist and want to present the data using as few dimensions as possible. You also notice that the garden gnomes, for some odd reason, form a nearly perfect line running from the North-East corner of the city to the South-West corner of the city. The data set isn’t a cloud of garden gnome locations, it’s a line. Noticing this, you realize that you could plot the location of each garden gnome in terms of distance from the city center in the NorthEast-SouthWest direction. And this representation would only require one dimension." }, { "code": null, "e": 3111, "s": 2777, "text": "The next step is then to perform the transformation. You need to calculate the distance of each point from the center of the city along the new axis, and declare that your new data set. The new distance can be done algebraically. And once that’s done, the resulting profile can be plotted showing your data set in a single dimension." }, { "code": null, "e": 3637, "s": 3111, "text": "We’ll walk through this process using the prior example of the Garden Gnome Demarcation Line. I’ll do all of this work in python, using the capabilities of pandas and numpy. For detailed instructions on how to use those tools, I highly recommend reading Python for Data Analysis by Wes McKinney (Wes is the creator of pandas, so you can bet he knows what he’s talking about. I’ll be generating plots using the python package bokeh. A useful introduction to that package can be found in Hands on Data Visualization with Bokeh." }, { "code": null, "e": 3911, "s": 3637, "text": "I’ve constructed my data set in a pandas dataframe called GardenGnomeLocations. It has an index for 31 entries, and columns representing the location of each garden gnome along the North-South and East-West axis. The columns are named ‘NorthSouth (mi)’ and ‘EastWest (mi)’." }, { "code": null, "e": 4359, "s": 3911, "text": "Figure 1 presents the original data set, showing the location of each garden gnome in the city along the North-South and East-West axes. Each circle represents the location of a garden gnome relative to the city center. Notice the previously described trend presented in the data; the location of the garden gnomes is, for some mysterious reason, a straight line running from the North-East corner of the city to the South-West corner of the city." }, { "code": null, "e": 4750, "s": 4359, "text": "Upon noticing that trend it becomes clear that the location of garden gnomes can really be presented using a single dimension, a single axis. We can use this knowledge to create a new axis, the NorthEast-SouthWest axis (Or, as I enjoy calling it, the Garden Gnome Demarcation Line). Then the data can be presented in a single dimension, as the distance from the city center along that axis." }, { "code": null, "e": 5141, "s": 4750, "text": "To perform this translation, we use the pythagorean theorem on each data point. To calculate the distance of each garden gnome from the city center along our new axis, we need to use a for loop, the pandas.loc function, the math.sqrt function, and some algebraic expressions. The code calculating the new distance and adding it to the ‘Distance (mi)’ column in the data frame is as follows:" }, { "code": null, "e": 5510, "s": 5141, "text": "for i in GardenGnomeLocations.index: GardenGnomeLocations.loc[i, 'Distance (mi)'] = math.sqrt(GardenGnomeLocations.loc[i, 'NorthSouth (mi)'] ** 2 + GardenGnomeLocations.loc[i, 'EastWest (mi)'] ** 2) if GardenGnomeLocations.loc[i, 'NorthSouth (mi)'] < 0: GardenGnomeLocations.loc[i, 'Distance (mi)'] = -1 * GardenGnomeLocations.loc[i, 'Distance (mi)']" }, { "code": null, "e": 6644, "s": 5510, "text": "The for loop at the top of the code block tells the script to perform this calculation for each row in the GardenGnomeLocations dataframe, and to use the variable i to keep track of it’s location in the dataframe. The second line performs the actual calculation and stores the data in the appropriate location in the dataframe. You’ll note that the equation boils down to c = sqrt(a2 + b2), which is the common form of the pythagorean theorem. The first term, GardenGnomeLocations.loc[i, ‘Distance (mi)’] tells python that the value we’re about to calculate should be placed in row i of column ‘Distance (mi)’ in the GardenGnomeLocations dataframe. The other side of the equation uses the corresponding data from the ‘NorthSouth (mi)’ and ‘EastWest (mi)’ columns to calculate the result. Keep in mind that the pythagorean theorem will only return absolute values of the distance. To overcome that, we add the final two lines of code. The first determines whether the values of the original data point were positive or negative. The second then multiplies the distance by -1, to make it negative, if the original values were negative." }, { "code": null, "e": 6996, "s": 6644, "text": "Plotting this data results in Figure 2. The data looks very similar, because this plot presents it in 2 dimensions, but notice the axes in this case. Instead of presenting each plot using the location in the North-South and East-West axes, Figure 2 shows the location of each gnome only in terms of the distance from the city center. In one dimension." }, { "code": null, "e": 7389, "s": 6996, "text": "This reduction to a single dimension makes the data set much easier to use. Fewer points are needed to ensure that the data set is dense enough to return accurate predictions. Fewer data points means reduced computational time for the same quality results. And some algorithms, like the k-nearest neighbors algorithm, are much more likely to return useful results than with higher dimensions." }, { "code": null, "e": 8000, "s": 7389, "text": "This transformation does make it harder to interpret the data, however. Originally the data was easily understood; each data point referred to the location of the garden gnome in terms we commonly use. We could fine the distance North/South, and the distance East/West and simple use that. Now instead we have a distance from the city center, but the data doesn’t clearly state the direction. In order to make sense of this data, we must retain all prior data sets and algorithms. In that way we can later translate the data from the new axis back to the original axis, so it can be easily understood and used." }, { "code": null, "e": 8675, "s": 8000, "text": "Unfortunately, no it isn’t really that simple. This was an overly simplified, somewhat comical, example meant to demonstrate the fundamental concepts. In reality no data set will operate along a perfectly shaped line like this data set did, and it won’t be possible to transform the data by simply using the pythagorean theorem. Real data sets will look more like clouds of data with vague trends hidden in them, and you’ll need to use a technique called principal component analysis to transform the data. This technique is beyond the scope of this introductory article, but Joel Gros does an excellent job of demonstrating how to implement it in Data Science from Scratch." }, { "code": null, "e": 9245, "s": 8675, "text": "Highly dimensional data sets provide a serious challenge for data scientists. As the number of dimensions increases, so does the data space. As more and more dimensions are added, the space becomes extremely large. This large space makes it hard for most machine learning algorithms to function because gaps in the data set present areas that the models cannot match. Some algorithms, such as the k-nearest neighbors algorithm, are especially sensitive because they require data points to be close in every dimension which gets very rare when there are many dimensions." }, { "code": null, "e": 9599, "s": 9245, "text": "The obvious solution to the dimensionality problem is larger data sets. This can be used to maintain data density; however, very large data spaces require very large data sets. These data sets can get too large, overwhelming the ability of computers to perform the necessary calculations. In that case, the solution is to apply dimensionality reduction." } ]
SAP HANA - SQL Expressions
An Expression is used to evaluate a clause to return values. There are different SQL expressions that can be used in HANA − Case Expressions Function Expressions Aggregate Expressions Subqueries in Expressions This is used to pass multiple conditions in a SQL expression. It allows the use of IF-ELSE-THEN logic without using procedures in SQL statements. SELECT COUNT( CASE WHEN sal < 2000 THEN 1 ELSE NULL END ) count1, COUNT( CASE WHEN sal BETWEEN 2001 AND 4000 THEN 1 ELSE NULL END ) count2, COUNT( CASE WHEN sal > 4000 THEN 1 ELSE NULL END ) count3 FROM emp; This statement will return count1, count2, count3 with integer value as per passed condition. Function expressions involve SQL inbuilt functions to be used in Expressions. Aggregate functions are used to perform complex calculations like Sum, Percentage, Min, Max, Count, Mode, Median, etc. Aggregate Expression uses Aggregate functions to calculate single value from multiple values. Aggregate Functions − Sum, Count, Minimum, Maximum. These are applied on measure values (facts) and It is always associated with a dimension. Common aggregate functions include − Average () Count () Maximum () Median () Minimum () Mode () Sum () A subquery as an expression is a Select statement. When it is used in an expression, it returns a zero or a single value. A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved. Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators like =, <, >, >=, <=, IN, BETWEEN etc. There are a few rules that subqueries must follow − Subqueries must be enclosed within parentheses. Subqueries must be enclosed within parentheses. A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns. A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns. An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY can be used to perform the same function as the ORDER BY in a subquery. An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY can be used to perform the same function as the ORDER BY in a subquery. Subqueries that return more than one row can only be used with multiple value operators, such as the IN operator. Subqueries that return more than one row can only be used with multiple value operators, such as the IN operator. The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY, CLOB, or NCLOB. The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY, CLOB, or NCLOB. A subquery cannot be immediately enclosed in a set function. A subquery cannot be immediately enclosed in a set function. The BETWEEN operator cannot be used with a subquery; however, the BETWEEN operator can be used within the subquery. The BETWEEN operator cannot be used with a subquery; however, the BETWEEN operator can be used within the subquery. Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows − SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS WHERE SALARY > 4500) ; +----+----------+-----+---------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+---------+----------+ | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+---------+----------+ 25 Lectures 6 hours Sanjo Thomas 26 Lectures 2 hours Neha Gupta 30 Lectures 2.5 hours Sumit Agarwal 30 Lectures 4 hours Sumit Agarwal 14 Lectures 1.5 hours Neha Malik 13 Lectures 1.5 hours Neha Malik Print Add Notes Bookmark this page
[ { "code": null, "e": 3231, "s": 3107, "text": "An Expression is used to evaluate a clause to return values. There are different SQL expressions that can be used in HANA −" }, { "code": null, "e": 3248, "s": 3231, "text": "Case Expressions" }, { "code": null, "e": 3269, "s": 3248, "text": "Function Expressions" }, { "code": null, "e": 3291, "s": 3269, "text": "Aggregate Expressions" }, { "code": null, "e": 3317, "s": 3291, "text": "Subqueries in Expressions" }, { "code": null, "e": 3463, "s": 3317, "text": "This is used to pass multiple conditions in a SQL expression. It allows the use of IF-ELSE-THEN logic without using procedures in SQL statements." }, { "code": null, "e": 3671, "s": 3463, "text": "SELECT COUNT( CASE WHEN sal < 2000 THEN 1 ELSE NULL END ) count1,\nCOUNT( CASE WHEN sal BETWEEN 2001 AND 4000 THEN 1 ELSE NULL END ) count2,\nCOUNT( CASE WHEN sal > 4000 THEN 1 ELSE NULL END ) count3 FROM emp;" }, { "code": null, "e": 3765, "s": 3671, "text": "This statement will return count1, count2, count3 with integer value as per passed condition." }, { "code": null, "e": 3843, "s": 3765, "text": "Function expressions involve SQL inbuilt functions to be used in Expressions." }, { "code": null, "e": 4056, "s": 3843, "text": "Aggregate functions are used to perform complex calculations like Sum, Percentage, Min, Max, Count, Mode, Median, etc. Aggregate Expression uses Aggregate functions to calculate single value from multiple values." }, { "code": null, "e": 4198, "s": 4056, "text": "Aggregate Functions − Sum, Count, Minimum, Maximum. These are applied on measure values (facts) and It is always associated with a dimension." }, { "code": null, "e": 4235, "s": 4198, "text": "Common aggregate functions include −" }, { "code": null, "e": 4246, "s": 4235, "text": "Average ()" }, { "code": null, "e": 4255, "s": 4246, "text": "Count ()" }, { "code": null, "e": 4266, "s": 4255, "text": "Maximum ()" }, { "code": null, "e": 4276, "s": 4266, "text": "Median ()" }, { "code": null, "e": 4287, "s": 4276, "text": "Minimum ()" }, { "code": null, "e": 4295, "s": 4287, "text": "Mode ()" }, { "code": null, "e": 4302, "s": 4295, "text": "Sum ()" }, { "code": null, "e": 4424, "s": 4302, "text": "A subquery as an expression is a Select statement. When it is used in an expression, it returns a zero or a single value." }, { "code": null, "e": 4555, "s": 4424, "text": "A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved." }, { "code": null, "e": 4697, "s": 4555, "text": "Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators like =, <, >, >=, <=, IN, BETWEEN etc." }, { "code": null, "e": 4749, "s": 4697, "text": "There are a few rules that subqueries must follow −" }, { "code": null, "e": 4797, "s": 4749, "text": "Subqueries must be enclosed within parentheses." }, { "code": null, "e": 4845, "s": 4797, "text": "Subqueries must be enclosed within parentheses." }, { "code": null, "e": 4999, "s": 4845, "text": "A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns." }, { "code": null, "e": 5153, "s": 4999, "text": "A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns." }, { "code": null, "e": 5325, "s": 5153, "text": "An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY can be used to perform the same function as the ORDER BY in a subquery." }, { "code": null, "e": 5497, "s": 5325, "text": "An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY can be used to perform the same function as the ORDER BY in a subquery." }, { "code": null, "e": 5611, "s": 5497, "text": "Subqueries that return more than one row can only be used with multiple value operators, such as the IN operator." }, { "code": null, "e": 5725, "s": 5611, "text": "Subqueries that return more than one row can only be used with multiple value operators, such as the IN operator." }, { "code": null, "e": 5829, "s": 5725, "text": "The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY, CLOB, or NCLOB." }, { "code": null, "e": 5933, "s": 5829, "text": "The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY, CLOB, or NCLOB." }, { "code": null, "e": 5994, "s": 5933, "text": "A subquery cannot be immediately enclosed in a set function." }, { "code": null, "e": 6055, "s": 5994, "text": "A subquery cannot be immediately enclosed in a set function." }, { "code": null, "e": 6171, "s": 6055, "text": "The BETWEEN operator cannot be used with a subquery; however, the BETWEEN operator can be used within the subquery." }, { "code": null, "e": 6287, "s": 6171, "text": "The BETWEEN operator cannot be used with a subquery; however, the BETWEEN operator can be used within the subquery." }, { "code": null, "e": 6383, "s": 6287, "text": "Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows −" }, { "code": null, "e": 6468, "s": 6383, "text": "SELECT * FROM CUSTOMERS\nWHERE ID IN (SELECT ID\nFROM CUSTOMERS\nWHERE SALARY > 4500) ;" }, { "code": null, "e": 6784, "s": 6468, "text": "+----+----------+-----+---------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+---------+----------+\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+---------+----------+\n" }, { "code": null, "e": 6817, "s": 6784, "text": "\n 25 Lectures \n 6 hours \n" }, { "code": null, "e": 6831, "s": 6817, "text": " Sanjo Thomas" }, { "code": null, "e": 6864, "s": 6831, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 6876, "s": 6864, "text": " Neha Gupta" }, { "code": null, "e": 6911, "s": 6876, "text": "\n 30 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6926, "s": 6911, "text": " Sumit Agarwal" }, { "code": null, "e": 6959, "s": 6926, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 6974, "s": 6959, "text": " Sumit Agarwal" }, { "code": null, "e": 7009, "s": 6974, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7021, "s": 7009, "text": " Neha Malik" }, { "code": null, "e": 7056, "s": 7021, "text": "\n 13 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7068, "s": 7056, "text": " Neha Malik" }, { "code": null, "e": 7075, "s": 7068, "text": " Print" }, { "code": null, "e": 7086, "s": 7075, "text": " Add Notes" } ]
Python Arrays - GeeksforGeeks
19 Jan, 2022 An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array).For simplicity, we can think of an array a fleet of stairs where on each step is placed a value (let’s say one of your friends). Here, you can identify the location of any of your friends by simply knowing the count of the step they are on. Array can be handled in Python by a module named array. They can be useful when we have to manipulate only a specific data type values. A user can treat lists as arrays. However, user cannot constraint the type of elements stored in a list. If you create arrays using the array module, all elements of the array must be of the same type. Array in Python can be created by importing array module. array(data_type, value_list) is used to create an array with data type and value list specified in its arguments. Python3 # Python program to demonstrate# Creation of Array # importing "array" for array creationsimport array as arr # creating an array with integer typea = arr.array('i', [1, 2, 3]) # printing original arrayprint ("The new created array is : ", end =" ")for i in range (0, 3): print (a[i], end =" ")print() # creating an array with float typeb = arr.array('d', [2.5, 3.2, 3.3]) # printing original arrayprint ("The new created array is : ", end =" ")for i in range (0, 3): print (b[i], end =" ") Output : The new created array is : 1 2 3 The new created array is : 2.5 3.2 3.3 Some of the data types are mentioned below which will help in creating an array of different data types. Elements can be added to the Array by using built-in insert() function. Insert is used to insert one or more data elements into an array. Based on the requirement, a new element can be added at the beginning, end, or any given index of array. append() is also used to add the value mentioned in its arguments at the end of the array. Python3 # Python program to demonstrate# Adding Elements to a Array # importing "array" for array creationsimport array as arr # array with int typea = arr.array('i', [1, 2, 3]) print ("Array before insertion : ", end =" ")for i in range (0, 3): print (a[i], end =" ")print() # inserting array using# insert() functiona.insert(1, 4) print ("Array after insertion : ", end =" ")for i in (a): print (i, end =" ")print() # array with float typeb = arr.array('d', [2.5, 3.2, 3.3]) print ("Array before insertion : ", end =" ")for i in range (0, 3): print (b[i], end =" ")print() # adding an element using append()b.append(4.4) print ("Array after insertion : ", end =" ")for i in (b): print (i, end =" ")print() Output : Array before insertion : 1 2 3 Array after insertion : 1 4 2 3 Array before insertion : 2.5 3.2 3.3 Array after insertion : 2.5 3.2 3.3 4.4 In order to access the array items refer to the index number. Use the index operator [ ] to access an item in a array. The index must be an integer. Python3 # Python program to demonstrate# accessing of element from list # importing array moduleimport array as arr # array with int typea = arr.array('i', [1, 2, 3, 4, 5, 6]) # accessing element of arrayprint("Access element is: ", a[0]) # accessing element of arrayprint("Access element is: ", a[3]) # array with float typeb = arr.array('d', [2.5, 3.2, 3.3]) # accessing element of arrayprint("Access element is: ", b[1]) # accessing element of arrayprint("Access element is: ", b[2]) Output : Access element is: 1 Access element is: 4 Access element is: 3.2 Access element is: 3.3 Elements can be removed from the array by using built-in remove() function but an Error arises if element doesn’t exist in the set. Remove() method only removes one element at a time, to remove range of elements, iterator is used. pop() function can also be used to remove and return an element from the array, but by default it removes only the last element of the array, to remove element from a specific position of the array, index of the element is passed as an argument to the pop() method.Note – Remove method in List will only remove the first occurrence of the searched element. Python3 # Python program to demonstrate# Removal of elements in a Array # importing "array" for array operationsimport array # initializing array with array values# initializes array with signed integersarr = array.array('i', [1, 2, 3, 1, 5]) # printing original arrayprint ("The new created array is : ", end ="")for i in range (0, 5): print (arr[i], end =" ") print ("\r") # using pop() to remove element at 2nd positionprint ("The popped element is : ", end ="")print (arr.pop(2)) # printing array after poppingprint ("The array after popping is : ", end ="")for i in range (0, 4): print (arr[i], end =" ") print("\r") # using remove() to remove 1st occurrence of 1arr.remove(1) # printing array after removingprint ("The array after removing is : ", end ="")for i in range (0, 3): print (arr[i], end =" ") Output: The new created array is : 1 2 3 1 5 The popped element is : 3 The array after popping is : 1 2 1 5 The array after removing is : 2 1 5 In Python array, there are multiple ways to print the whole array with all the elements, but to print a specific range of elements from the array, we use Slice operation. Slice operation is performed on array with the use of colon(:). To print elements from beginning to a range use [:Index], to print elements from end use [:-Index], to print elements from specific Index till the end use [Index:], to print elements within a range, use [Start Index:End Index] and to print whole List with the use of slicing operation, use [:]. Further, to print whole array in reverse order, use [::-1]. Python3 # Python program to demonstrate# slicing of elements in a Array # importing array moduleimport array as arr # creating a listl = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] a = arr.array('i', l)print("Initial Array: ")for i in (a): print(i, end =" ") # Print elements of a range# using Slice operationSliced_array = a[3:8]print("\nSlicing elements in a range 3-8: ")print(Sliced_array) # Print elements from a# pre-defined point to endSliced_array = a[5:]print("\nElements sliced from 5th " "element till the end: ")print(Sliced_array) # Printing elements from# beginning till endSliced_array = a[:]print("\nPrinting all elements using slice operation: ")print(Sliced_array) Initial Array: 1 2 3 4 5 6 7 8 9 10 Slicing elements in a range 3-8: array('i', [4, 5, 6, 7, 8]) Elements sliced from 5th element till the end: array('i', [6, 7, 8, 9, 10]) Printing all elements using slice operation: array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) Output : Initial Array: 1 2 3 4 5 6 7 8 9 10 Slicing elements in a range 3-8: array('i', [4, 5, 6, 7, 8]) Elements sliced from 5th element till the end: array('i', [6, 7, 8, 9, 10]) Printing all elements using slice operation: array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) In order to search an element in the array we use a python in-built index() method. This function returns the index of the first occurrence of value mentioned in arguments. Python3 # Python code to demonstrate# searching an element in array # importing array moduleimport array # initializing array with array values# initializes array with signed integersarr = array.array('i', [1, 2, 3, 1, 2, 5]) # printing original arrayprint ("The new created array is : ", end ="")for i in range (0, 6): print (arr[i], end =" ") print ("\r") # using index() to print index of 1st occurrence of 2print ("The index of 1st occurrence of 2 is : ", end ="")print (arr.index(2)) # using index() to print index of 1st occurrence of 1print ("The index of 1st occurrence of 1 is : ", end ="")print (arr.index(1)) Output: The new created array is : 1 2 3 1 2 5 The index of 1st occurrence of 2 is : 1 The index of 1st occurrence of 1 is : 0 In order to update an element in the array we simply reassign a new value to the desired index we want to update. Python3 # Python code to demonstrate# how to update an element in array # importing array moduleimport array # initializing array with array values# initializes array with signed integersarr = array.array('i', [1, 2, 3, 1, 2, 5]) # printing original arrayprint ("Array before updation : ", end ="")for i in range (0, 6): print (arr[i], end =" ") print ("\r") # updating a element in a arrayarr[2] = 6print("Array after updation : ", end ="")for i in range (0, 6): print (arr[i], end =" ")print() # updating a element in a arrayarr[4] = 8print("Array after updation : ", end ="")for i in range (0, 6): print (arr[i], end =" ") Output: Array before updation : 1 2 3 1 2 5 Array after updation : 1 2 6 1 2 5 Array after updation : 1 2 6 1 8 5 gulshankumarar231 ruhelaa48 sooda367 sumitgumber28 Python-array Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace()
[ { "code": null, "e": 41552, "s": 41524, "text": "\n19 Jan, 2022" }, { "code": null, "e": 42481, "s": 41552, "text": "An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array).For simplicity, we can think of an array a fleet of stairs where on each step is placed a value (let’s say one of your friends). Here, you can identify the location of any of your friends by simply knowing the count of the step they are on. Array can be handled in Python by a module named array. They can be useful when we have to manipulate only a specific data type values. A user can treat lists as arrays. However, user cannot constraint the type of elements stored in a list. If you create arrays using the array module, all elements of the array must be of the same type. " }, { "code": null, "e": 42657, "s": 42483, "text": "Array in Python can be created by importing array module. array(data_type, value_list) is used to create an array with data type and value list specified in its arguments. " }, { "code": null, "e": 42665, "s": 42657, "text": "Python3" }, { "code": "# Python program to demonstrate# Creation of Array # importing \"array\" for array creationsimport array as arr # creating an array with integer typea = arr.array('i', [1, 2, 3]) # printing original arrayprint (\"The new created array is : \", end =\" \")for i in range (0, 3): print (a[i], end =\" \")print() # creating an array with float typeb = arr.array('d', [2.5, 3.2, 3.3]) # printing original arrayprint (\"The new created array is : \", end =\" \")for i in range (0, 3): print (b[i], end =\" \") ", "e": 43166, "s": 42665, "text": null }, { "code": null, "e": 43176, "s": 43166, "text": "Output : " }, { "code": null, "e": 43252, "s": 43176, "text": "The new created array is : 1 2 3 \nThe new created array is : 2.5 3.2 3.3 " }, { "code": null, "e": 43359, "s": 43252, "text": "Some of the data types are mentioned below which will help in creating an array of different data types. " }, { "code": null, "e": 43697, "s": 43361, "text": "Elements can be added to the Array by using built-in insert() function. Insert is used to insert one or more data elements into an array. Based on the requirement, a new element can be added at the beginning, end, or any given index of array. append() is also used to add the value mentioned in its arguments at the end of the array. " }, { "code": null, "e": 43705, "s": 43697, "text": "Python3" }, { "code": "# Python program to demonstrate# Adding Elements to a Array # importing \"array\" for array creationsimport array as arr # array with int typea = arr.array('i', [1, 2, 3]) print (\"Array before insertion : \", end =\" \")for i in range (0, 3): print (a[i], end =\" \")print() # inserting array using# insert() functiona.insert(1, 4) print (\"Array after insertion : \", end =\" \")for i in (a): print (i, end =\" \")print() # array with float typeb = arr.array('d', [2.5, 3.2, 3.3]) print (\"Array before insertion : \", end =\" \")for i in range (0, 3): print (b[i], end =\" \")print() # adding an element using append()b.append(4.4) print (\"Array after insertion : \", end =\" \")for i in (b): print (i, end =\" \")print()", "e": 44418, "s": 43705, "text": null }, { "code": null, "e": 44428, "s": 44418, "text": "Output : " }, { "code": null, "e": 44574, "s": 44428, "text": "Array before insertion : 1 2 3 \nArray after insertion : 1 4 2 3 \nArray before insertion : 2.5 3.2 3.3 \nArray after insertion : 2.5 3.2 3.3 4.4 " }, { "code": null, "e": 44727, "s": 44576, "text": "In order to access the array items refer to the index number. Use the index operator [ ] to access an item in a array. The index must be an integer. " }, { "code": null, "e": 44735, "s": 44727, "text": "Python3" }, { "code": "# Python program to demonstrate# accessing of element from list # importing array moduleimport array as arr # array with int typea = arr.array('i', [1, 2, 3, 4, 5, 6]) # accessing element of arrayprint(\"Access element is: \", a[0]) # accessing element of arrayprint(\"Access element is: \", a[3]) # array with float typeb = arr.array('d', [2.5, 3.2, 3.3]) # accessing element of arrayprint(\"Access element is: \", b[1]) # accessing element of arrayprint(\"Access element is: \", b[2])", "e": 45214, "s": 44735, "text": null }, { "code": null, "e": 45224, "s": 45214, "text": "Output : " }, { "code": null, "e": 45316, "s": 45224, "text": "Access element is: 1\nAccess element is: 4\nAccess element is: 3.2\nAccess element is: 3.3" }, { "code": null, "e": 45908, "s": 45318, "text": "Elements can be removed from the array by using built-in remove() function but an Error arises if element doesn’t exist in the set. Remove() method only removes one element at a time, to remove range of elements, iterator is used. pop() function can also be used to remove and return an element from the array, but by default it removes only the last element of the array, to remove element from a specific position of the array, index of the element is passed as an argument to the pop() method.Note – Remove method in List will only remove the first occurrence of the searched element. " }, { "code": null, "e": 45916, "s": 45908, "text": "Python3" }, { "code": "# Python program to demonstrate# Removal of elements in a Array # importing \"array\" for array operationsimport array # initializing array with array values# initializes array with signed integersarr = array.array('i', [1, 2, 3, 1, 5]) # printing original arrayprint (\"The new created array is : \", end =\"\")for i in range (0, 5): print (arr[i], end =\" \") print (\"\\r\") # using pop() to remove element at 2nd positionprint (\"The popped element is : \", end =\"\")print (arr.pop(2)) # printing array after poppingprint (\"The array after popping is : \", end =\"\")for i in range (0, 4): print (arr[i], end =\" \") print(\"\\r\") # using remove() to remove 1st occurrence of 1arr.remove(1) # printing array after removingprint (\"The array after removing is : \", end =\"\")for i in range (0, 3): print (arr[i], end =\" \")", "e": 46729, "s": 45916, "text": null }, { "code": null, "e": 46738, "s": 46729, "text": "Output: " }, { "code": null, "e": 46877, "s": 46738, "text": "The new created array is : 1 2 3 1 5 \nThe popped element is : 3\nThe array after popping is : 1 2 1 5 \nThe array after removing is : 2 1 5 " }, { "code": null, "e": 47471, "s": 46879, "text": "In Python array, there are multiple ways to print the whole array with all the elements, but to print a specific range of elements from the array, we use Slice operation. Slice operation is performed on array with the use of colon(:). To print elements from beginning to a range use [:Index], to print elements from end use [:-Index], to print elements from specific Index till the end use [Index:], to print elements within a range, use [Start Index:End Index] and to print whole List with the use of slicing operation, use [:]. Further, to print whole array in reverse order, use [::-1]. " }, { "code": null, "e": 47481, "s": 47473, "text": "Python3" }, { "code": "# Python program to demonstrate# slicing of elements in a Array # importing array moduleimport array as arr # creating a listl = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] a = arr.array('i', l)print(\"Initial Array: \")for i in (a): print(i, end =\" \") # Print elements of a range# using Slice operationSliced_array = a[3:8]print(\"\\nSlicing elements in a range 3-8: \")print(Sliced_array) # Print elements from a# pre-defined point to endSliced_array = a[5:]print(\"\\nElements sliced from 5th \" \"element till the end: \")print(Sliced_array) # Printing elements from# beginning till endSliced_array = a[:]print(\"\\nPrinting all elements using slice operation: \")print(Sliced_array)", "e": 48152, "s": 47481, "text": null }, { "code": null, "e": 48421, "s": 48152, "text": "Initial Array: \n1 2 3 4 5 6 7 8 9 10 \nSlicing elements in a range 3-8: \narray('i', [4, 5, 6, 7, 8])\n\nElements sliced from 5th element till the end: \narray('i', [6, 7, 8, 9, 10])\n\nPrinting all elements using slice operation: \narray('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])" }, { "code": null, "e": 48431, "s": 48421, "text": "Output : " }, { "code": null, "e": 48700, "s": 48431, "text": "Initial Array: \n1 2 3 4 5 6 7 8 9 10 \nSlicing elements in a range 3-8: \narray('i', [4, 5, 6, 7, 8])\n\nElements sliced from 5th element till the end: \narray('i', [6, 7, 8, 9, 10])\n\nPrinting all elements using slice operation: \narray('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])" }, { "code": null, "e": 48877, "s": 48702, "text": "In order to search an element in the array we use a python in-built index() method. This function returns the index of the first occurrence of value mentioned in arguments. " }, { "code": null, "e": 48885, "s": 48877, "text": "Python3" }, { "code": "# Python code to demonstrate# searching an element in array # importing array moduleimport array # initializing array with array values# initializes array with signed integersarr = array.array('i', [1, 2, 3, 1, 2, 5]) # printing original arrayprint (\"The new created array is : \", end =\"\")for i in range (0, 6): print (arr[i], end =\" \") print (\"\\r\") # using index() to print index of 1st occurrence of 2print (\"The index of 1st occurrence of 2 is : \", end =\"\")print (arr.index(2)) # using index() to print index of 1st occurrence of 1print (\"The index of 1st occurrence of 1 is : \", end =\"\")print (arr.index(1))", "e": 49503, "s": 48885, "text": null }, { "code": null, "e": 49513, "s": 49503, "text": "Output: " }, { "code": null, "e": 49633, "s": 49513, "text": "The new created array is : 1 2 3 1 2 5 \nThe index of 1st occurrence of 2 is : 1\nThe index of 1st occurrence of 1 is : 0" }, { "code": null, "e": 49751, "s": 49635, "text": "In order to update an element in the array we simply reassign a new value to the desired index we want to update. " }, { "code": null, "e": 49759, "s": 49751, "text": "Python3" }, { "code": "# Python code to demonstrate# how to update an element in array # importing array moduleimport array # initializing array with array values# initializes array with signed integersarr = array.array('i', [1, 2, 3, 1, 2, 5]) # printing original arrayprint (\"Array before updation : \", end =\"\")for i in range (0, 6): print (arr[i], end =\" \") print (\"\\r\") # updating a element in a arrayarr[2] = 6print(\"Array after updation : \", end =\"\")for i in range (0, 6): print (arr[i], end =\" \")print() # updating a element in a arrayarr[4] = 8print(\"Array after updation : \", end =\"\")for i in range (0, 6): print (arr[i], end =\" \")", "e": 50386, "s": 49759, "text": null }, { "code": null, "e": 50395, "s": 50386, "text": "Output: " }, { "code": null, "e": 50504, "s": 50395, "text": "Array before updation : 1 2 3 1 2 5 \nArray after updation : 1 2 6 1 2 5 \nArray after updation : 1 2 6 1 8 5 " }, { "code": null, "e": 50522, "s": 50504, "text": "gulshankumarar231" }, { "code": null, "e": 50532, "s": 50522, "text": "ruhelaa48" }, { "code": null, "e": 50541, "s": 50532, "text": "sooda367" }, { "code": null, "e": 50555, "s": 50541, "text": "sumitgumber28" }, { "code": null, "e": 50568, "s": 50555, "text": "Python-array" }, { "code": null, "e": 50575, "s": 50568, "text": "Python" }, { "code": null, "e": 50673, "s": 50575, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 50701, "s": 50673, "text": "Read JSON file using Python" }, { "code": null, "e": 50751, "s": 50701, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 50773, "s": 50751, "text": "Python map() function" }, { "code": null, "e": 50817, "s": 50773, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 50852, "s": 50817, "text": "Read a file line by line in Python" }, { "code": null, "e": 50874, "s": 50852, "text": "Enumerate() in Python" }, { "code": null, "e": 50906, "s": 50874, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 50936, "s": 50906, "text": "Iterate over a list in Python" }, { "code": null, "e": 50978, "s": 50936, "text": "Different ways to create Pandas Dataframe" } ]
How to use OR condition in a JavaScript IF statement?
To use OR condition in JavaScript IF statement, use the || operator i.e Logical OR operator. If any of the two operands are non-zero, then the condition becomes true. Here’s how you can use the operator || in JavaScript Live Demo <html> <body> <script> var a = true; var b = false; document.write("(a || b) => "); result = (a || b); document.write(result); </script> </body> </html>
[ { "code": null, "e": 1229, "s": 1062, "text": "To use OR condition in JavaScript IF statement, use the || operator i.e Logical OR operator. If any of the two operands are non-zero, then the condition becomes true." }, { "code": null, "e": 1282, "s": 1229, "text": "Here’s how you can use the operator || in JavaScript" }, { "code": null, "e": 1292, "s": 1282, "text": "Live Demo" }, { "code": null, "e": 1509, "s": 1292, "text": "<html>\n <body>\n <script>\n var a = true;\n var b = false;\n\n document.write(\"(a || b) => \");\n result = (a || b);\n document.write(result);\n </script>\n </body>\n</html>" } ]
How to change the column names and row names of a data frame in R?
We can colnames function to change the column names and rownames function to change the row names. > df <- data.frame(ID=1:5,Salry=c(10000,30000,22000,27000,18000)) > df ID Salry 1 1 10000 2 2 30000 3 3 22000 4 4 27000 5 5 18000 > colnames(df)<-c("EmployeeID","Salary") > df EmployeeID Salary 1 1 10000 2 2 30000 3 3 22000 4 4 27000 5 5 18000 > rownames(df)<-c("001","025","019","102","089") df EmployeeID Salary 001 1 10000 025 2 30000 019 3 22000 102 4 27000 089 5 18000
[ { "code": null, "e": 1161, "s": 1062, "text": "We can colnames function to change the column names and rownames function to\nchange the row names." }, { "code": null, "e": 1535, "s": 1161, "text": "> df <- data.frame(ID=1:5,Salry=c(10000,30000,22000,27000,18000))\n> df\nID Salry\n1 1 10000\n2 2 30000\n3 3 22000\n4 4 27000\n5 5 18000\n> colnames(df)<-c(\"EmployeeID\",\"Salary\")\n> df\nEmployeeID Salary\n1 1 10000\n2 2 30000\n3 3 22000\n4 4 27000\n5 5 18000\n> rownames(df)<-c(\"001\",\"025\",\"019\",\"102\",\"089\")\ndf\nEmployeeID Salary\n001 1 10000\n025 2 30000\n019 3 22000\n102 4 27000\n089 5 18000" } ]
Cosine Similarity - GeeksforGeeks
06 Oct, 2020 Prerequisite – Measures of Distance in Data Mining In Data Mining, similarity measure refers to distance with dimensions representing features of the data object, in a dataset. If this distance is less, there will be a high degree of similarity, but when the distance is large, there will be a low degree of similarity. Some of the popular similarity measures are – Euclidean Distance.Manhattan Distance.Jaccard Similarity.Minkowski Distance.Cosine Similarity. Euclidean Distance. Manhattan Distance. Jaccard Similarity. Minkowski Distance. Cosine Similarity. Cosine similarity is a metric, helpful in determining, how similar the data objects are irrespective of their size. We can measure the similarity between two sentences in Python using Cosine Similarity. In cosine similarity, data objects in a dataset are treated as a vector. The formula to find the cosine similarity between two vectors is – Cos(x, y) = x . y / ||x|| * ||y|| where, x . y = product (dot) of the vectors ‘x’ and ‘y’. ||x|| and ||y|| = length of the two vectors ‘x’ and ‘y’. ||x|| * ||y|| = cross product of the two vectors ‘x’ and ‘y’. Example :Consider an example to find the similarity between two vectors – ‘x’ and ‘y’, using Cosine Similarity. The ‘x’ vector has values, x = { 3, 2, 0, 5 }The ‘y’ vector has values, y = { 1, 0, 0, 0 } The formula for calculating the cosine similarity is : Cos(x, y) = x . y / ||x|| * ||y|| x . y = 3*1 + 2*0 + 0*0 + 5*0 = 3 ||x|| = √ (3)^2 + (2)^2 + (0)^2 + (5)^2 = 6.16 ||y|| = √ (1)^2 + (0)^2 + (0)^2 + (0)^2 = 1 ∴ Cos(x, y) = 3 / (6.16 * 1) = 0.49 The dissimilarity between the two vectors ‘x’ and ‘y’ is given by – ∴ Dis(x, y) = 1 - Cos(x, y) = 1 - 0.49 = 0.51 The cosine similarity between two vectors is measured in ‘θ’. If θ = 0°, the ‘x’ and ‘y’ vectors overlap, thus proving they are similar. If θ = 90°, the ‘x’ and ‘y’ vectors are dissimilar. Cosine Similarity between two vectors Advantages : The cosine similarity is beneficial because even if the two similar data objects are far apart by the Euclidean distance because of the size, they could still have a smaller angle between them. Smaller the angle, higher the similarity. When plotted on a multi-dimensional space, the cosine similarity captures the orientation (the angle) of the data objects and not the magnitude. data mining DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction of B-Tree Difference between Clustered and Non-clustered index CTE in SQL SQL | Views SQL Interview Questions Third Normal Form (3NF) SQL | GROUP BY Difference between Primary Key and Foreign Key Second Normal Form (2NF) Difference between DELETE, DROP and TRUNCATE
[ { "code": null, "e": 24413, "s": 24385, "text": "\n06 Oct, 2020" }, { "code": null, "e": 24464, "s": 24413, "text": "Prerequisite – Measures of Distance in Data Mining" }, { "code": null, "e": 24733, "s": 24464, "text": "In Data Mining, similarity measure refers to distance with dimensions representing features of the data object, in a dataset. If this distance is less, there will be a high degree of similarity, but when the distance is large, there will be a low degree of similarity." }, { "code": null, "e": 24779, "s": 24733, "text": "Some of the popular similarity measures are –" }, { "code": null, "e": 24874, "s": 24779, "text": "Euclidean Distance.Manhattan Distance.Jaccard Similarity.Minkowski Distance.Cosine Similarity." }, { "code": null, "e": 24894, "s": 24874, "text": "Euclidean Distance." }, { "code": null, "e": 24914, "s": 24894, "text": "Manhattan Distance." }, { "code": null, "e": 24934, "s": 24914, "text": "Jaccard Similarity." }, { "code": null, "e": 24954, "s": 24934, "text": "Minkowski Distance." }, { "code": null, "e": 24973, "s": 24954, "text": "Cosine Similarity." }, { "code": null, "e": 25316, "s": 24973, "text": "Cosine similarity is a metric, helpful in determining, how similar the data objects are irrespective of their size. We can measure the similarity between two sentences in Python using Cosine Similarity. In cosine similarity, data objects in a dataset are treated as a vector. The formula to find the cosine similarity between two vectors is –" }, { "code": null, "e": 25350, "s": 25316, "text": "Cos(x, y) = x . y / ||x|| * ||y||" }, { "code": null, "e": 25357, "s": 25350, "text": "where," }, { "code": null, "e": 25407, "s": 25357, "text": "x . y = product (dot) of the vectors ‘x’ and ‘y’." }, { "code": null, "e": 25464, "s": 25407, "text": "||x|| and ||y|| = length of the two vectors ‘x’ and ‘y’." }, { "code": null, "e": 25526, "s": 25464, "text": "||x|| * ||y|| = cross product of the two vectors ‘x’ and ‘y’." }, { "code": null, "e": 25638, "s": 25526, "text": "Example :Consider an example to find the similarity between two vectors – ‘x’ and ‘y’, using Cosine Similarity." }, { "code": null, "e": 25729, "s": 25638, "text": "The ‘x’ vector has values, x = { 3, 2, 0, 5 }The ‘y’ vector has values, y = { 1, 0, 0, 0 }" }, { "code": null, "e": 25818, "s": 25729, "text": "The formula for calculating the cosine similarity is : Cos(x, y) = x . y / ||x|| * ||y||" }, { "code": null, "e": 25983, "s": 25818, "text": "x . y = 3*1 + 2*0 + 0*0 + 5*0 = 3\n\n||x|| = √ (3)^2 + (2)^2 + (0)^2 + (5)^2 = 6.16\n\n||y|| = √ (1)^2 + (0)^2 + (0)^2 + (0)^2 = 1\n\n∴ Cos(x, y) = 3 / (6.16 * 1) = 0.49 " }, { "code": null, "e": 26051, "s": 25983, "text": "The dissimilarity between the two vectors ‘x’ and ‘y’ is given by –" }, { "code": null, "e": 26097, "s": 26051, "text": "∴ Dis(x, y) = 1 - Cos(x, y) = 1 - 0.49 = 0.51" }, { "code": null, "e": 26159, "s": 26097, "text": "The cosine similarity between two vectors is measured in ‘θ’." }, { "code": null, "e": 26234, "s": 26159, "text": "If θ = 0°, the ‘x’ and ‘y’ vectors overlap, thus proving they are similar." }, { "code": null, "e": 26286, "s": 26234, "text": "If θ = 90°, the ‘x’ and ‘y’ vectors are dissimilar." }, { "code": null, "e": 26324, "s": 26286, "text": "Cosine Similarity between two vectors" }, { "code": null, "e": 26337, "s": 26324, "text": "Advantages :" }, { "code": null, "e": 26573, "s": 26337, "text": "The cosine similarity is beneficial because even if the two similar data objects are far apart by the Euclidean distance because of the size, they could still have a smaller angle between them. Smaller the angle, higher the similarity." }, { "code": null, "e": 26718, "s": 26573, "text": "When plotted on a multi-dimensional space, the cosine similarity captures the orientation (the angle) of the data objects and not the magnitude." }, { "code": null, "e": 26730, "s": 26718, "text": "data mining" }, { "code": null, "e": 26735, "s": 26730, "text": "DBMS" }, { "code": null, "e": 26740, "s": 26735, "text": "DBMS" }, { "code": null, "e": 26838, "s": 26740, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26861, "s": 26838, "text": "Introduction of B-Tree" }, { "code": null, "e": 26914, "s": 26861, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 26925, "s": 26914, "text": "CTE in SQL" }, { "code": null, "e": 26937, "s": 26925, "text": "SQL | Views" }, { "code": null, "e": 26961, "s": 26937, "text": "SQL Interview Questions" }, { "code": null, "e": 26985, "s": 26961, "text": "Third Normal Form (3NF)" }, { "code": null, "e": 27000, "s": 26985, "text": "SQL | GROUP BY" }, { "code": null, "e": 27047, "s": 27000, "text": "Difference between Primary Key and Foreign Key" }, { "code": null, "e": 27072, "s": 27047, "text": "Second Normal Form (2NF)" } ]
JavaScript - The Function() Constructor
The function statement is not the only way to define a new function; you can define your function dynamically using Function() constructor along with the new operator. Note − Constructor is a terminology from Object Oriented Programming. You may not feel comfortable for the first time, which is OK. Following is the syntax to create a function using Function( ) constructor along with the new operator. <script type = "text/javascript"> <!-- var variablename = new Function(Arg1, Arg2..., "Function Body"); //--> </script> The Function() constructor expects any number of string arguments. The last argument is the body of the function – it can contain arbitrary JavaScript statements, separated from each other by semicolons. Notice that the Function() constructor is not passed any argument that specifies a name for the function it creates. The unnamed functions created with the Function() constructor are called anonymous functions. Try the following example. <html> <head> <script type = "text/javascript"> <!-- var func = new Function("x", "y", "return x*y;"); function secondFunction() { var result; result = func(10,20); document.write ( result ); } //--> </script> </head> <body> <p>Click the following button to call the function</p> <form> <input type = "button" onclick = "secondFunction()" value = "Call Function"> </form> <p>Use different parameters inside the function and then try...</p> </body> </html> Click the following button to call the function Use different parameters inside the function and then try... 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2634, "s": 2466, "text": "The function statement is not the only way to define a new function; you can define your function dynamically using Function() constructor along with the new operator." }, { "code": null, "e": 2766, "s": 2634, "text": "Note − Constructor is a terminology from Object Oriented Programming. You may not feel comfortable for the first time, which is OK." }, { "code": null, "e": 2870, "s": 2766, "text": "Following is the syntax to create a function using Function( ) constructor along with the new operator." }, { "code": null, "e": 3003, "s": 2870, "text": "<script type = \"text/javascript\">\n <!--\n var variablename = new Function(Arg1, Arg2..., \"Function Body\");\n //-->\n</script>\n" }, { "code": null, "e": 3207, "s": 3003, "text": "The Function() constructor expects any number of string arguments. The last argument is the body of the function – it can contain arbitrary JavaScript statements, separated from each other by semicolons." }, { "code": null, "e": 3418, "s": 3207, "text": "Notice that the Function() constructor is not passed any argument that specifies a name for the function it creates. The unnamed functions created with the Function() constructor are called anonymous functions." }, { "code": null, "e": 3445, "s": 3418, "text": "Try the following example." }, { "code": null, "e": 4075, "s": 3445, "text": "<html>\n <head>\n <script type = \"text/javascript\">\n <!--\n var func = new Function(\"x\", \"y\", \"return x*y;\");\n function secondFunction() {\n var result;\n result = func(10,20);\n document.write ( result );\n }\n //-->\n </script>\n </head>\n \n <body>\n <p>Click the following button to call the function</p>\n \n <form>\n <input type = \"button\" onclick = \"secondFunction()\" value = \"Call Function\">\n </form>\n \n <p>Use different parameters inside the function and then try...</p>\n </body>\n</html>" }, { "code": null, "e": 4123, "s": 4075, "text": "Click the following button to call the function" }, { "code": null, "e": 4184, "s": 4123, "text": "Use different parameters inside the function and then try..." }, { "code": null, "e": 4219, "s": 4184, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4233, "s": 4219, "text": " Anadi Sharma" }, { "code": null, "e": 4267, "s": 4233, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 4281, "s": 4267, "text": " Lets Kode It" }, { "code": null, "e": 4316, "s": 4281, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4333, "s": 4316, "text": " Frahaan Hussain" }, { "code": null, "e": 4368, "s": 4333, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4385, "s": 4368, "text": " Frahaan Hussain" }, { "code": null, "e": 4418, "s": 4385, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 4446, "s": 4418, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4480, "s": 4446, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 4508, "s": 4480, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4515, "s": 4508, "text": " Print" }, { "code": null, "e": 4526, "s": 4515, "text": " Add Notes" } ]
Introduction to Bootstrapping in Data Science — part 1 | by Alejandro Rodríguez | Towards Data Science
You know the drill: there is a population and you would like to estimate a characteristic, for example, the mean. Unfortunately, you cannot measure every individual in the population, so you draw a sample. Following the guidelines in your favourite statistics book, you simplify the problem by assuming that the parameter distribution is normal and the sample size is large enough for the Central Limit Theorem to kick in. Under these assumptions, you notice that the task at hand resembles the “Confidence interval on the mean of a normal distribution with variance unknown”, so you look up the corresponding mathematical equations, fill in the values and... job done! Traditional statistical methods rely on large samples, a handful of well-known theoretical distributions and the safety net of the Central Limit Theorem to work. These shortcuts allow researchers to square the circle most of the time, although this is simply impossible in certain scenarios. As data scientists, we often face challenging problems that fall outside the safe haven of traditional statistics, which is constricted to a limited number of familiar scenarios. Sadly, the reality is stubborn, data comes in all flavours of skewed shapes, and sometimes you just need to estimate parameters more complex than a simple mean. But there is still hope. Thanks to the unstoppable evolution of computing, the study of large and complex datasets is now feasible. So are simulations that a few years ago were prohibitive to undertake. Currently, there are ways to relax some of the requisites of traditional inference and make things easier for data scientists. You can still thrive in challenging scenarios where there is not any approach sanctioned by theory. This article gently introduces the bootstrapping method, which can be applied to almost any statistic over a sample of univariate data. The first section solves a well-known problem to set a common ground for demonstrating that bootstrapping and theoretical approaches concur. Then we move into a more complex scenario where theory is of little help and, subsequently, we address the problem with bootstrapping. Before we move on, let’s tackle some misconceptions: bootstrap does not create data. What it actually does is estimating statistics, confidence intervals and performing hypothesis testing on a wide range of scenarios, even if they are not covered by the extant statistical theory. There are still some completely unavoidable limitations: The input must be a random sample of the population. There is no workaround around this. If the sample is not random then it is not representative, and thus the method will fail. Very small samples are still a problem. We cannot stretch things and create data out of nothing. Bootstrapping introduces a certain amount of variation that is intrinsic to the method. Most of it comes from the selection of the original sample and only a little from the resampling process. Consequently, the larger the sample, the better. Small samples will seriously harm the reliability of the bootstrapped results. Some statistics are inherently more difficult than others. For example, bootstrapping the median or other quantiles is problematic unless the sample size is quite large. In this example, we are solving a common problem by applying both traditional and bootstrapping methods. For the population shown in figure 2, let’s estimate the mean through a random sample. As described in figure 1, this is a typical inference problem where we can safely apply the theory. Under certain assumptions, we may use the familiar expression at the right-bottom corner to calculate a confidence interval. So the process is as follows: Take a random sample of the population (see figure 3).Apply the formula with the t-statistic to calculate the interval. Take a random sample of the population (see figure 3). Apply the formula with the t-statistic to calculate the interval. sample_mean=0.566 sample_std=0.502(0.46606681302580744, 0.6661796676261962) The sample mean is 0.566, the standard deviation 0.502 and the 95% confidence interval for the population mean is [0.466, 0.666], which contains the actual value (0.500). One of the advantages of bootstrapping is its surprising simplicity (see figure 4): Take a random sample of the population (the same as before).Draw a resample with replacement from the original sample, with exactly the same size.Calculate the statistic (mean, in this case) for the resample and store the result in a list.Go to 2, repeat hundreds or even thousands of times. Take a random sample of the population (the same as before). Draw a resample with replacement from the original sample, with exactly the same size. Calculate the statistic (mean, in this case) for the resample and store the result in a list. Go to 2, repeat hundreds or even thousands of times. The distribution of these values is the bootstrap distribution, which should mimic the theoretical sampling distribution. Generally, it is centred on the value of the statistic in the sample (not the population), allowing for a small bias. It is always a good idea to plot it and check whether it is approximately normal. If it is, you may revert to a traditional t-statistic and this approach is known as bootstrap-t. Otherwise, just compute the non-parametric bootstrap percentile confidence interval, that is, pick the two quantiles that enclose under the bootstrap distribution the area required for your confidence level. The second approach is impervious to skewness, so it is usually more accurate as long as the bias is small. Bootstrapping is a technique that works pretty well. However, if you get a relatively large bias or the bootstrap distribution deviates noticeably from normal, those are two clear symptoms that the procedure may not be working as expected. In that case, you should proceed with caution. Bootstrap results: n=100 m=1000 sample_fn=0.566 bootstrap_mean=0.567 bias=-0.001 bootstrap_se=0.049Confidence interval 95%: [0.471 .. 0.566 .. 0.670] If we compare with the traditional approach, both results are pretty close. Again, let’s stress that bootstrapping does not create data. It is a way to move forward without the theoretical support of a sampling distribution. We use the bootstrapping results for two purposes: estimating a parameter and its variability. We don’t need to make theoretical assumptions such as the normality of the population nor rely on the Central Limit Theorem. This approach works even if the theory does not explain the sampling distribution of our statistic (more on this in the next example). The bootstrap distribution (see figure 5) fills that gap and allows us to estimate confidence intervals directly from it. We would like to calculate the average of the individuals in the top 50% of a population. In other words, the mean of the values above the median. This custom parameter is not as common as the mean, and consequently, you will not find any hint in your textbook to estimate it. Without a theoretical approach, we have to resort to bootstrapping. Thanks to the Plug-in principle, we may estimate almost any attribute of a population by calculating the same attribute on a sample drawn from it. Bootstrapping will take care of the rest, providing us with the appropriate bootstrap distribution to approximate everything else. The procedure is exactly the same as before with just a slight change: we have to replace the mean with the new statistic. Therefore, we write a new function and reuse the rest of the code. Bootstrap results: n=100 m=1000 sample_fn=0.979 bootstrap_mean=0.981 bias=-0.002 bootstrap_se=0.067Confidence interval 95%: [0.850 .. 0.983 .. 1.112] The result is quite good because the actual value of the mean of the top 50% is 0.902, well within the provided interval. In a blink of an eye, the computer has run a thousand iterations to build the bootstrap distribution and calculated the confidence interval of a novel statistic that was not available in our textbooks. This is a good example of the power and convenience of the method. Final words The alleged origin of the word bootstrapping is a passage from one of the editions of “The Singular Adventures of Baron Munchausen” (1786) when the main character gets out of a hole by pulling the straps of his own boots. This metaphor applies to some extent: while bootstrapping does not create data, this simple computational technique allows us to go one step farther with the data at hand, and it works even when theory is not available or assumptions cannot be safely made. There is a wide range of bootstrapping applications that I cover in subsequent articles (see below). If you are interested in the topic, I strongly recommend you to have a look at the references. Thank you for reading! towardsdatascience.com References [1] Efron, B. (1979). Bootstrap Methods: Another Look at the Jackknife. The Annals of Statistics, 1–26. [2] Efron, B., Tibshirani, R., & Tibshirani, R. J. (1994). An introduction to the bootstrap. Chapman & Hall/CRC. [3] Davison, A., & Hinkley, D. (1997). Bootstrap Methods and their Application (Cambridge Series in Statistical and Probabilistic Mathematics). Cambridge: Cambridge University Press. [4] Montgomery, D. C., & Runger, G. C. (2013). Applied statistics and probability for engineers. John Wiley & Sons. [5] Moore, D. S., McCabe, G. P., & Craig, B. A. (2014). Introduction to the practice of statistics. Eighth edition. New York: W.H. Freeman and Company, a Macmillan Higher Education Company.
[ { "code": null, "e": 717, "s": 47, "text": "You know the drill: there is a population and you would like to estimate a characteristic, for example, the mean. Unfortunately, you cannot measure every individual in the population, so you draw a sample. Following the guidelines in your favourite statistics book, you simplify the problem by assuming that the parameter distribution is normal and the sample size is large enough for the Central Limit Theorem to kick in. Under these assumptions, you notice that the task at hand resembles the “Confidence interval on the mean of a normal distribution with variance unknown”, so you look up the corresponding mathematical equations, fill in the values and... job done!" }, { "code": null, "e": 1349, "s": 717, "text": "Traditional statistical methods rely on large samples, a handful of well-known theoretical distributions and the safety net of the Central Limit Theorem to work. These shortcuts allow researchers to square the circle most of the time, although this is simply impossible in certain scenarios. As data scientists, we often face challenging problems that fall outside the safe haven of traditional statistics, which is constricted to a limited number of familiar scenarios. Sadly, the reality is stubborn, data comes in all flavours of skewed shapes, and sometimes you just need to estimate parameters more complex than a simple mean." }, { "code": null, "e": 1779, "s": 1349, "text": "But there is still hope. Thanks to the unstoppable evolution of computing, the study of large and complex datasets is now feasible. So are simulations that a few years ago were prohibitive to undertake. Currently, there are ways to relax some of the requisites of traditional inference and make things easier for data scientists. You can still thrive in challenging scenarios where there is not any approach sanctioned by theory." }, { "code": null, "e": 2191, "s": 1779, "text": "This article gently introduces the bootstrapping method, which can be applied to almost any statistic over a sample of univariate data. The first section solves a well-known problem to set a common ground for demonstrating that bootstrapping and theoretical approaches concur. Then we move into a more complex scenario where theory is of little help and, subsequently, we address the problem with bootstrapping." }, { "code": null, "e": 2529, "s": 2191, "text": "Before we move on, let’s tackle some misconceptions: bootstrap does not create data. What it actually does is estimating statistics, confidence intervals and performing hypothesis testing on a wide range of scenarios, even if they are not covered by the extant statistical theory. There are still some completely unavoidable limitations:" }, { "code": null, "e": 2708, "s": 2529, "text": "The input must be a random sample of the population. There is no workaround around this. If the sample is not random then it is not representative, and thus the method will fail." }, { "code": null, "e": 3127, "s": 2708, "text": "Very small samples are still a problem. We cannot stretch things and create data out of nothing. Bootstrapping introduces a certain amount of variation that is intrinsic to the method. Most of it comes from the selection of the original sample and only a little from the resampling process. Consequently, the larger the sample, the better. Small samples will seriously harm the reliability of the bootstrapped results." }, { "code": null, "e": 3297, "s": 3127, "text": "Some statistics are inherently more difficult than others. For example, bootstrapping the median or other quantiles is problematic unless the sample size is quite large." }, { "code": null, "e": 3744, "s": 3297, "text": "In this example, we are solving a common problem by applying both traditional and bootstrapping methods. For the population shown in figure 2, let’s estimate the mean through a random sample. As described in figure 1, this is a typical inference problem where we can safely apply the theory. Under certain assumptions, we may use the familiar expression at the right-bottom corner to calculate a confidence interval. So the process is as follows:" }, { "code": null, "e": 3864, "s": 3744, "text": "Take a random sample of the population (see figure 3).Apply the formula with the t-statistic to calculate the interval." }, { "code": null, "e": 3919, "s": 3864, "text": "Take a random sample of the population (see figure 3)." }, { "code": null, "e": 3985, "s": 3919, "text": "Apply the formula with the t-statistic to calculate the interval." }, { "code": null, "e": 4061, "s": 3985, "text": "sample_mean=0.566 sample_std=0.502(0.46606681302580744, 0.6661796676261962)" }, { "code": null, "e": 4232, "s": 4061, "text": "The sample mean is 0.566, the standard deviation 0.502 and the 95% confidence interval for the population mean is [0.466, 0.666], which contains the actual value (0.500)." }, { "code": null, "e": 4316, "s": 4232, "text": "One of the advantages of bootstrapping is its surprising simplicity (see figure 4):" }, { "code": null, "e": 4608, "s": 4316, "text": "Take a random sample of the population (the same as before).Draw a resample with replacement from the original sample, with exactly the same size.Calculate the statistic (mean, in this case) for the resample and store the result in a list.Go to 2, repeat hundreds or even thousands of times." }, { "code": null, "e": 4669, "s": 4608, "text": "Take a random sample of the population (the same as before)." }, { "code": null, "e": 4756, "s": 4669, "text": "Draw a resample with replacement from the original sample, with exactly the same size." }, { "code": null, "e": 4850, "s": 4756, "text": "Calculate the statistic (mean, in this case) for the resample and store the result in a list." }, { "code": null, "e": 4903, "s": 4850, "text": "Go to 2, repeat hundreds or even thousands of times." }, { "code": null, "e": 5638, "s": 4903, "text": "The distribution of these values is the bootstrap distribution, which should mimic the theoretical sampling distribution. Generally, it is centred on the value of the statistic in the sample (not the population), allowing for a small bias. It is always a good idea to plot it and check whether it is approximately normal. If it is, you may revert to a traditional t-statistic and this approach is known as bootstrap-t. Otherwise, just compute the non-parametric bootstrap percentile confidence interval, that is, pick the two quantiles that enclose under the bootstrap distribution the area required for your confidence level. The second approach is impervious to skewness, so it is usually more accurate as long as the bias is small." }, { "code": null, "e": 5925, "s": 5638, "text": "Bootstrapping is a technique that works pretty well. However, if you get a relatively large bias or the bootstrap distribution deviates noticeably from normal, those are two clear symptoms that the procedure may not be working as expected. In that case, you should proceed with caution." }, { "code": null, "e": 6075, "s": 5925, "text": "Bootstrap results: n=100 m=1000 sample_fn=0.566 bootstrap_mean=0.567 bias=-0.001 bootstrap_se=0.049Confidence interval 95%: [0.471 .. 0.566 .. 0.670]" }, { "code": null, "e": 6777, "s": 6075, "text": "If we compare with the traditional approach, both results are pretty close. Again, let’s stress that bootstrapping does not create data. It is a way to move forward without the theoretical support of a sampling distribution. We use the bootstrapping results for two purposes: estimating a parameter and its variability. We don’t need to make theoretical assumptions such as the normality of the population nor rely on the Central Limit Theorem. This approach works even if the theory does not explain the sampling distribution of our statistic (more on this in the next example). The bootstrap distribution (see figure 5) fills that gap and allows us to estimate confidence intervals directly from it." }, { "code": null, "e": 7122, "s": 6777, "text": "We would like to calculate the average of the individuals in the top 50% of a population. In other words, the mean of the values above the median. This custom parameter is not as common as the mean, and consequently, you will not find any hint in your textbook to estimate it. Without a theoretical approach, we have to resort to bootstrapping." }, { "code": null, "e": 7400, "s": 7122, "text": "Thanks to the Plug-in principle, we may estimate almost any attribute of a population by calculating the same attribute on a sample drawn from it. Bootstrapping will take care of the rest, providing us with the appropriate bootstrap distribution to approximate everything else." }, { "code": null, "e": 7590, "s": 7400, "text": "The procedure is exactly the same as before with just a slight change: we have to replace the mean with the new statistic. Therefore, we write a new function and reuse the rest of the code." }, { "code": null, "e": 7740, "s": 7590, "text": "Bootstrap results: n=100 m=1000 sample_fn=0.979 bootstrap_mean=0.981 bias=-0.002 bootstrap_se=0.067Confidence interval 95%: [0.850 .. 0.983 .. 1.112]" }, { "code": null, "e": 8131, "s": 7740, "text": "The result is quite good because the actual value of the mean of the top 50% is 0.902, well within the provided interval. In a blink of an eye, the computer has run a thousand iterations to build the bootstrap distribution and calculated the confidence interval of a novel statistic that was not available in our textbooks. This is a good example of the power and convenience of the method." }, { "code": null, "e": 8143, "s": 8131, "text": "Final words" }, { "code": null, "e": 8365, "s": 8143, "text": "The alleged origin of the word bootstrapping is a passage from one of the editions of “The Singular Adventures of Baron Munchausen” (1786) when the main character gets out of a hole by pulling the straps of his own boots." }, { "code": null, "e": 8622, "s": 8365, "text": "This metaphor applies to some extent: while bootstrapping does not create data, this simple computational technique allows us to go one step farther with the data at hand, and it works even when theory is not available or assumptions cannot be safely made." }, { "code": null, "e": 8841, "s": 8622, "text": "There is a wide range of bootstrapping applications that I cover in subsequent articles (see below). If you are interested in the topic, I strongly recommend you to have a look at the references. Thank you for reading!" }, { "code": null, "e": 8864, "s": 8841, "text": "towardsdatascience.com" }, { "code": null, "e": 8875, "s": 8864, "text": "References" }, { "code": null, "e": 8979, "s": 8875, "text": "[1] Efron, B. (1979). Bootstrap Methods: Another Look at the Jackknife. The Annals of Statistics, 1–26." }, { "code": null, "e": 9092, "s": 8979, "text": "[2] Efron, B., Tibshirani, R., & Tibshirani, R. J. (1994). An introduction to the bootstrap. Chapman & Hall/CRC." }, { "code": null, "e": 9275, "s": 9092, "text": "[3] Davison, A., & Hinkley, D. (1997). Bootstrap Methods and their Application (Cambridge Series in Statistical and Probabilistic Mathematics). Cambridge: Cambridge University Press." }, { "code": null, "e": 9391, "s": 9275, "text": "[4] Montgomery, D. C., & Runger, G. C. (2013). Applied statistics and probability for engineers. John Wiley & Sons." } ]
DAX Other - SUMMARIZECOLUMNS function
Returns a summary table over a set of groups. DAX SUMMARIZECOLUMNS function is new in Excel 2016. SUMMARIZECOLUMNS (<groupBy_columnName>, [< groupBy_columnName >] ..., [<filterTable>] ..., [<name>, <expression>] ...) groupBy_columnName A fully qualified column reference (Table[Column]) to a base table for which the distinct values are included in the returned table. Each groupBy_columnName column is cross-joined (different tables), or auto-existed (same table) with the subsequent specified columns. filterTable A table expression which is added to the filter context of all columns specified as groupBy_columnName arguments. The values present in the filter table are used to filter before cross-join/auto-exist is performed. name A string representing the column name to use for the subsequent expression specified. expression Any DAX expression that returns a single value (not a table). A table which includes the combinations of values from the supplied columns, based on the grouping specified. Only rows for which at least one of the supplied expressions return a non-blank value are included in the table returned. Only rows for which at least one of the supplied expressions return a non-blank value are included in the table returned. If all expressions evaluate to BLANK/NULL for a row, that row is not included in the table returned. If all expressions evaluate to BLANK/NULL for a row, that row is not included in the table returned. SUMMARIZECOLUMNS does not guarantee any sort order for the results. A column cannot be specified more than once in the groupBy_columnName parameter. = SUMX ( SUMMARIZECOLUMNS (Salesperson[Salesperson], FILTER (Sales, Sales[Region]="South"), "Sales Amount", SUMX (Sales, Sales[Sales Amount])), [Sales Amount] ) 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": 2047, "s": 2001, "text": "Returns a summary table over a set of groups." }, { "code": null, "e": 2099, "s": 2047, "text": "DAX SUMMARIZECOLUMNS function is new in Excel 2016." }, { "code": null, "e": 2224, "s": 2099, "text": "SUMMARIZECOLUMNS (<groupBy_columnName>, [< groupBy_columnName >] ..., \n [<filterTable>] ..., [<name>, <expression>] ...) \n" }, { "code": null, "e": 2243, "s": 2224, "text": "groupBy_columnName" }, { "code": null, "e": 2410, "s": 2243, "text": "A fully qualified column reference (Table[Column]) to a base table for which the distinct values are included in the returned table. Each groupBy_columnName column is" }, { "code": null, "e": 2446, "s": 2410, "text": "cross-joined (different tables), or" }, { "code": null, "e": 2472, "s": 2446, "text": "auto-existed (same table)" }, { "code": null, "e": 2511, "s": 2472, "text": "with the subsequent specified columns." }, { "code": null, "e": 2523, "s": 2511, "text": "filterTable" }, { "code": null, "e": 2637, "s": 2523, "text": "A table expression which is added to the filter context of all columns specified as groupBy_columnName arguments." }, { "code": null, "e": 2738, "s": 2637, "text": "The values present in the filter table are used to filter before cross-join/auto-exist is performed." }, { "code": null, "e": 2743, "s": 2738, "text": "name" }, { "code": null, "e": 2829, "s": 2743, "text": "A string representing the column name to use for the subsequent expression specified." }, { "code": null, "e": 2840, "s": 2829, "text": "expression" }, { "code": null, "e": 2902, "s": 2840, "text": "Any DAX expression that returns a single value (not a table)." }, { "code": null, "e": 3012, "s": 2902, "text": "A table which includes the combinations of values from the supplied columns, based on the grouping specified." }, { "code": null, "e": 3134, "s": 3012, "text": "Only rows for which at least one of the supplied expressions return a non-blank value are included in the table returned." }, { "code": null, "e": 3256, "s": 3134, "text": "Only rows for which at least one of the supplied expressions return a non-blank value are included in the table returned." }, { "code": null, "e": 3357, "s": 3256, "text": "If all expressions evaluate to BLANK/NULL for a row, that row is not included in the table returned." }, { "code": null, "e": 3458, "s": 3357, "text": "If all expressions evaluate to BLANK/NULL for a row, that row is not included in the table returned." }, { "code": null, "e": 3526, "s": 3458, "text": "SUMMARIZECOLUMNS does not guarantee any sort order for the results." }, { "code": null, "e": 3607, "s": 3526, "text": "A column cannot be specified more than once in the groupBy_columnName parameter." }, { "code": null, "e": 3786, "s": 3607, "text": "= SUMX ( \n SUMMARIZECOLUMNS (Salesperson[Salesperson], \n FILTER (Sales, Sales[Region]=\"South\"), \n \"Sales Amount\", SUMX (Sales, Sales[Sales Amount])), \n [Sales Amount]\n) " }, { "code": null, "e": 3821, "s": 3786, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3835, "s": 3821, "text": " Abhay Gadiya" }, { "code": null, "e": 3868, "s": 3835, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3882, "s": 3868, "text": " Randy Minder" }, { "code": null, "e": 3917, "s": 3882, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3931, "s": 3917, "text": " Randy Minder" }, { "code": null, "e": 3938, "s": 3931, "text": " Print" }, { "code": null, "e": 3949, "s": 3938, "text": " Add Notes" } ]
Understanding Generator Expressions In Python | by Richmond Alake | Towards Data Science
This article is an introduction to generator expressions(Genexps) within the Python programming language. This article is aimed at developers of all levels. If you’re a beginner, you can pick up new concepts such as generator expressions, list comprehensions(listcomps) and sequence type generations. Intermediate developers can learn a thing or two on scalability and memory efficiency, or simply use this article as a refresher. Within this article, you will find the following: Description of generator expression How to utilize generator expressions (Code) Advantages of generator expressions to other similar solutions Memory and time measurements of genexps and listcomps Genexps are elegant and memory-efficient solutions to generating sequence types such as arrays, tuples, collections within python. Generator expressions are comparable to list comprehensions(listcomps) — another means of constructing the list sequence type within python. Genexps and listcomps share similarities in the way they are implemented. The shortcode snippet below depicts their syntactic similarity: In the code below, generator expression used to calculate the sum of a range of values that are incremented by an integer. #Generator Expressionaccumulated_gexp = sum((1 + x for x in range(2000000)))print(accumulated_gexp)>> 2000001000000#List Comprehensionaccumulated_listcomp = sum([1 + x for x in range(2000000)])print(accumulated_listcomp)>>2000001000000 Although subtle, the main difference between the genexp and listcomp examples above is that the genexp start and end with brackets, while the listcomp starts and ends with square brackets — a better term would be ‘parenthesis’. Here is another example of using generator expressions to create a tuple. beginning_topic = ['Machine', 'Deep', 'Reinforcement']ending_topic = 'Learning'tuple(print(beginning + " " + ending_topic) for beginning in beginning_topic)>> Machine Learning>> Deep Learning>> Reinforcement Learning Generation expressions are memory-efficient in comparison to listcomps. Genexps memory efficiency is a result of the utilization of the python iterator protocol to ‘yield’ or return the items within the iterator. In contrast, list comprehensions utilize memory for a generated list, and it’s content. A generator will only yield items within its iterator when required, hence giving genexps memory-efficient characteristics. If what is written above is not clear enough, the code snippet below will make it all more apparent. The snippet below shows the memory size requirement (in bytes) of genexps and listcomps examples. from sys import getsizeofaccumulated_gexp = (1 + x for x in range(2000000))print(type(accumulated_gexp))print(getsizeof(accumulated_gexp))>> <class 'generator'>>> 112accumulated_listcomp = [1 + x for x in range(2000000)]print(type(accumulated_listcomp))print(getsizeof(accumulated_listcomp))>> <class 'list'>>> 17632624 In the code snippet above, we can observe that the list comprehension uses 17632624 bytes; whereas the generator expression utilized a measly 112 bytes in memory. It’s also possible to access the content of the sequences by using the next function of the iterator for the generator expression and list indexing for the list comprehension. print(next(accumulated_gexp))>> 1print(accumulated_listcomp[0])>> 1 Another advantage of generator expressions is their time efficiency characteristics when compared to list comprehensions. For many developers out there, especially beginners, you are more familiar and exposed to the utilization of list comprehension. But in most cases, the benefits of using generator expressions are not so easy to ignore, especially when the speed of program execution is of great importance. In practical scenarios, when you are iterating over a sequence once, you’ll most likely be better off utilizing a genexps. For more flexibility and multiple iterations of sequences, you are likely to utilize listcomps. The code snippet below demonstrates the execution time differences between listcomps and genexps. import timeitgenerator_exp_time = timeit.timeit('''accumulated_gexp = (1 + x for x in range(200))''', number=1000000)print(generator_exp_time)>> 1.5132575110037578list_comp_time = timeit.timeit('''accumulated_listcomp = [1 + x for x in range(200)]''', number=1000000)print(list_comp_time)>> 29.604462443996454 Using the timeit python module, we can measure the execution time of lines of code, just as seen above. As we can observe, the generator expression takes less than two seconds (generator_exp_time: 1.51...), and the list comprehension execution time is almost 20x more. Here is a summary of the advantages of generation expressions within python: Memory efficient method of generating sequence types in python. Adds further brevity and readability to written code. Generator expressions are generator functions shortened. Time-efficient when compared to list comparisons. Generator expressions aren’t complicated at all, and they make python written code efficient and scalable. For beginners, learning when to use list comprehensions and generator expressions is an excellent concept to grasp early on in your career. To connect with me or find more content similar to this article, do the following: Subscribe to my YouTube channel for video contents coming soon hereFollow me on MediumConnect and reach me on LinkedIn Subscribe to my YouTube channel for video contents coming soon here Follow me on Medium Connect and reach me on LinkedIn
[ { "code": null, "e": 278, "s": 172, "text": "This article is an introduction to generator expressions(Genexps) within the Python programming language." }, { "code": null, "e": 603, "s": 278, "text": "This article is aimed at developers of all levels. If you’re a beginner, you can pick up new concepts such as generator expressions, list comprehensions(listcomps) and sequence type generations. Intermediate developers can learn a thing or two on scalability and memory efficiency, or simply use this article as a refresher." }, { "code": null, "e": 653, "s": 603, "text": "Within this article, you will find the following:" }, { "code": null, "e": 689, "s": 653, "text": "Description of generator expression" }, { "code": null, "e": 733, "s": 689, "text": "How to utilize generator expressions (Code)" }, { "code": null, "e": 796, "s": 733, "text": "Advantages of generator expressions to other similar solutions" }, { "code": null, "e": 850, "s": 796, "text": "Memory and time measurements of genexps and listcomps" }, { "code": null, "e": 981, "s": 850, "text": "Genexps are elegant and memory-efficient solutions to generating sequence types such as arrays, tuples, collections within python." }, { "code": null, "e": 1196, "s": 981, "text": "Generator expressions are comparable to list comprehensions(listcomps) — another means of constructing the list sequence type within python. Genexps and listcomps share similarities in the way they are implemented." }, { "code": null, "e": 1260, "s": 1196, "text": "The shortcode snippet below depicts their syntactic similarity:" }, { "code": null, "e": 1383, "s": 1260, "text": "In the code below, generator expression used to calculate the sum of a range of values that are incremented by an integer." }, { "code": null, "e": 1619, "s": 1383, "text": "#Generator Expressionaccumulated_gexp = sum((1 + x for x in range(2000000)))print(accumulated_gexp)>> 2000001000000#List Comprehensionaccumulated_listcomp = sum([1 + x for x in range(2000000)])print(accumulated_listcomp)>>2000001000000" }, { "code": null, "e": 1847, "s": 1619, "text": "Although subtle, the main difference between the genexp and listcomp examples above is that the genexp start and end with brackets, while the listcomp starts and ends with square brackets — a better term would be ‘parenthesis’." }, { "code": null, "e": 1921, "s": 1847, "text": "Here is another example of using generator expressions to create a tuple." }, { "code": null, "e": 2138, "s": 1921, "text": "beginning_topic = ['Machine', 'Deep', 'Reinforcement']ending_topic = 'Learning'tuple(print(beginning + \" \" + ending_topic) for beginning in beginning_topic)>> Machine Learning>> Deep Learning>> Reinforcement Learning" }, { "code": null, "e": 2439, "s": 2138, "text": "Generation expressions are memory-efficient in comparison to listcomps. Genexps memory efficiency is a result of the utilization of the python iterator protocol to ‘yield’ or return the items within the iterator. In contrast, list comprehensions utilize memory for a generated list, and it’s content." }, { "code": null, "e": 2563, "s": 2439, "text": "A generator will only yield items within its iterator when required, hence giving genexps memory-efficient characteristics." }, { "code": null, "e": 2762, "s": 2563, "text": "If what is written above is not clear enough, the code snippet below will make it all more apparent. The snippet below shows the memory size requirement (in bytes) of genexps and listcomps examples." }, { "code": null, "e": 3082, "s": 2762, "text": "from sys import getsizeofaccumulated_gexp = (1 + x for x in range(2000000))print(type(accumulated_gexp))print(getsizeof(accumulated_gexp))>> <class 'generator'>>> 112accumulated_listcomp = [1 + x for x in range(2000000)]print(type(accumulated_listcomp))print(getsizeof(accumulated_listcomp))>> <class 'list'>>> 17632624" }, { "code": null, "e": 3245, "s": 3082, "text": "In the code snippet above, we can observe that the list comprehension uses 17632624 bytes; whereas the generator expression utilized a measly 112 bytes in memory." }, { "code": null, "e": 3421, "s": 3245, "text": "It’s also possible to access the content of the sequences by using the next function of the iterator for the generator expression and list indexing for the list comprehension." }, { "code": null, "e": 3489, "s": 3421, "text": "print(next(accumulated_gexp))>> 1print(accumulated_listcomp[0])>> 1" }, { "code": null, "e": 3611, "s": 3489, "text": "Another advantage of generator expressions is their time efficiency characteristics when compared to list comprehensions." }, { "code": null, "e": 3740, "s": 3611, "text": "For many developers out there, especially beginners, you are more familiar and exposed to the utilization of list comprehension." }, { "code": null, "e": 3901, "s": 3740, "text": "But in most cases, the benefits of using generator expressions are not so easy to ignore, especially when the speed of program execution is of great importance." }, { "code": null, "e": 4120, "s": 3901, "text": "In practical scenarios, when you are iterating over a sequence once, you’ll most likely be better off utilizing a genexps. For more flexibility and multiple iterations of sequences, you are likely to utilize listcomps." }, { "code": null, "e": 4218, "s": 4120, "text": "The code snippet below demonstrates the execution time differences between listcomps and genexps." }, { "code": null, "e": 4528, "s": 4218, "text": "import timeitgenerator_exp_time = timeit.timeit('''accumulated_gexp = (1 + x for x in range(200))''', number=1000000)print(generator_exp_time)>> 1.5132575110037578list_comp_time = timeit.timeit('''accumulated_listcomp = [1 + x for x in range(200)]''', number=1000000)print(list_comp_time)>> 29.604462443996454" }, { "code": null, "e": 4632, "s": 4528, "text": "Using the timeit python module, we can measure the execution time of lines of code, just as seen above." }, { "code": null, "e": 4797, "s": 4632, "text": "As we can observe, the generator expression takes less than two seconds (generator_exp_time: 1.51...), and the list comprehension execution time is almost 20x more." }, { "code": null, "e": 4874, "s": 4797, "text": "Here is a summary of the advantages of generation expressions within python:" }, { "code": null, "e": 4938, "s": 4874, "text": "Memory efficient method of generating sequence types in python." }, { "code": null, "e": 5049, "s": 4938, "text": "Adds further brevity and readability to written code. Generator expressions are generator functions shortened." }, { "code": null, "e": 5099, "s": 5049, "text": "Time-efficient when compared to list comparisons." }, { "code": null, "e": 5206, "s": 5099, "text": "Generator expressions aren’t complicated at all, and they make python written code efficient and scalable." }, { "code": null, "e": 5346, "s": 5206, "text": "For beginners, learning when to use list comprehensions and generator expressions is an excellent concept to grasp early on in your career." }, { "code": null, "e": 5429, "s": 5346, "text": "To connect with me or find more content similar to this article, do the following:" }, { "code": null, "e": 5548, "s": 5429, "text": "Subscribe to my YouTube channel for video contents coming soon hereFollow me on MediumConnect and reach me on LinkedIn" }, { "code": null, "e": 5616, "s": 5548, "text": "Subscribe to my YouTube channel for video contents coming soon here" }, { "code": null, "e": 5636, "s": 5616, "text": "Follow me on Medium" } ]
Object Oriented Python - Object Serialization
In the context of data storage, serialization is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer) or transmitted and reconstructed later. In serialization, an object is transformed into a format that can be stored, so as to be able to deserialize it later and recreate the original object from the serialized format. Pickling is the process whereby a Python object hierarchy is converted into a byte stream (usually not human readable) to be written to a file, this is also known as Serialization. Unpickling is the reverse operation, whereby a byte stream is converted back into a working Python object hierarchy. Pickle is operationally simplest way to store the object. The Python Pickle module is an object-oriented way to store objects directly in a special storage format. Pickle can store and reproduce dictionaries and lists very easily. Stores object attributes and restores them back to the same State. It does not save an objects code. Only it’s attributes values. It cannot store file handles or connection sockets. In short we can say, pickling is a way to store and retrieve data variables into and out from files where variables can be lists, classes, etc. To Pickle something you must − import pickle Write a variable to file, something like pickle.dump(mystring, outfile, protocol), where 3rd argument protocol is optional To unpickling something you must − Import pickle Write a variable to a file, something like myString = pickle.load(inputfile) The pickle interface provides four different methods. dump() − The dump() method serializes to an open file (file-like object). dump() − The dump() method serializes to an open file (file-like object). dumps() − Serializes to a string dumps() − Serializes to a string load() − Deserializes from an open-like object. load() − Deserializes from an open-like object. loads() − Deserializes from a string. loads() − Deserializes from a string. Based on above procedure, below is an example of “pickling”. My Cat pussy is White and has 4 legs Would you like to see her pickled? Here she is! b'\x80\x03c__main__\nCat\nq\x00)\x81q\x01}q\x02(X\x0e\x00\x00\x00number_of_legsq\x03K\x04X\x05\x00\x00\x00colorq\x04X\x05\x00\x00\x00Whiteq\x05ub.' So, in the example above, we have created an instance of a Cat class and then we’ve pickled it, transforming our “Cat” instance into a simple array of bytes. This way we can easily store the bytes array on a binary file or in a database field and restore it back to its original form from our storage support in a later time. Also if you want to create a file with a pickled object, you can use the dump() method ( instead of the dumps*()* one) passing also an opened binary file and the pickling result will be stored in the file automatically. [....] binary_file = open(my_pickled_Pussy.bin', mode='wb') my_pickled_Pussy = pickle.dump(Pussy, binary_file) binary_file.close() The process that takes a binary array and converts it to an object hierarchy is called unpickling. The unpickling process is done by using the load() function of the pickle module and returns a complete object hierarchy from a simple bytes array. Let’s use the load function in our previous example. MeOw is black Pussy is white JSON(JavaScript Object Notation) has been part of the Python standard library is a lightweight data-interchange format. It is easy for humans to read and write. It is easy to parse and generate. Because of its simplicity, JSON is a way by which we store and exchange data, which is accomplished through its JSON syntax, and is used in many web applications. As it is in human readable format, and this may be one of the reasons for using it in data transmission, in addition to its effectiveness when working with APIs. An example of JSON-formatted data is as follow − {"EmployID": 40203, "Name": "Zack", "Age":54, "isEmployed": True} Python makes it simple to work with Json files. The module sused for this purpose is the JSON module. This module should be included (built-in) within your Python installation. So let’s see how can we convert Python dictionary to JSON and write it to a text file. Reading JSON means converting JSON into a Python value (object). The json library parses JSON into a dictionary or list in Python. In order to do that, we use the loads() function (load from a string), as follow − Below is one sample json file, data1.json {"menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } }} Above content (Data1.json) looks like a conventional dictionary. We can use pickle to store this file but the output of it is not human readable form. JSON(Java Script Object Notification) is a very simple format and that’s one of the reason for its popularity. Now let’s look into json output through below program. Above we open the json file (data1.json) for reading, obtain the file handler and pass on to json.load and getting back the object. When we try to print the output of the object, its same as the json file. Although the type of the object is dictionary, it comes out as a Python object. Writing to the json is simple as we saw this pickle. Above we load the json file, add another key value pair and writing it back to the same json file. Now if we see out data1.json, it looks different .i.e. not in the same format as we see previously. To make our Output looks same (human readable format), add the couple of arguments into our last line of the program, json.dump(conf, fh, indent = 4, separators = (‘,’, ‘: ‘)) Similarly like pickle, we can print the string with dumps and load with loads. Below is an example of that, YAML may be the most human friendly data serialization standard for all programming languages. Python yaml module is called pyaml YAML is an alternative to JSON − Human readable code − YAML is the most human readable format so much so that even its front-page content is displayed in YAML to make this point. Human readable code − YAML is the most human readable format so much so that even its front-page content is displayed in YAML to make this point. Compact code − In YAML we use whitespace indentation to denote structure not brackets. Compact code − In YAML we use whitespace indentation to denote structure not brackets. Syntax for relational data − For internal references we use anchors (&) and aliases (*). Syntax for relational data − For internal references we use anchors (&) and aliases (*). One of the area where it is used widely is for viewing/editing of data structures − for example configuration files, dumping during debugging and document headers. One of the area where it is used widely is for viewing/editing of data structures − for example configuration files, dumping during debugging and document headers. As yaml is not a built-in module, we need to install it manually. Best way to install yaml on windows machine is through pip. Run below command on your windows terminal to install yaml, pip install pyaml (Windows machine) sudo pip install pyaml (*nix and Mac) On running above command, screen will display something like below based on what’s the current latest version. Collecting pyaml Using cached pyaml-17.12.1-py2.py3-none-any.whl Collecting PyYAML (from pyaml) Using cached PyYAML-3.12.tar.gz Installing collected packages: PyYAML, pyaml Running setup.py install for PyYAML ... done Successfully installed PyYAML-3.12 pyaml-17.12.1 To test it, go to the Python shell and import the yaml module, import yaml, if no error is found, then we can say installation is successful. After installing pyaml, let’s look at below code, script_yaml1.py Above we created three different data structure, dictionary, list and tuple. On each of the structure, we do yaml.dump. Important point is how the output is displayed on the screen. Dictionary output looks clean .ie. key: value. White space to separate different objects. List is notated with dash (-) Tuple is indicated first with !!Python/tuple and then in the same format as lists. Loading a yaml file So let’s say I have one yaml file, which contains, --- # An employee record name: Raagvendra Joshi job: Developer skill: Oracle employed: True foods: - Apple - Orange - Strawberry - Mango languages: Oracle: Elite power_builder: Elite Full Stack Developer: Lame education: 4 GCSEs 3 A-Levels MCA in something called com Now let’s write a code to load this yaml file through yaml.load function. Below is code for the same. As the output doesn’t looks that much readable, I prettify it by using json in the end. Compare the output we got and the actual yaml file we have. One of the most important aspect of software development is debugging. In this section we’ll see different ways of Python debugging either with built-in debugger or third party debuggers. The module PDB supports setting breakpoints. A breakpoint is an intentional pause of the program, where you can get more information about the programs state. To set a breakpoint, insert the line pdb.set_trace() pdb_example1.py import pdb x = 9 y = 7 pdb.set_trace() total = x + y pdb.set_trace() We have inserted a few breakpoints in this program. The program will pause at each breakpoint (pdb.set_trace()). To view a variables contents simply type the variable name. c:\Python\Python361>Python pdb_example1.py > c:\Python\Python361\pdb_example1.py(8)<module>() -> total = x + y (Pdb) x 9 (Pdb) y 7 (Pdb) total *** NameError: name 'total' is not defined (Pdb) Press c or continue to go on with the programs execution until the next breakpoint. (Pdb) c --Return-- > c:\Python\Python361\pdb_example1.py(8)<module>()->None -> total = x + y (Pdb) total 16 Eventually, you will need to debug much bigger programs – programs that use subroutines. And sometimes, the problem that you’re trying to find will lie inside a subroutine. Consider the following program. import pdb def squar(x, y): out_squared = x^2 + y^2 return out_squared if __name__ == "__main__": #pdb.set_trace() print (squar(4, 5)) Now on running the above program, c:\Python\Python361>Python pdb_example2.py > c:\Python\Python361\pdb_example2.py(10)<module>() -> print (squar(4, 5)) (Pdb) We can use ? to get help, but the arrow indicates the line that’s about to be executed. At this point it’s helpful to hit s to s to step into that line. (Pdb) s --Call-- >c:\Python\Python361\pdb_example2.py(3)squar() -> def squar(x, y): This is a call to a function. If you want an overview of where you are in your code, try l − (Pdb) l 1 import pdb 2 3 def squar(x, y): 4 -> out_squared = x^2 + y^2 5 6 return out_squared 7 8 if __name__ == "__main__": 9 pdb.set_trace() 10 print (squar(4, 5)) [EOF] (Pdb) You can hit n to advance to the next line. At this point you are inside the out_squared method and you have access to the variable declared inside the function .i.e. x and y. (Pdb) x 4 (Pdb) y 5 (Pdb) x^2 6 (Pdb) y^2 7 (Pdb) x**2 16 (Pdb) y**2 25 (Pdb) So we can see the ^ operator is not what we wanted instead we need to use ** operator to do squares. This way we can debug our program inside the functions/methods. The logging module has been a part of Python’s Standard Library since Python version 2.3. As it’s a built-in module all Python module can participate in logging, so that our application log can include your own message integrated with messages from third party module. It provides a lot of flexibility and functionality. Diagnostic logging − It records events related to the application’s operation. Diagnostic logging − It records events related to the application’s operation. Audit logging − It records events for business analysis. Audit logging − It records events for business analysis. Messages are written and logged at levels of “severity” &minu DEBUG (debug()) − diagnostic messages for development. DEBUG (debug()) − diagnostic messages for development. INFO (info()) − standard “progress” messages. INFO (info()) − standard “progress” messages. WARNING (warning()) − detected a non-serious issue. WARNING (warning()) − detected a non-serious issue. ERROR (error()) − encountered an error, possibly serious. ERROR (error()) − encountered an error, possibly serious. CRITICAL (critical()) − usually a fatal error (program stops). CRITICAL (critical()) − usually a fatal error (program stops). Let’s looks into below simple program, import logging logging.basicConfig(level=logging.INFO) logging.debug('this message will be ignored') # This will not print logging.info('This should be logged') # it'll print logging.warning('And this, too') # It'll print Above we are logging messages on severity level. First we import the module, call basicConfig and set the logging level. Level we set above is INFO. Then we have three different statement: debug statement, info statement and a warning statement. INFO:root:This should be logged WARNING:root:And this, too As the info statement is below debug statement, we are not able to see the debug message. To get the debug statement too in the Output terminal, all we need to change is the basicConfig level. logging.basicConfig(level = logging.DEBUG) And in the Output we can see, DEBUG:root:this message will be ignored INFO:root:This should be logged WARNING:root:And this, too Also the default behavior means if we don’t set any logging level is warning. Just comment out the second line from the above program and run the code. #logging.basicConfig(level = logging.DEBUG) WARNING:root:And this, too Python built in logging level are actually integers. >>> import logging >>> >>> logging.DEBUG 10 >>> logging.CRITICAL 50 >>> logging.WARNING 30 >>> logging.INFO 20 >>> logging.ERROR 40 >>> We can also save the log messages into the file. logging.basicConfig(level = logging.DEBUG, filename = 'logging.log') Now all log messages will go the file (logging.log) in your current working directory instead of the screen. This is a much better approach as it lets us to do post analysis of the messages we got. We can also set the date stamp with our log message. logging.basicConfig(level=logging.DEBUG, format = '%(asctime)s %(levelname)s:%(message)s') Output will get something like, 2018-03-08 19:30:00,066 DEBUG:this message will be ignored 2018-03-08 19:30:00,176 INFO:This should be logged 2018-03-08 19:30:00,201 WARNING:And this, too Benchmarking or profiling is basically to test how fast is your code executes and where the bottlenecks are? The main reason to do this is for optimization. Python comes with a in-built module called timeit. You can use it to time small code snippets. The timeit module uses platform-specific time functions so that you will get the most accurate timings possible. So, it allows us to compare two shipment of code taken by each and then optimize the scripts to given better performance. The timeit module has a command line interface, but it can also be imported. There are two ways to call a script. Let’s use the script first, for that run the below code and see the Output. import timeit print ( 'by index: ', timeit.timeit(stmt = "mydict['c']", setup = "mydict = {'a':5, 'b':10, 'c':15}", number = 1000000)) print ( 'by get: ', timeit.timeit(stmt = 'mydict.get("c")', setup = 'mydict = {"a":5, "b":10, "c":15}', number = 1000000)) by index: 0.1809192126703489 by get: 0.6088525265034692 Above we use two different method .i.e. by subscript and get to access the dictionary key value. We execute statement 1 million times as it executes too fast for a very small data. Now we can see the index access much faster as compared to the get. We can run the code multiply times and there will be slight variation in the time execution to get the better understanding. Another way is to run the above test in the command line. Let’s do it, c:\Python\Python361>Python -m timeit -n 1000000 -s "mydict = {'a': 5, 'b':10, 'c':15}" "mydict['c']" 1000000 loops, best of 3: 0.187 usec per loop c:\Python\Python361>Python -m timeit -n 1000000 -s "mydict = {'a': 5, 'b':10, 'c':15}" "mydict.get('c')" 1000000 loops, best of 3: 0.659 usec per loop Above output may vary based on your system hardware and what all applications are running currently in your system. Below we can use the timeit module, if we want to call to a function. As we can add multiple statement inside the function to test. import timeit def testme(this_dict, key): return this_dict[key] print (timeit.timeit("testme(mydict, key)", setup = "from __main__ import testme; mydict = {'a':9, 'b':18, 'c':27}; key = 'c'", number = 1000000)) 0.7713474590139164 14 Lectures 1.5 hours Harshit Srivastava 60 Lectures 8 hours DigiFisk (Programming Is Fun) 11 Lectures 35 mins Sandip Bhattacharya 21 Lectures 2 hours Pranjal Srivastava 6 Lectures 43 mins Frahaan Hussain 49 Lectures 4.5 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2033, "s": 1810, "text": "In the context of data storage, serialization is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer) or transmitted and reconstructed later." }, { "code": null, "e": 2212, "s": 2033, "text": "In serialization, an object is transformed into a format that can be stored, so as to be able to deserialize it later and recreate the original object from the serialized format." }, { "code": null, "e": 2510, "s": 2212, "text": "Pickling is the process whereby a Python object hierarchy is converted into a byte stream (usually not human readable) to be written to a file, this is also known as Serialization. Unpickling is the reverse operation, whereby a byte stream is converted back into a working Python object hierarchy." }, { "code": null, "e": 2674, "s": 2510, "text": "Pickle is operationally simplest way to store the object. The Python Pickle module is an object-oriented way to store objects directly in a special storage format." }, { "code": null, "e": 2741, "s": 2674, "text": "Pickle can store and reproduce dictionaries and lists very easily." }, { "code": null, "e": 2808, "s": 2741, "text": "Stores object attributes and restores them back to the same State." }, { "code": null, "e": 2871, "s": 2808, "text": "It does not save an objects code. Only it’s attributes values." }, { "code": null, "e": 2923, "s": 2871, "text": "It cannot store file handles or connection sockets." }, { "code": null, "e": 3067, "s": 2923, "text": "In short we can say, pickling is a way to store and retrieve data variables into and out from files where variables can be lists, classes, etc." }, { "code": null, "e": 3098, "s": 3067, "text": "To Pickle something you must −" }, { "code": null, "e": 3112, "s": 3098, "text": "import pickle" }, { "code": null, "e": 3153, "s": 3112, "text": "Write a variable to file, something like" }, { "code": null, "e": 3196, "s": 3153, "text": "pickle.dump(mystring, outfile, protocol),\n" }, { "code": null, "e": 3271, "s": 3196, "text": "where 3rd argument protocol is optional\nTo unpickling something you must −" }, { "code": null, "e": 3285, "s": 3271, "text": "Import pickle" }, { "code": null, "e": 3328, "s": 3285, "text": "Write a variable to a file, something like" }, { "code": null, "e": 3363, "s": 3328, "text": "myString = pickle.load(inputfile)\n" }, { "code": null, "e": 3417, "s": 3363, "text": "The pickle interface provides four different methods." }, { "code": null, "e": 3491, "s": 3417, "text": "dump() − The dump() method serializes to an open file (file-like object)." }, { "code": null, "e": 3565, "s": 3491, "text": "dump() − The dump() method serializes to an open file (file-like object)." }, { "code": null, "e": 3598, "s": 3565, "text": "dumps() − Serializes to a string" }, { "code": null, "e": 3631, "s": 3598, "text": "dumps() − Serializes to a string" }, { "code": null, "e": 3679, "s": 3631, "text": "load() − Deserializes from an open-like object." }, { "code": null, "e": 3727, "s": 3679, "text": "load() − Deserializes from an open-like object." }, { "code": null, "e": 3765, "s": 3727, "text": "loads() − Deserializes from a string." }, { "code": null, "e": 3803, "s": 3765, "text": "loads() − Deserializes from a string." }, { "code": null, "e": 3864, "s": 3803, "text": "Based on above procedure, below is an example of “pickling”." }, { "code": null, "e": 4098, "s": 3864, "text": "My Cat pussy is White and has 4 legs\nWould you like to see her pickled? Here she is!\nb'\\x80\\x03c__main__\\nCat\\nq\\x00)\\x81q\\x01}q\\x02(X\\x0e\\x00\\x00\\x00number_of_legsq\\x03K\\x04X\\x05\\x00\\x00\\x00colorq\\x04X\\x05\\x00\\x00\\x00Whiteq\\x05ub.'\n" }, { "code": null, "e": 4256, "s": 4098, "text": "So, in the example above, we have created an instance of a Cat class and then we’ve pickled it, transforming our “Cat” instance into a simple array of bytes." }, { "code": null, "e": 4424, "s": 4256, "text": "This way we can easily store the bytes array on a binary file or in a database field and restore it back to its original form from our storage support in a later time." }, { "code": null, "e": 4644, "s": 4424, "text": "Also if you want to create a file with a pickled object, you can use the dump() method ( instead of the dumps*()* one) passing also an opened binary file and the pickling result will be stored in the file automatically." }, { "code": null, "e": 4775, "s": 4644, "text": "[....]\nbinary_file = open(my_pickled_Pussy.bin', mode='wb')\nmy_pickled_Pussy = pickle.dump(Pussy, binary_file)\nbinary_file.close()" }, { "code": null, "e": 4874, "s": 4775, "text": "The process that takes a binary array and converts it to an object hierarchy is called unpickling." }, { "code": null, "e": 5022, "s": 4874, "text": "The unpickling process is done by using the load() function of the pickle module and returns a complete object hierarchy from a simple bytes array." }, { "code": null, "e": 5075, "s": 5022, "text": "Let’s use the load function in our previous example." }, { "code": null, "e": 5105, "s": 5075, "text": "MeOw is black\nPussy is white\n" }, { "code": null, "e": 5300, "s": 5105, "text": "JSON(JavaScript Object Notation) has been part of the Python standard library is a lightweight data-interchange format. It is easy for humans to read and write. It is easy to parse and generate." }, { "code": null, "e": 5625, "s": 5300, "text": "Because of its simplicity, JSON is a way by which we store and exchange data, which is accomplished through its JSON syntax, and is used in many web applications. As it is in human readable format, and this may be one of the reasons for using it in data transmission, in addition to its effectiveness when working with APIs." }, { "code": null, "e": 5674, "s": 5625, "text": "An example of JSON-formatted data is as follow −" }, { "code": null, "e": 5740, "s": 5674, "text": "{\"EmployID\": 40203, \"Name\": \"Zack\", \"Age\":54, \"isEmployed\": True}" }, { "code": null, "e": 5917, "s": 5740, "text": "Python makes it simple to work with Json files. The module sused for this purpose is the JSON module. This module should be included (built-in) within your Python installation." }, { "code": null, "e": 6004, "s": 5917, "text": "So let’s see how can we convert Python dictionary to JSON and write it to a text file." }, { "code": null, "e": 6218, "s": 6004, "text": "Reading JSON means converting JSON into a Python value (object). The json library parses JSON into a dictionary or list in Python. In order to do that, we use the loads() function (load from a string), as follow −" }, { "code": null, "e": 6249, "s": 6218, "text": "Below is one sample json file," }, { "code": null, "e": 6519, "s": 6249, "text": "data1.json\n{\"menu\": {\n \"id\": \"file\",\n \"value\": \"File\",\n \"popup\": {\n \"menuitem\": [\n {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"},\n {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"},\n {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}\n ]\n }\n}}" }, { "code": null, "e": 6670, "s": 6519, "text": "Above content (Data1.json) looks like a conventional dictionary. We can use pickle to store this file but the output of it is not human readable form." }, { "code": null, "e": 6836, "s": 6670, "text": "JSON(Java Script Object Notification) is a very simple format and that’s one of the reason for its popularity. Now let’s look into json output through below program." }, { "code": null, "e": 7374, "s": 6836, "text": "Above we open the json file (data1.json) for reading, obtain the file handler and pass on to json.load and getting back the object. When we try to print the output of the object, its same as the json file. Although the type of the object is dictionary, it comes out as a Python object. Writing to the json is simple as we saw this pickle. Above we load the json file, add another key value pair and writing it back to the same json file. Now if we see out data1.json, it looks different .i.e. not in the same format as we see previously." }, { "code": null, "e": 7492, "s": 7374, "text": "To make our Output looks same (human readable format), add the couple of arguments into our last line of the program," }, { "code": null, "e": 7551, "s": 7492, "text": "json.dump(conf, fh, indent = 4, separators = (‘,’, ‘: ‘))\n" }, { "code": null, "e": 7659, "s": 7551, "text": "Similarly like pickle, we can print the string with dumps and load with loads. Below is an example of that," }, { "code": null, "e": 7754, "s": 7659, "text": "YAML may be the most human friendly data serialization standard for all programming languages." }, { "code": null, "e": 7789, "s": 7754, "text": "Python yaml module is called pyaml" }, { "code": null, "e": 7822, "s": 7789, "text": "YAML is an alternative to JSON −" }, { "code": null, "e": 7968, "s": 7822, "text": "Human readable code − YAML is the most human readable format so much so that even its front-page content is displayed in YAML to make this point." }, { "code": null, "e": 8114, "s": 7968, "text": "Human readable code − YAML is the most human readable format so much so that even its front-page content is displayed in YAML to make this point." }, { "code": null, "e": 8201, "s": 8114, "text": "Compact code − In YAML we use whitespace indentation to denote structure not brackets." }, { "code": null, "e": 8288, "s": 8201, "text": "Compact code − In YAML we use whitespace indentation to denote structure not brackets." }, { "code": null, "e": 8377, "s": 8288, "text": "Syntax for relational data − For internal references we use anchors (&) and aliases (*)." }, { "code": null, "e": 8466, "s": 8377, "text": "Syntax for relational data − For internal references we use anchors (&) and aliases (*)." }, { "code": null, "e": 8630, "s": 8466, "text": "One of the area where it is used widely is for viewing/editing of data structures − for example configuration files, dumping during debugging and document headers." }, { "code": null, "e": 8794, "s": 8630, "text": "One of the area where it is used widely is for viewing/editing of data structures − for example configuration files, dumping during debugging and document headers." }, { "code": null, "e": 8980, "s": 8794, "text": "As yaml is not a built-in module, we need to install it manually. Best way to install yaml on windows machine is through pip. Run below command on your windows terminal to install yaml," }, { "code": null, "e": 9054, "s": 8980, "text": "pip install pyaml (Windows machine)\nsudo pip install pyaml (*nix and Mac)" }, { "code": null, "e": 9165, "s": 9054, "text": "On running above command, screen will display something like below based on what’s the current latest version." }, { "code": null, "e": 9432, "s": 9165, "text": "Collecting pyaml\nUsing cached pyaml-17.12.1-py2.py3-none-any.whl\nCollecting PyYAML (from pyaml)\nUsing cached PyYAML-3.12.tar.gz\nInstalling collected packages: PyYAML, pyaml\nRunning setup.py install for PyYAML ... done\nSuccessfully installed PyYAML-3.12 pyaml-17.12.1" }, { "code": null, "e": 9574, "s": 9432, "text": "To test it, go to the Python shell and import the yaml module,\nimport yaml, if no error is found, then we can say installation is successful." }, { "code": null, "e": 9624, "s": 9574, "text": "After installing pyaml, let’s look at below code," }, { "code": null, "e": 9640, "s": 9624, "text": "script_yaml1.py" }, { "code": null, "e": 9822, "s": 9640, "text": "Above we created three different data structure, dictionary, list and tuple. On each of the structure, we do yaml.dump. Important point is how the output is displayed on the screen." }, { "code": null, "e": 9869, "s": 9822, "text": "Dictionary output looks clean .ie. key: value." }, { "code": null, "e": 9912, "s": 9869, "text": "White space to separate different objects." }, { "code": null, "e": 9942, "s": 9912, "text": "List is notated with dash (-)" }, { "code": null, "e": 10025, "s": 9942, "text": "Tuple is indicated first with !!Python/tuple and then in the same format as lists." }, { "code": null, "e": 10045, "s": 10025, "text": "Loading a yaml file" }, { "code": null, "e": 10096, "s": 10045, "text": "So let’s say I have one yaml file, which contains," }, { "code": null, "e": 10394, "s": 10096, "text": "---\n# An employee record\nname: Raagvendra Joshi\njob: Developer\nskill: Oracle\nemployed: True\nfoods:\n - Apple\n - Orange\n - Strawberry\n - Mango\nlanguages:\n Oracle: Elite\n power_builder: Elite\n Full Stack Developer: Lame\neducation:\n 4 GCSEs\n 3 A-Levels\n MCA in something called com" }, { "code": null, "e": 10496, "s": 10394, "text": "Now let’s write a code to load this yaml file through yaml.load function. Below is code for the same." }, { "code": null, "e": 10644, "s": 10496, "text": "As the output doesn’t looks that much readable, I prettify it by using json in the end. Compare the output we got and the actual yaml file we have." }, { "code": null, "e": 10832, "s": 10644, "text": "One of the most important aspect of software development is debugging. In this section we’ll see different ways of Python debugging either with built-in debugger or third party debuggers." }, { "code": null, "e": 10991, "s": 10832, "text": "The module PDB supports setting breakpoints. A breakpoint is an intentional pause of the program, where you can get more information about the programs state." }, { "code": null, "e": 11028, "s": 10991, "text": "To set a breakpoint, insert the line" }, { "code": null, "e": 11044, "s": 11028, "text": "pdb.set_trace()" }, { "code": null, "e": 11129, "s": 11044, "text": "pdb_example1.py\nimport pdb\nx = 9\ny = 7\npdb.set_trace()\ntotal = x + y\npdb.set_trace()" }, { "code": null, "e": 11302, "s": 11129, "text": "We have inserted a few breakpoints in this program. The program will pause at each breakpoint (pdb.set_trace()). To view a variables contents simply type the variable name." }, { "code": null, "e": 11494, "s": 11302, "text": "c:\\Python\\Python361>Python pdb_example1.py\n> c:\\Python\\Python361\\pdb_example1.py(8)<module>()\n-> total = x + y\n(Pdb) x\n9\n(Pdb) y\n7\n(Pdb) total\n*** NameError: name 'total' is not defined\n(Pdb)" }, { "code": null, "e": 11578, "s": 11494, "text": "Press c or continue to go on with the programs execution until the next breakpoint." }, { "code": null, "e": 11686, "s": 11578, "text": "(Pdb) c\n--Return--\n> c:\\Python\\Python361\\pdb_example1.py(8)<module>()->None\n-> total = x + y\n(Pdb) total\n16" }, { "code": null, "e": 11891, "s": 11686, "text": "Eventually, you will need to debug much bigger programs – programs that use subroutines. And sometimes, the problem that you’re trying to find will lie inside a subroutine. Consider the following program." }, { "code": null, "e": 12038, "s": 11891, "text": "import pdb\ndef squar(x, y):\n out_squared = x^2 + y^2\n return out_squared\nif __name__ == \"__main__\":\n #pdb.set_trace()\n print (squar(4, 5))" }, { "code": null, "e": 12072, "s": 12038, "text": "Now on running the above program," }, { "code": null, "e": 12196, "s": 12072, "text": "c:\\Python\\Python361>Python pdb_example2.py\n> c:\\Python\\Python361\\pdb_example2.py(10)<module>()\n-> print (squar(4, 5))\n(Pdb)" }, { "code": null, "e": 12349, "s": 12196, "text": "We can use ? to get help, but the arrow indicates the line that’s about to be executed. At this point it’s helpful to hit s to s to step into that line." }, { "code": null, "e": 12433, "s": 12349, "text": "(Pdb) s\n--Call--\n>c:\\Python\\Python361\\pdb_example2.py(3)squar()\n-> def squar(x, y):" }, { "code": null, "e": 12526, "s": 12433, "text": "This is a call to a function. If you want an overview of where you are in your code, try l −" }, { "code": null, "e": 12704, "s": 12526, "text": "(Pdb) l\n1 import pdb\n2\n3 def squar(x, y):\n4 -> out_squared = x^2 + y^2\n5\n6 return out_squared\n7\n8 if __name__ == \"__main__\":\n9 pdb.set_trace()\n10 print (squar(4, 5))\n[EOF]\n(Pdb)" }, { "code": null, "e": 12879, "s": 12704, "text": "You can hit n to advance to the next line. At this point you are inside the out_squared method and you have access to the variable declared inside the function .i.e. x and y." }, { "code": null, "e": 12957, "s": 12879, "text": "(Pdb) x\n4\n(Pdb) y\n5\n(Pdb) x^2\n6\n(Pdb) y^2\n7\n(Pdb) x**2\n16\n(Pdb) y**2\n25\n(Pdb)" }, { "code": null, "e": 13058, "s": 12957, "text": "So we can see the ^ operator is not what we wanted instead we need to use ** operator to do squares." }, { "code": null, "e": 13122, "s": 13058, "text": "This way we can debug our program inside the functions/methods." }, { "code": null, "e": 13443, "s": 13122, "text": "The logging module has been a part of Python’s Standard Library since Python version 2.3. As it’s a built-in module all Python module can participate in logging, so that our application log can include your own message integrated with messages from third party module. It provides a lot of flexibility and functionality." }, { "code": null, "e": 13522, "s": 13443, "text": "Diagnostic logging − It records events related to the application’s operation." }, { "code": null, "e": 13601, "s": 13522, "text": "Diagnostic logging − It records events related to the application’s operation." }, { "code": null, "e": 13658, "s": 13601, "text": "Audit logging − It records events for business analysis." }, { "code": null, "e": 13715, "s": 13658, "text": "Audit logging − It records events for business analysis." }, { "code": null, "e": 13777, "s": 13715, "text": "Messages are written and logged at levels of “severity” &minu" }, { "code": null, "e": 13832, "s": 13777, "text": "DEBUG (debug()) − diagnostic messages for development." }, { "code": null, "e": 13887, "s": 13832, "text": "DEBUG (debug()) − diagnostic messages for development." }, { "code": null, "e": 13933, "s": 13887, "text": "INFO (info()) − standard “progress” messages." }, { "code": null, "e": 13979, "s": 13933, "text": "INFO (info()) − standard “progress” messages." }, { "code": null, "e": 14031, "s": 13979, "text": "WARNING (warning()) − detected a non-serious issue." }, { "code": null, "e": 14083, "s": 14031, "text": "WARNING (warning()) − detected a non-serious issue." }, { "code": null, "e": 14141, "s": 14083, "text": "ERROR (error()) − encountered an error, possibly serious." }, { "code": null, "e": 14199, "s": 14141, "text": "ERROR (error()) − encountered an error, possibly serious." }, { "code": null, "e": 14262, "s": 14199, "text": "CRITICAL (critical()) − usually a fatal error (program stops)." }, { "code": null, "e": 14325, "s": 14262, "text": "CRITICAL (critical()) − usually a fatal error (program stops)." }, { "code": null, "e": 14364, "s": 14325, "text": "Let’s looks into below simple program," }, { "code": null, "e": 14588, "s": 14364, "text": "import logging\n\nlogging.basicConfig(level=logging.INFO)\n\nlogging.debug('this message will be ignored') # This will not print\nlogging.info('This should be logged') # it'll print\nlogging.warning('And this, too') # It'll print" }, { "code": null, "e": 14834, "s": 14588, "text": "Above we are logging messages on severity level. First we import the module, call basicConfig and set the logging level. Level we set above is INFO. Then we have three different statement: debug statement, info statement and a warning statement." }, { "code": null, "e": 14894, "s": 14834, "text": "INFO:root:This should be logged\nWARNING:root:And this, too\n" }, { "code": null, "e": 15087, "s": 14894, "text": "As the info statement is below debug statement, we are not able to see the debug message. To get the debug statement too in the Output terminal, all we need to change is the basicConfig level." }, { "code": null, "e": 15131, "s": 15087, "text": "logging.basicConfig(level = logging.DEBUG)\n" }, { "code": null, "e": 15161, "s": 15131, "text": "And in the Output we can see," }, { "code": null, "e": 15261, "s": 15161, "text": "DEBUG:root:this message will be ignored\nINFO:root:This should be logged\nWARNING:root:And this, too\n" }, { "code": null, "e": 15413, "s": 15261, "text": "Also the default behavior means if we don’t set any logging level is warning. Just comment out the second line from the above program and run the code." }, { "code": null, "e": 15457, "s": 15413, "text": "#logging.basicConfig(level = logging.DEBUG)" }, { "code": null, "e": 15485, "s": 15457, "text": "WARNING:root:And this, too\n" }, { "code": null, "e": 15538, "s": 15485, "text": "Python built in logging level are actually integers." }, { "code": null, "e": 15674, "s": 15538, "text": ">>> import logging\n>>>\n>>> logging.DEBUG\n10\n>>> logging.CRITICAL\n50\n>>> logging.WARNING\n30\n>>> logging.INFO\n20\n>>> logging.ERROR\n40\n>>>" }, { "code": null, "e": 15723, "s": 15674, "text": "We can also save the log messages into the file." }, { "code": null, "e": 15792, "s": 15723, "text": "logging.basicConfig(level = logging.DEBUG, filename = 'logging.log')" }, { "code": null, "e": 15990, "s": 15792, "text": "Now all log messages will go the file (logging.log) in your current working directory instead of the screen. This is a much better approach as it lets us to do post analysis of the messages we got." }, { "code": null, "e": 16043, "s": 15990, "text": "We can also set the date stamp with our log message." }, { "code": null, "e": 16134, "s": 16043, "text": "logging.basicConfig(level=logging.DEBUG, format = '%(asctime)s %(levelname)s:%(message)s')" }, { "code": null, "e": 16166, "s": 16134, "text": "Output will get something like," }, { "code": null, "e": 16323, "s": 16166, "text": "2018-03-08 19:30:00,066 DEBUG:this message will be ignored\n2018-03-08 19:30:00,176 INFO:This should be logged\n2018-03-08 19:30:00,201 WARNING:And this, too\n" }, { "code": null, "e": 16480, "s": 16323, "text": "Benchmarking or profiling is basically to test how fast is your code executes and where the bottlenecks are? The main reason to do this is for optimization." }, { "code": null, "e": 16688, "s": 16480, "text": "Python comes with a in-built module called timeit. You can use it to time small code snippets. The timeit module uses platform-specific time functions so that you will get the most accurate timings possible." }, { "code": null, "e": 16810, "s": 16688, "text": "So, it allows us to compare two shipment of code taken by each and then optimize the scripts to given better performance." }, { "code": null, "e": 16887, "s": 16810, "text": "The timeit module has a command line interface, but it can also be imported." }, { "code": null, "e": 17000, "s": 16887, "text": "There are two ways to call a script. Let’s use the script first, for that run the below code and see the Output." }, { "code": null, "e": 17259, "s": 17000, "text": "import timeit\nprint ( 'by index: ', timeit.timeit(stmt = \"mydict['c']\", setup = \"mydict = {'a':5, 'b':10, 'c':15}\", number = 1000000))\nprint ( 'by get: ', timeit.timeit(stmt = 'mydict.get(\"c\")', setup = 'mydict = {\"a\":5, \"b\":10, \"c\":15}', number = 1000000))\n" }, { "code": null, "e": 17316, "s": 17259, "text": "by index: 0.1809192126703489\nby get: 0.6088525265034692\n" }, { "code": null, "e": 17690, "s": 17316, "text": "Above we use two different method .i.e. by subscript and get to access the dictionary key value. We execute statement 1 million times as it executes too fast for a very small data. Now we can see the index access much faster as compared to the get. We can run the code multiply times and there will be slight variation in the time execution to get the better understanding." }, { "code": null, "e": 17761, "s": 17690, "text": "Another way is to run the above test in the command line. Let’s do it," }, { "code": null, "e": 18060, "s": 17761, "text": "c:\\Python\\Python361>Python -m timeit -n 1000000 -s \"mydict = {'a': 5, 'b':10, 'c':15}\" \"mydict['c']\"\n1000000 loops, best of 3: 0.187 usec per loop\n\nc:\\Python\\Python361>Python -m timeit -n 1000000 -s \"mydict = {'a': 5, 'b':10, 'c':15}\" \"mydict.get('c')\"\n1000000 loops, best of 3: 0.659 usec per loop" }, { "code": null, "e": 18176, "s": 18060, "text": "Above output may vary based on your system hardware and what all applications are running currently in your system." }, { "code": null, "e": 18308, "s": 18176, "text": "Below we can use the timeit module, if we want to call to a function. As we can add multiple statement inside the function to test." }, { "code": null, "e": 18524, "s": 18308, "text": "import timeit\n\ndef testme(this_dict, key):\n return this_dict[key]\n\nprint (timeit.timeit(\"testme(mydict, key)\", setup = \"from __main__ import testme; mydict = {'a':9, 'b':18, 'c':27}; key = 'c'\", number = 1000000))" }, { "code": null, "e": 18544, "s": 18524, "text": "0.7713474590139164\n" }, { "code": null, "e": 18579, "s": 18544, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 18599, "s": 18579, "text": " Harshit Srivastava" }, { "code": null, "e": 18632, "s": 18599, "text": "\n 60 Lectures \n 8 hours \n" }, { "code": null, "e": 18663, "s": 18632, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 18695, "s": 18663, "text": "\n 11 Lectures \n 35 mins\n" }, { "code": null, "e": 18716, "s": 18695, "text": " Sandip Bhattacharya" }, { "code": null, "e": 18749, "s": 18716, "text": "\n 21 Lectures \n 2 hours \n" }, { "code": null, "e": 18769, "s": 18749, "text": " Pranjal Srivastava" }, { "code": null, "e": 18800, "s": 18769, "text": "\n 6 Lectures \n 43 mins\n" }, { "code": null, "e": 18817, "s": 18800, "text": " Frahaan Hussain" }, { "code": null, "e": 18852, "s": 18817, "text": "\n 49 Lectures \n 4.5 hours \n" }, { "code": null, "e": 18869, "s": 18852, "text": " Abhilash Nelson" }, { "code": null, "e": 18876, "s": 18869, "text": " Print" }, { "code": null, "e": 18887, "s": 18876, "text": " Add Notes" } ]
Groovy - ceil()
The method ceil gives the smallest integer that is greater than or equal to the argument. double ceil(double d) double ceil(float f) Parameters − A double or float primitive data type. Return Value − This method Returns the smallest integer that is greater than or equal to the argument. Returned as a double. Following is an example of the usage of this method − class Example { static void main(String[] args) { double a = -100.675; float b = -90; System.out.println(Math.ceil(a)); System.out.println(Math.ceil(b)); } } When we run the above program, we will get the following result − -100.0 -90. 52 Lectures 8 hours Krishna Sakinala 49 Lectures 2.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2328, "s": 2238, "text": "The method ceil gives the smallest integer that is greater than or equal to the argument." }, { "code": null, "e": 2373, "s": 2328, "text": "double ceil(double d) \ndouble ceil(float f)\n" }, { "code": null, "e": 2425, "s": 2373, "text": "Parameters − A double or float primitive data type." }, { "code": null, "e": 2550, "s": 2425, "text": "Return Value − This method Returns the smallest integer that is greater than or equal to the argument. Returned as a double." }, { "code": null, "e": 2604, "s": 2550, "text": "Following is an example of the usage of this method −" }, { "code": null, "e": 2801, "s": 2604, "text": "class Example { \n static void main(String[] args) { \n double a = -100.675; \n float b = -90;\n\t\t\n System.out.println(Math.ceil(a)); \n System.out.println(Math.ceil(b)); \n } \n}" }, { "code": null, "e": 2867, "s": 2801, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 2881, "s": 2867, "text": "-100.0 \n-90.\n" }, { "code": null, "e": 2914, "s": 2881, "text": "\n 52 Lectures \n 8 hours \n" }, { "code": null, "e": 2932, "s": 2914, "text": " Krishna Sakinala" }, { "code": null, "e": 2967, "s": 2932, "text": "\n 49 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2985, "s": 2967, "text": " Packt Publishing" }, { "code": null, "e": 2992, "s": 2985, "text": " Print" }, { "code": null, "e": 3003, "s": 2992, "text": " Add Notes" } ]
HTML Data Cleaning in Python for NLP | by Brandon Ko | Towards Data Science
The most important step of any data-driven project is obtaining quality data. Without these preprocessing steps, the results of a project can easily be biased or completely misunderstood. Here, we will focus on cleaning data that is composed of scraped web pages. There are many tools to scrape the web. If you are looking for something quick and simple, the URL handling module in Python called urllib might do the trick for you. Otherwise, I recommend scrapyd because of the possible customizations and robustness. It is important to ensure that the pages you are scraping contain rich text data that is suitable for your use case. Once we have obtained our scraped web pages, we begin by extracting the text out of each web page. Websites have lots of tags that don’t contain useful information when it comes to NLP, such as <script> and <button>. Thankfully, there is a Python module called boilerpy3 that makes text extraction easy. We use the ArticleExtractor to extract the text. This extractor has been tuned for news articles that works well for most HTMLs. You can try out other extractors listed in the documentation for boilerpy3 and see what works best for your dataset. Next, we condense all newline characters (\n and \r) into one \n character. This is done so that when we split the text up into sentences by \n and periods, we don’t get sentences with no words. If the extractors from boilerpy3 are not working for your web pages, you can use beautifulsoup to build your own custom text extractor. Below is an example replacement of the parse_html method. Once the text has been extracted, we want to continue with the cleaning process. It is common for web pages to contain repeated information, especially if you scrape multiple articles from the same domain. Elements such as website titles, company slogans, and page footers can be present in your parsed text. To detect and remove these phrases, we analyze our corpus by looking at the frequency of large n-grams. N-grams is a concept from NLP where the “gram” is a contiguous sequence of words from a body of text, and “N” is the size of these sequences. This is frequently used to build language models which can assist in tasks ranging from text summarization to word prediction. Below is an example for trigrams (3-grams): input = 'It is quite sunny today.'output = ['It is quite', is quite sunny', 'quite sunny today.'] When we read articles, there are many single words (unigrams) that are repeated, such as “the” and “a”. However, as we increase our n-gram size, the probability of the n-gram repeating decreases. Trigrams start to become more rare, and it is almost impossible for the articles to contain the same sequence of 20 words. By searching for large n-grams that occur frequently, we are able to detect the repeated elements across websites in our corpus, and manually filter them out. We begin this process by breaking up our dataset up into sentences by splitting the text chunks up by the newline characters and periods. Next, we tokenize our sentences (break up the sentence into single word strings). With these tokenized sentences, we are able to generate n-grams of a specific size (we want to start large, around 15). We want to sort the n-grams by frequency using the FreqDist function provided by nltk. Once we have our frequency dictionary, we print the top 10 n-grams. If the frequency is higher than 1 or 2, the sentence might be something you would consider removing from the corpus. To remove the sentence, copy the entire sentence and add it as a single string in the filter_strs array. Copying the entire sentence can be accomplished by increasing the n-gram size until the entire sentence is captured in one n-gram and printed on the console, or simply printing the parsed_texts and searching for the sentence. If there is multiple unwanted sentences with slightly different words, you can copy the common substring into filter_strs, and the regular expression will filter out all sentences containing the substring. If you run the code above on your dataset without adding any filters to filter_strs, you might get a graph similar to the one below. In my dataset, you can see that there are several 15-grams that are repeated 6, 3, and 2 times. Once we go through the process of populating filter_strs with unwanted sentences, our plot of 15-grams flattens out. Keep in mind there is no optimal threshold for n-gram size and frequency that determines whether or not a sentence should be removed, so play around with these two parameters. Sometimes you will need to lower the n-gram size to 3 or 4 to pick up a repeated title, but be careful not to remove valuable data. This block of code is designed to be an iterative process, where you slowly build the filter_strs array after many different experiments. After we clean the corpus, the next step is to process the words of our corpus. We want to remove punctuation, lowercase all words, and break each sentence up into arrays of individual words (tokenization). To do this, I like to use the simple_preprocess library method from gensim. This function accomplishes all three of these tasks in one go and has a few parameters that allow some customization. By setting deacc=True, accents will be removed. When punctuation is removed, the punctuation itself is treated as a space, and the two substrings on each side of the punctuation is treated as two separate words. In most cases, words will be split up with one substring having a length of one. For example, “don’t” will end up as “don” and “t”. As a result, the default min_len value is 2, so words with 1 letter are not kept. If this is not suitable for your use case, you can also create a text processor from scratch. Python’s string class contains a punctuation attribute that lists all commonly used punctuation. Using this set of punctuation marks, you can use str.maketrans to remove all punctuation from a string, but keeping those words that did have punctuation as one single word (“don’t” becomes “dont”). Keep in mind this does not capture punctuation as well as gensim’s simple_preprocess. For example, there are three types of dashes (‘ — ’ em dash, –’ en dash, ‘-’ hyphen), and while simple_preprocess removes them all, string.punctuation does not contain the em dash, and therefore does not remove it. Once we have our corpus nicely tokenized, we will remove all stop words from the corpus. Stop words are words that don’t provide much additional meaning to a sentence. Words in the English vocabulary include “the”, “a”, and “in”. nltk contains a list of English stopwords, so we use that to filter our lists of tokens. Lemmatization is the process of grouping together different forms of the same word and replacing these instances with the word’s lemma (dictionary form). For example, “functions” is reduced to “function”. Stemming is the process of reducing a word to its root word (without any suffixes or prefixes). For example, “running” is reduced to “run”. These two steps decreases the vocabulary size, making it easier for the machine to understand our corpus. Now that you know how to extract and preprocess your text data, you can begin the data analysis. Best of luck with your NLP adventures! If you are tagging the corpus with parts-of-speech tags, stop words should be kept in the dataset and lemmatization should not be done prior to tagging. The GitHub repository for the Jupyter Notebook can be found here.
[ { "code": null, "e": 435, "s": 171, "text": "The most important step of any data-driven project is obtaining quality data. Without these preprocessing steps, the results of a project can easily be biased or completely misunderstood. Here, we will focus on cleaning data that is composed of scraped web pages." }, { "code": null, "e": 688, "s": 435, "text": "There are many tools to scrape the web. If you are looking for something quick and simple, the URL handling module in Python called urllib might do the trick for you. Otherwise, I recommend scrapyd because of the possible customizations and robustness." }, { "code": null, "e": 805, "s": 688, "text": "It is important to ensure that the pages you are scraping contain rich text data that is suitable for your use case." }, { "code": null, "e": 1109, "s": 805, "text": "Once we have obtained our scraped web pages, we begin by extracting the text out of each web page. Websites have lots of tags that don’t contain useful information when it comes to NLP, such as <script> and <button>. Thankfully, there is a Python module called boilerpy3 that makes text extraction easy." }, { "code": null, "e": 1355, "s": 1109, "text": "We use the ArticleExtractor to extract the text. This extractor has been tuned for news articles that works well for most HTMLs. You can try out other extractors listed in the documentation for boilerpy3 and see what works best for your dataset." }, { "code": null, "e": 1550, "s": 1355, "text": "Next, we condense all newline characters (\\n and \\r) into one \\n character. This is done so that when we split the text up into sentences by \\n and periods, we don’t get sentences with no words." }, { "code": null, "e": 1744, "s": 1550, "text": "If the extractors from boilerpy3 are not working for your web pages, you can use beautifulsoup to build your own custom text extractor. Below is an example replacement of the parse_html method." }, { "code": null, "e": 2157, "s": 1744, "text": "Once the text has been extracted, we want to continue with the cleaning process. It is common for web pages to contain repeated information, especially if you scrape multiple articles from the same domain. Elements such as website titles, company slogans, and page footers can be present in your parsed text. To detect and remove these phrases, we analyze our corpus by looking at the frequency of large n-grams." }, { "code": null, "e": 2470, "s": 2157, "text": "N-grams is a concept from NLP where the “gram” is a contiguous sequence of words from a body of text, and “N” is the size of these sequences. This is frequently used to build language models which can assist in tasks ranging from text summarization to word prediction. Below is an example for trigrams (3-grams):" }, { "code": null, "e": 2568, "s": 2470, "text": "input = 'It is quite sunny today.'output = ['It is quite', is quite sunny', 'quite sunny today.']" }, { "code": null, "e": 3046, "s": 2568, "text": "When we read articles, there are many single words (unigrams) that are repeated, such as “the” and “a”. However, as we increase our n-gram size, the probability of the n-gram repeating decreases. Trigrams start to become more rare, and it is almost impossible for the articles to contain the same sequence of 20 words. By searching for large n-grams that occur frequently, we are able to detect the repeated elements across websites in our corpus, and manually filter them out." }, { "code": null, "e": 4195, "s": 3046, "text": "We begin this process by breaking up our dataset up into sentences by splitting the text chunks up by the newline characters and periods. Next, we tokenize our sentences (break up the sentence into single word strings). With these tokenized sentences, we are able to generate n-grams of a specific size (we want to start large, around 15). We want to sort the n-grams by frequency using the FreqDist function provided by nltk. Once we have our frequency dictionary, we print the top 10 n-grams. If the frequency is higher than 1 or 2, the sentence might be something you would consider removing from the corpus. To remove the sentence, copy the entire sentence and add it as a single string in the filter_strs array. Copying the entire sentence can be accomplished by increasing the n-gram size until the entire sentence is captured in one n-gram and printed on the console, or simply printing the parsed_texts and searching for the sentence. If there is multiple unwanted sentences with slightly different words, you can copy the common substring into filter_strs, and the regular expression will filter out all sentences containing the substring." }, { "code": null, "e": 4424, "s": 4195, "text": "If you run the code above on your dataset without adding any filters to filter_strs, you might get a graph similar to the one below. In my dataset, you can see that there are several 15-grams that are repeated 6, 3, and 2 times." }, { "code": null, "e": 4541, "s": 4424, "text": "Once we go through the process of populating filter_strs with unwanted sentences, our plot of 15-grams flattens out." }, { "code": null, "e": 4987, "s": 4541, "text": "Keep in mind there is no optimal threshold for n-gram size and frequency that determines whether or not a sentence should be removed, so play around with these two parameters. Sometimes you will need to lower the n-gram size to 3 or 4 to pick up a repeated title, but be careful not to remove valuable data. This block of code is designed to be an iterative process, where you slowly build the filter_strs array after many different experiments." }, { "code": null, "e": 6505, "s": 4987, "text": "After we clean the corpus, the next step is to process the words of our corpus. We want to remove punctuation, lowercase all words, and break each sentence up into arrays of individual words (tokenization). To do this, I like to use the simple_preprocess library method from gensim. This function accomplishes all three of these tasks in one go and has a few parameters that allow some customization. By setting deacc=True, accents will be removed. When punctuation is removed, the punctuation itself is treated as a space, and the two substrings on each side of the punctuation is treated as two separate words. In most cases, words will be split up with one substring having a length of one. For example, “don’t” will end up as “don” and “t”. As a result, the default min_len value is 2, so words with 1 letter are not kept. If this is not suitable for your use case, you can also create a text processor from scratch. Python’s string class contains a punctuation attribute that lists all commonly used punctuation. Using this set of punctuation marks, you can use str.maketrans to remove all punctuation from a string, but keeping those words that did have punctuation as one single word (“don’t” becomes “dont”). Keep in mind this does not capture punctuation as well as gensim’s simple_preprocess. For example, there are three types of dashes (‘ — ’ em dash, –’ en dash, ‘-’ hyphen), and while simple_preprocess removes them all, string.punctuation does not contain the em dash, and therefore does not remove it." }, { "code": null, "e": 6824, "s": 6505, "text": "Once we have our corpus nicely tokenized, we will remove all stop words from the corpus. Stop words are words that don’t provide much additional meaning to a sentence. Words in the English vocabulary include “the”, “a”, and “in”. nltk contains a list of English stopwords, so we use that to filter our lists of tokens." }, { "code": null, "e": 7275, "s": 6824, "text": "Lemmatization is the process of grouping together different forms of the same word and replacing these instances with the word’s lemma (dictionary form). For example, “functions” is reduced to “function”. Stemming is the process of reducing a word to its root word (without any suffixes or prefixes). For example, “running” is reduced to “run”. These two steps decreases the vocabulary size, making it easier for the machine to understand our corpus." }, { "code": null, "e": 7411, "s": 7275, "text": "Now that you know how to extract and preprocess your text data, you can begin the data analysis. Best of luck with your NLP adventures!" }, { "code": null, "e": 7564, "s": 7411, "text": "If you are tagging the corpus with parts-of-speech tags, stop words should be kept in the dataset and lemmatization should not be done prior to tagging." } ]
Bitwise Operators in C
The following table lists the Bitwise operators supported by C. Assume variable 'A' holds 60 and variable 'B' holds 13, then − Try the following example to understand all the bitwise operators available in C − #include <stdio.h> main() { unsigned int a = 60; /* 60 = 0011 1100 */ unsigned int b = 13; /* 13 = 0000 1101 */ int c = 0; c = a & b; /* 12 = 0000 1100 */ printf("Line 1 - Value of c is %d\n", c ); c = a | b; /* 61 = 0011 1101 */ printf("Line 2 - Value of c is %d\n", c ); c = a ^ b; /* 49 = 0011 0001 */ printf("Line 3 - Value of c is %d\n", c ); c = ~a; /*-61 = 1100 0011 */ printf("Line 4 - Value of c is %d\n", c ); c = a << 2; /* 240 = 1111 0000 */ printf("Line 5 - Value of c is %d\n", c ); c = a >> 2; /* 15 = 0000 1111 */ printf("Line 6 - Value of c is %d\n", c ); } When you compile and execute the above program, it produces the following result − Line 1 - Value of c is 12 Line 2 - Value of c is 61 Line 3 - Value of c is 49 Line 4 - Value of c is -61 Line 5 - Value of c is 240 Line 6 - Value of c is 15 Print Add Notes Bookmark this page
[ { "code": null, "e": 2211, "s": 2084, "text": "The following table lists the Bitwise operators supported by C. Assume variable 'A' holds 60 and variable 'B' holds 13, then −" }, { "code": null, "e": 2294, "s": 2211, "text": "Try the following example to understand all the bitwise operators available in C −" }, { "code": null, "e": 2971, "s": 2294, "text": "#include <stdio.h>\n\nmain() {\n\n unsigned int a = 60;\t/* 60 = 0011 1100 */ \n unsigned int b = 13;\t/* 13 = 0000 1101 */\n int c = 0; \n\n c = a & b; /* 12 = 0000 1100 */ \n printf(\"Line 1 - Value of c is %d\\n\", c );\n\n c = a | b; /* 61 = 0011 1101 */\n printf(\"Line 2 - Value of c is %d\\n\", c );\n\n c = a ^ b; /* 49 = 0011 0001 */\n printf(\"Line 3 - Value of c is %d\\n\", c );\n\n c = ~a; /*-61 = 1100 0011 */\n printf(\"Line 4 - Value of c is %d\\n\", c );\n\n c = a << 2; /* 240 = 1111 0000 */\n printf(\"Line 5 - Value of c is %d\\n\", c );\n\n c = a >> 2; /* 15 = 0000 1111 */\n printf(\"Line 6 - Value of c is %d\\n\", c );\n}" }, { "code": null, "e": 3054, "s": 2971, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 3213, "s": 3054, "text": "Line 1 - Value of c is 12\nLine 2 - Value of c is 61\nLine 3 - Value of c is 49\nLine 4 - Value of c is -61\nLine 5 - Value of c is 240\nLine 6 - Value of c is 15\n" }, { "code": null, "e": 3220, "s": 3213, "text": " Print" }, { "code": null, "e": 3231, "s": 3220, "text": " Add Notes" } ]
Backtracking to find all subsets - GeeksforGeeks
10 Feb, 2022 Given a set of positive integers, find all its subsets. Examples: Input: array = {1, 2, 3} Output: // this space denotes null element. 1 1 2 1 2 3 1 3 2 2 3 3 Explanation: These are all the subsets that can be formed using the array. Input: 1 2 Output: 1 2 1 2 Explanation: These are all the subsets that can be formed using the array. The iterative solution is already discussed here: the iterative approach to find all subsets. This article aims to provide a backtracking approach.Approach: The idea is simple, that if there are n number of elements inside an array, there are two choices for every element. Either include that element in the subset or do not include it. Using the above idea forms a recursive solution to the problem.Algorithm: Create a recursive function that takes the following parameters, input array, the current index, the output array, or current subset, if all the subsets need to be stored then a vector of the array is needed if the subsets need to be printed only then this space can be ignored.if the current index is equal to the size of the array, then print the subset or output array or insert the output array into the vector of arrays (or vectors) and return.There are exactly two choices for very index.Ignore the current element and call the recursive function with the current subset and next index, i.e i + 1.Insert the current element in the subset and call the recursive function with the current subset and next index, i.e i + 1. Create a recursive function that takes the following parameters, input array, the current index, the output array, or current subset, if all the subsets need to be stored then a vector of the array is needed if the subsets need to be printed only then this space can be ignored. if the current index is equal to the size of the array, then print the subset or output array or insert the output array into the vector of arrays (or vectors) and return. There are exactly two choices for very index. Ignore the current element and call the recursive function with the current subset and next index, i.e i + 1. Insert the current element in the subset and call the recursive function with the current subset and next index, i.e i + 1. Implementation: C++ Java Python3 C# Javascript // CPP program to find all subsets by backtracking.#include <bits/stdc++.h>using namespace std; // In the array A at every step we have two// choices for each element either we can// ignore the element or we can include the// element in our subsetvoid subsetsUtil(vector<int>& A, vector<vector<int> >& res, vector<int>& subset, int index){ res.push_back(subset); for (int i = index; i < A.size(); i++) { // include the A[i] in subset. subset.push_back(A[i]); // move onto the next element. subsetsUtil(A, res, subset, i + 1); // exclude the A[i] from subset and triggers // backtracking. subset.pop_back(); } return;} // below function returns the subsets of vector A.vector<vector<int> > subsets(vector<int>& A){ vector<int> subset; vector<vector<int> > res; // keeps track of current element in vector A; int index = 0; subsetsUtil(A, res, subset, index); return res;} // Driver Code.int main(){ // find the subsets of below vector. vector<int> array = { 1, 2, 3 }; // res will store all subsets. // O(2 ^ (number of elements inside array)) // because at every step we have two choices // either include or ignore. vector<vector<int> > res = subsets(array); // Print result for (int i = 0; i < res.size(); i++) { for (int j = 0; j < res[i].size(); j++) cout << res[i][j] << " "; cout << endl; } return 0;} /*package whatever //do not write package name here */ import java.io.*;import java.util.*;class GFG { public static void findSubsets(List<List<Integer>> subset, ArrayList<Integer> nums, ArrayList<Integer> output, int index) { // Base Condition if (index == nums.size()) { subset.add(output); return; } // Not Including Value which is at Index findSubsets(subset, nums, new ArrayList<>(output), index + 1); // Including Value which is at Index output.add(nums.get(index)); findSubsets(subset, nums, new ArrayList<>(output), index + 1); } public static void main(String[] args) { //Main List for storing all subsets List<List<Integer>> subset = new ArrayList<>(); // Input ArrayList ArrayList<Integer> input = new ArrayList<>(); input.add(1); input.add(2); input.add(3); findSubsets(subset, input, new ArrayList<>(), 0); // Comparator is used so that all subset get // sorted in ascending order of values Collections.sort(subset, (o1, o2) -> { int n = Math.min(o1.size(), o2.size()); for (int i = 0; i < n; i++) { if (o1.get(i) == o2.get(i)){ continue; }else{ return o1.get(i) - o2.get(i); } } return 1; }); // Printing Subset for(int i = 0; i < subset.size(); i++){ for(int j = 0; j < subset.get(i).size(); j++){ System.out.print(subset.get(i).get(j) + " "); } System.out.println(); } }} # Python3 program to find all subsets# by backtracking. # In the array A at every step we have two# choices for each element either we can# ignore the element or we can include the# element in our subsetdef subsetsUtil(A, subset, index): print(*subset) for i in range(index, len(A)): # include the A[i] in subset. subset.append(A[i]) # move onto the next element. subsetsUtil(A, subset, i + 1) # exclude the A[i] from subset and # triggers backtracking. subset.pop(-1) return # below function returns the subsets of vector A.def subsets(A): global res subset = [] # keeps track of current element in vector A index = 0 subsetsUtil(A, subset, index) # Driver Code # find the subsets of below vector.array = [1, 2, 3] # res will store all subsets.# O(2 ^ (number of elements inside array))# because at every step we have two choices# either include or ignore.subsets(array) # This code is contributed by SHUBHAMSINGH8410 /*package whatever //do not write package name here */using System;using System.Collections.Generic; public class GFG { public static void findSubsets(List<List<int>> subset, List<int> nums, List<int> output, int index) { // Base Condition if (index == nums.Count) { subset.Add(output); return; } // Not Including Value which is at Index findSubsets(subset, nums, new List<int>(output), index + 1); // Including Value which is at Index output.Add(nums[index]); findSubsets(subset, nums, new List<int>(output), index + 1); } public static void Main(String[] args) { // Main List for storing all subsets List<List<int>> subset = new List<List<int>>(); // Input List List<int> input = new List<int>(); input.Add(1); input.Add(2); input.Add(3); findSubsets(subset, input, new List<int>(), 0); // Comparator is used so that all subset get // sorted in ascending order of values subset.Sort((o1, o2) => { int n = Math.Min(o1.Count, o2.Count); for (int i = 0; i < n; i++) { if (o1[i] == o2[i]){ continue; }else{ return o1[i] - o2[i]; } } return 1; }); // Printing Subset for(int i = 0; i < subset.Count; i++){ for(int j = 0; j < subset[i].Count; j++){ Console.Write(subset[i][j] + " "); } Console.WriteLine(); } }} // This code is contributed by shikhasingrajput <script>/*package whatever //do not write package name here */function findSubsets(subset, nums, output, index){ // Base Condition if (index == nums.length) { subset.push(output); return; } // Not Including Value which is at Index findSubsets(subset, nums, [...output], index + 1); // Including Value which is at Index output.push(nums[index]); findSubsets(subset, nums, [...output], index + 1);} // Main List for storing all subsetslet subset = []; // Input ArrayListlet input = [];input.push(1);input.push(2);input.push(3); findSubsets(subset, input, [], 0); // Comparator is used so that all subset get// sorted in ascending order of valuessubset.sort((o1, o2) => { let n = Math.min(o1.length, o2.length); for (let i = 0; i < n; i++) { if (o1[i] == o2[i]) { continue; } else { return o1[i] - o2[i]; } } return 1;}); // Printing Subsetfor (let i = 0; i < subset.length; i++) { for (let j = 0; j < subset[i].length; j++) { document.write(subset[i][j] + " "); } document.write("<br>");} // This code is contributed by saurabh_jaiswal.</script> 1 1 2 1 2 3 1 3 2 2 3 3 Complexity Analysis: Time Complexity: O(n(2 ^ n)). For every index i two recursive cases originate, So Time Complexity is O(2^n). If we include the time taken to copy the subset vector into the res vector the time taken will be equal to the size of the subset vector. Space Complexity: O(n). The space complexity can be reduced if the output array is not stored and the static and global variable is used to store the output string. AbdulWadood SHUBHAMSINGH10 andrew1234 Akanksha_Rai srivastavaharshit333 vaibhavpatel1904 _saurabh_jaiswal shikhasingrajput subset Arrays Backtracking Arrays subset Backtracking Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Introduction to Arrays Linear Search Maximum and minimum of an array using minimum number of comparisons N Queen Problem | Backtracking-3 Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Rat in a Maze | Backtracking-2 Backtracking | Introduction Sudoku | Backtracking-7
[ { "code": null, "e": 24896, "s": 24868, "text": "\n10 Feb, 2022" }, { "code": null, "e": 24964, "s": 24896, "text": "Given a set of positive integers, find all its subsets. Examples: " }, { "code": null, "e": 25330, "s": 24964, "text": "Input: array = {1, 2, 3}\nOutput: // this space denotes null element. \n 1\n 1 2\n 1 2 3\n 1 3\n 2\n 2 3\n 3\nExplanation: These are all the subsets that \ncan be formed using the array.\n\nInput: 1 2\nOutput: \n 1 \n 2\n 1 2\nExplanation: These are all the subsets that \ncan be formed using the array." }, { "code": null, "e": 25746, "s": 25332, "text": "The iterative solution is already discussed here: the iterative approach to find all subsets. This article aims to provide a backtracking approach.Approach: The idea is simple, that if there are n number of elements inside an array, there are two choices for every element. Either include that element in the subset or do not include it. Using the above idea forms a recursive solution to the problem.Algorithm: " }, { "code": null, "e": 26473, "s": 25746, "text": "Create a recursive function that takes the following parameters, input array, the current index, the output array, or current subset, if all the subsets need to be stored then a vector of the array is needed if the subsets need to be printed only then this space can be ignored.if the current index is equal to the size of the array, then print the subset or output array or insert the output array into the vector of arrays (or vectors) and return.There are exactly two choices for very index.Ignore the current element and call the recursive function with the current subset and next index, i.e i + 1.Insert the current element in the subset and call the recursive function with the current subset and next index, i.e i + 1." }, { "code": null, "e": 26752, "s": 26473, "text": "Create a recursive function that takes the following parameters, input array, the current index, the output array, or current subset, if all the subsets need to be stored then a vector of the array is needed if the subsets need to be printed only then this space can be ignored." }, { "code": null, "e": 26924, "s": 26752, "text": "if the current index is equal to the size of the array, then print the subset or output array or insert the output array into the vector of arrays (or vectors) and return." }, { "code": null, "e": 26970, "s": 26924, "text": "There are exactly two choices for very index." }, { "code": null, "e": 27080, "s": 26970, "text": "Ignore the current element and call the recursive function with the current subset and next index, i.e i + 1." }, { "code": null, "e": 27204, "s": 27080, "text": "Insert the current element in the subset and call the recursive function with the current subset and next index, i.e i + 1." }, { "code": null, "e": 27222, "s": 27204, "text": "Implementation: " }, { "code": null, "e": 27226, "s": 27222, "text": "C++" }, { "code": null, "e": 27231, "s": 27226, "text": "Java" }, { "code": null, "e": 27239, "s": 27231, "text": "Python3" }, { "code": null, "e": 27242, "s": 27239, "text": "C#" }, { "code": null, "e": 27253, "s": 27242, "text": "Javascript" }, { "code": "// CPP program to find all subsets by backtracking.#include <bits/stdc++.h>using namespace std; // In the array A at every step we have two// choices for each element either we can// ignore the element or we can include the// element in our subsetvoid subsetsUtil(vector<int>& A, vector<vector<int> >& res, vector<int>& subset, int index){ res.push_back(subset); for (int i = index; i < A.size(); i++) { // include the A[i] in subset. subset.push_back(A[i]); // move onto the next element. subsetsUtil(A, res, subset, i + 1); // exclude the A[i] from subset and triggers // backtracking. subset.pop_back(); } return;} // below function returns the subsets of vector A.vector<vector<int> > subsets(vector<int>& A){ vector<int> subset; vector<vector<int> > res; // keeps track of current element in vector A; int index = 0; subsetsUtil(A, res, subset, index); return res;} // Driver Code.int main(){ // find the subsets of below vector. vector<int> array = { 1, 2, 3 }; // res will store all subsets. // O(2 ^ (number of elements inside array)) // because at every step we have two choices // either include or ignore. vector<vector<int> > res = subsets(array); // Print result for (int i = 0; i < res.size(); i++) { for (int j = 0; j < res[i].size(); j++) cout << res[i][j] << \" \"; cout << endl; } return 0;}", "e": 28724, "s": 27253, "text": null }, { "code": "/*package whatever //do not write package name here */ import java.io.*;import java.util.*;class GFG { public static void findSubsets(List<List<Integer>> subset, ArrayList<Integer> nums, ArrayList<Integer> output, int index) { // Base Condition if (index == nums.size()) { subset.add(output); return; } // Not Including Value which is at Index findSubsets(subset, nums, new ArrayList<>(output), index + 1); // Including Value which is at Index output.add(nums.get(index)); findSubsets(subset, nums, new ArrayList<>(output), index + 1); } public static void main(String[] args) { //Main List for storing all subsets List<List<Integer>> subset = new ArrayList<>(); // Input ArrayList ArrayList<Integer> input = new ArrayList<>(); input.add(1); input.add(2); input.add(3); findSubsets(subset, input, new ArrayList<>(), 0); // Comparator is used so that all subset get // sorted in ascending order of values Collections.sort(subset, (o1, o2) -> { int n = Math.min(o1.size(), o2.size()); for (int i = 0; i < n; i++) { if (o1.get(i) == o2.get(i)){ continue; }else{ return o1.get(i) - o2.get(i); } } return 1; }); // Printing Subset for(int i = 0; i < subset.size(); i++){ for(int j = 0; j < subset.get(i).size(); j++){ System.out.print(subset.get(i).get(j) + \" \"); } System.out.println(); } }}", "e": 30404, "s": 28724, "text": null }, { "code": "# Python3 program to find all subsets# by backtracking. # In the array A at every step we have two# choices for each element either we can# ignore the element or we can include the# element in our subsetdef subsetsUtil(A, subset, index): print(*subset) for i in range(index, len(A)): # include the A[i] in subset. subset.append(A[i]) # move onto the next element. subsetsUtil(A, subset, i + 1) # exclude the A[i] from subset and # triggers backtracking. subset.pop(-1) return # below function returns the subsets of vector A.def subsets(A): global res subset = [] # keeps track of current element in vector A index = 0 subsetsUtil(A, subset, index) # Driver Code # find the subsets of below vector.array = [1, 2, 3] # res will store all subsets.# O(2 ^ (number of elements inside array))# because at every step we have two choices# either include or ignore.subsets(array) # This code is contributed by SHUBHAMSINGH8410", "e": 31432, "s": 30404, "text": null }, { "code": "/*package whatever //do not write package name here */using System;using System.Collections.Generic; public class GFG { public static void findSubsets(List<List<int>> subset, List<int> nums, List<int> output, int index) { // Base Condition if (index == nums.Count) { subset.Add(output); return; } // Not Including Value which is at Index findSubsets(subset, nums, new List<int>(output), index + 1); // Including Value which is at Index output.Add(nums[index]); findSubsets(subset, nums, new List<int>(output), index + 1); } public static void Main(String[] args) { // Main List for storing all subsets List<List<int>> subset = new List<List<int>>(); // Input List List<int> input = new List<int>(); input.Add(1); input.Add(2); input.Add(3); findSubsets(subset, input, new List<int>(), 0); // Comparator is used so that all subset get // sorted in ascending order of values subset.Sort((o1, o2) => { int n = Math.Min(o1.Count, o2.Count); for (int i = 0; i < n; i++) { if (o1[i] == o2[i]){ continue; }else{ return o1[i] - o2[i]; } } return 1; }); // Printing Subset for(int i = 0; i < subset.Count; i++){ for(int j = 0; j < subset[i].Count; j++){ Console.Write(subset[i][j] + \" \"); } Console.WriteLine(); } }} // This code is contributed by shikhasingrajput", "e": 32865, "s": 31432, "text": null }, { "code": "<script>/*package whatever //do not write package name here */function findSubsets(subset, nums, output, index){ // Base Condition if (index == nums.length) { subset.push(output); return; } // Not Including Value which is at Index findSubsets(subset, nums, [...output], index + 1); // Including Value which is at Index output.push(nums[index]); findSubsets(subset, nums, [...output], index + 1);} // Main List for storing all subsetslet subset = []; // Input ArrayListlet input = [];input.push(1);input.push(2);input.push(3); findSubsets(subset, input, [], 0); // Comparator is used so that all subset get// sorted in ascending order of valuessubset.sort((o1, o2) => { let n = Math.min(o1.length, o2.length); for (let i = 0; i < n; i++) { if (o1[i] == o2[i]) { continue; } else { return o1[i] - o2[i]; } } return 1;}); // Printing Subsetfor (let i = 0; i < subset.length; i++) { for (let j = 0; j < subset[i].length; j++) { document.write(subset[i][j] + \" \"); } document.write(\"<br>\");} // This code is contributed by saurabh_jaiswal.</script>", "e": 34021, "s": 32865, "text": null }, { "code": null, "e": 34052, "s": 34021, "text": "1 \n1 2 \n1 2 3 \n1 3 \n2 \n2 3 \n3 " }, { "code": null, "e": 34075, "s": 34052, "text": "Complexity Analysis: " }, { "code": null, "e": 34322, "s": 34075, "text": "Time Complexity: O(n(2 ^ n)). For every index i two recursive cases originate, So Time Complexity is O(2^n). If we include the time taken to copy the subset vector into the res vector the time taken will be equal to the size of the subset vector." }, { "code": null, "e": 34487, "s": 34322, "text": "Space Complexity: O(n). The space complexity can be reduced if the output array is not stored and the static and global variable is used to store the output string." }, { "code": null, "e": 34501, "s": 34489, "text": "AbdulWadood" }, { "code": null, "e": 34516, "s": 34501, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 34527, "s": 34516, "text": "andrew1234" }, { "code": null, "e": 34540, "s": 34527, "text": "Akanksha_Rai" }, { "code": null, "e": 34561, "s": 34540, "text": "srivastavaharshit333" }, { "code": null, "e": 34578, "s": 34561, "text": "vaibhavpatel1904" }, { "code": null, "e": 34595, "s": 34578, "text": "_saurabh_jaiswal" }, { "code": null, "e": 34612, "s": 34595, "text": "shikhasingrajput" }, { "code": null, "e": 34619, "s": 34612, "text": "subset" }, { "code": null, "e": 34626, "s": 34619, "text": "Arrays" }, { "code": null, "e": 34639, "s": 34626, "text": "Backtracking" }, { "code": null, "e": 34646, "s": 34639, "text": "Arrays" }, { "code": null, "e": 34653, "s": 34646, "text": "subset" }, { "code": null, "e": 34666, "s": 34653, "text": "Backtracking" }, { "code": null, "e": 34764, "s": 34666, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34808, "s": 34764, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 34840, "s": 34808, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 34863, "s": 34840, "text": "Introduction to Arrays" }, { "code": null, "e": 34877, "s": 34863, "text": "Linear Search" }, { "code": null, "e": 34945, "s": 34877, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 34978, "s": 34945, "text": "N Queen Problem | Backtracking-3" }, { "code": null, "e": 35063, "s": 34978, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 35094, "s": 35063, "text": "Rat in a Maze | Backtracking-2" }, { "code": null, "e": 35122, "s": 35094, "text": "Backtracking | Introduction" } ]
Data science classification for mobile app malware | Towards Data Science
TL;DR: Bad guys abuse permissions and outdated software to infect your devices. At the time of writing this piece, Apple Inc. and Epic Games, Inc. are in the throes of a legal dispute. Epic Games claims that Apple’s App Store is a monopoly, and should not have control over in-app purchases. Apple countersued Epic and accused it of breaching its contract. The outcome of the ruling could fundamentally alter how Apple runs its App Store and how app developers monetize their content. There is one aspect to the lawsuit that piqued my interest: Apple’s argument for maintaining its current model of having complete control over the App Store. The argument goes that Apple’s tight grip over the App Store guarantees a safe environment where every single application is vetted for malware and compliance with Apple’s standards. Hence, the user is shielded from malware and can focus on what’s important: finding an app you like. The metaphor of the walled garden is often used here since you can pick and enjoy any fruit within the garden as long as you stick within the confines of its walls. This got me asking: What’s the security landscape in a third party store compared to Apple’s? Can we create a simple data-driven model to vet apps for malware regardless of who controls the store? Full disclosure: This entire project was done on an Apple MacBook, I’m not taking any sides in the legal case. My objective in this piece is to show how a data-driven approach can flag malicious smartphone apps, and provide an explanation for each step leading up to that goal. I will also see how my results compare to other research on the topic. The operating system (OS) examined is Android, which has a 72% share of the world wide mobile OS market. Given its widespread popularity, it is more likely to be abused by malicious actors. The repository associated with this project can be found here: github.com The data is from Kaggle user Saurabh Shahane, and can be downloaded in one click: www.kaggle.com The dataset was originally used in the paper “ADROIT: Android malware detection using meta-information” by Martín, Alejandro; Calleja, Alejandro; Menéndez, Héctor D.; Tapiador, Juan; Camacho, David. Each row in the dataset represents meta-information of an app available on the Aptoide app store website and also information from the app’s Android Manifest. In addition, the paper will serve as a benchmark for model performance. Please note that I assume that the information in the dataset is as truthful and accurate as possible. Any changes to this fundamental assumption might entirely alter the findings of this article. In addition, I highly recommend reading the paper as it explains how the data was aggregated and labeled. In this section, I give a general description of how I munge disparate data types into actionable features. Rather straightforward, the target variable takes one of two values: benign or malware. The data is about 70% benign and 30% malware. For comparison, according to Apple CEO Tim Cook, only 1–2% of the Apple App Store is malware. The authors of the ADROIT paper achieved 94% AUC. I will see if I can replicate similar results with my methods. Moreover, I will also use F1 score for checking model performance. Indeed, ROC averages over all possible thresholds whereas the F1 score applies to any arbitrary point on the ROC curve. Using the F1 score also raises core business questions: do we sacrifice precision for more recall? Is the cost of missing a malware app much higher than barring well-meaning developers from using the marketplace (False Positive)? To rephrase the previous question: For a store like Aptoide, how much potential income would they be missing out on if they barred a well-meaning developer? On the other hand, how much reputational damage, user harm, and lost income is there from missing malware? Furthermore, not all malware is created equal. Indeed, it can be adware, spyware, ransomware, or some other kind. These questions are tied to core business benchmarks and are beyond the scope of this article. Out of 166 numerical features, 160 are binary and 6 are continuous. We have too many features on our hands, and it might hinder a model’s predictive performance. For this reason, it’s useful to look at each feature’s variance and remove features that have a low variance. For the continuous variables, we have to look at outliers. This is particularly relevant to the number of ratings an app receives since an overwhelming number of apps never received a single rating. In order to weed out outliers, I used Tukey’s method: the outliers are values more than 1.5 times the interquartile range from the quartiles, either below Q1 − 1.5IQR, or above Q3 + 1.5IQR. When it comes to NLP, I usually pose the following questions: Can I understand what a column is about by skimming the text? Does it use the Latin alphabet and is it all in the same language? What are the preprocessing functions needed? What’s the most compact and representative way to transform the text? As it turns out, many entries have a description in Chinese characters (Also some Turkish, Korean, etc...). If one day I want to productionize or explain this model, I will have to understand and explain its choices to stakeholders. However, I can’t explain that which I don’t understand and therefore decided to drop non-Latin characters from the text. Below is a sample from an app description: Tap Tap Gems is a very addictive puzzle game. Tap two or more gems with the same colour to remove them from the board. You must think which gems should be removed next. To pass each level you must score certain amount of points. The more gems removed the more points you score. Game features 120 levels and 7 different gems. And another sample shows that even with strictly Latin characters, one might still have no idea what is going on (I’m guessing this is Vietnamese?). Game bi dn gian Vit bao gm 15+ cc mini quen thuc vi ngi Vit ta t xa n nay nh: Xm, Phm, Tin ln min Nam, Ling, Poker, X t, Mu binh, Bi co, X dzach v Tin ln min Nam m l. t lu Tin Ln Min Nam m L - Game bi dn gian Vit c cc game th yu qu bi ha cc p, giao din c chm sc rt k. Cc chc nng trong game hn hn cc game cng loi khc nh After preprocessing, the text data is transformed using TF-IDF vectorization. In order to optimize prediction, TF-IDF parameters are tuned using a grid search cross validation. At first I wanted to choose XGBoost since it had the highest AUC. So I set out to do a vanilla data science workflow that comes after data munging: Instantiate TF-IDF vectorizer Instantiate a pipeline to avoid leakage Research how parameters influence the model predictions with GridSearchCV With an AUC of 0.94, I was happy since it matched the authors’ findings. However, when comparing train/test AUC, the plot below suggested I was overfitting: In contrast, Random Forest (RF) shows underfitting: Logistic regression is not overfitting, but it might be severely underfitting. XGBoost should be the clear winner here, however, I decided to continue with a vanilla logistic regression. It comes with a rather straightforward interpretability and saves me the trouble of using methods such as SHAP, feature permutation, or LIME. Since this task involves NLP, I want to mine as much information as possible from the text data. Logistic regression tends to suffer when working with sparse data, and sparse data is typical when working with text. We have two plots below, one is the ROC curve and the other is the precision recall curve. Multiple curves show how as we add more features the model performance improves only slightly. Spoiler Alert: Text data did not matter, the next section will show that the numerical features in the Android Manifest are the most important factors for classification. It’s fair to assume that black box models are not exactly popular. Therefore, I set out to understand how the classifier weighs its decisions and dive deeper into these features. In terms of what is a strong indicator for malware, the top 5 are: android.permission.READ_SYNC_SETTINGSandroid.permission.WRITE_SYNC_SETTINGSandroid.permission.MANAGE_ACCOUNTScom.android.launcher.permission.UNINSTALL_SHORTCUTandroid.permission.RECEIVE_BOOT_COMPLETED android.permission.READ_SYNC_SETTINGS android.permission.WRITE_SYNC_SETTINGS android.permission.MANAGE_ACCOUNTS com.android.launcher.permission.UNINSTALL_SHORTCUT android.permission.RECEIVE_BOOT_COMPLETED Take for example the permission to write sync settings, what does it mean? When a device synchronizes (syncs), it is synchronizes data on your phone with the service’s servers. The table below is a snapshot from the training data, and it suggests that giving an unvetted app these permissions is a strong case for caution. In addition, MANAGE_ACCOUNTS, allows the app to add/remove accounts and delete their passwords. Moreover, the RECEIVE_BOOT_COMPLETED stood out as a strong indication of compromise. The android documentation sums it up nicely: Though holding this permission does not have any security implications, it can have a negative impact on the user experience by increasing the amount of time it takes the system to start and allowing applications to have themselves running without the user being aware of them. Lastly, the UNINSTALL_SHORTCUT permission is no longer supported. This might be associated with malware as older software tends to have more outstanding vulnerabilities. For the indicators against malware, the main features are not as obvious: android.permission.BLUETOOTHandroid.permission.READ_LOGS.//Min_SDKandroid.permission.READ_EXTERNAL_STORAGE“ringtones” android.permission.BLUETOOTH android.permission.READ_LOGS .//Min_SDK android.permission.READ_EXTERNAL_STORAGE “ringtones” It’s not entirely clear to me why permissions to connect to paired Bluetooth and reading low-level system log files is a case against malware. Perhaps it’s not as bad as other permissions that allow the device to advertise to nearby Bluetooth devices (see BLUETOOTH_ADVERTISE). Moreover, it’s beyond me why having “ringtones” in the app description gives you the green light to download it. However, I can comprehend how setting a higher SDK version (Min_SDK) can protect your device against infection. This feature aligns well with READ_EXTERNAL_STORAGE. The latter is enforced starting API level 19 and prompts the user for themselves to enable/disable the permission. Unfortunately, the referenced paper does not come with code or an explanation of model weights. Therefore, I’m unable to rigorously compare my findings with the authors’. Working with data from the Aptoide store suggests that there’s an ample amount of malware on third party stores. Therefore, Apple’s business practices could seem reasonable if they guarantee the safety of the user. However, data science can be leveraged to create a speedy and accurate classification system where such restrictions by Apple are not necessary. The logistic regression model is simple to set up and offers adequate performance when compared to existing literature. Projects like these have the potential to boost the safety of app stores and give a deeper understanding of how vulnerabilities are exploited. The methodology can be expanded to other stores and operating systems. If you’re interested in learning more about the intersection between cybersecurity and data science, check out this other project:
[ { "code": null, "e": 252, "s": 172, "text": "TL;DR: Bad guys abuse permissions and outdated software to infect your devices." }, { "code": null, "e": 657, "s": 252, "text": "At the time of writing this piece, Apple Inc. and Epic Games, Inc. are in the throes of a legal dispute. Epic Games claims that Apple’s App Store is a monopoly, and should not have control over in-app purchases. Apple countersued Epic and accused it of breaching its contract. The outcome of the ruling could fundamentally alter how Apple runs its App Store and how app developers monetize their content." }, { "code": null, "e": 815, "s": 657, "text": "There is one aspect to the lawsuit that piqued my interest: Apple’s argument for maintaining its current model of having complete control over the App Store." }, { "code": null, "e": 1264, "s": 815, "text": "The argument goes that Apple’s tight grip over the App Store guarantees a safe environment where every single application is vetted for malware and compliance with Apple’s standards. Hence, the user is shielded from malware and can focus on what’s important: finding an app you like. The metaphor of the walled garden is often used here since you can pick and enjoy any fruit within the garden as long as you stick within the confines of its walls." }, { "code": null, "e": 1461, "s": 1264, "text": "This got me asking: What’s the security landscape in a third party store compared to Apple’s? Can we create a simple data-driven model to vet apps for malware regardless of who controls the store?" }, { "code": null, "e": 1572, "s": 1461, "text": "Full disclosure: This entire project was done on an Apple MacBook, I’m not taking any sides in the legal case." }, { "code": null, "e": 1810, "s": 1572, "text": "My objective in this piece is to show how a data-driven approach can flag malicious smartphone apps, and provide an explanation for each step leading up to that goal. I will also see how my results compare to other research on the topic." }, { "code": null, "e": 2000, "s": 1810, "text": "The operating system (OS) examined is Android, which has a 72% share of the world wide mobile OS market. Given its widespread popularity, it is more likely to be abused by malicious actors." }, { "code": null, "e": 2063, "s": 2000, "text": "The repository associated with this project can be found here:" }, { "code": null, "e": 2074, "s": 2063, "text": "github.com" }, { "code": null, "e": 2156, "s": 2074, "text": "The data is from Kaggle user Saurabh Shahane, and can be downloaded in one click:" }, { "code": null, "e": 2171, "s": 2156, "text": "www.kaggle.com" }, { "code": null, "e": 2373, "s": 2171, "text": "The dataset was originally used in the paper “ADROIT: Android malware detection using meta-information” by Martín, Alejandro; Calleja, Alejandro; Menéndez, Héctor D.; Tapiador, Juan; Camacho, David." }, { "code": null, "e": 2604, "s": 2373, "text": "Each row in the dataset represents meta-information of an app available on the Aptoide app store website and also information from the app’s Android Manifest. In addition, the paper will serve as a benchmark for model performance." }, { "code": null, "e": 2907, "s": 2604, "text": "Please note that I assume that the information in the dataset is as truthful and accurate as possible. Any changes to this fundamental assumption might entirely alter the findings of this article. In addition, I highly recommend reading the paper as it explains how the data was aggregated and labeled." }, { "code": null, "e": 3015, "s": 2907, "text": "In this section, I give a general description of how I munge disparate data types into actionable features." }, { "code": null, "e": 3243, "s": 3015, "text": "Rather straightforward, the target variable takes one of two values: benign or malware. The data is about 70% benign and 30% malware. For comparison, according to Apple CEO Tim Cook, only 1–2% of the Apple App Store is malware." }, { "code": null, "e": 3356, "s": 3243, "text": "The authors of the ADROIT paper achieved 94% AUC. I will see if I can replicate similar results with my methods." }, { "code": null, "e": 3543, "s": 3356, "text": "Moreover, I will also use F1 score for checking model performance. Indeed, ROC averages over all possible thresholds whereas the F1 score applies to any arbitrary point on the ROC curve." }, { "code": null, "e": 3773, "s": 3543, "text": "Using the F1 score also raises core business questions: do we sacrifice precision for more recall? Is the cost of missing a malware app much higher than barring well-meaning developers from using the marketplace (False Positive)?" }, { "code": null, "e": 4037, "s": 3773, "text": "To rephrase the previous question: For a store like Aptoide, how much potential income would they be missing out on if they barred a well-meaning developer? On the other hand, how much reputational damage, user harm, and lost income is there from missing malware?" }, { "code": null, "e": 4151, "s": 4037, "text": "Furthermore, not all malware is created equal. Indeed, it can be adware, spyware, ransomware, or some other kind." }, { "code": null, "e": 4246, "s": 4151, "text": "These questions are tied to core business benchmarks and are beyond the scope of this article." }, { "code": null, "e": 4518, "s": 4246, "text": "Out of 166 numerical features, 160 are binary and 6 are continuous. We have too many features on our hands, and it might hinder a model’s predictive performance. For this reason, it’s useful to look at each feature’s variance and remove features that have a low variance." }, { "code": null, "e": 4717, "s": 4518, "text": "For the continuous variables, we have to look at outliers. This is particularly relevant to the number of ratings an app receives since an overwhelming number of apps never received a single rating." }, { "code": null, "e": 4907, "s": 4717, "text": "In order to weed out outliers, I used Tukey’s method: the outliers are values more than 1.5 times the interquartile range from the quartiles, either below Q1 − 1.5IQR, or above Q3 + 1.5IQR." }, { "code": null, "e": 4969, "s": 4907, "text": "When it comes to NLP, I usually pose the following questions:" }, { "code": null, "e": 5031, "s": 4969, "text": "Can I understand what a column is about by skimming the text?" }, { "code": null, "e": 5098, "s": 5031, "text": "Does it use the Latin alphabet and is it all in the same language?" }, { "code": null, "e": 5143, "s": 5098, "text": "What are the preprocessing functions needed?" }, { "code": null, "e": 5213, "s": 5143, "text": "What’s the most compact and representative way to transform the text?" }, { "code": null, "e": 5567, "s": 5213, "text": "As it turns out, many entries have a description in Chinese characters (Also some Turkish, Korean, etc...). If one day I want to productionize or explain this model, I will have to understand and explain its choices to stakeholders. However, I can’t explain that which I don’t understand and therefore decided to drop non-Latin characters from the text." }, { "code": null, "e": 5610, "s": 5567, "text": "Below is a sample from an app description:" }, { "code": null, "e": 5941, "s": 5610, "text": "Tap Tap Gems is a very addictive puzzle game. Tap two or more gems with the same colour to remove them from the board. You must think which gems should be removed next. To pass each level you must score certain amount of points. The more gems removed the more points you score. Game features 120 levels and 7 different gems." }, { "code": null, "e": 6090, "s": 5941, "text": "And another sample shows that even with strictly Latin characters, one might still have no idea what is going on (I’m guessing this is Vietnamese?)." }, { "code": null, "e": 6412, "s": 6090, "text": "Game bi dn gian Vit bao gm 15+ cc mini quen thuc vi ngi Vit ta t xa n nay nh: Xm, Phm, Tin ln min Nam, Ling, Poker, X t, Mu binh, Bi co, X dzach v Tin ln min Nam m l. t lu Tin Ln Min Nam m L - Game bi dn gian Vit c cc game th yu qu bi ha cc p, giao din c chm sc rt k. Cc chc nng trong game hn hn cc game cng loi khc nh" }, { "code": null, "e": 6589, "s": 6412, "text": "After preprocessing, the text data is transformed using TF-IDF vectorization. In order to optimize prediction, TF-IDF parameters are tuned using a grid search cross validation." }, { "code": null, "e": 6737, "s": 6589, "text": "At first I wanted to choose XGBoost since it had the highest AUC. So I set out to do a vanilla data science workflow that comes after data munging:" }, { "code": null, "e": 6767, "s": 6737, "text": "Instantiate TF-IDF vectorizer" }, { "code": null, "e": 6807, "s": 6767, "text": "Instantiate a pipeline to avoid leakage" }, { "code": null, "e": 6881, "s": 6807, "text": "Research how parameters influence the model predictions with GridSearchCV" }, { "code": null, "e": 7038, "s": 6881, "text": "With an AUC of 0.94, I was happy since it matched the authors’ findings. However, when comparing train/test AUC, the plot below suggested I was overfitting:" }, { "code": null, "e": 7090, "s": 7038, "text": "In contrast, Random Forest (RF) shows underfitting:" }, { "code": null, "e": 7169, "s": 7090, "text": "Logistic regression is not overfitting, but it might be severely underfitting." }, { "code": null, "e": 7419, "s": 7169, "text": "XGBoost should be the clear winner here, however, I decided to continue with a vanilla logistic regression. It comes with a rather straightforward interpretability and saves me the trouble of using methods such as SHAP, feature permutation, or LIME." }, { "code": null, "e": 7634, "s": 7419, "text": "Since this task involves NLP, I want to mine as much information as possible from the text data. Logistic regression tends to suffer when working with sparse data, and sparse data is typical when working with text." }, { "code": null, "e": 7820, "s": 7634, "text": "We have two plots below, one is the ROC curve and the other is the precision recall curve. Multiple curves show how as we add more features the model performance improves only slightly." }, { "code": null, "e": 7991, "s": 7820, "text": "Spoiler Alert: Text data did not matter, the next section will show that the numerical features in the Android Manifest are the most important factors for classification." }, { "code": null, "e": 8170, "s": 7991, "text": "It’s fair to assume that black box models are not exactly popular. Therefore, I set out to understand how the classifier weighs its decisions and dive deeper into these features." }, { "code": null, "e": 8237, "s": 8170, "text": "In terms of what is a strong indicator for malware, the top 5 are:" }, { "code": null, "e": 8438, "s": 8237, "text": "android.permission.READ_SYNC_SETTINGSandroid.permission.WRITE_SYNC_SETTINGSandroid.permission.MANAGE_ACCOUNTScom.android.launcher.permission.UNINSTALL_SHORTCUTandroid.permission.RECEIVE_BOOT_COMPLETED" }, { "code": null, "e": 8476, "s": 8438, "text": "android.permission.READ_SYNC_SETTINGS" }, { "code": null, "e": 8515, "s": 8476, "text": "android.permission.WRITE_SYNC_SETTINGS" }, { "code": null, "e": 8550, "s": 8515, "text": "android.permission.MANAGE_ACCOUNTS" }, { "code": null, "e": 8601, "s": 8550, "text": "com.android.launcher.permission.UNINSTALL_SHORTCUT" }, { "code": null, "e": 8643, "s": 8601, "text": "android.permission.RECEIVE_BOOT_COMPLETED" }, { "code": null, "e": 8820, "s": 8643, "text": "Take for example the permission to write sync settings, what does it mean? When a device synchronizes (syncs), it is synchronizes data on your phone with the service’s servers." }, { "code": null, "e": 8966, "s": 8820, "text": "The table below is a snapshot from the training data, and it suggests that giving an unvetted app these permissions is a strong case for caution." }, { "code": null, "e": 9062, "s": 8966, "text": "In addition, MANAGE_ACCOUNTS, allows the app to add/remove accounts and delete their passwords." }, { "code": null, "e": 9192, "s": 9062, "text": "Moreover, the RECEIVE_BOOT_COMPLETED stood out as a strong indication of compromise. The android documentation sums it up nicely:" }, { "code": null, "e": 9470, "s": 9192, "text": "Though holding this permission does not have any security implications, it can have a negative impact on the user experience by increasing the amount of time it takes the system to start and allowing applications to have themselves running without the user being aware of them." }, { "code": null, "e": 9640, "s": 9470, "text": "Lastly, the UNINSTALL_SHORTCUT permission is no longer supported. This might be associated with malware as older software tends to have more outstanding vulnerabilities." }, { "code": null, "e": 9714, "s": 9640, "text": "For the indicators against malware, the main features are not as obvious:" }, { "code": null, "e": 9832, "s": 9714, "text": "android.permission.BLUETOOTHandroid.permission.READ_LOGS.//Min_SDKandroid.permission.READ_EXTERNAL_STORAGE“ringtones”" }, { "code": null, "e": 9861, "s": 9832, "text": "android.permission.BLUETOOTH" }, { "code": null, "e": 9890, "s": 9861, "text": "android.permission.READ_LOGS" }, { "code": null, "e": 9901, "s": 9890, "text": ".//Min_SDK" }, { "code": null, "e": 9942, "s": 9901, "text": "android.permission.READ_EXTERNAL_STORAGE" }, { "code": null, "e": 9954, "s": 9942, "text": "“ringtones”" }, { "code": null, "e": 10232, "s": 9954, "text": "It’s not entirely clear to me why permissions to connect to paired Bluetooth and reading low-level system log files is a case against malware. Perhaps it’s not as bad as other permissions that allow the device to advertise to nearby Bluetooth devices (see BLUETOOTH_ADVERTISE)." }, { "code": null, "e": 10345, "s": 10232, "text": "Moreover, it’s beyond me why having “ringtones” in the app description gives you the green light to download it." }, { "code": null, "e": 10625, "s": 10345, "text": "However, I can comprehend how setting a higher SDK version (Min_SDK) can protect your device against infection. This feature aligns well with READ_EXTERNAL_STORAGE. The latter is enforced starting API level 19 and prompts the user for themselves to enable/disable the permission." }, { "code": null, "e": 10796, "s": 10625, "text": "Unfortunately, the referenced paper does not come with code or an explanation of model weights. Therefore, I’m unable to rigorously compare my findings with the authors’." }, { "code": null, "e": 11011, "s": 10796, "text": "Working with data from the Aptoide store suggests that there’s an ample amount of malware on third party stores. Therefore, Apple’s business practices could seem reasonable if they guarantee the safety of the user." }, { "code": null, "e": 11276, "s": 11011, "text": "However, data science can be leveraged to create a speedy and accurate classification system where such restrictions by Apple are not necessary. The logistic regression model is simple to set up and offers adequate performance when compared to existing literature." }, { "code": null, "e": 11490, "s": 11276, "text": "Projects like these have the potential to boost the safety of app stores and give a deeper understanding of how vulnerabilities are exploited. The methodology can be expanded to other stores and operating systems." } ]
Boundary Value Test Cases, Robust Cases and Worst Case Test Cases - GeeksforGeeks
29 May, 2020 Generate boundary Value analysis, robust and worst-case test case for the program to find the median of three numbers. Its input is a triple of positive integers (say x, y, and z) and the minimum value can be 100 and maximum can be 500. Median of three numbers is the middle number when all three numbers are sorted. Example – 10, 40, 20 In this case, the median is 20 (10, 20, 40). 1. Boundary Value Test Cases are – for x, y, z : min value = 100 close to min = 101 nominal = 300 close to max = 499 max = 500 Test cases are, 4*3 + 1 = 13 2. Robust Test Cases –Here, we go outside the legitimate boundary, it is an extension of boundary value analysis. for x, y, z : min value : 100 close to min : 101 nominal : 300 close to max : 499 max : 500 lesser than min value : 99 larger than max value : 501 Total test cases, = 6*n+1 = 6*3+1 = 19 So there will be extra 6 cases apart from the above 13 cases – 3. Worst Test Cases –If we reject “single” fault assumption theory of reliability, and consider cases where more than 1 variable has extreme values, then it is known as worst case analysis. Total no. of test cases, 5^n = 5^3 = 125 cases Mathematically, the test cases will be a cross product of 3 sets – {100, 101, 300, 499, 500} x {100, 101, 300, 499, 500} x {100, 101, 300, 499, 500} Let set A, = {100, 101, 300, 499, 500} So, the set of worst cases will be represented by, = A x A x A Software Testing Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Software Requirement Specification (SRS) Format Software Engineering | Requirements Engineering Process Software Engineering | SDLC V-Model Levels in Data Flow Diagrams (DFD) Software Testing Life Cycle (STLC) Class Diagram for Library Management System Software Engineering | Iterative Waterfall Model Software Engineering | Requirements Elicitation Software Engineering | Quality Characteristics of a good SRS Difference between Spring and Spring Boot
[ { "code": null, "e": 24291, "s": 24263, "text": "\n29 May, 2020" }, { "code": null, "e": 24528, "s": 24291, "text": "Generate boundary Value analysis, robust and worst-case test case for the program to find the median of three numbers. Its input is a triple of positive integers (say x, y, and z) and the minimum value can be 100 and maximum can be 500." }, { "code": null, "e": 24608, "s": 24528, "text": "Median of three numbers is the middle number when all three numbers are sorted." }, { "code": null, "e": 24618, "s": 24608, "text": "Example –" }, { "code": null, "e": 24629, "s": 24618, "text": "10, 40, 20" }, { "code": null, "e": 24674, "s": 24629, "text": "In this case, the median is 20 (10, 20, 40)." }, { "code": null, "e": 24709, "s": 24674, "text": "1. Boundary Value Test Cases are –" }, { "code": null, "e": 24802, "s": 24709, "text": "for x, y, z :\nmin value = 100\nclose to min = 101\nnominal = 300\nclose to max = 499\nmax = 500 " }, { "code": null, "e": 24818, "s": 24802, "text": "Test cases are," }, { "code": null, "e": 24832, "s": 24818, "text": "4*3 + 1 = 13 " }, { "code": null, "e": 24946, "s": 24832, "text": "2. Robust Test Cases –Here, we go outside the legitimate boundary, it is an extension of boundary value analysis." }, { "code": null, "e": 25103, "s": 24946, "text": "for x, y, z :\nmin value : 100 \nclose to min : 101 \nnominal : 300 \nclose to max : 499 \nmax : 500 \nlesser than min value : 99 \nlarger than max value : 501 " }, { "code": null, "e": 25121, "s": 25103, "text": "Total test cases," }, { "code": null, "e": 25143, "s": 25121, "text": "= 6*n+1 = 6*3+1 = 19 " }, { "code": null, "e": 25206, "s": 25143, "text": "So there will be extra 6 cases apart from the above 13 cases –" }, { "code": null, "e": 25396, "s": 25206, "text": "3. Worst Test Cases –If we reject “single” fault assumption theory of reliability, and consider cases where more than 1 variable has extreme values, then it is known as worst case analysis." }, { "code": null, "e": 25421, "s": 25396, "text": "Total no. of test cases," }, { "code": null, "e": 25444, "s": 25421, "text": "5^n = 5^3 = 125 cases " }, { "code": null, "e": 25511, "s": 25444, "text": "Mathematically, the test cases will be a cross product of 3 sets –" }, { "code": null, "e": 25597, "s": 25511, "text": " {100, 101, 300, 499, 500} \nx {100, 101, 300, 499, 500} \nx {100, 101, 300, 499, 500}" }, { "code": null, "e": 25608, "s": 25597, "text": "Let set A," }, { "code": null, "e": 25636, "s": 25608, "text": "= {100, 101, 300, 499, 500}" }, { "code": null, "e": 25687, "s": 25636, "text": "So, the set of worst cases will be represented by," }, { "code": null, "e": 25700, "s": 25687, "text": "= A x A x A " }, { "code": null, "e": 25717, "s": 25700, "text": "Software Testing" }, { "code": null, "e": 25738, "s": 25717, "text": "Software Engineering" }, { "code": null, "e": 25836, "s": 25738, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25845, "s": 25836, "text": "Comments" }, { "code": null, "e": 25858, "s": 25845, "text": "Old Comments" }, { "code": null, "e": 25906, "s": 25858, "text": "Software Requirement Specification (SRS) Format" }, { "code": null, "e": 25962, "s": 25906, "text": "Software Engineering | Requirements Engineering Process" }, { "code": null, "e": 25998, "s": 25962, "text": "Software Engineering | SDLC V-Model" }, { "code": null, "e": 26033, "s": 25998, "text": "Levels in Data Flow Diagrams (DFD)" }, { "code": null, "e": 26068, "s": 26033, "text": "Software Testing Life Cycle (STLC)" }, { "code": null, "e": 26112, "s": 26068, "text": "Class Diagram for Library Management System" }, { "code": null, "e": 26161, "s": 26112, "text": "Software Engineering | Iterative Waterfall Model" }, { "code": null, "e": 26209, "s": 26161, "text": "Software Engineering | Requirements Elicitation" }, { "code": null, "e": 26270, "s": 26209, "text": "Software Engineering | Quality Characteristics of a good SRS" } ]
Difference between Seek Time and Disk Access Time in Disk Scheduling - GeeksforGeeks
01 Apr, 2020 Seek Time:A disk is divided into many circular tracks. Seek Time is defined as the time required by the read/write head to move from one track to another. Example,Consider the following diagram, the read/write head is currently on track 1. Now, on the next read/write request, we may want to read data from Track 4, in this case, our read/write head will move to track 4. The time it will take to reach track 4 is the seek time. Disk Access Time:Disk Access Time is defined as the total time required by the computer to process a read/write request and then retrieve the required data from the disk storage. Disk Access Time is divided into 2 parts: Access TimeData Transfer Time Access Time Data Transfer Time Disk Access Time = Access Time + Data Transfer Time 1. Access Time:Access Time is defined as the setup time before the actual data transfer takes place.For example, the read/write head is on track 1 but we need to read data from another track or segment. Thus, the read/write head will move to the data block location before the actual transfer can take place. This delay is called Access Time. Access Time is calculated by summation of the following: (a). Seek Time (b). Rotational Latency (c). Command Processing Time (d). Settle Time These are explained as following below in brief. (a). Seek Time –It is the time required by the read/write head to move from the current track to the requested track.Seek Time = (Number of tracks/cylinders crossed) * (Time to cross one track/cylinder) Seek Time = (Number of tracks/cylinders crossed) * (Time to cross one track/cylinder) (b). Rotational Latency –It is the time required by the read/write head to move from the current sector to the requested sector.Rotational Latency = (Angle by which disk is rotated) / (Angular Frequency) Rotational Latency = (Angle by which disk is rotated) / (Angular Frequency) (c). Command Processing Time –It is the time required by the disk device to process the command and establish a connection between the various components of the disk device to read/write data. It is due to the internal circuitry. (d). Settle Time –Settle Time is the time required by read/write head to stop vibrating. Note: Command Processing Time and Settle Time are not normally mentioned in numerical question. We take them as zero. 2. Data Transfer Time:Data Transfer Time is defined as the time required to transfer data between the system and the disk.Data Transfer Time is of two types: (a). Internal Transfer Rate (b). External Transfer Rate These are explained as following below in brief. (a). Internal Transfer Rate –It is defined as the time required to move data between the disk surface and hard disk cache. (b). External Transfer Rate –It is defined as the time required to move data between the hard disk cache and the system. Let’s see the difference between Seek Time and Disk Access Time: File & Disk Management Picked Difference Between GATE CS Operating Systems Write From Home Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Difference between Informed and Uninformed Search in AI Difference between HashMap and HashSet Difference between Internal and External fragmentation Layers of OSI Model ACID Properties in DBMS Types of Operating Systems TCP/IP Model Page Replacement Algorithms in Operating Systems
[ { "code": null, "e": 24492, "s": 24464, "text": "\n01 Apr, 2020" }, { "code": null, "e": 24647, "s": 24492, "text": "Seek Time:A disk is divided into many circular tracks. Seek Time is defined as the time required by the read/write head to move from one track to another." }, { "code": null, "e": 24732, "s": 24647, "text": "Example,Consider the following diagram, the read/write head is currently on track 1." }, { "code": null, "e": 24921, "s": 24732, "text": "Now, on the next read/write request, we may want to read data from Track 4, in this case, our read/write head will move to track 4. The time it will take to reach track 4 is the seek time." }, { "code": null, "e": 25100, "s": 24921, "text": "Disk Access Time:Disk Access Time is defined as the total time required by the computer to process a read/write request and then retrieve the required data from the disk storage." }, { "code": null, "e": 25142, "s": 25100, "text": "Disk Access Time is divided into 2 parts:" }, { "code": null, "e": 25172, "s": 25142, "text": "Access TimeData Transfer Time" }, { "code": null, "e": 25184, "s": 25172, "text": "Access Time" }, { "code": null, "e": 25203, "s": 25184, "text": "Data Transfer Time" }, { "code": null, "e": 25256, "s": 25203, "text": "Disk Access Time = Access Time + Data Transfer Time " }, { "code": null, "e": 25599, "s": 25256, "text": "1. Access Time:Access Time is defined as the setup time before the actual data transfer takes place.For example, the read/write head is on track 1 but we need to read data from another track or segment. Thus, the read/write head will move to the data block location before the actual transfer can take place. This delay is called Access Time." }, { "code": null, "e": 25656, "s": 25599, "text": "Access Time is calculated by summation of the following:" }, { "code": null, "e": 25742, "s": 25656, "text": "(a). Seek Time\n(b). Rotational Latency\n(c). Command Processing Time\n(d). Settle Time " }, { "code": null, "e": 25791, "s": 25742, "text": "These are explained as following below in brief." }, { "code": null, "e": 25996, "s": 25791, "text": "(a). Seek Time –It is the time required by the read/write head to move from the current track to the requested track.Seek Time \n= (Number of tracks/cylinders crossed) * (Time to cross one track/cylinder) " }, { "code": null, "e": 26084, "s": 25996, "text": "Seek Time \n= (Number of tracks/cylinders crossed) * (Time to cross one track/cylinder) " }, { "code": null, "e": 26290, "s": 26084, "text": "(b). Rotational Latency –It is the time required by the read/write head to move from the current sector to the requested sector.Rotational Latency \n= (Angle by which disk is rotated) / (Angular Frequency) " }, { "code": null, "e": 26368, "s": 26290, "text": "Rotational Latency \n= (Angle by which disk is rotated) / (Angular Frequency) " }, { "code": null, "e": 26598, "s": 26368, "text": "(c). Command Processing Time –It is the time required by the disk device to process the command and establish a connection between the various components of the disk device to read/write data. It is due to the internal circuitry." }, { "code": null, "e": 26687, "s": 26598, "text": "(d). Settle Time –Settle Time is the time required by read/write head to stop vibrating." }, { "code": null, "e": 26805, "s": 26687, "text": "Note: Command Processing Time and Settle Time are not normally mentioned in numerical question. We take them as zero." }, { "code": null, "e": 26963, "s": 26805, "text": "2. Data Transfer Time:Data Transfer Time is defined as the time required to transfer data between the system and the disk.Data Transfer Time is of two types:" }, { "code": null, "e": 27020, "s": 26963, "text": "(a). Internal Transfer Rate\n(b). External Transfer Rate " }, { "code": null, "e": 27069, "s": 27020, "text": "These are explained as following below in brief." }, { "code": null, "e": 27192, "s": 27069, "text": "(a). Internal Transfer Rate –It is defined as the time required to move data between the disk surface and hard disk cache." }, { "code": null, "e": 27313, "s": 27192, "text": "(b). External Transfer Rate –It is defined as the time required to move data between the hard disk cache and the system." }, { "code": null, "e": 27378, "s": 27313, "text": "Let’s see the difference between Seek Time and Disk Access Time:" }, { "code": null, "e": 27401, "s": 27378, "text": "File & Disk Management" }, { "code": null, "e": 27408, "s": 27401, "text": "Picked" }, { "code": null, "e": 27427, "s": 27408, "text": "Difference Between" }, { "code": null, "e": 27435, "s": 27427, "text": "GATE CS" }, { "code": null, "e": 27453, "s": 27435, "text": "Operating Systems" }, { "code": null, "e": 27469, "s": 27453, "text": "Write From Home" }, { "code": null, "e": 27487, "s": 27469, "text": "Operating Systems" }, { "code": null, "e": 27585, "s": 27487, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27594, "s": 27585, "text": "Comments" }, { "code": null, "e": 27607, "s": 27594, "text": "Old Comments" }, { "code": null, "e": 27668, "s": 27607, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27736, "s": 27668, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 27792, "s": 27736, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 27831, "s": 27792, "text": "Difference between HashMap and HashSet" }, { "code": null, "e": 27886, "s": 27831, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 27906, "s": 27886, "text": "Layers of OSI Model" }, { "code": null, "e": 27930, "s": 27906, "text": "ACID Properties in DBMS" }, { "code": null, "e": 27957, "s": 27930, "text": "Types of Operating Systems" }, { "code": null, "e": 27970, "s": 27957, "text": "TCP/IP Model" } ]
How to Count Unique Values in Excel? - GeeksforGeeks
17 Dec, 2021 We often need to report the Unique number of customers purchased, the number of products in our stock, List of regions our business covered. In this article, we explain how to count unique values in an excel column. Sample Data: We have given sample data with two fields Customer and Products purchased. Need to create a summary report to show how many customers are in our database. Syntax: COUNTIF (range, criteria) Range – List of data Criteria – A number or text. Apply on input range Return an integer value that match the criteria Step 1: Type “Number of Customers” in cell D5 Step 2: Write the below formula in cell E5, to count the Number of unique customers. We use the Array formula to compute unique count, So make sure you have to Press Ctrl+Shift+Enter as shown in Image 1 below: =SUM(1/COUNTIF(B2:B30,B2:B30)) Your formula in cell E5 should be covered with “{}“ Curly braces as shown in Image 2 below: Image 1 Image 2 IF you are using MS office 365, you can use the below formula to compute unique count. =COUNTA(UNIQUE(B2:B30)) Syntax COUNTA(Value1, Value2,...) Value1 – a cell, excel range, array of text Return count of non-empty cells UNIQUE(array, by_col, exactly_once) Array - list of data value to return unique By_col – Boolean value [True - return unique columns / False – return unique rows] Exactly_once – Boolean value [return only distinct values] Excel-functions Picked Excel Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Use Solver in Excel? How to Find the Last Used Row and Column in Excel VBA? How to Get Length of Array in Excel VBA? Using CHOOSE Function along with VLOOKUP in Excel Macros in Excel How to Extract the Last Word From a Cell in Excel? Introduction to Excel Spreadsheet How to Show Percentages in Stacked Column Chart in Excel? How to Remove Duplicates From Array Using VBA in Excel? How to Sum Values Based on Criteria in Another Column in Excel?
[ { "code": null, "e": 26289, "s": 26261, "text": "\n17 Dec, 2021" }, { "code": null, "e": 26432, "s": 26289, "text": "We often need to report the Unique number of customers purchased, the number of products in our stock, List of regions our business covered. " }, { "code": null, "e": 26507, "s": 26432, "text": "In this article, we explain how to count unique values in an excel column." }, { "code": null, "e": 26520, "s": 26507, "text": "Sample Data:" }, { "code": null, "e": 26676, "s": 26520, "text": "We have given sample data with two fields Customer and Products purchased. Need to create a summary report to show how many customers are in our database." }, { "code": null, "e": 26684, "s": 26676, "text": "Syntax:" }, { "code": null, "e": 26835, "s": 26684, "text": "COUNTIF (range, criteria)\n\nRange – List of data\n\nCriteria – A number or text. Apply on input range\n\nReturn an integer value that match the criteria " }, { "code": null, "e": 26881, "s": 26835, "text": "Step 1: Type “Number of Customers” in cell D5" }, { "code": null, "e": 27092, "s": 26881, "text": "Step 2: Write the below formula in cell E5, to count the Number of unique customers. We use the Array formula to compute unique count, So make sure you have to Press Ctrl+Shift+Enter as shown in Image 1 below:" }, { "code": null, "e": 27123, "s": 27092, "text": "=SUM(1/COUNTIF(B2:B30,B2:B30))" }, { "code": null, "e": 27216, "s": 27123, "text": "Your formula in cell E5 should be covered with “{}“ Curly braces as shown in Image 2 below:" }, { "code": null, "e": 27224, "s": 27216, "text": "Image 1" }, { "code": null, "e": 27232, "s": 27224, "text": "Image 2" }, { "code": null, "e": 27319, "s": 27232, "text": "IF you are using MS office 365, you can use the below formula to compute unique count." }, { "code": null, "e": 27343, "s": 27319, "text": "=COUNTA(UNIQUE(B2:B30))" }, { "code": null, "e": 27350, "s": 27343, "text": "Syntax" }, { "code": null, "e": 27455, "s": 27350, "text": "COUNTA(Value1, Value2,...)\n\nValue1 – a cell, excel range, array of text\n\nReturn count of non-empty cells" }, { "code": null, "e": 27680, "s": 27455, "text": "UNIQUE(array, by_col, exactly_once)\n\nArray - list of data value to return unique\n\nBy_col – Boolean value [True - return unique columns / False – return unique rows]\n\nExactly_once – Boolean value [return only distinct values]" }, { "code": null, "e": 27696, "s": 27680, "text": "Excel-functions" }, { "code": null, "e": 27703, "s": 27696, "text": "Picked" }, { "code": null, "e": 27709, "s": 27703, "text": "Excel" }, { "code": null, "e": 27807, "s": 27709, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27835, "s": 27807, "text": "How to Use Solver in Excel?" }, { "code": null, "e": 27890, "s": 27835, "text": "How to Find the Last Used Row and Column in Excel VBA?" }, { "code": null, "e": 27931, "s": 27890, "text": "How to Get Length of Array in Excel VBA?" }, { "code": null, "e": 27981, "s": 27931, "text": "Using CHOOSE Function along with VLOOKUP in Excel" }, { "code": null, "e": 27997, "s": 27981, "text": "Macros in Excel" }, { "code": null, "e": 28048, "s": 27997, "text": "How to Extract the Last Word From a Cell in Excel?" }, { "code": null, "e": 28082, "s": 28048, "text": "Introduction to Excel Spreadsheet" }, { "code": null, "e": 28140, "s": 28082, "text": "How to Show Percentages in Stacked Column Chart in Excel?" }, { "code": null, "e": 28196, "s": 28140, "text": "How to Remove Duplicates From Array Using VBA in Excel?" } ]
Number of balanced bracket expressions that can be formed from a string - GeeksforGeeks
25 May, 2021 Given a string str comprising of characters (, ), {, }, [, ] and ?. The task is to find the total number of balanced bracket expressions formed when ? can be replaced with any of the bracket characters. Here are some examples of balanced bracket expressions: {([])}, {()}[{}] etc. And, unbalanced bracket expressions: {[}, {()], {()}[) etc. Examples: Input: str = “(?([?)]?}?” Output: 3 ({([()]]}), ()([()]{}) and ([([])]{}) are the only possible balanced expressions that can be generated from the input. Input: str = “???[???????]????” Output: 392202 Approach: If n is odd, then the result will always be 0 as there will be no balanced expression possible.If n id even, then create a dp array for storing precomputations.Call a recursive function with the following operations: If starting index > ending index then you return 1.If dp[start][end] is already computed, return dp[start][end].Run a loop from start + 1 till end incrementing by 2 to find its pair bracket or ‘?’.Then divide the string into two halves to check to proper subsequent bracket expressions from start + 1 till i – 1 and i + 1 till the end by calling the recursive function.If st[start] = ’?’ and st[i] = ’?’ then a total of 3 combinations of bracket pairs can be formed, thus multiplying the result of the recursive function by 3.Return dp[start][end] If n is odd, then the result will always be 0 as there will be no balanced expression possible. If n id even, then create a dp array for storing precomputations. Call a recursive function with the following operations: If starting index > ending index then you return 1.If dp[start][end] is already computed, return dp[start][end].Run a loop from start + 1 till end incrementing by 2 to find its pair bracket or ‘?’.Then divide the string into two halves to check to proper subsequent bracket expressions from start + 1 till i – 1 and i + 1 till the end by calling the recursive function.If st[start] = ’?’ and st[i] = ’?’ then a total of 3 combinations of bracket pairs can be formed, thus multiplying the result of the recursive function by 3. If starting index > ending index then you return 1. If dp[start][end] is already computed, return dp[start][end]. Run a loop from start + 1 till end incrementing by 2 to find its pair bracket or ‘?’. Then divide the string into two halves to check to proper subsequent bracket expressions from start + 1 till i – 1 and i + 1 till the end by calling the recursive function. If st[start] = ’?’ and st[i] = ’?’ then a total of 3 combinations of bracket pairs can be formed, thus multiplying the result of the recursive function by 3. Return dp[start][end] Below is the implementation of the above approach: C++ Java Python 3 C# Javascript // C++ program to find number of balanced// bracket expressions possible#include <bits/stdc++.h>using namespace std;typedef long long int lli; // Max string lengthconst int MAX = 300; // Function to check whether index start// and end can form a bracket pair or notint checkFunc(int i, int j, string st){ // Check for brackets ( ) if (st[i] == '(' && st[j] == ')') return 1; if (st[i] == '(' && st[j] == '?') return 1; if (st[i] == '?' && st[j] == ')') return 1; // Check for brackets [ ] if (st[i] == '[' && st[j] == ']') return 1; if (st[i] == '[' && st[j] == '?') return 1; if (st[i] == '?' && st[j] == ']') return 1; // Check for brackets { } if (st[i] == '{' && st[j] == '}') return 1; if (st[i] == '{' && st[j] == '?') return 1; if (st[i] == '?' && st[j] == '}') return 1; return 0;} // Function to find number of// proper bracket expressionsint countRec(int start, int end, int dp[][MAX], string st){ int sum = 0; // If starting index is greater // than ending index if (start > end) return 1; // If dp[start][end] has already been computed if (dp[start][end] != -1) return dp[start][end]; lli i, r = 0; // Search for the bracket in from next index for (i = start + 1; i <= end; i += 2) { // If bracket pair is formed, // add number of combination if (checkFunc(start, i, st)) { sum = sum + countRec(start + 1, i - 1, dp, st) * countRec(i + 1, end, dp, st); } // If ? comes then all three bracket // expressions are possible else if (st[start] == '?' && st[i] == '?') { sum = sum + countRec(start + 1, i - 1, dp, st) * countRec(i + 1, end, dp, st) * 3; } } // Return answer return dp[start][end] = sum;} int countWays(string st){ int n = st.length(); // If n is odd, string cannot be balanced if (n % 2 == 1) return 0; int dp[MAX][MAX]; memset(dp, -1, sizeof(dp)); return countRec(0, n - 1, dp, st);} // Driving functionint main(){ string st = "(?([?)]?}?"; cout << countWays(st); return 0;} // Java program to find number of balanced// bracket expressions possible class GFG { // Max string length static int MAX = 300; // Function to check whether index start // and end can form a bracket pair or not static int checkFunc(int i, int j, String st) { // Check for brackets ( ) if (st.charAt(i) == '(' && st.charAt(j) == ')') return 1; if (st.charAt(i) == '(' && st.charAt(j) == '?') return 1; if (st.charAt(i) == '?' && st.charAt(j) == ')') return 1; // Check for brackets [ ] if (st.charAt(i) == '[' && st.charAt(j) == ']') return 1; if (st.charAt(i) == '[' && st.charAt(j) == '?') return 1; if (st.charAt(i) == '?' && st.charAt(j) == ']') return 1; // Check for brackets { } if (st.charAt(i) == '{' && st.charAt(j) == '}') return 1; if (st.charAt(i) == '{' && st.charAt(j) == '?') return 1; if (st.charAt(i) == '?' && st.charAt(j) == '}') return 1; return 0; } // Function to find number of // proper bracket expressions static int countRec(int start, int end, int dp[][], String st) { int sum = 0; // If starting index is greater // than ending index if (start > end) return 1; // If dp[start][end] has already been computed if (dp[start][end] != -1) return dp[start][end]; int i, r = 0; // Search for the bracket in from next index for (i = start + 1; i <= end; i += 2) { // If bracket pair is formed, // add number of combination if (checkFunc(start, i, st) == 1) { sum = sum + countRec(start + 1, i - 1, dp, st) * countRec(i + 1, end, dp, st); } // If ? comes then all three bracket // expressions are possible else if (st.charAt(start) == '?' && st.charAt(i) == '?') { sum = sum + countRec(start + 1, i - 1, dp, st) * countRec(i + 1, end, dp, st) * 3; } } // Return answer return dp[start][end] = sum; } static int countWays(String st) { int n = st.length(); // If n is odd, string cannot be balanced if (n % 2 == 1) return 0; int dp[][] = new int[MAX][MAX]; for (int i = 0; i < MAX; i++) for (int j = 0; j < MAX; j++) dp[i][j] = -1; return countRec(0, n - 1, dp, st); } // Driving function public static void main(String[] args) { String st = "(?([?)]?}?"; System.out.println(countWays(st)); }} // This code is contributed by ihritik # Python 3 program to find number of balanced# bracket expressions possible # Max string lengthMAX = 300 # Function to check whether index start# and end can form a bracket pair or notdef checkFunc(i, j, st): # Check for brackets ( ) if (st[i] == '(' and st[j] == ')'): return 1 if (st[i] == '(' and st[j] == '?'): return 1 if (st[i] == '?' and st[j] == ')'): return 1 # Check for brackets [ ] if (st[i] == '[' and st[j] == ']'): return 1 if (st[i] == '[' and st[j] == '?'): return 1 if (st[i] == '?' and st[j] == ']'): return 1 # Check for brackets { } if (st[i] == '{' and st[j] == '}'): return 1 if (st[i] == '{' and st[j] == '?'): return 1 if (st[i] == '?' and st[j] == '}'): return 1 return 0 # Function to find number of# proper bracket expressionsdef countRec(start, end, dp, st): sum = 0 # If starting index is greater # than ending index if (start > end): return 1 # If dp[start][end] has already # been computed if (dp[start][end] != -1): return dp[start][end] r = 0 # Search for the bracket in from next index for i in range(start + 1, end + 1, 2): # If bracket pair is formed, # add number of combination if (checkFunc(start, i, st)): sum = (sum + countRec(start + 1, i - 1, dp, st) * countRec(i + 1, end, dp, st)) # If ? comes then all three bracket # expressions are possible elif (st[start] == '?' and st[i] == '?'): sum = (sum + countRec(start + 1, i - 1, dp, st) * countRec(i + 1, end, dp, st) * 3) # Return answer dp[start][end] = sum return dp[start][end] def countWays( st): n = len(st) # If n is odd, string cannot be balanced if (n % 2 == 1): return 0 dp = [[-1 for i in range(MAX)] for i in range(MAX)] return countRec(0, n - 1, dp, st) # Driver Codeif __name__ =="__main__": st = "(?([?)]?}?" print(countWays(st)) # This code is contributed by ita_c // C# program to find number of balanced// bracket expressions possible using System;class GFG { // Max string length static int MAX = 300; // Function to check whether index start // and end can form a bracket pair or not static int checkFunc(int i, int j, string st) { // Check for brackets ( ) if (st[i] == '(' && st[j] == ')') return 1; if (st[i] == '(' && st[j] == '?') return 1; if (st[i] == '?' && st[j] == ')') return 1; // Check for brackets [ ] if (st[i] == '[' && st[j] == ']') return 1; if (st[i] == '[' && st[j] == '?') return 1; if (st[i] == '?' && st[j] == ']') return 1; // Check for brackets { } if (st[i] == '{' && st[j] == '}') return 1; if (st[i] == '{' && st[j] == '?') return 1; if (st[i] == '?' && st[j] == '}') return 1; return 0; } // Function to find number of // proper bracket expressions static int countRec(int start, int end, int[, ] dp, string st) { int sum = 0; // If starting index is greater // than ending index if (start > end) return 1; // If dp[start, end] has already been computed if (dp[start, end] != -1) return dp[start, end]; int i; // Search for the bracket in from next index for (i = start + 1; i <= end; i += 2) { // If bracket pair is formed, // add number of combination if (checkFunc(start, i, st) == 1) { sum = sum + countRec(start + 1, i - 1, dp, st) * countRec(i + 1, end, dp, st); } // If ? comes then all three bracket // expressions are possible else if (st[start] == '?' && st[i] == '?') { sum = sum + countRec(start + 1, i - 1, dp, st) * countRec(i + 1, end, dp, st) * 3; } } // Return answer return dp[start, end] = sum; } static int countWays(string st) { int n = st.Length; // If n is odd, string cannot be balanced if (n % 2 == 1) return 0; int[, ] dp = new int[MAX, MAX]; for (int i = 0; i < MAX; i++) for (int j = 0; j < MAX; j++) dp[i, j] = -1; return countRec(0, n - 1, dp, st); } // Driving function public static void Main() { string st = "(?([?)]?}?"; Console.WriteLine(countWays(st)); }} // This code is contributed by ihritik <script>// Javascript program to find number of balanced// bracket expressions possible // Max string length let MAX = 300; // Function to check whether index start // and end can form a bracket pair or not function checkFunc(i,j,st) { // Check for brackets ( ) if (st[i] == '(' && st[j] == ')') return 1; if (st[i] == '(' && st[j] == '?') return 1; if (st[i] == '?' && st[j] == ')') return 1; // Check for brackets [ ] if (st[i] == '[' && st[j] == ']') return 1; if (st[i] == '[' && st[j] == '?') return 1; if (st[i] == '?' && st[j] == ']') return 1; // Check for brackets { } if (st[i] == '{' && st[j] == '}') return 1; if (st[i] == '{' && st[j] == '?') return 1; if (st[i] == '?' && st[j] == '}') return 1; return 0; } // Function to find number of // proper bracket expressions function countRec(start,end,dp,st) { let sum = 0; // If starting index is greater // than ending index if (start > end) return 1; // If dp[start][end] has already been computed if (dp[start][end] != -1) return dp[start][end]; let i, r = 0; // Search for the bracket in from next index for (i = start + 1; i <= end; i += 2) { // If bracket pair is formed, // add number of combination if (checkFunc(start, i, st) == 1) { sum = sum + countRec(start + 1, i - 1, dp, st) * countRec(i + 1, end, dp, st); } // If ? comes then all three bracket // expressions are possible else if (st[start] == '?' && st[i] == '?') { sum = sum + countRec(start + 1, i - 1, dp, st) * countRec(i + 1, end, dp, st) * 3; } } // Return answer return dp[start][end] = sum; } function countWays(st) { let n = st.length; // If n is odd, string cannot be balanced if (n % 2 == 1) return 0; let dp = new Array(MAX); for (let i = 0; i < MAX; i++) { dp[i]=new Array(MAX); for (let j = 0; j < MAX; j++) dp[i][j] = -1; } return countRec(0, n - 1, dp, st); } // Driving function let st = "(?([?)]?}?"; document.write(countWays(st)); // This code is contributed by rag2127</script> 3 ukasp ihritik rag2127 Parentheses-Problems Technical Scripter 2018 Algorithms Dynamic Programming Recursion Dynamic Programming Recursion Algorithms 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 Introduction to Algorithms How to Start Learning DSA? Recursive Practice Problems with Solutions 0-1 Knapsack Problem | DP-10 Largest Sum Contiguous Subarray Longest Common Subsequence | DP-4 Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16
[ { "code": null, "e": 26045, "s": 26017, "text": "\n25 May, 2021" }, { "code": null, "e": 26386, "s": 26045, "text": "Given a string str comprising of characters (, ), {, }, [, ] and ?. The task is to find the total number of balanced bracket expressions formed when ? can be replaced with any of the bracket characters. Here are some examples of balanced bracket expressions: {([])}, {()}[{}] etc. And, unbalanced bracket expressions: {[}, {()], {()}[) etc." }, { "code": null, "e": 26397, "s": 26386, "text": "Examples: " }, { "code": null, "e": 26552, "s": 26397, "text": "Input: str = “(?([?)]?}?” Output: 3 ({([()]]}), ()([()]{}) and ([([])]{}) are the only possible balanced expressions that can be generated from the input." }, { "code": null, "e": 26600, "s": 26552, "text": "Input: str = “???[???????]????” Output: 392202 " }, { "code": null, "e": 26611, "s": 26600, "text": "Approach: " }, { "code": null, "e": 27376, "s": 26611, "text": "If n is odd, then the result will always be 0 as there will be no balanced expression possible.If n id even, then create a dp array for storing precomputations.Call a recursive function with the following operations: If starting index > ending index then you return 1.If dp[start][end] is already computed, return dp[start][end].Run a loop from start + 1 till end incrementing by 2 to find its pair bracket or ‘?’.Then divide the string into two halves to check to proper subsequent bracket expressions from start + 1 till i – 1 and i + 1 till the end by calling the recursive function.If st[start] = ’?’ and st[i] = ’?’ then a total of 3 combinations of bracket pairs can be formed, thus multiplying the result of the recursive function by 3.Return dp[start][end]" }, { "code": null, "e": 27472, "s": 27376, "text": "If n is odd, then the result will always be 0 as there will be no balanced expression possible." }, { "code": null, "e": 27538, "s": 27472, "text": "If n id even, then create a dp array for storing precomputations." }, { "code": null, "e": 28122, "s": 27538, "text": "Call a recursive function with the following operations: If starting index > ending index then you return 1.If dp[start][end] is already computed, return dp[start][end].Run a loop from start + 1 till end incrementing by 2 to find its pair bracket or ‘?’.Then divide the string into two halves to check to proper subsequent bracket expressions from start + 1 till i – 1 and i + 1 till the end by calling the recursive function.If st[start] = ’?’ and st[i] = ’?’ then a total of 3 combinations of bracket pairs can be formed, thus multiplying the result of the recursive function by 3." }, { "code": null, "e": 28174, "s": 28122, "text": "If starting index > ending index then you return 1." }, { "code": null, "e": 28236, "s": 28174, "text": "If dp[start][end] is already computed, return dp[start][end]." }, { "code": null, "e": 28322, "s": 28236, "text": "Run a loop from start + 1 till end incrementing by 2 to find its pair bracket or ‘?’." }, { "code": null, "e": 28495, "s": 28322, "text": "Then divide the string into two halves to check to proper subsequent bracket expressions from start + 1 till i – 1 and i + 1 till the end by calling the recursive function." }, { "code": null, "e": 28653, "s": 28495, "text": "If st[start] = ’?’ and st[i] = ’?’ then a total of 3 combinations of bracket pairs can be formed, thus multiplying the result of the recursive function by 3." }, { "code": null, "e": 28675, "s": 28653, "text": "Return dp[start][end]" }, { "code": null, "e": 28727, "s": 28675, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 28731, "s": 28727, "text": "C++" }, { "code": null, "e": 28736, "s": 28731, "text": "Java" }, { "code": null, "e": 28745, "s": 28736, "text": "Python 3" }, { "code": null, "e": 28748, "s": 28745, "text": "C#" }, { "code": null, "e": 28759, "s": 28748, "text": "Javascript" }, { "code": "// C++ program to find number of balanced// bracket expressions possible#include <bits/stdc++.h>using namespace std;typedef long long int lli; // Max string lengthconst int MAX = 300; // Function to check whether index start// and end can form a bracket pair or notint checkFunc(int i, int j, string st){ // Check for brackets ( ) if (st[i] == '(' && st[j] == ')') return 1; if (st[i] == '(' && st[j] == '?') return 1; if (st[i] == '?' && st[j] == ')') return 1; // Check for brackets [ ] if (st[i] == '[' && st[j] == ']') return 1; if (st[i] == '[' && st[j] == '?') return 1; if (st[i] == '?' && st[j] == ']') return 1; // Check for brackets { } if (st[i] == '{' && st[j] == '}') return 1; if (st[i] == '{' && st[j] == '?') return 1; if (st[i] == '?' && st[j] == '}') return 1; return 0;} // Function to find number of// proper bracket expressionsint countRec(int start, int end, int dp[][MAX], string st){ int sum = 0; // If starting index is greater // than ending index if (start > end) return 1; // If dp[start][end] has already been computed if (dp[start][end] != -1) return dp[start][end]; lli i, r = 0; // Search for the bracket in from next index for (i = start + 1; i <= end; i += 2) { // If bracket pair is formed, // add number of combination if (checkFunc(start, i, st)) { sum = sum + countRec(start + 1, i - 1, dp, st) * countRec(i + 1, end, dp, st); } // If ? comes then all three bracket // expressions are possible else if (st[start] == '?' && st[i] == '?') { sum = sum + countRec(start + 1, i - 1, dp, st) * countRec(i + 1, end, dp, st) * 3; } } // Return answer return dp[start][end] = sum;} int countWays(string st){ int n = st.length(); // If n is odd, string cannot be balanced if (n % 2 == 1) return 0; int dp[MAX][MAX]; memset(dp, -1, sizeof(dp)); return countRec(0, n - 1, dp, st);} // Driving functionint main(){ string st = \"(?([?)]?}?\"; cout << countWays(st); return 0;}", "e": 31050, "s": 28759, "text": null }, { "code": "// Java program to find number of balanced// bracket expressions possible class GFG { // Max string length static int MAX = 300; // Function to check whether index start // and end can form a bracket pair or not static int checkFunc(int i, int j, String st) { // Check for brackets ( ) if (st.charAt(i) == '(' && st.charAt(j) == ')') return 1; if (st.charAt(i) == '(' && st.charAt(j) == '?') return 1; if (st.charAt(i) == '?' && st.charAt(j) == ')') return 1; // Check for brackets [ ] if (st.charAt(i) == '[' && st.charAt(j) == ']') return 1; if (st.charAt(i) == '[' && st.charAt(j) == '?') return 1; if (st.charAt(i) == '?' && st.charAt(j) == ']') return 1; // Check for brackets { } if (st.charAt(i) == '{' && st.charAt(j) == '}') return 1; if (st.charAt(i) == '{' && st.charAt(j) == '?') return 1; if (st.charAt(i) == '?' && st.charAt(j) == '}') return 1; return 0; } // Function to find number of // proper bracket expressions static int countRec(int start, int end, int dp[][], String st) { int sum = 0; // If starting index is greater // than ending index if (start > end) return 1; // If dp[start][end] has already been computed if (dp[start][end] != -1) return dp[start][end]; int i, r = 0; // Search for the bracket in from next index for (i = start + 1; i <= end; i += 2) { // If bracket pair is formed, // add number of combination if (checkFunc(start, i, st) == 1) { sum = sum + countRec(start + 1, i - 1, dp, st) * countRec(i + 1, end, dp, st); } // If ? comes then all three bracket // expressions are possible else if (st.charAt(start) == '?' && st.charAt(i) == '?') { sum = sum + countRec(start + 1, i - 1, dp, st) * countRec(i + 1, end, dp, st) * 3; } } // Return answer return dp[start][end] = sum; } static int countWays(String st) { int n = st.length(); // If n is odd, string cannot be balanced if (n % 2 == 1) return 0; int dp[][] = new int[MAX][MAX]; for (int i = 0; i < MAX; i++) for (int j = 0; j < MAX; j++) dp[i][j] = -1; return countRec(0, n - 1, dp, st); } // Driving function public static void main(String[] args) { String st = \"(?([?)]?}?\"; System.out.println(countWays(st)); }} // This code is contributed by ihritik", "e": 33932, "s": 31050, "text": null }, { "code": "# Python 3 program to find number of balanced# bracket expressions possible # Max string lengthMAX = 300 # Function to check whether index start# and end can form a bracket pair or notdef checkFunc(i, j, st): # Check for brackets ( ) if (st[i] == '(' and st[j] == ')'): return 1 if (st[i] == '(' and st[j] == '?'): return 1 if (st[i] == '?' and st[j] == ')'): return 1 # Check for brackets [ ] if (st[i] == '[' and st[j] == ']'): return 1 if (st[i] == '[' and st[j] == '?'): return 1 if (st[i] == '?' and st[j] == ']'): return 1 # Check for brackets { } if (st[i] == '{' and st[j] == '}'): return 1 if (st[i] == '{' and st[j] == '?'): return 1 if (st[i] == '?' and st[j] == '}'): return 1 return 0 # Function to find number of# proper bracket expressionsdef countRec(start, end, dp, st): sum = 0 # If starting index is greater # than ending index if (start > end): return 1 # If dp[start][end] has already # been computed if (dp[start][end] != -1): return dp[start][end] r = 0 # Search for the bracket in from next index for i in range(start + 1, end + 1, 2): # If bracket pair is formed, # add number of combination if (checkFunc(start, i, st)): sum = (sum + countRec(start + 1, i - 1, dp, st) * countRec(i + 1, end, dp, st)) # If ? comes then all three bracket # expressions are possible elif (st[start] == '?' and st[i] == '?'): sum = (sum + countRec(start + 1, i - 1, dp, st) * countRec(i + 1, end, dp, st) * 3) # Return answer dp[start][end] = sum return dp[start][end] def countWays( st): n = len(st) # If n is odd, string cannot be balanced if (n % 2 == 1): return 0 dp = [[-1 for i in range(MAX)] for i in range(MAX)] return countRec(0, n - 1, dp, st) # Driver Codeif __name__ ==\"__main__\": st = \"(?([?)]?}?\" print(countWays(st)) # This code is contributed by ita_c", "e": 36035, "s": 33932, "text": null }, { "code": "// C# program to find number of balanced// bracket expressions possible using System;class GFG { // Max string length static int MAX = 300; // Function to check whether index start // and end can form a bracket pair or not static int checkFunc(int i, int j, string st) { // Check for brackets ( ) if (st[i] == '(' && st[j] == ')') return 1; if (st[i] == '(' && st[j] == '?') return 1; if (st[i] == '?' && st[j] == ')') return 1; // Check for brackets [ ] if (st[i] == '[' && st[j] == ']') return 1; if (st[i] == '[' && st[j] == '?') return 1; if (st[i] == '?' && st[j] == ']') return 1; // Check for brackets { } if (st[i] == '{' && st[j] == '}') return 1; if (st[i] == '{' && st[j] == '?') return 1; if (st[i] == '?' && st[j] == '}') return 1; return 0; } // Function to find number of // proper bracket expressions static int countRec(int start, int end, int[, ] dp, string st) { int sum = 0; // If starting index is greater // than ending index if (start > end) return 1; // If dp[start, end] has already been computed if (dp[start, end] != -1) return dp[start, end]; int i; // Search for the bracket in from next index for (i = start + 1; i <= end; i += 2) { // If bracket pair is formed, // add number of combination if (checkFunc(start, i, st) == 1) { sum = sum + countRec(start + 1, i - 1, dp, st) * countRec(i + 1, end, dp, st); } // If ? comes then all three bracket // expressions are possible else if (st[start] == '?' && st[i] == '?') { sum = sum + countRec(start + 1, i - 1, dp, st) * countRec(i + 1, end, dp, st) * 3; } } // Return answer return dp[start, end] = sum; } static int countWays(string st) { int n = st.Length; // If n is odd, string cannot be balanced if (n % 2 == 1) return 0; int[, ] dp = new int[MAX, MAX]; for (int i = 0; i < MAX; i++) for (int j = 0; j < MAX; j++) dp[i, j] = -1; return countRec(0, n - 1, dp, st); } // Driving function public static void Main() { string st = \"(?([?)]?}?\"; Console.WriteLine(countWays(st)); }} // This code is contributed by ihritik", "e": 38765, "s": 36035, "text": null }, { "code": "<script>// Javascript program to find number of balanced// bracket expressions possible // Max string length let MAX = 300; // Function to check whether index start // and end can form a bracket pair or not function checkFunc(i,j,st) { // Check for brackets ( ) if (st[i] == '(' && st[j] == ')') return 1; if (st[i] == '(' && st[j] == '?') return 1; if (st[i] == '?' && st[j] == ')') return 1; // Check for brackets [ ] if (st[i] == '[' && st[j] == ']') return 1; if (st[i] == '[' && st[j] == '?') return 1; if (st[i] == '?' && st[j] == ']') return 1; // Check for brackets { } if (st[i] == '{' && st[j] == '}') return 1; if (st[i] == '{' && st[j] == '?') return 1; if (st[i] == '?' && st[j] == '}') return 1; return 0; } // Function to find number of // proper bracket expressions function countRec(start,end,dp,st) { let sum = 0; // If starting index is greater // than ending index if (start > end) return 1; // If dp[start][end] has already been computed if (dp[start][end] != -1) return dp[start][end]; let i, r = 0; // Search for the bracket in from next index for (i = start + 1; i <= end; i += 2) { // If bracket pair is formed, // add number of combination if (checkFunc(start, i, st) == 1) { sum = sum + countRec(start + 1, i - 1, dp, st) * countRec(i + 1, end, dp, st); } // If ? comes then all three bracket // expressions are possible else if (st[start] == '?' && st[i] == '?') { sum = sum + countRec(start + 1, i - 1, dp, st) * countRec(i + 1, end, dp, st) * 3; } } // Return answer return dp[start][end] = sum; } function countWays(st) { let n = st.length; // If n is odd, string cannot be balanced if (n % 2 == 1) return 0; let dp = new Array(MAX); for (let i = 0; i < MAX; i++) { dp[i]=new Array(MAX); for (let j = 0; j < MAX; j++) dp[i][j] = -1; } return countRec(0, n - 1, dp, st); } // Driving function let st = \"(?([?)]?}?\"; document.write(countWays(st)); // This code is contributed by rag2127</script>", "e": 41464, "s": 38765, "text": null }, { "code": null, "e": 41466, "s": 41464, "text": "3" }, { "code": null, "e": 41474, "s": 41468, "text": "ukasp" }, { "code": null, "e": 41482, "s": 41474, "text": "ihritik" }, { "code": null, "e": 41490, "s": 41482, "text": "rag2127" }, { "code": null, "e": 41511, "s": 41490, "text": "Parentheses-Problems" }, { "code": null, "e": 41535, "s": 41511, "text": "Technical Scripter 2018" }, { "code": null, "e": 41546, "s": 41535, "text": "Algorithms" }, { "code": null, "e": 41566, "s": 41546, "text": "Dynamic Programming" }, { "code": null, "e": 41576, "s": 41566, "text": "Recursion" }, { "code": null, "e": 41596, "s": 41576, "text": "Dynamic Programming" }, { "code": null, "e": 41606, "s": 41596, "text": "Recursion" }, { "code": null, "e": 41617, "s": 41606, "text": "Algorithms" }, { "code": null, "e": 41715, "s": 41617, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41764, "s": 41715, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 41789, "s": 41764, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 41816, "s": 41789, "text": "Introduction to Algorithms" }, { "code": null, "e": 41843, "s": 41816, "text": "How to Start Learning DSA?" }, { "code": null, "e": 41886, "s": 41843, "text": "Recursive Practice Problems with Solutions" }, { "code": null, "e": 41915, "s": 41886, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 41947, "s": 41915, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 41981, "s": 41947, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 42012, "s": 41981, "text": "Bellman–Ford Algorithm | DP-23" } ]
bokeh.plotting.figure.diamond() function in Python - GeeksforGeeks
28 Jul, 2020 Bokeh is a data visualization library in Python that provides high-performance interactive charts and plots and the output can be obtained in various mediums like notebook, HTML and server. Figure Class create a new Figure for plotting. It is a subclass of Plot that simplifies plot creation with default axes, grids, tools, etc. The diamond() function in the plotting module of the bokeh library is used to Configure and add Diamond glyphs to this Figure. Syntax: diamond(x, y, size=4, angle=0.0, *, angle_units=’rad’, fill_alpha=1.0, fill_color=’gray’, line_alpha=1.0, line_cap=’butt’, line_color=’black’, line_dash=[], line_dash_offset=0, line_join=’bevel’, line_width=1, name=None, tags=[], **kwargs) Parameters: This method accept the following parameters that are described below: x: This parameter is the x-coordinates for the center of the markers. y: This parameter is the y-coordinates for the center of the markers. size: This parameter is the size (diameter) values for the markers in screen space units. angle: This parameter is the angles to rotate the markers. fill_color: This parameter is the fill color values for the markers. line_color: This parameter is the line color values for the markers with default value of black.1. name: This parameter is the user-supplied name for this model. tags: This parameter is the user-supplied values for this model. Return: This method return the GlyphRenderer value. Below examples illustrate the bokeh.plotting.figure.diamond() function in bokeh.plotting: Example 1: Python3 # Implementation of bokeh function import numpy as np from bokeh.plotting import figure, output_file, show plot = figure(plot_width = 300, plot_height = 300) plot.diamond(x = [1, 2, 3], y = [3, 7, 5], size = 20, color ="red", alpha = 0.9) show(plot) Output: Example 2: Python3 # Implementation of bokeh function import numpy as np from bokeh.plotting import figure, output_file, show x = [1, 2, 3, 4, 5] y = [6, 7, 8, 7, 3] output_file("geeksforgeeks.html") p = figure(plot_width = 300, plot_height = 300) p.line(x, y, line_width = 2) p.diamond(x, y, fill_color ="red", line_color ="green", size = 18) show(p) Output: Python Bokeh-plotting-figure-class Python-Bokeh Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n28 Jul, 2020" }, { "code": null, "e": 25869, "s": 25537, "text": "Bokeh is a data visualization library in Python that provides high-performance interactive charts and plots and the output can be obtained in various mediums like notebook, HTML and server. Figure Class create a new Figure for plotting. It is a subclass of Plot that simplifies plot creation with default axes, grids, tools, etc. " }, { "code": null, "e": 25998, "s": 25869, "text": "The diamond() function in the plotting module of the bokeh library is used to Configure and add Diamond glyphs to this Figure. " }, { "code": null, "e": 26246, "s": 25998, "text": "Syntax: diamond(x, y, size=4, angle=0.0, *, angle_units=’rad’, fill_alpha=1.0, fill_color=’gray’, line_alpha=1.0, line_cap=’butt’, line_color=’black’, line_dash=[], line_dash_offset=0, line_join=’bevel’, line_width=1, name=None, tags=[], **kwargs)" }, { "code": null, "e": 26330, "s": 26246, "text": "Parameters: This method accept the following parameters that are described below: " }, { "code": null, "e": 26400, "s": 26330, "text": "x: This parameter is the x-coordinates for the center of the markers." }, { "code": null, "e": 26470, "s": 26400, "text": "y: This parameter is the y-coordinates for the center of the markers." }, { "code": null, "e": 26560, "s": 26470, "text": "size: This parameter is the size (diameter) values for the markers in screen space units." }, { "code": null, "e": 26619, "s": 26560, "text": "angle: This parameter is the angles to rotate the markers." }, { "code": null, "e": 26688, "s": 26619, "text": "fill_color: This parameter is the fill color values for the markers." }, { "code": null, "e": 26787, "s": 26688, "text": "line_color: This parameter is the line color values for the markers with default value of black.1." }, { "code": null, "e": 26850, "s": 26787, "text": "name: This parameter is the user-supplied name for this model." }, { "code": null, "e": 26915, "s": 26850, "text": "tags: This parameter is the user-supplied values for this model." }, { "code": null, "e": 26969, "s": 26915, "text": "Return: This method return the GlyphRenderer value. " }, { "code": null, "e": 27072, "s": 26969, "text": "Below examples illustrate the bokeh.plotting.figure.diamond() function in bokeh.plotting: Example 1: " }, { "code": null, "e": 27080, "s": 27072, "text": "Python3" }, { "code": "# Implementation of bokeh function import numpy as np from bokeh.plotting import figure, output_file, show plot = figure(plot_width = 300, plot_height = 300) plot.diamond(x = [1, 2, 3], y = [3, 7, 5], size = 20, color =\"red\", alpha = 0.9) show(plot) ", "e": 27360, "s": 27080, "text": null }, { "code": null, "e": 27370, "s": 27360, "text": "Output: " }, { "code": null, "e": 27383, "s": 27370, "text": "Example 2: " }, { "code": null, "e": 27391, "s": 27383, "text": "Python3" }, { "code": "# Implementation of bokeh function import numpy as np from bokeh.plotting import figure, output_file, show x = [1, 2, 3, 4, 5] y = [6, 7, 8, 7, 3] output_file(\"geeksforgeeks.html\") p = figure(plot_width = 300, plot_height = 300) p.line(x, y, line_width = 2) p.diamond(x, y, fill_color =\"red\", line_color =\"green\", size = 18) show(p) ", "e": 27760, "s": 27391, "text": null }, { "code": null, "e": 27770, "s": 27760, "text": "Output: " }, { "code": null, "e": 27807, "s": 27772, "text": "Python Bokeh-plotting-figure-class" }, { "code": null, "e": 27820, "s": 27807, "text": "Python-Bokeh" }, { "code": null, "e": 27827, "s": 27820, "text": "Python" }, { "code": null, "e": 27925, "s": 27827, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27957, "s": 27925, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27999, "s": 27957, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28041, "s": 27999, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28097, "s": 28041, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28124, "s": 28097, "text": "Python Classes and Objects" }, { "code": null, "e": 28163, "s": 28124, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28194, "s": 28163, "text": "Python | os.path.join() method" }, { "code": null, "e": 28216, "s": 28194, "text": "Defaultdict in Python" }, { "code": null, "e": 28245, "s": 28216, "text": "Create a directory in Python" } ]
How to get the structure of a given DataFrame in R? - GeeksforGeeks
26 Mar, 2021 In this article, we will see how to get the structure of a DataFrame in R programming. Steps for Getting Structure of DataFrame: Create dataframe. The size of each vector should be the same. Follow the syntax while creating data frames. Function Used: To get the structure of a data frame we use a built-in function called srt(). Syntax: srt( Dataframe_name ) We have to pass the data frame which is already created. If we don’t pass an already created data frame we are not getting anything. Example 1: Creating a data frame with 2 columns: R df1 = data.frame(id = c(1 ,2 , 3), name = c("karhik" , "nikhil" , "sravan"))print(df1) Output: Example 2: Creating dataframe with 3 columns. R df2 = data.frame(sid = c(1, 2, 3), sname = c("karthik" , "nikhil" , "sravan"), Branch = c("IT" , "CSE" , "IT"))print(df2) Output: Example 3: Creating dataframe with 4 columns. R df3 = data.frame(eid = c(1, 2, 3) , ename = c("krishna" , "nikhil" , "manoj"), salary = c(50,000 , 60,000 , 70,000), Designation = c("senior manager" , "HR" , "Manager"))print(df3) Output: Example 1: Structure of df1 R df1 = data.frame(id = c(1 , 2, 3), name = c("karhik" , "nikhil" , "sravan"))srt(df1) Output: Example 2: Structure of df2 R df2 = data.frame(sid = c(1, 2, 3), sname = c("karthik" , "nikhil" , "sravan"), Branch = c("IT" , "CSE" , "IT"))str(df2) Output: Example 3: Structure of df3 R df3 = data.frame(eid = c(1, 2, 3) , ename = c("krishna" , "nikhil" , "manoj"), salary = c(50000 , 60000 , 70000), Designation = c("senior manager" , "HR" , "Manager"))str(df3) Output: Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Convert Matrix to Dataframe in R
[ { "code": null, "e": 26511, "s": 26483, "text": "\n26 Mar, 2021" }, { "code": null, "e": 26598, "s": 26511, "text": "In this article, we will see how to get the structure of a DataFrame in R programming." }, { "code": null, "e": 26640, "s": 26598, "text": "Steps for Getting Structure of DataFrame:" }, { "code": null, "e": 26658, "s": 26640, "text": "Create dataframe." }, { "code": null, "e": 26702, "s": 26658, "text": "The size of each vector should be the same." }, { "code": null, "e": 26748, "s": 26702, "text": "Follow the syntax while creating data frames." }, { "code": null, "e": 26763, "s": 26748, "text": "Function Used:" }, { "code": null, "e": 26841, "s": 26763, "text": "To get the structure of a data frame we use a built-in function called srt()." }, { "code": null, "e": 26871, "s": 26841, "text": "Syntax: srt( Dataframe_name )" }, { "code": null, "e": 26928, "s": 26871, "text": "We have to pass the data frame which is already created." }, { "code": null, "e": 27004, "s": 26928, "text": "If we don’t pass an already created data frame we are not getting anything." }, { "code": null, "e": 27053, "s": 27004, "text": "Example 1: Creating a data frame with 2 columns:" }, { "code": null, "e": 27055, "s": 27053, "text": "R" }, { "code": "df1 = data.frame(id = c(1 ,2 , 3), name = c(\"karhik\" , \"nikhil\" , \"sravan\"))print(df1)", "e": 27228, "s": 27055, "text": null }, { "code": null, "e": 27236, "s": 27228, "text": "Output:" }, { "code": null, "e": 27282, "s": 27236, "text": "Example 2: Creating dataframe with 3 columns." }, { "code": null, "e": 27284, "s": 27282, "text": "R" }, { "code": "df2 = data.frame(sid = c(1, 2, 3), sname = c(\"karthik\" , \"nikhil\" , \"sravan\"), Branch = c(\"IT\" , \"CSE\" , \"IT\"))print(df2)", "e": 27438, "s": 27284, "text": null }, { "code": null, "e": 27446, "s": 27438, "text": "Output:" }, { "code": null, "e": 27492, "s": 27446, "text": "Example 3: Creating dataframe with 4 columns." }, { "code": null, "e": 27494, "s": 27492, "text": "R" }, { "code": "df3 = data.frame(eid = c(1, 2, 3) , ename = c(\"krishna\" , \"nikhil\" , \"manoj\"), salary = c(50,000 , 60,000 , 70,000), Designation = c(\"senior manager\" , \"HR\" , \"Manager\"))print(df3)", "e": 27724, "s": 27494, "text": null }, { "code": null, "e": 27732, "s": 27724, "text": "Output:" }, { "code": null, "e": 27760, "s": 27732, "text": "Example 1: Structure of df1" }, { "code": null, "e": 27762, "s": 27760, "text": "R" }, { "code": "df1 = data.frame(id = c(1 , 2, 3), name = c(\"karhik\" , \"nikhil\" , \"sravan\"))srt(df1)", "e": 27864, "s": 27762, "text": null }, { "code": null, "e": 27872, "s": 27864, "text": "Output:" }, { "code": null, "e": 27900, "s": 27872, "text": "Example 2: Structure of df2" }, { "code": null, "e": 27902, "s": 27900, "text": "R" }, { "code": "df2 = data.frame(sid = c(1, 2, 3), sname = c(\"karthik\" , \"nikhil\" , \"sravan\"), Branch = c(\"IT\" , \"CSE\" , \"IT\"))str(df2)", "e": 28054, "s": 27902, "text": null }, { "code": null, "e": 28062, "s": 28054, "text": "Output:" }, { "code": null, "e": 28090, "s": 28062, "text": "Example 3: Structure of df3" }, { "code": null, "e": 28092, "s": 28090, "text": "R" }, { "code": "df3 = data.frame(eid = c(1, 2, 3) , ename = c(\"krishna\" , \"nikhil\" , \"manoj\"), salary = c(50000 , 60000 , 70000), Designation = c(\"senior manager\" , \"HR\" , \"Manager\"))str(df3)", "e": 28317, "s": 28092, "text": null }, { "code": null, "e": 28325, "s": 28317, "text": "Output:" }, { "code": null, "e": 28332, "s": 28325, "text": "Picked" }, { "code": null, "e": 28353, "s": 28332, "text": "R DataFrame-Programs" }, { "code": null, "e": 28365, "s": 28353, "text": "R-DataFrame" }, { "code": null, "e": 28376, "s": 28365, "text": "R Language" }, { "code": null, "e": 28387, "s": 28376, "text": "R Programs" }, { "code": null, "e": 28485, "s": 28387, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28537, "s": 28485, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28572, "s": 28537, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28610, "s": 28572, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 28668, "s": 28610, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28711, "s": 28668, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 28769, "s": 28711, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28812, "s": 28769, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 28861, "s": 28812, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28911, "s": 28861, "text": "How to filter R dataframe by multiple conditions?" } ]
Maximal Disjoint Intervals - GeeksforGeeks
30 Aug, 2021 Given a set of N intervals, the task is to find the maximal set of mutually disjoint intervals. Two intervals [i, j] & [k, l] are said to be disjoint if they do not have any point in common. Examples: Input: intervals[][] = {{1, 4}, {2, 3}, {4, 6}, {8, 9}} Output: [2, 3] [4, 6] [8, 9] Intervals sorted w.r.t. end points = {{2, 3}, {1, 4}, {4, 6}, {8, 9}} Intervals [2, 3] and [1, 4] overlap. We must include [2, 3] because if [1, 4] is included then we cannot include [4, 6].Input: intervals[][] = {{1, 9}, {2, 3}, {5, 7}} Output: [2, 3] [5, 7] Approach: Sort the intervals, with respect to their end points.Now, traverse through all the intervals, if we get two overlapping intervals, then greedily choose the interval with lower end point since, choosing it will ensure that intervals further can be accommodated without any overlap.Apply the same procedure for all the intervals and print all the intervals which satisfy the above criteria. Sort the intervals, with respect to their end points. Now, traverse through all the intervals, if we get two overlapping intervals, then greedily choose the interval with lower end point since, choosing it will ensure that intervals further can be accommodated without any overlap. Apply the same procedure for all the intervals and print all the intervals which satisfy the above criteria. Below is the implementation of the above approach: C++ Java Python3 Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define ll long long int // Function to sort the vector elements// by second element of pairsbool sortbysec(const pair<int, int>& a, const pair<int, int>& b){ return (a.second < b.second);} // Function to find maximal disjoint setvoid maxDisjointIntervals(vector<pair<int, int> > list){ // Sort the list of intervals sort(list.begin(), list.end(), sortbysec); // First Interval will always be // included in set cout << "[" << list[0].first << ", " << list[0].second << "]" << endl; // End point of first interval int r1 = list[0].second; for (int i = 1; i < list.size(); i++) { int l1 = list[i].first; int r2 = list[i].second; // Check if given interval overlap with // previously included interval, if not // then include this interval and update // the end point of last added interval if (l1 > r1) { cout << "[" << l1 << ", " << r2 << "]" << endl; r1 = r2; } }} // Driver codeint main(){ int N = 4; vector<pair<int, int> > intervals = { { 1, 4 }, { 2, 3 }, { 4, 6 }, { 8, 9 } }; maxDisjointIntervals(intervals); return 0;} // Java implementation of the approachimport java.util.*;class GFG{ static class Pair implements Comparable<Pair> { int first, second; Pair(int f, int s) { first = f; second = s; } @Override // Function to sort the vector elements // by second element of Pairs public int compareTo(Pair o) { if(this.second > o.second) return 1; else if(this.second == o.second) return 0; return -1; } } // Function to find maximal disjoint setstatic void maxDisjointIntervals(Pair []list){ // Sort the list of intervals Collections.sort(Arrays.asList(list)); // First Interval will always be // included in set System.out.print("[" + list[0].first+ ", " + list[0].second+ "]" +"\n"); // End point of first interval int r1 = list[0].second; for (int i = 1; i < list.length; i++) { int l1 = list[i].first; int r2 = list[i].second; // Check if given interval overlap with // previously included interval, if not // then include this interval and update // the end point of last added interval if (l1 > r1) { System.out.print("[" + l1+ ", " + r2+ "]" +"\n"); r1 = r2; } }} // Driver codepublic static void main(String[] args){ int N = 4; Pair []intervals = { new Pair(1, 4 ), new Pair( 2, 3 ), new Pair( 4, 6 ), new Pair( 8, 9 ) }; maxDisjointIntervals(intervals);}} // This code is contributed by Princi Singh # Python3 implementation of the approach # Function to find maximal disjoint setdef maxDisjointIntervals(list_): # Lambda function to sort the list # elements by second element of pairs list_.sort(key = lambda x: x[1]) # First interval will always be # included in set print("[", list_[0][0], ", ", list_[0][1], "]") # End point of first interval r1 = list_[0][1] for i in range(1, len(list_)): l1 = list_[i][0] r2 = list_[i][1] # Check if given interval overlap with # previously included interval, if not # then include this interval and update # the end point of last added interval if l1 > r1: print("[", l1, ", ", r2, "]") r1 = r2 # Driver codeif __name__ == "__main__": N = 4 intervals = [ [ 1, 4 ], [ 2, 3 ], [ 4, 6 ], [ 8, 9 ] ] # Call the function maxDisjointIntervals(intervals) # This code is contributed by Tokir Manva <script> // Javascript implementation of the approach // Function to find maximal disjoint setfunction maxDisjointIntervals(list){ // Sort the list of intervals list.sort((a,b)=> a[1]-b[1]); // First Interval will always be // included in set document.write( "[" + list[0][0] + ", " + list[0][1] + "]" + "<br>"); // End point of first interval var r1 = list[0][1]; for (var i = 1; i < list.length; i++) { var l1 = list[i][0]; var r2 = list[i][1]; // Check if given interval overlap with // previously included interval, if not // then include this interval and update // the end point of last added interval if (l1 > r1) { document.write( "[" + l1 + ", " + r2 + "]" + "<br>"); r1 = r2; } }} // Driver codevar N = 4;var intervals = [ [ 1, 4 ], [ 2, 3 ], [ 4, 6 ], [ 8, 9 ] ];maxDisjointIntervals(intervals); </script> [2, 3] [4, 6] [8, 9] draculemihawk princi singh noob2000 simmytarika5 Greedy Sorting Greedy Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Huffman Coding | Greedy Algo-3 Coin Change | DP-7 Activity Selection Problem | Greedy Algo-1 Fractional Knapsack Problem Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)
[ { "code": null, "e": 26157, "s": 26129, "text": "\n30 Aug, 2021" }, { "code": null, "e": 26349, "s": 26157, "text": "Given a set of N intervals, the task is to find the maximal set of mutually disjoint intervals. Two intervals [i, j] & [k, l] are said to be disjoint if they do not have any point in common. " }, { "code": null, "e": 26361, "s": 26349, "text": "Examples: " }, { "code": null, "e": 26708, "s": 26361, "text": "Input: intervals[][] = {{1, 4}, {2, 3}, {4, 6}, {8, 9}} Output: [2, 3] [4, 6] [8, 9] Intervals sorted w.r.t. end points = {{2, 3}, {1, 4}, {4, 6}, {8, 9}} Intervals [2, 3] and [1, 4] overlap. We must include [2, 3] because if [1, 4] is included then we cannot include [4, 6].Input: intervals[][] = {{1, 9}, {2, 3}, {5, 7}} Output: [2, 3] [5, 7] " }, { "code": null, "e": 26720, "s": 26708, "text": "Approach: " }, { "code": null, "e": 27109, "s": 26720, "text": "Sort the intervals, with respect to their end points.Now, traverse through all the intervals, if we get two overlapping intervals, then greedily choose the interval with lower end point since, choosing it will ensure that intervals further can be accommodated without any overlap.Apply the same procedure for all the intervals and print all the intervals which satisfy the above criteria." }, { "code": null, "e": 27163, "s": 27109, "text": "Sort the intervals, with respect to their end points." }, { "code": null, "e": 27391, "s": 27163, "text": "Now, traverse through all the intervals, if we get two overlapping intervals, then greedily choose the interval with lower end point since, choosing it will ensure that intervals further can be accommodated without any overlap." }, { "code": null, "e": 27500, "s": 27391, "text": "Apply the same procedure for all the intervals and print all the intervals which satisfy the above criteria." }, { "code": null, "e": 27553, "s": 27500, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27557, "s": 27553, "text": "C++" }, { "code": null, "e": 27562, "s": 27557, "text": "Java" }, { "code": null, "e": 27570, "s": 27562, "text": "Python3" }, { "code": null, "e": 27581, "s": 27570, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define ll long long int // Function to sort the vector elements// by second element of pairsbool sortbysec(const pair<int, int>& a, const pair<int, int>& b){ return (a.second < b.second);} // Function to find maximal disjoint setvoid maxDisjointIntervals(vector<pair<int, int> > list){ // Sort the list of intervals sort(list.begin(), list.end(), sortbysec); // First Interval will always be // included in set cout << \"[\" << list[0].first << \", \" << list[0].second << \"]\" << endl; // End point of first interval int r1 = list[0].second; for (int i = 1; i < list.size(); i++) { int l1 = list[i].first; int r2 = list[i].second; // Check if given interval overlap with // previously included interval, if not // then include this interval and update // the end point of last added interval if (l1 > r1) { cout << \"[\" << l1 << \", \" << r2 << \"]\" << endl; r1 = r2; } }} // Driver codeint main(){ int N = 4; vector<pair<int, int> > intervals = { { 1, 4 }, { 2, 3 }, { 4, 6 }, { 8, 9 } }; maxDisjointIntervals(intervals); return 0;}", "e": 28976, "s": 27581, "text": null }, { "code": "// Java implementation of the approachimport java.util.*;class GFG{ static class Pair implements Comparable<Pair> { int first, second; Pair(int f, int s) { first = f; second = s; } @Override // Function to sort the vector elements // by second element of Pairs public int compareTo(Pair o) { if(this.second > o.second) return 1; else if(this.second == o.second) return 0; return -1; } } // Function to find maximal disjoint setstatic void maxDisjointIntervals(Pair []list){ // Sort the list of intervals Collections.sort(Arrays.asList(list)); // First Interval will always be // included in set System.out.print(\"[\" + list[0].first+ \", \" + list[0].second+ \"]\" +\"\\n\"); // End point of first interval int r1 = list[0].second; for (int i = 1; i < list.length; i++) { int l1 = list[i].first; int r2 = list[i].second; // Check if given interval overlap with // previously included interval, if not // then include this interval and update // the end point of last added interval if (l1 > r1) { System.out.print(\"[\" + l1+ \", \" + r2+ \"]\" +\"\\n\"); r1 = r2; } }} // Driver codepublic static void main(String[] args){ int N = 4; Pair []intervals = { new Pair(1, 4 ), new Pair( 2, 3 ), new Pair( 4, 6 ), new Pair( 8, 9 ) }; maxDisjointIntervals(intervals);}} // This code is contributed by Princi Singh", "e": 30622, "s": 28976, "text": null }, { "code": "# Python3 implementation of the approach # Function to find maximal disjoint setdef maxDisjointIntervals(list_): # Lambda function to sort the list # elements by second element of pairs list_.sort(key = lambda x: x[1]) # First interval will always be # included in set print(\"[\", list_[0][0], \", \", list_[0][1], \"]\") # End point of first interval r1 = list_[0][1] for i in range(1, len(list_)): l1 = list_[i][0] r2 = list_[i][1] # Check if given interval overlap with # previously included interval, if not # then include this interval and update # the end point of last added interval if l1 > r1: print(\"[\", l1, \", \", r2, \"]\") r1 = r2 # Driver codeif __name__ == \"__main__\": N = 4 intervals = [ [ 1, 4 ], [ 2, 3 ], [ 4, 6 ], [ 8, 9 ] ] # Call the function maxDisjointIntervals(intervals) # This code is contributed by Tokir Manva", "e": 31633, "s": 30622, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to find maximal disjoint setfunction maxDisjointIntervals(list){ // Sort the list of intervals list.sort((a,b)=> a[1]-b[1]); // First Interval will always be // included in set document.write( \"[\" + list[0][0] + \", \" + list[0][1] + \"]\" + \"<br>\"); // End point of first interval var r1 = list[0][1]; for (var i = 1; i < list.length; i++) { var l1 = list[i][0]; var r2 = list[i][1]; // Check if given interval overlap with // previously included interval, if not // then include this interval and update // the end point of last added interval if (l1 > r1) { document.write( \"[\" + l1 + \", \" + r2 + \"]\" + \"<br>\"); r1 = r2; } }} // Driver codevar N = 4;var intervals = [ [ 1, 4 ], [ 2, 3 ], [ 4, 6 ], [ 8, 9 ] ];maxDisjointIntervals(intervals); </script>", "e": 32696, "s": 31633, "text": null }, { "code": null, "e": 32717, "s": 32696, "text": "[2, 3]\n[4, 6]\n[8, 9]" }, { "code": null, "e": 32733, "s": 32719, "text": "draculemihawk" }, { "code": null, "e": 32746, "s": 32733, "text": "princi singh" }, { "code": null, "e": 32755, "s": 32746, "text": "noob2000" }, { "code": null, "e": 32768, "s": 32755, "text": "simmytarika5" }, { "code": null, "e": 32775, "s": 32768, "text": "Greedy" }, { "code": null, "e": 32783, "s": 32775, "text": "Sorting" }, { "code": null, "e": 32790, "s": 32783, "text": "Greedy" }, { "code": null, "e": 32798, "s": 32790, "text": "Sorting" }, { "code": null, "e": 32896, "s": 32798, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32927, "s": 32896, "text": "Huffman Coding | Greedy Algo-3" }, { "code": null, "e": 32946, "s": 32927, "text": "Coin Change | DP-7" }, { "code": null, "e": 32989, "s": 32946, "text": "Activity Selection Problem | Greedy Algo-1" }, { "code": null, "e": 33017, "s": 32989, "text": "Fractional Knapsack Problem" } ]
Implementation of Perceptron Algorithm for NAND Logic Gate with 2-bit Binary Input - GeeksforGeeks
08 Jul, 2020 In the field of Machine Learning, the Perceptron is a Supervised Learning Algorithm for binary classifiers. The Perceptron Model implements the following function: For a particular choice of the weight vector and bias parameter , the model predicts output for the corresponding input vector . NAND logical function truth table for 2-bit binary variables, i.e, the input vector and the corresponding output – We can observe that, Now for the corresponding weight vector of the input vector to the AND node, the associated Perceptron Function can be defined as: Later on, the output of AND node is the input to the NOT node with weight . Then the corresponding output is the final output of the NAND logic function and the associated Perceptron Function can be defined as: For the implementation, considered weight parameters are and the bias parameters are . Python Implementation: # importing Python libraryimport numpy as np # define Unit Step Functiondef unitStep(v): if v >= 0: return 1 else: return 0 # design Perceptron Modeldef perceptronModel(x, w, b): v = np.dot(w, x) + b y = unitStep(v) return y # NOT Logic Function# wNOT = -1, bNOT = 0.5def NOT_logicFunction(x): wNOT = -1 bNOT = 0.5 return perceptronModel(x, wNOT, bNOT) # AND Logic Function# w1 = 1, w2 = 1, bAND = -1.5def AND_logicFunction(x): w = np.array([1, 1]) bAND = -1.5 return perceptronModel(x, w, bAND) # NAND Logic Function# with AND and NOT # function calls in sequencedef NAND_logicFunction(x): output_AND = AND_logicFunction(x) output_NOT = NOT_logicFunction(output_AND) return output_NOT # testing the Perceptron Modeltest1 = np.array([0, 1])test2 = np.array([1, 1])test3 = np.array([0, 0])test4 = np.array([1, 0]) print("NAND({}, {}) = {}".format(0, 1, NAND_logicFunction(test1)))print("NAND({}, {}) = {}".format(1, 1, NAND_logicFunction(test2)))print("NAND({}, {}) = {}".format(0, 0, NAND_logicFunction(test3)))print("NAND({}, {}) = {}".format(1, 0, NAND_logicFunction(test4))) NAND(0, 1) = 1 NAND(1, 1) = 0 NAND(0, 0) = 1 NAND(1, 0) = 1 Here, the model predicted output () for each of the test inputs are exactly matched with the NAND logic gate conventional output () according to the truth table for 2-bit binary input.Hence, it is verified that the perceptron algorithm for NAND logic gate is correctly implemented. Akanksha_Rai Neural Network Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Reinforcement learning Decision Tree Decision Tree Introduction with example Support Vector Machine Algorithm Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 26839, "s": 26811, "text": "\n08 Jul, 2020" }, { "code": null, "e": 27003, "s": 26839, "text": "In the field of Machine Learning, the Perceptron is a Supervised Learning Algorithm for binary classifiers. The Perceptron Model implements the following function:" }, { "code": null, "e": 27139, "s": 27008, "text": "For a particular choice of the weight vector and bias parameter , the model predicts output for the corresponding input vector ." }, { "code": null, "e": 27256, "s": 27139, "text": "NAND logical function truth table for 2-bit binary variables, i.e, the input vector and the corresponding output –" }, { "code": null, "e": 27410, "s": 27256, "text": "We can observe that, Now for the corresponding weight vector of the input vector to the AND node, the associated Perceptron Function can be defined as:" }, { "code": null, "e": 27628, "s": 27415, "text": "Later on, the output of AND node is the input to the NOT node with weight . Then the corresponding output is the final output of the NAND logic function and the associated Perceptron Function can be defined as:" }, { "code": null, "e": 27721, "s": 27633, "text": "For the implementation, considered weight parameters are and the bias parameters are ." }, { "code": null, "e": 27744, "s": 27721, "text": "Python Implementation:" }, { "code": "# importing Python libraryimport numpy as np # define Unit Step Functiondef unitStep(v): if v >= 0: return 1 else: return 0 # design Perceptron Modeldef perceptronModel(x, w, b): v = np.dot(w, x) + b y = unitStep(v) return y # NOT Logic Function# wNOT = -1, bNOT = 0.5def NOT_logicFunction(x): wNOT = -1 bNOT = 0.5 return perceptronModel(x, wNOT, bNOT) # AND Logic Function# w1 = 1, w2 = 1, bAND = -1.5def AND_logicFunction(x): w = np.array([1, 1]) bAND = -1.5 return perceptronModel(x, w, bAND) # NAND Logic Function# with AND and NOT # function calls in sequencedef NAND_logicFunction(x): output_AND = AND_logicFunction(x) output_NOT = NOT_logicFunction(output_AND) return output_NOT # testing the Perceptron Modeltest1 = np.array([0, 1])test2 = np.array([1, 1])test3 = np.array([0, 0])test4 = np.array([1, 0]) print(\"NAND({}, {}) = {}\".format(0, 1, NAND_logicFunction(test1)))print(\"NAND({}, {}) = {}\".format(1, 1, NAND_logicFunction(test2)))print(\"NAND({}, {}) = {}\".format(0, 0, NAND_logicFunction(test3)))print(\"NAND({}, {}) = {}\".format(1, 0, NAND_logicFunction(test4)))", "e": 28886, "s": 27744, "text": null }, { "code": null, "e": 28947, "s": 28886, "text": "NAND(0, 1) = 1\nNAND(1, 1) = 0\nNAND(0, 0) = 1\nNAND(1, 0) = 1\n" }, { "code": null, "e": 29229, "s": 28947, "text": "Here, the model predicted output () for each of the test inputs are exactly matched with the NAND logic gate conventional output () according to the truth table for 2-bit binary input.Hence, it is verified that the perceptron algorithm for NAND logic gate is correctly implemented." }, { "code": null, "e": 29242, "s": 29229, "text": "Akanksha_Rai" }, { "code": null, "e": 29257, "s": 29242, "text": "Neural Network" }, { "code": null, "e": 29274, "s": 29257, "text": "Machine Learning" }, { "code": null, "e": 29281, "s": 29274, "text": "Python" }, { "code": null, "e": 29298, "s": 29281, "text": "Machine Learning" }, { "code": null, "e": 29396, "s": 29298, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29419, "s": 29396, "text": "ML | Linear Regression" }, { "code": null, "e": 29442, "s": 29419, "text": "Reinforcement learning" }, { "code": null, "e": 29456, "s": 29442, "text": "Decision Tree" }, { "code": null, "e": 29496, "s": 29456, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 29529, "s": 29496, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 29557, "s": 29529, "text": "Read JSON file using Python" }, { "code": null, "e": 29607, "s": 29557, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 29629, "s": 29607, "text": "Python map() function" } ]
Materialize CSS Navbars - GeeksforGeeks
10 Jul, 2020 A navigation bar is a user interface element within a webpage that contains links to other sections of the website. It is displayed as a list of horizontal links at the top of each page. It is placed before the main content of the page or below the header. The navbar is contained in an HTML5 <nav> followed by a container “div”, that holds 2 main parts of the navbar. A logo or brand link, and the navigation link. The links can be aligned left or right according to the application requirement. Following are the different ways of using Navbars. 1. Right Aligned: To right align the navbar links, right class is added to <ul> element. HTML <!DOCTYPE html><html> <head> <!--Import Google Icon Font--> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!-- Compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"> </script> <!-- Let browser know website is optimized for mobile --> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /></head> <body> <nav> <div class="nav-wrapper green"> <a href="#" class="brand-logo"> Materialize </a> <ul id="nav-mobile" class= "right hide-on-med-and-down"> <li> <a href="https://www.geeksforgeeks.org/materialize-css-tables/?ref=rp"> Table </a> </li> <li> <a href="https://www.geeksforgeeks.org/materialize-css-colors/?ref=rp"> Colors </a> </li> <li><a href="https://www.geeksforgeeks.org/materialize-css-typography/?ref=rp"> Typography </a> </li> </ul> </div> </nav> <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js"> </script></body> </html> Output: Left Aligned: To left align the navbar links, left class is added to <ul> element. HTML <!DOCTYPE html><html> <head> <!--Import Google Icon Font--> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!-- Compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css"> <script type="text/javascript" src= "https://code.jquery.com/jquery-2.1.1.min.js"> </script> <!-- Let browser know website is optimized for mobile --> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /></head> <body> <nav> <div class="nav-wrapper green"> <a href="#" class="brand-logo right">Materialize </a> <ul id="nav-mobile" class= "left hide-on-med-and-down"> <li> <a href="https://www.geeksforgeeks.org/materialize-css-tables/?ref=rp"> Table </a> </li> <li> <a href="https://www.geeksforgeeks.org/materialize-css-colors/?ref=rp"> Colors </a> </li> <li> <a href="https://www.geeksforgeeks.org/materialize-css-typography/?ref=rp"> Typography </a> </li> </ul> </div> </nav> <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js"> </script></body> </html> Output: Center Logo: To align the logo in center, center class is added to <a class=”brand-logo”>. Although the logo will center itself on medium and down screens. While using this, make sure that links do not overlap. HTML <!DOCTYPE html><html> <head> <!--Import Google Icon Font--> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!-- Compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"> </script> <!-- Let browser know website is optimized for mobile --> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /></head> <body> <nav> <div class="nav-wrapper green"> <a href="#" class="brand-logo center">Materialize </a> <ul id="nav-mobile" class= "left hide-on-med-and-down"> <li> <a href="https://www.geeksforgeeks.org/materialize-css-tables/?ref=rp"> Table </a> </li> <li><a href="https://www.geeksforgeeks.org/materialize-css-colors/?ref=rp"> Colors </a> </li> <li><a href="https://www.geeksforgeeks.org/materialize-css-typography/?ref=rp"> Typography </a> </li> </ul> </div> </nav> <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js"> </script></body> </html> Output: Active Items: It is used to denote the current active page, for this active class is added to the “li” tag. HTML <!DOCTYPE html><html> <head> <!--Import Google Icon Font--> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!-- Compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"> </script> <!-- Let browser know website is optimized for mobile --> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /></head> <body> <nav> <div class="nav-wrapper green"> <a href="#" class="brand-logo center">Materialize </a> <ul id="nav-mobile" class= "left hide-on-med-and-down"> <li> <a href="https://www.geeksforgeeks.org/materialize-css-tables/?ref=rp"> Table </a> </li> <li class="active"> <a href="https://www.geeksforgeeks.org/materialize-css-colors/?ref=rp"> Colors </a> </li> <li><a href="https://www.geeksforgeeks.org/materialize-css-typography/?ref=rp"> Typography </a> </li> </ul> </div> </nav> <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js"> </script></body> </html> Output: Navbar with Tabs: It is used to extend the component of the navbar. To use this, nav-extended class is added to the outer “nav” tag. This will allow tabs component inside the” nav-wrapper” and the “height” to be variable. HTML <!DOCTYPE html><html> <head> <!--Import Google Icon Font--> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!-- Compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"> </script> <!-- Let browser know website is optimized for mobile --> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /></head> <body> <nav class="nav-extended green"> <div class="nav-wrapper"> <div class="container"> <a href="#" class="brand-logo"> LOGO </a> <a href="#" data-activates="mobile-menu" class="button-collapse"> <i class="material-icons">menu</i> </a> <ul class="right hide-on-med-and-down"> <li><a href="#">item1</a></li> <li><a href="#">item2</a></li> <li><a href="#">item3</a></li> <li><a href="#">item4</a></li> </ul> <ul class="side-nav" id="mobile-menu"> <li><a href="#">item1</a></li> <li><a href="#">item2</a></li> <li><a href="#">item3</a></li> <li><a href="#">item4</a></li> </ul> <!-- tabs items --> <ul class="tabs tabs-transparent"> <li class="tab"><a href="#test1"> Test 1 </a></li> <li class="tab"><a class="active" href="#test2">Test 2</a></li> <li class="tab disabled"><a href= "#test3">Disabled Tab</a></li> <li class="tab"><a href="#test4"> Test 4 </a></li> </ul> </div> </div> </nav> <!-- tabs content --> <div id="test1" class="col s12">Test 1</div> <div id="test2" class="col s12">Test 2</div> <div id="test3" class="col s12">Test 3</div> <div id="test4" class="col s12">Test 4</div> <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js"> </script></body> </html> Output: Dropdown Menu: To add a navbar dropdown menu, “ul” dropdown structure is added into the page. Then, an element is added to trigger the dropdown menu. The “id” of the dropdown structure is supplied to the “data-target” attribute of the dropdown . HTML <!DOCTYPE html><html> <head> <!--Import Google Icon Font--> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!-- Compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"> </script> <!-- Let browser know website is optimized for mobile --> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /></head> <body> <nav> <div class="nav-wrapper green"> <div class="container"> <a href="#" class="brand-logo">LOGO</a> <!-- mobile menu trigger --> <a href="#" data-activates="mobile-menu" class="button-collapse"> <i class="material-icons">menu</i> </a> <!-- desktop menu content --> <ul class="right hide-on-med-and-down"> <li><a href="#">Option-1</a></li> <li><a href="#">Option-2</a></li> <!-- desktop menu dropdown trigger --> <li><a class="dropdown-button" href="#!" data-activates="dropdown1"> Dropdown <i class="material-icons right"> arrow_drop_down </i> </a></li> <li><a href="#">Option-3</a></li> <!-- desktop menu dropdown content --> <ul id='dropdown1' class= 'dropdown-content green-text'> <li><a href="#!">sub-dropdown1</a></li> <li><a href="#!">sub-dropdown2</a></li> <li><a href="#!">sub-dropdown3</a></li> <li><a href="#!">sub-dropdown4</a></li> </ul> </ul> <!-- mobile and tablet menu content --> <ul id="mobile-menu" class="side-nav"> <li> <div class="userView"> <div class="background"> <img src="http://lorempixel.com/output/abstract-q-c-640-480-10.jpg" alt=""> </div> </div> </li> <li><a href="#!">Option-1</a></li> <li><a href="#!">Option-2</a></li> <li class="no-padding"> <ul class="collapsible collapsible-accordion"> <li> <!-- Mobile and tablet menu dropdown trigger --> <a class="collapsible-header">Dropdown <i class="material-icons right"> arrow_drop_down </i> </a> <div class="collapsible-body"> <!-- Mobile and tablet dropdown content --> <ul> <li><a href="#!">sub-dropdown1</a></li> <li><a href="#!">sub-dropdown2</a></li> <li><a href="#!">sub-dropdown3</a></li> <li><a href="#!">sub-dropdown4</a></li> </ul> </div> </li> </ul> </li> <li><a href="#!">Option-3</a></li> </ul> </div> </div> </nav> <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js"> </script></body> </html> Output: Fixed Navbar: To make the navbar fixed, an outer wrapping “div” with the navbar-fixed class is added. This will give offset to all the other content while making the navbar fixed. HTML <!DOCTYPE html><html> <head> <!--Import Google Icon Font--> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!-- Compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"> </script> <!-- Let browser know website is optimized for mobile --> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /></head> <body> <div class="navbar-fixed "> <nav> <div class="nav-wrapper green"> <a href="#" class="brand-logo">LOGO</a> <a href="#" data-activates= "mobile-menu" class="button-collapse"> <i class="material-icons">menu</i></a> <ul class="right hide-on-med-and-down"> <li><a href="#">item1</a></li> <li><a href="#">item2</a></li> <li><a href="#">item3</a></li> <li><a href="#">item4</a></li> </ul> <ul class="side-nav" id="mobile-menu"> <li><a href="#">item1</a></li> <li><a href="#">item2</a></li> <li><a href="#">item3</a></li> <li><a href="#">item4</a></li> </ul> </div> </nav> </div> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js"> </script></body> </html> Output: Icon Links: Icons can be added into links inside the navbar. For “icon” as links, there is no need to add additional class just use the i tag. HTML <!DOCTYPE html><html> <head> <!--Import Google Icon Font--> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!-- Compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"> </script> <!-- Let browser know website is optimized for mobile --> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /></head> <body> <nav> <div class="nav-wrapper green"> <a href="#!" class="brand-logo"> <i class="material-icons"> account_box </i>Logo </a> <ul class="right hide-on-med-and-down"> <li><a href="sass.html"><i class= "material-icons">search</i></a> </li> <li><a href="badges.html"><i class= "material-icons">add_to_photos</i></a> </li> <li><a href="collapsible.html"> <i class="material-icons">refresh</i></a> </li> <li><a href="mobile.html"><i class= "material-icons">dehaze</i></a> </li> </ul> </div> </nav> <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js"> </script> </body> </html> Output: Materialize-CSS CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 29291, "s": 29263, "text": "\n10 Jul, 2020" }, { "code": null, "e": 29788, "s": 29291, "text": "A navigation bar is a user interface element within a webpage that contains links to other sections of the website. It is displayed as a list of horizontal links at the top of each page. It is placed before the main content of the page or below the header. The navbar is contained in an HTML5 <nav> followed by a container “div”, that holds 2 main parts of the navbar. A logo or brand link, and the navigation link. The links can be aligned left or right according to the application requirement." }, { "code": null, "e": 29839, "s": 29788, "text": "Following are the different ways of using Navbars." }, { "code": null, "e": 29928, "s": 29839, "text": "1. Right Aligned: To right align the navbar links, right class is added to <ul> element." }, { "code": null, "e": 29933, "s": 29928, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!--Import Google Icon Font--> <link href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\"> <!-- Compiled and minified CSS --> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css\"> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"> </script> <!-- Let browser know website is optimized for mobile --> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /></head> <body> <nav> <div class=\"nav-wrapper green\"> <a href=\"#\" class=\"brand-logo\"> Materialize </a> <ul id=\"nav-mobile\" class= \"right hide-on-med-and-down\"> <li> <a href=\"https://www.geeksforgeeks.org/materialize-css-tables/?ref=rp\"> Table </a> </li> <li> <a href=\"https://www.geeksforgeeks.org/materialize-css-colors/?ref=rp\"> Colors </a> </li> <li><a href=\"https://www.geeksforgeeks.org/materialize-css-typography/?ref=rp\"> Typography </a> </li> </ul> </div> </nav> <!-- Compiled and minified JavaScript --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js\"> </script></body> </html>", "e": 31546, "s": 29933, "text": null }, { "code": null, "e": 31554, "s": 31546, "text": "Output:" }, { "code": null, "e": 31637, "s": 31554, "text": "Left Aligned: To left align the navbar links, left class is added to <ul> element." }, { "code": null, "e": 31642, "s": 31637, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!--Import Google Icon Font--> <link href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\"> <!-- Compiled and minified CSS --> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css\"> <script type=\"text/javascript\" src= \"https://code.jquery.com/jquery-2.1.1.min.js\"> </script> <!-- Let browser know website is optimized for mobile --> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /></head> <body> <nav> <div class=\"nav-wrapper green\"> <a href=\"#\" class=\"brand-logo right\">Materialize </a> <ul id=\"nav-mobile\" class= \"left hide-on-med-and-down\"> <li> <a href=\"https://www.geeksforgeeks.org/materialize-css-tables/?ref=rp\"> Table </a> </li> <li> <a href=\"https://www.geeksforgeeks.org/materialize-css-colors/?ref=rp\"> Colors </a> </li> <li> <a href=\"https://www.geeksforgeeks.org/materialize-css-typography/?ref=rp\"> Typography </a> </li> </ul> </div> </nav> <!-- Compiled and minified JavaScript --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js\"> </script></body> </html>", "e": 33307, "s": 31642, "text": null }, { "code": null, "e": 33315, "s": 33307, "text": "Output:" }, { "code": null, "e": 33526, "s": 33315, "text": "Center Logo: To align the logo in center, center class is added to <a class=”brand-logo”>. Although the logo will center itself on medium and down screens. While using this, make sure that links do not overlap." }, { "code": null, "e": 33531, "s": 33526, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!--Import Google Icon Font--> <link href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\"> <!-- Compiled and minified CSS --> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css\"> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"> </script> <!-- Let browser know website is optimized for mobile --> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /></head> <body> <nav> <div class=\"nav-wrapper green\"> <a href=\"#\" class=\"brand-logo center\">Materialize </a> <ul id=\"nav-mobile\" class= \"left hide-on-med-and-down\"> <li> <a href=\"https://www.geeksforgeeks.org/materialize-css-tables/?ref=rp\"> Table </a> </li> <li><a href=\"https://www.geeksforgeeks.org/materialize-css-colors/?ref=rp\"> Colors </a> </li> <li><a href=\"https://www.geeksforgeeks.org/materialize-css-typography/?ref=rp\"> Typography </a> </li> </ul> </div> </nav> <!-- Compiled and minified JavaScript --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js\"> </script></body> </html>", "e": 35149, "s": 33531, "text": null }, { "code": null, "e": 35157, "s": 35149, "text": "Output:" }, { "code": null, "e": 35265, "s": 35157, "text": "Active Items: It is used to denote the current active page, for this active class is added to the “li” tag." }, { "code": null, "e": 35270, "s": 35265, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!--Import Google Icon Font--> <link href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\"> <!-- Compiled and minified CSS --> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css\"> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"> </script> <!-- Let browser know website is optimized for mobile --> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /></head> <body> <nav> <div class=\"nav-wrapper green\"> <a href=\"#\" class=\"brand-logo center\">Materialize </a> <ul id=\"nav-mobile\" class= \"left hide-on-med-and-down\"> <li> <a href=\"https://www.geeksforgeeks.org/materialize-css-tables/?ref=rp\"> Table </a> </li> <li class=\"active\"> <a href=\"https://www.geeksforgeeks.org/materialize-css-colors/?ref=rp\"> Colors </a> </li> <li><a href=\"https://www.geeksforgeeks.org/materialize-css-typography/?ref=rp\"> Typography </a> </li> </ul> </div> </nav> <!-- Compiled and minified JavaScript --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js\"> </script></body> </html>", "e": 36907, "s": 35270, "text": null }, { "code": null, "e": 36915, "s": 36907, "text": "Output:" }, { "code": null, "e": 37137, "s": 36915, "text": "Navbar with Tabs: It is used to extend the component of the navbar. To use this, nav-extended class is added to the outer “nav” tag. This will allow tabs component inside the” nav-wrapper” and the “height” to be variable." }, { "code": null, "e": 37142, "s": 37137, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!--Import Google Icon Font--> <link href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\"> <!-- Compiled and minified CSS --> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css\"> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"> </script> <!-- Let browser know website is optimized for mobile --> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /></head> <body> <nav class=\"nav-extended green\"> <div class=\"nav-wrapper\"> <div class=\"container\"> <a href=\"#\" class=\"brand-logo\"> LOGO </a> <a href=\"#\" data-activates=\"mobile-menu\" class=\"button-collapse\"> <i class=\"material-icons\">menu</i> </a> <ul class=\"right hide-on-med-and-down\"> <li><a href=\"#\">item1</a></li> <li><a href=\"#\">item2</a></li> <li><a href=\"#\">item3</a></li> <li><a href=\"#\">item4</a></li> </ul> <ul class=\"side-nav\" id=\"mobile-menu\"> <li><a href=\"#\">item1</a></li> <li><a href=\"#\">item2</a></li> <li><a href=\"#\">item3</a></li> <li><a href=\"#\">item4</a></li> </ul> <!-- tabs items --> <ul class=\"tabs tabs-transparent\"> <li class=\"tab\"><a href=\"#test1\"> Test 1 </a></li> <li class=\"tab\"><a class=\"active\" href=\"#test2\">Test 2</a></li> <li class=\"tab disabled\"><a href= \"#test3\">Disabled Tab</a></li> <li class=\"tab\"><a href=\"#test4\"> Test 4 </a></li> </ul> </div> </div> </nav> <!-- tabs content --> <div id=\"test1\" class=\"col s12\">Test 1</div> <div id=\"test2\" class=\"col s12\">Test 2</div> <div id=\"test3\" class=\"col s12\">Test 3</div> <div id=\"test4\" class=\"col s12\">Test 4</div> <!-- Compiled and minified JavaScript --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js\"> </script></body> </html>", "e": 39650, "s": 37142, "text": null }, { "code": null, "e": 39658, "s": 39650, "text": "Output:" }, { "code": null, "e": 39904, "s": 39658, "text": "Dropdown Menu: To add a navbar dropdown menu, “ul” dropdown structure is added into the page. Then, an element is added to trigger the dropdown menu. The “id” of the dropdown structure is supplied to the “data-target” attribute of the dropdown ." }, { "code": null, "e": 39909, "s": 39904, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!--Import Google Icon Font--> <link href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\"> <!-- Compiled and minified CSS --> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css\"> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"> </script> <!-- Let browser know website is optimized for mobile --> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /></head> <body> <nav> <div class=\"nav-wrapper green\"> <div class=\"container\"> <a href=\"#\" class=\"brand-logo\">LOGO</a> <!-- mobile menu trigger --> <a href=\"#\" data-activates=\"mobile-menu\" class=\"button-collapse\"> <i class=\"material-icons\">menu</i> </a> <!-- desktop menu content --> <ul class=\"right hide-on-med-and-down\"> <li><a href=\"#\">Option-1</a></li> <li><a href=\"#\">Option-2</a></li> <!-- desktop menu dropdown trigger --> <li><a class=\"dropdown-button\" href=\"#!\" data-activates=\"dropdown1\"> Dropdown <i class=\"material-icons right\"> arrow_drop_down </i> </a></li> <li><a href=\"#\">Option-3</a></li> <!-- desktop menu dropdown content --> <ul id='dropdown1' class= 'dropdown-content green-text'> <li><a href=\"#!\">sub-dropdown1</a></li> <li><a href=\"#!\">sub-dropdown2</a></li> <li><a href=\"#!\">sub-dropdown3</a></li> <li><a href=\"#!\">sub-dropdown4</a></li> </ul> </ul> <!-- mobile and tablet menu content --> <ul id=\"mobile-menu\" class=\"side-nav\"> <li> <div class=\"userView\"> <div class=\"background\"> <img src=\"http://lorempixel.com/output/abstract-q-c-640-480-10.jpg\" alt=\"\"> </div> </div> </li> <li><a href=\"#!\">Option-1</a></li> <li><a href=\"#!\">Option-2</a></li> <li class=\"no-padding\"> <ul class=\"collapsible collapsible-accordion\"> <li> <!-- Mobile and tablet menu dropdown trigger --> <a class=\"collapsible-header\">Dropdown <i class=\"material-icons right\"> arrow_drop_down </i> </a> <div class=\"collapsible-body\"> <!-- Mobile and tablet dropdown content --> <ul> <li><a href=\"#!\">sub-dropdown1</a></li> <li><a href=\"#!\">sub-dropdown2</a></li> <li><a href=\"#!\">sub-dropdown3</a></li> <li><a href=\"#!\">sub-dropdown4</a></li> </ul> </div> </li> </ul> </li> <li><a href=\"#!\">Option-3</a></li> </ul> </div> </div> </nav> <!-- Compiled and minified JavaScript --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js\"> </script></body> </html>", "e": 43091, "s": 39909, "text": null }, { "code": null, "e": 43099, "s": 43091, "text": "Output:" }, { "code": null, "e": 43279, "s": 43099, "text": "Fixed Navbar: To make the navbar fixed, an outer wrapping “div” with the navbar-fixed class is added. This will give offset to all the other content while making the navbar fixed." }, { "code": null, "e": 43284, "s": 43279, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!--Import Google Icon Font--> <link href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\"> <!-- Compiled and minified CSS --> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css\"> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"> </script> <!-- Let browser know website is optimized for mobile --> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /></head> <body> <div class=\"navbar-fixed \"> <nav> <div class=\"nav-wrapper green\"> <a href=\"#\" class=\"brand-logo\">LOGO</a> <a href=\"#\" data-activates= \"mobile-menu\" class=\"button-collapse\"> <i class=\"material-icons\">menu</i></a> <ul class=\"right hide-on-med-and-down\"> <li><a href=\"#\">item1</a></li> <li><a href=\"#\">item2</a></li> <li><a href=\"#\">item3</a></li> <li><a href=\"#\">item4</a></li> </ul> <ul class=\"side-nav\" id=\"mobile-menu\"> <li><a href=\"#\">item1</a></li> <li><a href=\"#\">item2</a></li> <li><a href=\"#\">item3</a></li> <li><a href=\"#\">item4</a></li> </ul> </div> </nav> </div> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <!-- Compiled and minified JavaScript --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js\"> </script></body> </html>", "e": 44927, "s": 43284, "text": null }, { "code": null, "e": 44935, "s": 44927, "text": "Output:" }, { "code": null, "e": 45078, "s": 44935, "text": "Icon Links: Icons can be added into links inside the navbar. For “icon” as links, there is no need to add additional class just use the i tag." }, { "code": null, "e": 45083, "s": 45078, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!--Import Google Icon Font--> <link href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\"> <!-- Compiled and minified CSS --> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css\"> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"> </script> <!-- Let browser know website is optimized for mobile --> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /></head> <body> <nav> <div class=\"nav-wrapper green\"> <a href=\"#!\" class=\"brand-logo\"> <i class=\"material-icons\"> account_box </i>Logo </a> <ul class=\"right hide-on-med-and-down\"> <li><a href=\"sass.html\"><i class= \"material-icons\">search</i></a> </li> <li><a href=\"badges.html\"><i class= \"material-icons\">add_to_photos</i></a> </li> <li><a href=\"collapsible.html\"> <i class=\"material-icons\">refresh</i></a> </li> <li><a href=\"mobile.html\"><i class= \"material-icons\">dehaze</i></a> </li> </ul> </div> </nav> <!-- Compiled and minified JavaScript --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js\"> </script> </body> </html>", "e": 46468, "s": 45083, "text": null }, { "code": null, "e": 46476, "s": 46468, "text": "Output:" }, { "code": null, "e": 46492, "s": 46476, "text": "Materialize-CSS" }, { "code": null, "e": 46496, "s": 46492, "text": "CSS" }, { "code": null, "e": 46513, "s": 46496, "text": "Web Technologies" }, { "code": null, "e": 46611, "s": 46513, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46673, "s": 46611, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 46723, "s": 46673, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 46771, "s": 46723, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 46829, "s": 46771, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 46884, "s": 46829, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 46924, "s": 46884, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 46957, "s": 46924, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 47002, "s": 46957, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 47045, "s": 47002, "text": "How to fetch data from an API in ReactJS ?" } ]
Histogram in R using ggplot2 - GeeksforGeeks
25 Feb, 2021 ggplot2 is an R Package that is dedicated to Data visualization. ggplot2 Package Improve the quality and the beauty (aesthetics ) of the graph. By Using ggplot2 we can make almost every kind of graph In RStudio A histogram is an approximate representation of the distribution of numerical data. In a histogram, each bar groups numbers into ranges. Taller bars show that more data falls in that range. A histogram displays the shape and spread of continuous sample data. Histograms roughly give us an idea about the probability distribution of a given variable by depicting the frequencies of observations occurring in certain ranges of values. Basically, Histograms are used to show distributions of a given variable while bar charts are used to compare variables. Histograms plot quantitative data with ranges of the data grouped into the intervals while bar charts plot categorical data. geom_histogram() function is an in-built function of ggplot2 module. Approach Import module Create dataframe Create histogram using function Display plot Example 1: R set.seed(123) # In the above line,123 is set as the # random number value # The main point of using the seed is to # be able to reproduce a particular sequence # of 'random' numbers. and sed(n) reproduces # random numbers results by seed df <- data.frame( gender=factor(rep(c( "Average Female income ", "Average Male incmome"), each=20000)), Average_income=round(c(rnorm(20000, mean=15500, sd=500), rnorm(20000, mean=17500, sd=600))) ) head(df) # if already installed ggplot2 then use library(ggplot2) library(ggplot2) # Basic histogram ggplot(df, aes(x=Average_income)) + geom_histogram() # Change the width of bins ggplot(df, aes(x=Average_income)) + geom_histogram(binwidth=1) # Change colors p<-ggplot(df, aes(x=Average_income)) + geom_histogram(color="white", fill="red") p Output : Example 2: R plot_hist <- ggplot(airquality, aes(x = Ozone)) + # binwidth help to change the thickness (Width) of the bar geom_histogram(aes(fill = ..count..), binwidth = 10)+ # name = "Mean ozone(03) in ppm parts per million " # name is used to give name to axis scale_x_continuous(name = "Mean ozone(03) in ppm parts per million ", breaks = seq(0, 200, 25), limits=c(0, 200)) + scale_y_continuous(name = "Count") + # ggtitle is used to give name to a chart ggtitle("Frequency of mean ozone(03)") + scale_fill_gradient("Count", low = "green", high = "red") plot_hist Output : Picked R-Charts R-Graphs R-plots R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to import an Excel File into R ? How to filter R DataFrame by values in a column? Time Series Analysis in R Logistic Regression in R Programming R - if statement
[ { "code": null, "e": 26585, "s": 26554, "text": " \n25 Feb, 2021\n" }, { "code": null, "e": 26797, "s": 26585, "text": "ggplot2 is an R Package that is dedicated to Data visualization. ggplot2 Package Improve the quality and the beauty (aesthetics ) of the graph. By Using ggplot2 we can make almost every kind of graph In RStudio" }, { "code": null, "e": 27056, "s": 26797, "text": "A histogram is an approximate representation of the distribution of numerical data. In a histogram, each bar groups numbers into ranges. Taller bars show that more data falls in that range. A histogram displays the shape and spread of continuous sample data." }, { "code": null, "e": 27476, "s": 27056, "text": "Histograms roughly give us an idea about the probability distribution of a given variable by depicting the frequencies of observations occurring in certain ranges of values. Basically, Histograms are used to show distributions of a given variable while bar charts are used to compare variables. Histograms plot quantitative data with ranges of the data grouped into the intervals while bar charts plot categorical data." }, { "code": null, "e": 27545, "s": 27476, "text": "geom_histogram() function is an in-built function of ggplot2 module." }, { "code": null, "e": 27554, "s": 27545, "text": "Approach" }, { "code": null, "e": 27568, "s": 27554, "text": "Import module" }, { "code": null, "e": 27585, "s": 27568, "text": "Create dataframe" }, { "code": null, "e": 27617, "s": 27585, "text": "Create histogram using function" }, { "code": null, "e": 27630, "s": 27617, "text": "Display plot" }, { "code": null, "e": 27641, "s": 27630, "text": "Example 1:" }, { "code": null, "e": 27643, "s": 27641, "text": "R" }, { "code": "\n\n\n\n\n\n\nset.seed(123) \n \n# In the above line,123 is set as the \n# random number value \n# The main point of using the seed is to \n# be able to reproduce a particular sequence \n# of 'random' numbers. and sed(n) reproduces \n# random numbers results by seed \ndf <- data.frame( \n gender=factor(rep(c( \n \"Average Female income \", \"Average Male incmome\"), each=20000)), \n Average_income=round(c(rnorm(20000, mean=15500, sd=500), \n rnorm(20000, mean=17500, sd=600))) \n) \nhead(df) \n \n# if already installed ggplot2 then use library(ggplot2) \nlibrary(ggplot2) \n \n# Basic histogram \nggplot(df, aes(x=Average_income)) + geom_histogram() \n \n# Change the width of bins \nggplot(df, aes(x=Average_income)) + \n \n geom_histogram(binwidth=1) \n \n# Change colors \np<-ggplot(df, aes(x=Average_income)) + \n \n geom_histogram(color=\"white\", fill=\"red\") \np\n\n\n\n\n\n", "e": 28548, "s": 27653, "text": null }, { "code": null, "e": 28558, "s": 28548, "text": "Output : " }, { "code": null, "e": 28569, "s": 28558, "text": "Example 2:" }, { "code": null, "e": 28571, "s": 28569, "text": "R" }, { "code": "\n\n\n\n\n\n\nplot_hist <- ggplot(airquality, aes(x = Ozone)) + \n \n # binwidth help to change the thickness (Width) of the bar \n geom_histogram(aes(fill = ..count..), binwidth = 10)+ \n \n # name = \"Mean ozone(03) in ppm parts per million \" \n # name is used to give name to axis \n scale_x_continuous(name = \"Mean ozone(03) in ppm parts per million \", \n breaks = seq(0, 200, 25), \n limits=c(0, 200)) + \n scale_y_continuous(name = \"Count\") + \n \n # ggtitle is used to give name to a chart \n ggtitle(\"Frequency of mean ozone(03)\") + \n scale_fill_gradient(\"Count\", low = \"green\", high = \"red\") \n \nplot_hist\n\n\n\n\n\n", "e": 29247, "s": 28581, "text": null }, { "code": null, "e": 29257, "s": 29247, "text": "Output : " }, { "code": null, "e": 29266, "s": 29257, "text": "\nPicked\n" }, { "code": null, "e": 29277, "s": 29266, "text": "\nR-Charts\n" }, { "code": null, "e": 29288, "s": 29277, "text": "\nR-Graphs\n" }, { "code": null, "e": 29298, "s": 29288, "text": "\nR-plots\n" }, { "code": null, "e": 29311, "s": 29298, "text": "\nR Language\n" }, { "code": null, "e": 29516, "s": 29311, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 29568, "s": 29516, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29603, "s": 29568, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29641, "s": 29603, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29699, "s": 29641, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29742, "s": 29699, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 29779, "s": 29742, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 29828, "s": 29779, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29854, "s": 29828, "text": "Time Series Analysis in R" }, { "code": null, "e": 29891, "s": 29854, "text": "Logistic Regression in R Programming" } ]
ML | Ridge Regressor using sklearn - GeeksforGeeks
20 Oct, 2021 A Ridge regressor is basically a regularized version of a Linear Regressor. i.e to the original cost function of linear regressor we add a regularized term that forces the learning algorithm to fit the data and helps to keep the weights lower as possible. The regularized term has the parameter ‘alpha’ which controls the regularization of the model i.e helps in reducing the variance of the estimates. Cost Function for Ridge Regressor. (1) Here, The first term is our basic linear regression’s cost function and the second term is our new regularized weights term which uses the L2 norm to fit the data. If the ‘alpha’ is zero the model is the same as linear regression and the larger ‘alpha’ value specifies a stronger regularization. Note: Before using Ridge regressor it is necessary to scale the inputs, because this model is sensitive to scaling of inputs. So performing the scaling through sklearn’s StandardScalar will be beneficial. Code : Python code for implementing Ridge Regressor. Python3 # importing librariesfrom sklearn.linear_model import Ridgefrom sklearn.model_selection import train_test_splitfrom sklearn.datasets import load_bostonfrom sklearn.preprocessing import StandardScaler # loading boston datasetboston = load_boston()X = boston.data[:, :13]y = boston.target print ("Boston dataset keys : \n", boston.keys()) print ("\nBoston data : \n", boston.data) # scaling the inputsscaler = StandardScaler()scaled_X = scaler.fit_transform(X) # Train Test split will be used for both modelsX_train, X_test, y_train, y_test = train_test_split(scaled_X, y, test_size = 0.3) # training model with 0.5 alpha valuemodel = Ridge(alpha = 0.5, normalize = False, tol = 0.001, \ solver ='auto', random_state = 42)model.fit(X_train, y_train) # predicting the y_testy_pred = model.predict(X_test) # finding score for our modelscore = model.score(X_test, y_test)print("\n\nModel score : ", score) Output : Boston dataset keys : dict_keys(['feature_names', 'DESCR', 'data', 'target']) Boston data : [[6.3200e-03 1.8000e+01 2.3100e+00 ... 1.5300e+01 3.9690e+02 4.9800e+00] [2.7310e-02 0.0000e+00 7.0700e+00 ... 1.7800e+01 3.9690e+02 9.1400e+00] [2.7290e-02 0.0000e+00 7.0700e+00 ... 1.7800e+01 3.9283e+02 4.0300e+00] ... [6.0760e-02 0.0000e+00 1.1930e+01 ... 2.1000e+01 3.9690e+02 5.6400e+00] [1.0959e-01 0.0000e+00 1.1930e+01 ... 2.1000e+01 3.9345e+02 6.4800e+00] [4.7410e-02 0.0000e+00 1.1930e+01 ... 2.1000e+01 3.9690e+02 7.8800e+00]] Model score : 0.6819292026260749 A newer version RidgeCV comes with built-in Cross-Validation for an alpha, so definitely better. Only pass the array of some alpha range values and it’ll automatically choose the optimal value for ‘alpha’.Note : ‘tol’ is the parameter which measures the loss drop and ensures to stop the model at that provided value position or drop at(global minima value). abhishek0719kadiyan Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Reinforcement learning Decision Tree Activation functions in Neural Networks Decision Tree Introduction with example Introduction to Recurrent Neural Network Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 25975, "s": 25947, "text": "\n20 Oct, 2021" }, { "code": null, "e": 26415, "s": 25975, "text": "A Ridge regressor is basically a regularized version of a Linear Regressor. i.e to the original cost function of linear regressor we add a regularized term that forces the learning algorithm to fit the data and helps to keep the weights lower as possible. The regularized term has the parameter ‘alpha’ which controls the regularization of the model i.e helps in reducing the variance of the estimates. Cost Function for Ridge Regressor. " }, { "code": null, "e": 26422, "s": 26415, "text": "(1) " }, { "code": null, "e": 26978, "s": 26422, "text": "Here, The first term is our basic linear regression’s cost function and the second term is our new regularized weights term which uses the L2 norm to fit the data. If the ‘alpha’ is zero the model is the same as linear regression and the larger ‘alpha’ value specifies a stronger regularization. Note: Before using Ridge regressor it is necessary to scale the inputs, because this model is sensitive to scaling of inputs. So performing the scaling through sklearn’s StandardScalar will be beneficial. Code : Python code for implementing Ridge Regressor. " }, { "code": null, "e": 26986, "s": 26978, "text": "Python3" }, { "code": "# importing librariesfrom sklearn.linear_model import Ridgefrom sklearn.model_selection import train_test_splitfrom sklearn.datasets import load_bostonfrom sklearn.preprocessing import StandardScaler # loading boston datasetboston = load_boston()X = boston.data[:, :13]y = boston.target print (\"Boston dataset keys : \\n\", boston.keys()) print (\"\\nBoston data : \\n\", boston.data) # scaling the inputsscaler = StandardScaler()scaled_X = scaler.fit_transform(X) # Train Test split will be used for both modelsX_train, X_test, y_train, y_test = train_test_split(scaled_X, y, test_size = 0.3) # training model with 0.5 alpha valuemodel = Ridge(alpha = 0.5, normalize = False, tol = 0.001, \\ solver ='auto', random_state = 42)model.fit(X_train, y_train) # predicting the y_testy_pred = model.predict(X_test) # finding score for our modelscore = model.score(X_test, y_test)print(\"\\n\\nModel score : \", score)", "e": 27959, "s": 26986, "text": null }, { "code": null, "e": 27970, "s": 27959, "text": "Output : " }, { "code": null, "e": 28547, "s": 27970, "text": "Boston dataset keys : \n dict_keys(['feature_names', 'DESCR', 'data', 'target'])\n\nBoston data : \n [[6.3200e-03 1.8000e+01 2.3100e+00 ... 1.5300e+01 3.9690e+02 4.9800e+00]\n [2.7310e-02 0.0000e+00 7.0700e+00 ... 1.7800e+01 3.9690e+02 9.1400e+00]\n [2.7290e-02 0.0000e+00 7.0700e+00 ... 1.7800e+01 3.9283e+02 4.0300e+00]\n ...\n [6.0760e-02 0.0000e+00 1.1930e+01 ... 2.1000e+01 3.9690e+02 5.6400e+00]\n [1.0959e-01 0.0000e+00 1.1930e+01 ... 2.1000e+01 3.9345e+02 6.4800e+00]\n [4.7410e-02 0.0000e+00 1.1930e+01 ... 2.1000e+01 3.9690e+02 7.8800e+00]]\n\n\nModel score : 0.6819292026260749" }, { "code": null, "e": 28907, "s": 28547, "text": "A newer version RidgeCV comes with built-in Cross-Validation for an alpha, so definitely better. Only pass the array of some alpha range values and it’ll automatically choose the optimal value for ‘alpha’.Note : ‘tol’ is the parameter which measures the loss drop and ensures to stop the model at that provided value position or drop at(global minima value). " }, { "code": null, "e": 28927, "s": 28907, "text": "abhishek0719kadiyan" }, { "code": null, "e": 28944, "s": 28927, "text": "Machine Learning" }, { "code": null, "e": 28951, "s": 28944, "text": "Python" }, { "code": null, "e": 28968, "s": 28951, "text": "Machine Learning" }, { "code": null, "e": 29066, "s": 28968, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29089, "s": 29066, "text": "Reinforcement learning" }, { "code": null, "e": 29103, "s": 29089, "text": "Decision Tree" }, { "code": null, "e": 29143, "s": 29103, "text": "Activation functions in Neural Networks" }, { "code": null, "e": 29183, "s": 29143, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 29224, "s": 29183, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 29252, "s": 29224, "text": "Read JSON file using Python" }, { "code": null, "e": 29302, "s": 29252, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 29324, "s": 29302, "text": "Python map() function" } ]
Python | Alternate range slicing in list - GeeksforGeeks
29 Mar, 2019 List slicing is quite common utility in Python, one can easily slice certain elements from a list, but sometimes, we need to perform that task in non-contiguous manner and slice alternate ranges. Let’s discuss how this particular problem can be solved. Method #1 : Using list comprehensionList comprehension can be used to perform this particular task with ease as it can be used to run a loop and only filter the elements that leave a remainder more than half of target slice size multiplied by 2. By this way we can extract the sliced numbers in range alternatively. # Python3 code to demonstrate# alternate range slicing # using list comprehension # initializing list test_list = [2, 4, 6, 8, 9, 10, 12, 16, 18, 20, 7, 30] # printing original listprint("The original list : " + str(test_list)) # Select range size N = 3 # using list comprehension# alternate range slicingres = [test_list[i] for i in range(len(test_list)) if i % (N * 2) >= N] # print resultprint("The alternate range sliced list : " + str(res)) The original list : [2, 4, 6, 8, 9, 10, 12, 16, 18, 20, 7, 30] The alternate range sliced list : [8, 9, 10, 20, 7, 30] Method #2 : Using enumerate() + list comprehensionThe list comprehension can also be combined with the enumerate function to perform this task. The advantage of using enumerate is that we can track of index along with the value and it’s more efficient and has lesser run-time than the above function. # Python3 code to demonstrate# alternate range slicing # using list comprehension + enumerate() # initializing list test_list = [2, 4, 6, 8, 9, 10, 12, 16, 18, 20, 7, 30] # printing original listprint("The original list : " + str(test_list)) # Select range size N = 3 # using list comprehension + enumerate()# alternate range slicingres = [val for i, val in enumerate(test_list) if i % (N * 2) >= N] # print resultprint("The alternate range sliced list : " + str(res)) The original list : [2, 4, 6, 8, 9, 10, 12, 16, 18, 20, 7, 30] The alternate range sliced list : [8, 9, 10, 20, 7, 30] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25607, "s": 25579, "text": "\n29 Mar, 2019" }, { "code": null, "e": 25860, "s": 25607, "text": "List slicing is quite common utility in Python, one can easily slice certain elements from a list, but sometimes, we need to perform that task in non-contiguous manner and slice alternate ranges. Let’s discuss how this particular problem can be solved." }, { "code": null, "e": 26176, "s": 25860, "text": "Method #1 : Using list comprehensionList comprehension can be used to perform this particular task with ease as it can be used to run a loop and only filter the elements that leave a remainder more than half of target slice size multiplied by 2. By this way we can extract the sliced numbers in range alternatively." }, { "code": "# Python3 code to demonstrate# alternate range slicing # using list comprehension # initializing list test_list = [2, 4, 6, 8, 9, 10, 12, 16, 18, 20, 7, 30] # printing original listprint(\"The original list : \" + str(test_list)) # Select range size N = 3 # using list comprehension# alternate range slicingres = [test_list[i] for i in range(len(test_list)) if i % (N * 2) >= N] # print resultprint(\"The alternate range sliced list : \" + str(res))", "e": 26657, "s": 26176, "text": null }, { "code": null, "e": 26777, "s": 26657, "text": "The original list : [2, 4, 6, 8, 9, 10, 12, 16, 18, 20, 7, 30]\nThe alternate range sliced list : [8, 9, 10, 20, 7, 30]\n" }, { "code": null, "e": 27080, "s": 26779, "text": "Method #2 : Using enumerate() + list comprehensionThe list comprehension can also be combined with the enumerate function to perform this task. The advantage of using enumerate is that we can track of index along with the value and it’s more efficient and has lesser run-time than the above function." }, { "code": "# Python3 code to demonstrate# alternate range slicing # using list comprehension + enumerate() # initializing list test_list = [2, 4, 6, 8, 9, 10, 12, 16, 18, 20, 7, 30] # printing original listprint(\"The original list : \" + str(test_list)) # Select range size N = 3 # using list comprehension + enumerate()# alternate range slicingres = [val for i, val in enumerate(test_list) if i % (N * 2) >= N] # print resultprint(\"The alternate range sliced list : \" + str(res))", "e": 27578, "s": 27080, "text": null }, { "code": null, "e": 27698, "s": 27578, "text": "The original list : [2, 4, 6, 8, 9, 10, 12, 16, 18, 20, 7, 30]\nThe alternate range sliced list : [8, 9, 10, 20, 7, 30]\n" }, { "code": null, "e": 27719, "s": 27698, "text": "Python list-programs" }, { "code": null, "e": 27726, "s": 27719, "text": "Python" }, { "code": null, "e": 27742, "s": 27726, "text": "Python Programs" }, { "code": null, "e": 27840, "s": 27742, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27858, "s": 27840, "text": "Python Dictionary" }, { "code": null, "e": 27893, "s": 27858, "text": "Read a file line by line in Python" }, { "code": null, "e": 27925, "s": 27893, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27947, "s": 27925, "text": "Enumerate() in Python" }, { "code": null, "e": 27989, "s": 27947, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28032, "s": 27989, "text": "Python program to convert a list to string" }, { "code": null, "e": 28054, "s": 28032, "text": "Defaultdict in Python" }, { "code": null, "e": 28093, "s": 28054, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28139, "s": 28093, "text": "Python | Split string into list of characters" } ]
C# Program to Generate Marksheet of Student - GeeksforGeeks
16 Oct, 2021 Given the marks of the students, now we generate a mark sheet of students by calculating three subject marks of students by entering student names and roll numbers. Example: Input: Enter Student Roll-Number: 1 Enter Student Name: manoj Enter Subject-1 Marks :90 Enter Subject-2 Marks :78 Enter Subject-3 Marks :96 Output: Total Marks: 264 Percentage: 88 Grade is A Approach Declare the variables(i.e., marks1, marks2, and marks3) that will holds the marks of three subjects, i.e., Subject-1, Subject-2, and Subject-3. Read the student data from the user. Calculate total marks of the three subjects. total = marks1 + marks2 + marks3; Find the percentage. percentage = total / 3.0f; Display the final percentage of the student. Calculate and display the grades of the student also according to their percentage. Example: C# // C# program to create marksheet for students.using System;using System.Collections.Generic;using System.Linq;using System.Text; class GFG{ static void Main(string[] args){ // Declare variables for marks and total int r, marks1, marks2, marks3, total; // Declare percentage variable float percentage; string n; // Enter student roll number Console.WriteLine("Enter Student Roll Number :"); r = Convert.ToInt32(Console.ReadLine()); // Enter student name Console.WriteLine("Enter Student Name :"); n = Console.ReadLine(); // Enter student subject 1 marks Console.WriteLine("Enter Subject-1 Marks : "); marks1 = Convert.ToInt32(Console.ReadLine()); // Enter student subject 2 marks Console.WriteLine("Enter Subject-2 Marks : "); marks2 = Convert.ToInt32(Console.ReadLine()); // Enter student subject 3 marks Console.WriteLine("Enter Subject-3 Marks :"); marks3 = Convert.ToInt32(Console.ReadLine()); // Calculate total marks total = marks1 + marks2 + marks3; // Calculate percentage percentage = total / 3.0f; // Display the final result Console.WriteLine("Final result of {0} is:", n); Console.WriteLine("Total Marks : " + total); Console.WriteLine("Percentage : " + percentage); // Calculate grades if (percentage <= 35) { Console.WriteLine("Grade is F"); } else if (percentage >= 34 && percentage <= 39) { Console.WriteLine("Grade is D"); } else if (percentage >= 40 && percentage <= 59) { Console.WriteLine("Grade is C"); } else if (percentage >= 60 && percentage <= 69) { Console.WriteLine("Grade is B"); } else if (percentage >= 70 && percentage <= 79) { Console.WriteLine("Grade is B+"); } else if (percentage >= 80 && percentage <= 90) { Console.WriteLine("Grade is A"); } else if (percentage >= 91) { Console.WriteLine("Grade is A+"); }}} Output: Enter Student Roll Number : 13 Enter Student Name : Hitesh Enter Subject-1 Marks : 56 Enter Subject-2 Marks : 78 Enter Subject-3 Marks : 87 Final result of Hitesh is: Total Marks : 221 Percentage : 73.66666 Grade is B+ CSharp-programs Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers Switch Statement in C# Convert String to Character Array in C# C# | How to insert an element in an Array? Linked List Implementation in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n16 Oct, 2021" }, { "code": null, "e": 25712, "s": 25547, "text": "Given the marks of the students, now we generate a mark sheet of students by calculating three subject marks of students by entering student names and roll numbers." }, { "code": null, "e": 25721, "s": 25712, "text": "Example:" }, { "code": null, "e": 25913, "s": 25721, "text": "Input:\nEnter Student Roll-Number: 1\nEnter Student Name: manoj\nEnter Subject-1 Marks :90\nEnter Subject-2 Marks :78\nEnter Subject-3 Marks :96\n\nOutput:\nTotal Marks: 264\nPercentage: 88\nGrade is A" }, { "code": null, "e": 25922, "s": 25913, "text": "Approach" }, { "code": null, "e": 26066, "s": 25922, "text": "Declare the variables(i.e., marks1, marks2, and marks3) that will holds the marks of three subjects, i.e., Subject-1, Subject-2, and Subject-3." }, { "code": null, "e": 26103, "s": 26066, "text": "Read the student data from the user." }, { "code": null, "e": 26148, "s": 26103, "text": "Calculate total marks of the three subjects." }, { "code": null, "e": 26182, "s": 26148, "text": "total = marks1 + marks2 + marks3;" }, { "code": null, "e": 26203, "s": 26182, "text": "Find the percentage." }, { "code": null, "e": 26231, "s": 26203, "text": " percentage = total / 3.0f;" }, { "code": null, "e": 26276, "s": 26231, "text": "Display the final percentage of the student." }, { "code": null, "e": 26360, "s": 26276, "text": "Calculate and display the grades of the student also according to their percentage." }, { "code": null, "e": 26369, "s": 26360, "text": "Example:" }, { "code": null, "e": 26372, "s": 26369, "text": "C#" }, { "code": "// C# program to create marksheet for students.using System;using System.Collections.Generic;using System.Linq;using System.Text; class GFG{ static void Main(string[] args){ // Declare variables for marks and total int r, marks1, marks2, marks3, total; // Declare percentage variable float percentage; string n; // Enter student roll number Console.WriteLine(\"Enter Student Roll Number :\"); r = Convert.ToInt32(Console.ReadLine()); // Enter student name Console.WriteLine(\"Enter Student Name :\"); n = Console.ReadLine(); // Enter student subject 1 marks Console.WriteLine(\"Enter Subject-1 Marks : \"); marks1 = Convert.ToInt32(Console.ReadLine()); // Enter student subject 2 marks Console.WriteLine(\"Enter Subject-2 Marks : \"); marks2 = Convert.ToInt32(Console.ReadLine()); // Enter student subject 3 marks Console.WriteLine(\"Enter Subject-3 Marks :\"); marks3 = Convert.ToInt32(Console.ReadLine()); // Calculate total marks total = marks1 + marks2 + marks3; // Calculate percentage percentage = total / 3.0f; // Display the final result Console.WriteLine(\"Final result of {0} is:\", n); Console.WriteLine(\"Total Marks : \" + total); Console.WriteLine(\"Percentage : \" + percentage); // Calculate grades if (percentage <= 35) { Console.WriteLine(\"Grade is F\"); } else if (percentage >= 34 && percentage <= 39) { Console.WriteLine(\"Grade is D\"); } else if (percentage >= 40 && percentage <= 59) { Console.WriteLine(\"Grade is C\"); } else if (percentage >= 60 && percentage <= 69) { Console.WriteLine(\"Grade is B\"); } else if (percentage >= 70 && percentage <= 79) { Console.WriteLine(\"Grade is B+\"); } else if (percentage >= 80 && percentage <= 90) { Console.WriteLine(\"Grade is A\"); } else if (percentage >= 91) { Console.WriteLine(\"Grade is A+\"); }}}", "e": 28391, "s": 26372, "text": null }, { "code": null, "e": 28399, "s": 28391, "text": "Output:" }, { "code": null, "e": 28618, "s": 28399, "text": "Enter Student Roll Number :\n13\nEnter Student Name :\nHitesh\nEnter Subject-1 Marks :\n56\nEnter Subject-2 Marks :\n78\nEnter Subject-3 Marks :\n87\nFinal result of Hitesh is:\nTotal Marks : 221\nPercentage : 73.66666\nGrade is B+" }, { "code": null, "e": 28634, "s": 28618, "text": "CSharp-programs" }, { "code": null, "e": 28641, "s": 28634, "text": "Picked" }, { "code": null, "e": 28644, "s": 28641, "text": "C#" }, { "code": null, "e": 28742, "s": 28644, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28765, "s": 28742, "text": "Extension Method in C#" }, { "code": null, "e": 28793, "s": 28765, "text": "HashSet in C# with Examples" }, { "code": null, "e": 28810, "s": 28793, "text": "C# | Inheritance" }, { "code": null, "e": 28832, "s": 28810, "text": "Partial Classes in C#" }, { "code": null, "e": 28861, "s": 28832, "text": "C# | Generics - Introduction" }, { "code": null, "e": 28901, "s": 28861, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 28924, "s": 28901, "text": "Switch Statement in C#" }, { "code": null, "e": 28964, "s": 28924, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 29007, "s": 28964, "text": "C# | How to insert an element in an Array?" } ]
Asynchronous Functions and the Node.js Event Loop - GeeksforGeeks
14 Oct, 2021 Asynchronous Functions Everyone knows JavaScript is asynchronous in nature and so is the Node. The fundamental principle behind Node is that an application is executed on a single thread or process and the events are thus handled asynchronously. If we consider any typical web server like Apache, it requires separate threads for each process until the request is satisfied. The disadvantage in using multi-thread is they are not memory intensive and doesn’t scale very well. Also, we have to ensure that each process must be thread safe and deadlock should not appear. But Node does things differently. On starting a Node application, it creates only a single thread of execution. When the Node receives a request, it assigns the thread to that process and no other request can be processed until it has finished processing the code for the current request. Therefore, Node handles multiple requests at the same time by using event loop and callback functions. An Event Loop is a type of functionality which basically polls for specific events and invokes event handlers when required. A Callback Function is this event handler in Node. In Node applications, the Node initiates the request but does not wait around the request to get the response. Instead of that, it attaches a callback function to the request. When the request has been completed or the response has been received by the request, the callback function emits an event to do something with either the results of the requested action or the resource requested. If multiple people access a Node application at the same time, and the application needs to access a resource from a file, Node attaches a callback function with each request. As soon as the resource becomes available to that particular request, a callback function is called to each person’s request. The Node can handle other requests in the meantime. The serving of the parallel requests in the Node application depends upon how busy the application is and how it is designed? Examples: // Normal Functionfunction add(a,b){ return a+b;} // Async Functionasync function asyncadd(a,b){ Return a+b;} Asynchronously opening and writing the contents of a file // load http modulevar http = require('http');var fs = require('fs'); // load http modulevar http = require('http');var fs = require('fs'); // create http serverhttp.createServer(function (req, res) { // open and read in helloworld.js fs.readFile('helloworld.js', 'utf8', function(err, data) { res.writeHead(200, {'Content-Type': 'text/plain'}); if (err) res.write('Could not find or open file for reading\n'); else // if no error, writing JS file to a client res.write(data); res.end(); });}).listen(8124, function() { console.log('bound to port 8124');}); console.log('Server running on 8124/'); Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.writeFile() Method Node.js fs.readFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js How to use an ES6 import in Node.js? Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26089, "s": 26061, "text": "\n14 Oct, 2021" }, { "code": null, "e": 26112, "s": 26089, "text": "Asynchronous Functions" }, { "code": null, "e": 26335, "s": 26112, "text": "Everyone knows JavaScript is asynchronous in nature and so is the Node. The fundamental principle behind Node is that an application is executed on a single thread or process and the events are thus handled asynchronously." }, { "code": null, "e": 26659, "s": 26335, "text": "If we consider any typical web server like Apache, it requires separate threads for each process until the request is satisfied. The disadvantage in using multi-thread is they are not memory intensive and doesn’t scale very well. Also, we have to ensure that each process must be thread safe and deadlock should not appear." }, { "code": null, "e": 27227, "s": 26659, "text": "But Node does things differently. On starting a Node application, it creates only a single thread of execution. When the Node receives a request, it assigns the thread to that process and no other request can be processed until it has finished processing the code for the current request. Therefore, Node handles multiple requests at the same time by using event loop and callback functions. An Event Loop is a type of functionality which basically polls for specific events and invokes event handlers when required. A Callback Function is this event handler in Node." }, { "code": null, "e": 27617, "s": 27227, "text": "In Node applications, the Node initiates the request but does not wait around the request to get the response. Instead of that, it attaches a callback function to the request. When the request has been completed or the response has been received by the request, the callback function emits an event to do something with either the results of the requested action or the resource requested." }, { "code": null, "e": 27971, "s": 27617, "text": "If multiple people access a Node application at the same time, and the application needs to access a resource from a file, Node attaches a callback function with each request. As soon as the resource becomes available to that particular request, a callback function is called to each person’s request. The Node can handle other requests in the meantime." }, { "code": null, "e": 28097, "s": 27971, "text": "The serving of the parallel requests in the Node application depends upon how busy the application is and how it is designed?" }, { "code": null, "e": 28107, "s": 28097, "text": "Examples:" }, { "code": "// Normal Functionfunction add(a,b){ return a+b;} // Async Functionasync function asyncadd(a,b){ Return a+b;}", "e": 28224, "s": 28107, "text": null }, { "code": null, "e": 28282, "s": 28224, "text": "Asynchronously opening and writing the contents of a file" }, { "code": "// load http modulevar http = require('http');var fs = require('fs'); // load http modulevar http = require('http');var fs = require('fs'); // create http serverhttp.createServer(function (req, res) { // open and read in helloworld.js fs.readFile('helloworld.js', 'utf8', function(err, data) { res.writeHead(200, {'Content-Type': 'text/plain'}); if (err) res.write('Could not find or open file for reading\\n'); else // if no error, writing JS file to a client res.write(data); res.end(); });}).listen(8124, function() { console.log('bound to port 8124');}); console.log('Server running on 8124/');", "e": 28979, "s": 28282, "text": null }, { "code": null, "e": 28987, "s": 28979, "text": "Node.js" }, { "code": null, "e": 29004, "s": 28987, "text": "Web Technologies" }, { "code": null, "e": 29102, "s": 29004, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29132, "s": 29102, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 29161, "s": 29132, "text": "Node.js fs.readFile() Method" }, { "code": null, "e": 29218, "s": 29161, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 29272, "s": 29218, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 29309, "s": 29272, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 29349, "s": 29309, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29394, "s": 29349, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29437, "s": 29394, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29499, "s": 29437, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Group all occurrences of characters according to first appearance - GeeksforGeeks
26 Aug, 2019 Given a string of lowercase characters, the task is to print the string in a manner such that a character comes first in string displays first with all its occurrences in string. Examples: Input : str = "geeksforgeeks" Output: ggeeeekkssfor Explanation: In the given string 'g' comes first and occurs 2 times so it is printed first Then 'e' comes in this string and 4 times so it gets printed. Similarly remaining string is printed. Input : str = "occurrence" output : occcurreen Input : str = "cdab" Output : cdab This problem is a string version of following problem for array of integers. Group multiple occurrence of array elements ordered by first occurrences Since given strings have only 26 possible characters, it is easier to implement for strings. Implementation:1- Count the occurrence of all the characters in given string using an array of size 26.2- Then start traversing the string. Print every character its count times. C++ Java Python3 C# // C++ program to print all occurrences of every character// together.# include<bits/stdc++.h>using namespace std; // Since only lower case characters are thereconst int MAX_CHAR = 26; // Function to print the stringvoid printGrouped(string str){ int n = str.length(); // Initialize counts of all characters as 0 int count[MAX_CHAR] = {0}; // Count occurrences of all characters in string for (int i = 0 ; i < n ; i++) count[str[i]-'a']++; // Starts traversing the string for (int i = 0; i < n ; i++) { // Print the character till its count in // hash array while (count[str[i]-'a']--) cout << str[i]; // Make this character's count value as 0. count[str[i]-'a'] = 0; }} // Driver codeint main(){ string str = "geeksforgeeks"; printGrouped(str); return 0;} // Java program to print all occurrences of every character// together. class Test{ // Since only lower case characters are there static final int MAX_CHAR = 26; // Method to print the string static void printGrouped(String str) { int n = str.length(); // Initialize counts of all characters as 0 int count[] = new int[MAX_CHAR]; // Count occurrences of all characters in string for (int i = 0 ; i < n ; i++) count[str.charAt(i)-'a']++; // Starts traversing the string for (int i = 0; i < n ; i++) { // Print the character till its count in // hash array while (count[str.charAt(i)-'a']!=0){ System.out.print(str.charAt(i)); count[str.charAt(i)-'a']--; } // Make this character's count value as 0. count[str.charAt(i)-'a'] = 0; } } // Driver method public static void main(String args[]) { String str = new String("geeksforgeeks"); printGrouped(str); }} # Python3 program to print all occurrences# of every character together. # Since only lower case characters are thereMAX_CHAR = 26 # Function to print the stringdef printGrouped(string): n = len(string) # Initialize counts of all characters as 0 count = [0] * MAX_CHAR # Count occurrences of all characters in string for i in range(n): count[ord(string[i]) - ord("a")] += 1 # Starts traversing the string for i in range(n): # Print the character till its count in # hash array while count[ord(string[i]) - ord("a")]: print(string[i], end = "") count[ord(string[i]) - ord("a")] -= 1 # Make this character's count value as 0. count[ord(string[i]) - ord("a")] = 0 # Driver codeif __name__ == "__main__": string = "geeksforgeeks" printGrouped(string) # This code is contributed by# sanjeev2552 // C# program to print all // occurrences of every // character together.using System; class GFG{ // Since only lower case // characters are there static int MAX_CHAR = 26; // Method to print // the string static void printGrouped(String str) { int n = str.Length; // Initialize counts of // all characters as 0 int []count = new int[MAX_CHAR]; // Count occurrences of // all characters in string for (int i = 0 ; i < n ; i++) count[str[i] - 'a']++; // Starts traversing // the string for (int i = 0; i < n ; i++) { // Print the character // till its count in // hash array while (count[str[i] - 'a'] != 0) { Console.Write(str[i]); count[str[i] - 'a']--; } // Make this character's // count value as 0. count[str[i] - 'a'] = 0; } } // Driver code public static void Main() { string str = "geeksforgeeks"; printGrouped(str); }} // This code is contributed by Sam007 ggeeeekkssfor This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Sam007 sanjeev2552 Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check for Balanced Brackets in an expression (well-formedness) using Stack Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching Different methods to reverse a string in C/C++ Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++ Check whether two strings are anagram of each other Longest Palindromic Substring | Set 1 Caesar Cipher in Cryptography Top 50 String Coding Problems for Interviews
[ { "code": null, "e": 26519, "s": 26491, "text": "\n26 Aug, 2019" }, { "code": null, "e": 26698, "s": 26519, "text": "Given a string of lowercase characters, the task is to print the string in a manner such that a character comes first in string displays first with all its occurrences in string." }, { "code": null, "e": 26708, "s": 26698, "text": "Examples:" }, { "code": null, "e": 27043, "s": 26708, "text": "Input : str = \"geeksforgeeks\"\nOutput: ggeeeekkssfor\nExplanation: In the given string 'g' comes first \nand occurs 2 times so it is printed first\nThen 'e' comes in this string and 4 times so \nit gets printed. Similarly remaining string is\nprinted.\n\nInput : str = \"occurrence\"\noutput : occcurreen \n\nInput : str = \"cdab\"\nOutput : cdab\n" }, { "code": null, "e": 27120, "s": 27043, "text": "This problem is a string version of following problem for array of integers." }, { "code": null, "e": 27193, "s": 27120, "text": "Group multiple occurrence of array elements ordered by first occurrences" }, { "code": null, "e": 27286, "s": 27193, "text": "Since given strings have only 26 possible characters, it is easier to implement for strings." }, { "code": null, "e": 27465, "s": 27286, "text": "Implementation:1- Count the occurrence of all the characters in given string using an array of size 26.2- Then start traversing the string. Print every character its count times." }, { "code": null, "e": 27469, "s": 27465, "text": "C++" }, { "code": null, "e": 27474, "s": 27469, "text": "Java" }, { "code": null, "e": 27482, "s": 27474, "text": "Python3" }, { "code": null, "e": 27485, "s": 27482, "text": "C#" }, { "code": "// C++ program to print all occurrences of every character// together.# include<bits/stdc++.h>using namespace std; // Since only lower case characters are thereconst int MAX_CHAR = 26; // Function to print the stringvoid printGrouped(string str){ int n = str.length(); // Initialize counts of all characters as 0 int count[MAX_CHAR] = {0}; // Count occurrences of all characters in string for (int i = 0 ; i < n ; i++) count[str[i]-'a']++; // Starts traversing the string for (int i = 0; i < n ; i++) { // Print the character till its count in // hash array while (count[str[i]-'a']--) cout << str[i]; // Make this character's count value as 0. count[str[i]-'a'] = 0; }} // Driver codeint main(){ string str = \"geeksforgeeks\"; printGrouped(str); return 0;}", "e": 28347, "s": 27485, "text": null }, { "code": "// Java program to print all occurrences of every character// together. class Test{ // Since only lower case characters are there static final int MAX_CHAR = 26; // Method to print the string static void printGrouped(String str) { int n = str.length(); // Initialize counts of all characters as 0 int count[] = new int[MAX_CHAR]; // Count occurrences of all characters in string for (int i = 0 ; i < n ; i++) count[str.charAt(i)-'a']++; // Starts traversing the string for (int i = 0; i < n ; i++) { // Print the character till its count in // hash array while (count[str.charAt(i)-'a']!=0){ System.out.print(str.charAt(i)); count[str.charAt(i)-'a']--; } // Make this character's count value as 0. count[str.charAt(i)-'a'] = 0; } } // Driver method public static void main(String args[]) { String str = new String(\"geeksforgeeks\"); printGrouped(str); }}", "e": 29468, "s": 28347, "text": null }, { "code": "# Python3 program to print all occurrences# of every character together. # Since only lower case characters are thereMAX_CHAR = 26 # Function to print the stringdef printGrouped(string): n = len(string) # Initialize counts of all characters as 0 count = [0] * MAX_CHAR # Count occurrences of all characters in string for i in range(n): count[ord(string[i]) - ord(\"a\")] += 1 # Starts traversing the string for i in range(n): # Print the character till its count in # hash array while count[ord(string[i]) - ord(\"a\")]: print(string[i], end = \"\") count[ord(string[i]) - ord(\"a\")] -= 1 # Make this character's count value as 0. count[ord(string[i]) - ord(\"a\")] = 0 # Driver codeif __name__ == \"__main__\": string = \"geeksforgeeks\" printGrouped(string) # This code is contributed by# sanjeev2552", "e": 30363, "s": 29468, "text": null }, { "code": "// C# program to print all // occurrences of every // character together.using System; class GFG{ // Since only lower case // characters are there static int MAX_CHAR = 26; // Method to print // the string static void printGrouped(String str) { int n = str.Length; // Initialize counts of // all characters as 0 int []count = new int[MAX_CHAR]; // Count occurrences of // all characters in string for (int i = 0 ; i < n ; i++) count[str[i] - 'a']++; // Starts traversing // the string for (int i = 0; i < n ; i++) { // Print the character // till its count in // hash array while (count[str[i] - 'a'] != 0) { Console.Write(str[i]); count[str[i] - 'a']--; } // Make this character's // count value as 0. count[str[i] - 'a'] = 0; } } // Driver code public static void Main() { string str = \"geeksforgeeks\"; printGrouped(str); }} // This code is contributed by Sam007", "e": 31545, "s": 30363, "text": null }, { "code": null, "e": 31560, "s": 31545, "text": "ggeeeekkssfor\n" }, { "code": null, "e": 31861, "s": 31560, "text": "This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 31986, "s": 31861, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 31993, "s": 31986, "text": "Sam007" }, { "code": null, "e": 32005, "s": 31993, "text": "sanjeev2552" }, { "code": null, "e": 32013, "s": 32005, "text": "Strings" }, { "code": null, "e": 32021, "s": 32013, "text": "Strings" }, { "code": null, "e": 32119, "s": 32021, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32194, "s": 32119, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 32251, "s": 32194, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 32287, "s": 32251, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 32334, "s": 32287, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 32387, "s": 32334, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 32423, "s": 32387, "text": "Convert string to char array in C++" }, { "code": null, "e": 32475, "s": 32423, "text": "Check whether two strings are anagram of each other" }, { "code": null, "e": 32513, "s": 32475, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 32543, "s": 32513, "text": "Caesar Cipher in Cryptography" } ]
numpy.argpartition() in Python - GeeksforGeeks
28 Dec, 2018 numpy.argpartition() function is used to create a indirect partitioned copy of input array with its elements rearranged in such a way that the value of the element in k-th position is in the position it would be in a sorted array. All elements smaller than the k-th element are moved before this element and all equal or greater are moved behind it. The ordering of the elements in the two partitions is undefined.It returns an array of indices of the same shape as arr, i.e arr[index_array] yields a partition of arr. Syntax : numpy.argpartition(arr, kth, axis=-1, kind=’introselect’, order=None) Parameters :arr : [array_like] Input array.kth : [int or sequence of ints ] Element index to partition by.axis : [int or None] Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis.kind : Selection algorithm. Default is ‘introselect’.order : [str or list of str] When arr is an array with fields defined, this argument specifies which fields to compare first, second, etc. Return : [index_array, ndarray] Array of indices that partition arr along the specified axis. Code #1 : # Python program explaining# argpartition() function import numpy as geek # input arrayin_arr = geek.array([[ 2, 0, 1], [ 5, 4, 9] ])print ("Input array : \n", in_arr) out_arr = geek.argpartition(in_arr, 1, axis = 1)print ("Output partitioned array indices :\n ", out_arr) Input array : [[2 0 1] [5 4 9]] Output partitioned array indices : [[1 2 0] [1 0 2]] Code #2 : # Python program explaining# argpartition() function import numpy as geek # input arrayin_arr = geek.array([ 2, 0, 1, 5, 4, 3])print ("Input array : ", in_arr) out_arr = geek.argpartition(in_arr, (0, 2))print ("Output partitioned array indices: ", out_arr) Input array : [2 0 1 5 4 3] Output partitioned array indices: [1 2 0 3 4 5] Python numpy-Sorting Searching Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 Convert integer to string in Python
[ { "code": null, "e": 25373, "s": 25345, "text": "\n28 Dec, 2018" }, { "code": null, "e": 25892, "s": 25373, "text": "numpy.argpartition() function is used to create a indirect partitioned copy of input array with its elements rearranged in such a way that the value of the element in k-th position is in the position it would be in a sorted array. All elements smaller than the k-th element are moved before this element and all equal or greater are moved behind it. The ordering of the elements in the two partitions is undefined.It returns an array of indices of the same shape as arr, i.e arr[index_array] yields a partition of arr." }, { "code": null, "e": 25971, "s": 25892, "text": "Syntax : numpy.argpartition(arr, kth, axis=-1, kind=’introselect’, order=None)" }, { "code": null, "e": 26415, "s": 25971, "text": "Parameters :arr : [array_like] Input array.kth : [int or sequence of ints ] Element index to partition by.axis : [int or None] Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis.kind : Selection algorithm. Default is ‘introselect’.order : [str or list of str] When arr is an array with fields defined, this argument specifies which fields to compare first, second, etc." }, { "code": null, "e": 26509, "s": 26415, "text": "Return : [index_array, ndarray] Array of indices that partition arr along the specified axis." }, { "code": null, "e": 26519, "s": 26509, "text": "Code #1 :" }, { "code": "# Python program explaining# argpartition() function import numpy as geek # input arrayin_arr = geek.array([[ 2, 0, 1], [ 5, 4, 9] ])print (\"Input array : \\n\", in_arr) out_arr = geek.argpartition(in_arr, 1, axis = 1)print (\"Output partitioned array indices :\\n \", out_arr)", "e": 26798, "s": 26519, "text": null }, { "code": null, "e": 26890, "s": 26798, "text": "Input array : \n [[2 0 1]\n [5 4 9]]\nOutput partitioned array indices :\n [[1 2 0]\n [1 0 2]]\n" }, { "code": null, "e": 26901, "s": 26890, "text": " Code #2 :" }, { "code": "# Python program explaining# argpartition() function import numpy as geek # input arrayin_arr = geek.array([ 2, 0, 1, 5, 4, 3])print (\"Input array : \", in_arr) out_arr = geek.argpartition(in_arr, (0, 2))print (\"Output partitioned array indices: \", out_arr)", "e": 27164, "s": 26901, "text": null }, { "code": null, "e": 27243, "s": 27164, "text": "Input array : [2 0 1 5 4 3]\nOutput partitioned array indices: [1 2 0 3 4 5]\n" }, { "code": null, "e": 27274, "s": 27243, "text": "Python numpy-Sorting Searching" }, { "code": null, "e": 27281, "s": 27274, "text": "Python" }, { "code": null, "e": 27379, "s": 27281, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27414, "s": 27379, "text": "Read a file line by line in Python" }, { "code": null, "e": 27446, "s": 27414, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27468, "s": 27446, "text": "Enumerate() in Python" }, { "code": null, "e": 27510, "s": 27468, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27540, "s": 27510, "text": "Iterate over a list in Python" }, { "code": null, "e": 27566, "s": 27540, "text": "Python String | replace()" }, { "code": null, "e": 27595, "s": 27566, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27639, "s": 27595, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27676, "s": 27639, "text": "Create a Pandas DataFrame from Lists" } ]
Kruskal's Minimum Spanning Tree using STL in C++ - GeeksforGeeks
11 Nov, 2021 Given an undirected, connected and weighted graph, find Minimum Spanning Tree (MST) of the graph using Kruskal’s algorithm. Input : Graph as an array of edges Output : Edges of MST are 6 - 7 2 - 8 5 - 6 0 - 1 2 - 5 2 - 3 0 - 7 3 - 4 Weight of MST is 37 Note : There are two possible MSTs, the other MST includes edge 1-2 in place of 0-7. We have discussed below Kruskal’s MST implementations. Greedy Algorithms | Set 2 (Kruskal’s Minimum Spanning Tree Algorithm) Below are the steps for finding MST using Kruskal’s algorithm Sort all the edges in non-decreasing order of their weight.Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If cycle is not formed, include this edge. Else, discard it.Repeat step#2 until there are (V-1) edges in the spanning tree. Sort all the edges in non-decreasing order of their weight. Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If cycle is not formed, include this edge. Else, discard it. Repeat step#2 until there are (V-1) edges in the spanning tree. Here are some key points which will be useful for us in implementing the Kruskal’s algorithm using STL. Use a vector of edges which consist of all the edges in the graph and each item of a vector will contain 3 parameters: source, destination and the cost of an edge between the source and destination. vector<pair<int, pair<int, int> > > edges;Here in the outer pair (i.e pair<int,pair<int,int> > ) the first element corresponds to the cost of a edge while the second element is itself a pair, and it contains two vertices of edge.Use the inbuilt std::sort to sort the edges in the non-decreasing order; by default the sort function sort in non-decreasing order.We use the Union Find Algorithm to check if it the current edge forms a cycle if it is added in the current MST. If yes discard it, else include it (union). Use a vector of edges which consist of all the edges in the graph and each item of a vector will contain 3 parameters: source, destination and the cost of an edge between the source and destination. vector<pair<int, pair<int, int> > > edges;Here in the outer pair (i.e pair<int,pair<int,int> > ) the first element corresponds to the cost of a edge while the second element is itself a pair, and it contains two vertices of edge. vector<pair<int, pair<int, int> > > edges; Here in the outer pair (i.e pair<int,pair<int,int> > ) the first element corresponds to the cost of a edge while the second element is itself a pair, and it contains two vertices of edge. Use the inbuilt std::sort to sort the edges in the non-decreasing order; by default the sort function sort in non-decreasing order. We use the Union Find Algorithm to check if it the current edge forms a cycle if it is added in the current MST. If yes discard it, else include it (union). Pseudo Code: // Initialize result mst_weight = 0 // Create V single item sets for each vertex v parent[v] = v; rank[v] = 0; Sort all edges into non decreasing order by weight w for each (u, v) taken from the sorted list E do if FIND-SET(u) != FIND-SET(v) print edge(u, v) mst_weight += weight of edge(u, v) UNION(u, v) Below is C++ implementation of above algorithm. // C++ program for Kruskal's algorithm to find Minimum// Spanning Tree of a given connected, undirected and// weighted graph#include<bits/stdc++.h>using namespace std; // Creating shortcut for an integer pairtypedef pair<int, int> iPair; // Structure to represent a graphstruct Graph{ int V, E; vector< pair<int, iPair> > edges; // Constructor Graph(int V, int E) { this->V = V; this->E = E; } // Utility function to add an edge void addEdge(int u, int v, int w) { edges.push_back({w, {u, v}}); } // Function to find MST using Kruskal's // MST algorithm int kruskalMST();}; // To represent Disjoint Setsstruct DisjointSets{ int *parent, *rnk; int n; // Constructor. DisjointSets(int n) { // Allocate memory this->n = n; parent = new int[n+1]; rnk = new int[n+1]; // Initially, all vertices are in // different sets and have rank 0. for (int i = 0; i <= n; i++) { rnk[i] = 0; //every element is parent of itself parent[i] = i; } } // Find the parent of a node 'u' // Path Compression int find(int u) { /* Make the parent of the nodes in the path from u--> parent[u] point to parent[u] */ if (u != parent[u]) parent[u] = find(parent[u]); return parent[u]; } // Union by rank void merge(int x, int y) { x = find(x), y = find(y); /* Make tree with smaller height a subtree of the other tree */ if (rnk[x] > rnk[y]) parent[y] = x; else // If rnk[x] <= rnk[y] parent[x] = y; if (rnk[x] == rnk[y]) rnk[y]++; }}; /* Functions returns weight of the MST*/ int Graph::kruskalMST(){ int mst_wt = 0; // Initialize result // Sort edges in increasing order on basis of cost sort(edges.begin(), edges.end()); // Create disjoint sets DisjointSets ds(V); // Iterate through all sorted edges vector< pair<int, iPair> >::iterator it; for (it=edges.begin(); it!=edges.end(); it++) { int u = it->second.first; int v = it->second.second; int set_u = ds.find(u); int set_v = ds.find(v); // Check if the selected edge is creating // a cycle or not (Cycle is created if u // and v belong to same set) if (set_u != set_v) { // Current edge will be in the MST // so print it cout << u << " - " << v << endl; // Update MST weight mst_wt += it->first; // Merge two sets ds.merge(set_u, set_v); } } return mst_wt;} // Driver program to test above functionsint main(){ /* Let us create above shown weighted and undirected graph */ int V = 9, E = 14; Graph g(V, E); // making above shown graph g.addEdge(0, 1, 4); g.addEdge(0, 7, 8); g.addEdge(1, 2, 8); g.addEdge(1, 7, 11); g.addEdge(2, 3, 7); g.addEdge(2, 8, 2); g.addEdge(2, 5, 4); g.addEdge(3, 4, 9); g.addEdge(3, 5, 14); g.addEdge(4, 5, 10); g.addEdge(5, 6, 2); g.addEdge(6, 7, 1); g.addEdge(6, 8, 6); g.addEdge(7, 8, 7); cout << "Edges of MST are \n"; int mst_wt = g.kruskalMST(); cout << "\nWeight of MST is " << mst_wt; return 0;} Output : Edges of MST are 6 - 7 2 - 8 5 - 6 0 - 1 2 - 5 2 - 3 0 - 7 3 - 4 Weight of MST is 37 Optimization:The above code can be optimized to stop the main loop of Kruskal when number of selected edges become V-1. We know that MST has V-1 edges and there is no point iterating after V-1 edges are selected. We have not added this optimization to keep code simple. References:Introduction to Algorithms by Cormen Leiserson Rivest and Stein(CLRS) 3 Time complexity and step by step illustration are discussed in previous post on Kruskal’s algorithm. This article is contributed by Chirag Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above varshagumber28 MST STL union-find Graph Graph STL union-find Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Longest Path in a Directed Acyclic Graph Best First Search (Informed Search) Graph Coloring | Set 2 (Greedy Algorithm) Maximum Bipartite Matching Graph Coloring | Set 1 (Introduction and Applications) Find if there is a path between two vertices in a directed graph Find minimum s-t cut in a flow network Eulerian path and circuit for undirected graph Real-time application of Data Structures Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)
[ { "code": null, "e": 26337, "s": 26309, "text": "\n11 Nov, 2021" }, { "code": null, "e": 26461, "s": 26337, "text": "Given an undirected, connected and weighted graph, find Minimum Spanning Tree (MST) of the graph using Kruskal’s algorithm." }, { "code": null, "e": 26794, "s": 26461, "text": "\n\nInput : Graph as an array of edges\nOutput : Edges of MST are \n 6 - 7\n 2 - 8\n 5 - 6\n 0 - 1\n 2 - 5\n 2 - 3\n 0 - 7\n 3 - 4\n \n Weight of MST is 37\n\nNote : There are two possible MSTs, the other\n MST includes edge 1-2 in place of 0-7. \n" }, { "code": null, "e": 26849, "s": 26794, "text": "We have discussed below Kruskal’s MST implementations." }, { "code": null, "e": 26919, "s": 26849, "text": "Greedy Algorithms | Set 2 (Kruskal’s Minimum Spanning Tree Algorithm)" }, { "code": null, "e": 26981, "s": 26919, "text": "Below are the steps for finding MST using Kruskal’s algorithm" }, { "code": null, "e": 27252, "s": 26981, "text": "Sort all the edges in non-decreasing order of their weight.Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If cycle is not formed, include this edge. Else, discard it.Repeat step#2 until there are (V-1) edges in the spanning tree." }, { "code": null, "e": 27312, "s": 27252, "text": "Sort all the edges in non-decreasing order of their weight." }, { "code": null, "e": 27461, "s": 27312, "text": "Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If cycle is not formed, include this edge. Else, discard it." }, { "code": null, "e": 27525, "s": 27461, "text": "Repeat step#2 until there are (V-1) edges in the spanning tree." }, { "code": null, "e": 27629, "s": 27525, "text": "Here are some key points which will be useful for us in implementing the Kruskal’s algorithm using STL." }, { "code": null, "e": 28352, "s": 27629, "text": "Use a vector of edges which consist of all the edges in the graph and each item of a vector will contain 3 parameters: source, destination and the cost of an edge between the source and destination. vector<pair<int, pair<int, int> > > edges;Here in the outer pair (i.e pair<int,pair<int,int> > ) the first element corresponds to the cost of a edge while the second element is itself a pair, and it contains two vertices of edge.Use the inbuilt std::sort to sort the edges in the non-decreasing order; by default the sort function sort in non-decreasing order.We use the Union Find Algorithm to check if it the current edge forms a cycle if it is added in the current MST. If yes discard it, else include it (union)." }, { "code": null, "e": 28788, "s": 28352, "text": "Use a vector of edges which consist of all the edges in the graph and each item of a vector will contain 3 parameters: source, destination and the cost of an edge between the source and destination. vector<pair<int, pair<int, int> > > edges;Here in the outer pair (i.e pair<int,pair<int,int> > ) the first element corresponds to the cost of a edge while the second element is itself a pair, and it contains two vertices of edge." }, { "code": null, "e": 28839, "s": 28788, "text": " vector<pair<int, pair<int, int> > > edges;" }, { "code": null, "e": 29027, "s": 28839, "text": "Here in the outer pair (i.e pair<int,pair<int,int> > ) the first element corresponds to the cost of a edge while the second element is itself a pair, and it contains two vertices of edge." }, { "code": null, "e": 29159, "s": 29027, "text": "Use the inbuilt std::sort to sort the edges in the non-decreasing order; by default the sort function sort in non-decreasing order." }, { "code": null, "e": 29316, "s": 29159, "text": "We use the Union Find Algorithm to check if it the current edge forms a cycle if it is added in the current MST. If yes discard it, else include it (union)." }, { "code": null, "e": 29329, "s": 29316, "text": "Pseudo Code:" }, { "code": null, "e": 29677, "s": 29329, "text": "// Initialize result\nmst_weight = 0\n\n// Create V single item sets\nfor each vertex v\n parent[v] = v;\n rank[v] = 0;\n\nSort all edges into non decreasing \norder by weight w\n\nfor each (u, v) taken from the sorted list E\n do if FIND-SET(u) != FIND-SET(v)\n print edge(u, v)\n mst_weight += weight of edge(u, v)\n UNION(u, v)\n" }, { "code": null, "e": 29725, "s": 29677, "text": "Below is C++ implementation of above algorithm." }, { "code": "// C++ program for Kruskal's algorithm to find Minimum// Spanning Tree of a given connected, undirected and// weighted graph#include<bits/stdc++.h>using namespace std; // Creating shortcut for an integer pairtypedef pair<int, int> iPair; // Structure to represent a graphstruct Graph{ int V, E; vector< pair<int, iPair> > edges; // Constructor Graph(int V, int E) { this->V = V; this->E = E; } // Utility function to add an edge void addEdge(int u, int v, int w) { edges.push_back({w, {u, v}}); } // Function to find MST using Kruskal's // MST algorithm int kruskalMST();}; // To represent Disjoint Setsstruct DisjointSets{ int *parent, *rnk; int n; // Constructor. DisjointSets(int n) { // Allocate memory this->n = n; parent = new int[n+1]; rnk = new int[n+1]; // Initially, all vertices are in // different sets and have rank 0. for (int i = 0; i <= n; i++) { rnk[i] = 0; //every element is parent of itself parent[i] = i; } } // Find the parent of a node 'u' // Path Compression int find(int u) { /* Make the parent of the nodes in the path from u--> parent[u] point to parent[u] */ if (u != parent[u]) parent[u] = find(parent[u]); return parent[u]; } // Union by rank void merge(int x, int y) { x = find(x), y = find(y); /* Make tree with smaller height a subtree of the other tree */ if (rnk[x] > rnk[y]) parent[y] = x; else // If rnk[x] <= rnk[y] parent[x] = y; if (rnk[x] == rnk[y]) rnk[y]++; }}; /* Functions returns weight of the MST*/ int Graph::kruskalMST(){ int mst_wt = 0; // Initialize result // Sort edges in increasing order on basis of cost sort(edges.begin(), edges.end()); // Create disjoint sets DisjointSets ds(V); // Iterate through all sorted edges vector< pair<int, iPair> >::iterator it; for (it=edges.begin(); it!=edges.end(); it++) { int u = it->second.first; int v = it->second.second; int set_u = ds.find(u); int set_v = ds.find(v); // Check if the selected edge is creating // a cycle or not (Cycle is created if u // and v belong to same set) if (set_u != set_v) { // Current edge will be in the MST // so print it cout << u << \" - \" << v << endl; // Update MST weight mst_wt += it->first; // Merge two sets ds.merge(set_u, set_v); } } return mst_wt;} // Driver program to test above functionsint main(){ /* Let us create above shown weighted and undirected graph */ int V = 9, E = 14; Graph g(V, E); // making above shown graph g.addEdge(0, 1, 4); g.addEdge(0, 7, 8); g.addEdge(1, 2, 8); g.addEdge(1, 7, 11); g.addEdge(2, 3, 7); g.addEdge(2, 8, 2); g.addEdge(2, 5, 4); g.addEdge(3, 4, 9); g.addEdge(3, 5, 14); g.addEdge(4, 5, 10); g.addEdge(5, 6, 2); g.addEdge(6, 7, 1); g.addEdge(6, 8, 6); g.addEdge(7, 8, 7); cout << \"Edges of MST are \\n\"; int mst_wt = g.kruskalMST(); cout << \"\\nWeight of MST is \" << mst_wt; return 0;}", "e": 33109, "s": 29725, "text": null }, { "code": null, "e": 33118, "s": 33109, "text": "Output :" }, { "code": null, "e": 33306, "s": 33118, "text": " Edges of MST are \n 6 - 7\n 2 - 8\n 5 - 6\n 0 - 1\n 2 - 5\n 2 - 3\n 0 - 7\n 3 - 4\n \n Weight of MST is 37" }, { "code": null, "e": 33576, "s": 33306, "text": "Optimization:The above code can be optimized to stop the main loop of Kruskal when number of selected edges become V-1. We know that MST has V-1 edges and there is no point iterating after V-1 edges are selected. We have not added this optimization to keep code simple." }, { "code": null, "e": 33659, "s": 33576, "text": "References:Introduction to Algorithms by Cormen Leiserson Rivest and Stein(CLRS) 3" }, { "code": null, "e": 33760, "s": 33659, "text": "Time complexity and step by step illustration are discussed in previous post on Kruskal’s algorithm." }, { "code": null, "e": 34029, "s": 33760, "text": "This article is contributed by Chirag Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 34153, "s": 34029, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 34168, "s": 34153, "text": "varshagumber28" }, { "code": null, "e": 34172, "s": 34168, "text": "MST" }, { "code": null, "e": 34176, "s": 34172, "text": "STL" }, { "code": null, "e": 34187, "s": 34176, "text": "union-find" }, { "code": null, "e": 34193, "s": 34187, "text": "Graph" }, { "code": null, "e": 34199, "s": 34193, "text": "Graph" }, { "code": null, "e": 34203, "s": 34199, "text": "STL" }, { "code": null, "e": 34214, "s": 34203, "text": "union-find" }, { "code": null, "e": 34312, "s": 34214, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34353, "s": 34312, "text": "Longest Path in a Directed Acyclic Graph" }, { "code": null, "e": 34389, "s": 34353, "text": "Best First Search (Informed Search)" }, { "code": null, "e": 34431, "s": 34389, "text": "Graph Coloring | Set 2 (Greedy Algorithm)" }, { "code": null, "e": 34458, "s": 34431, "text": "Maximum Bipartite Matching" }, { "code": null, "e": 34513, "s": 34458, "text": "Graph Coloring | Set 1 (Introduction and Applications)" }, { "code": null, "e": 34578, "s": 34513, "text": "Find if there is a path between two vertices in a directed graph" }, { "code": null, "e": 34617, "s": 34578, "text": "Find minimum s-t cut in a flow network" }, { "code": null, "e": 34664, "s": 34617, "text": "Eulerian path and circuit for undirected graph" }, { "code": null, "e": 34705, "s": 34664, "text": "Real-time application of Data Structures" } ]
Reorder Facets in ggplot2 Plot in R - GeeksforGeeks
31 Aug, 2021 In this article, we will be looking at an approach to reorder the facets in the ggplot2 plot in R programming language. To reorder the facets accordingly of the given ggplot2 plot, the user needs to reorder the levels of our grouping variable accordingly with the help of the levels function and required parameter passed into it, further it will lead to the reordering of the facets accordingly in the R programming language. Level function provides access to the levels attribute of a variable. The first form returns the value of the levels of its argument and the second sets the attribute. Syntax: levels(x) Parameters: x: an object, for example, a factor. Let us first look at the initial plot. so that the difference after reordering can be observed prominently. Example: initial plot R library(ggplot2) gfg < - data.frame(x=c(4, 9, 5, 6, 10, 2, 3, 7, 8, 1), y=c(9, 4, 3, 1, 5, 2, 8, 10, 7, 6), group=c('A', 'B', 'C', 'D', 'E')) gfg_plot < - ggplot(gfg, aes(x, y)) +geom_point() + facet_grid(.~group) gfg_plot Output: Now let’s reorder facets using the levels function. Example: Plot after reordering of facets R library(ggplot2) gfg < - data.frame(x=c(4, 9, 5, 6, 10, 2, 3, 7, 8, 1), y=c(9, 4, 3, 1, 5, 2, 8, 10, 7, 6), group=c('A', 'B', 'C', 'D', 'E')) gfg$group < - factor(gfg$group, levels=c("E", "B", "A", "C", "D")) gfg_plot < - ggplot(gfg, aes(x, y)) + geom_point() +facet_grid(.~group) gfg_plot Output: Example: In this example, we will be using a set of 10 data points for the ggplot2 bar plot and will be reordering the facets of this bar plot accordingly with the help of the level function. R library(ggplot2) gfg < - data.frame(x=c(4, 9, 5, 6, 10, 2, 3, 7, 8, 1), y=c(9, 4, 3, 1, 5, 2, 8, 10, 7, 6), group=c('A', 'B', 'C', 'D', 'E')) gfg$group < - factor(gfg$group, levels=c("C", "E", "B", "A", "D")) gfg_plot < - ggplot(gfg, aes(x, y)) + geom_bar(stat="identity") +facet_grid(.~group) gfg_plot Output: Picked R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to import an Excel File into R ? How to filter R DataFrame by values in a column? Time Series Analysis in R R - if statement Logistic Regression in R Programming
[ { "code": null, "e": 26487, "s": 26459, "text": "\n31 Aug, 2021" }, { "code": null, "e": 26607, "s": 26487, "text": "In this article, we will be looking at an approach to reorder the facets in the ggplot2 plot in R programming language." }, { "code": null, "e": 26914, "s": 26607, "text": "To reorder the facets accordingly of the given ggplot2 plot, the user needs to reorder the levels of our grouping variable accordingly with the help of the levels function and required parameter passed into it, further it will lead to the reordering of the facets accordingly in the R programming language." }, { "code": null, "e": 27082, "s": 26914, "text": "Level function provides access to the levels attribute of a variable. The first form returns the value of the levels of its argument and the second sets the attribute." }, { "code": null, "e": 27090, "s": 27082, "text": "Syntax:" }, { "code": null, "e": 27100, "s": 27090, "text": "levels(x)" }, { "code": null, "e": 27112, "s": 27100, "text": "Parameters:" }, { "code": null, "e": 27149, "s": 27112, "text": "x: an object, for example, a factor." }, { "code": null, "e": 27257, "s": 27149, "text": "Let us first look at the initial plot. so that the difference after reordering can be observed prominently." }, { "code": null, "e": 27279, "s": 27257, "text": "Example: initial plot" }, { "code": null, "e": 27281, "s": 27279, "text": "R" }, { "code": "library(ggplot2) gfg < - data.frame(x=c(4, 9, 5, 6, 10, 2, 3, 7, 8, 1), y=c(9, 4, 3, 1, 5, 2, 8, 10, 7, 6), group=c('A', 'B', 'C', 'D', 'E')) gfg_plot < - ggplot(gfg, aes(x, y)) +geom_point() + facet_grid(.~group) gfg_plot", "e": 27543, "s": 27281, "text": null }, { "code": null, "e": 27551, "s": 27543, "text": "Output:" }, { "code": null, "e": 27603, "s": 27551, "text": "Now let’s reorder facets using the levels function." }, { "code": null, "e": 27644, "s": 27603, "text": "Example: Plot after reordering of facets" }, { "code": null, "e": 27646, "s": 27644, "text": "R" }, { "code": "library(ggplot2) gfg < - data.frame(x=c(4, 9, 5, 6, 10, 2, 3, 7, 8, 1), y=c(9, 4, 3, 1, 5, 2, 8, 10, 7, 6), group=c('A', 'B', 'C', 'D', 'E')) gfg$group < - factor(gfg$group, levels=c(\"E\", \"B\", \"A\", \"C\", \"D\")) gfg_plot < - ggplot(gfg, aes(x, y)) + geom_point() +facet_grid(.~group) gfg_plot", "e": 27976, "s": 27646, "text": null }, { "code": null, "e": 27984, "s": 27976, "text": "Output:" }, { "code": null, "e": 28176, "s": 27984, "text": "Example: In this example, we will be using a set of 10 data points for the ggplot2 bar plot and will be reordering the facets of this bar plot accordingly with the help of the level function." }, { "code": null, "e": 28178, "s": 28176, "text": "R" }, { "code": "library(ggplot2) gfg < - data.frame(x=c(4, 9, 5, 6, 10, 2, 3, 7, 8, 1), y=c(9, 4, 3, 1, 5, 2, 8, 10, 7, 6), group=c('A', 'B', 'C', 'D', 'E')) gfg$group < - factor(gfg$group, levels=c(\"C\", \"E\", \"B\", \"A\", \"D\")) gfg_plot < - ggplot(gfg, aes(x, y)) + geom_bar(stat=\"identity\") +facet_grid(.~group) gfg_plot", "e": 28521, "s": 28178, "text": null }, { "code": null, "e": 28529, "s": 28521, "text": "Output:" }, { "code": null, "e": 28536, "s": 28529, "text": "Picked" }, { "code": null, "e": 28545, "s": 28536, "text": "R-ggplot" }, { "code": null, "e": 28556, "s": 28545, "text": "R Language" }, { "code": null, "e": 28654, "s": 28556, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28706, "s": 28654, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28741, "s": 28706, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28779, "s": 28741, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 28837, "s": 28779, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28880, "s": 28837, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 28917, "s": 28880, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 28966, "s": 28917, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28992, "s": 28966, "text": "Time Series Analysis in R" }, { "code": null, "e": 29009, "s": 28992, "text": "R - if statement" } ]
Longest Common Prefix using Sorting - GeeksforGeeks
27 Apr, 2021 Problem Statement: Given a set of strings, find the longest common prefix.Examples: Input: {"geeksforgeeks", "geeks", "geek", "geezer"} Output: "gee" Input: {"apple", "ape", "april"} Output: "ap" The longest common prefix for an array of strings is the common prefix between 2 most dissimilar strings. For example, in the given array {“apple”, “ape”, “zebra”}, there is no common prefix because the 2 most dissimilar strings of the array “ape” and “zebra” do not share any starting characters. We have discussed five different approaches in below posts. Word by Word MatchingCharacter by Character MatchingDivide and ConquerBinary Search.Using Trie) Word by Word Matching Character by Character Matching Divide and Conquer Binary Search. Using Trie) In this post a new method based on sorting is discussed. The idea is to sort the array of strings and find the common prefix of the first and last string of the sorted array. C++ Java Python 3 C# Javascript // C++ program to find longest common prefix// of given array of words.#include<iostream>#include<algorithm> using namespace std; // Function to find the longest common prefixstring longestCommonPrefix(string ar[], int n){ // If size is 0, return empty string if (n == 0) return ""; if (n == 1) return ar[0]; // Sort the given array sort(ar, ar + n); // Find the minimum length from // first and last string int en = min(ar[0].size(), ar[n - 1].size()); // Now the common prefix in first and // last string is the longest common prefix string first = ar[0], last = ar[n - 1]; int i = 0; while (i < en && first[i] == last[i]) i++; string pre = first.substr(0, i); return pre;} // Driver Codeint main(){ string ar[] = {"geeksforgeeks", "geeks", "geek", "geezer"}; int n = sizeof(ar) / sizeof(ar[0]); cout << "The longest common prefix is: " << longestCommonPrefix(ar, n); return 0;} // This code is contributed by jrolofmeister // Java program to find longest common prefix of// given array of words.import java.util.*; public class GFG{ public String longestCommonPrefix(String[] a) { int size = a.length; /* if size is 0, return empty string */ if (size == 0) return ""; if (size == 1) return a[0]; /* sort the array of strings */ Arrays.sort(a); /* find the minimum length from first and last string */ int end = Math.min(a[0].length(), a[size-1].length()); /* find the common prefix between the first and last string */ int i = 0; while (i < end && a[0].charAt(i) == a[size-1].charAt(i) ) i++; String pre = a[0].substring(0, i); return pre; } /* Driver Function to test other function */ public static void main(String[] args) { GFG gfg = new GFG(); String[] input = {"geeksforgeeks", "geeks", "geek", "geezer"}; System.out.println( "The longest Common Prefix is : " + gfg.longestCommonPrefix(input)); }} # Python 3 program to find longest# common prefix of given array of words.def longestCommonPrefix( a): size = len(a) # if size is 0, return empty string if (size == 0): return "" if (size == 1): return a[0] # sort the array of strings a.sort() # find the minimum length from # first and last string end = min(len(a[0]), len(a[size - 1])) # find the common prefix between # the first and last string i = 0 while (i < end and a[0][i] == a[size - 1][i]): i += 1 pre = a[0][0: i] return pre # Driver Codeif __name__ == "__main__": input = ["geeksforgeeks", "geeks", "geek", "geezer"] print("The longest Common Prefix is :" , longestCommonPrefix(input)) # This code is contributed by ita_c // C# program to find longest common prefix of// given array of words.using System; public class GFG { static string longestCommonPrefix(String[] a) { int size = a.Length; /* if size is 0, return empty string */ if (size == 0) return ""; if (size == 1) return a[0]; /* sort the array of strings */ Array.Sort(a); /* find the minimum length from first and last string */ int end = Math.Min(a[0].Length, a[size-1].Length); /* find the common prefix between the first and last string */ int i = 0; while (i < end && a[0][i] == a[size-1][i] ) i++; string pre = a[0].Substring(0, i); return pre; } /* Driver Function to test other function */ public static void Main() { string[] input = {"geeksforgeeks", "geeks", "geek", "geezer"}; Console.WriteLine( "The longest Common" + " Prefix is : " + longestCommonPrefix(input)); }} // This code is contributed by Sam007. <script>// Javascript program to find longest common prefix of// given array of words. function longestCommonPrefix(a) { let size = a.length; /* if size is 0, return empty string */ if (size == 0) return ""; if (size == 1) return a[0]; /* sort the array of strings */ a.sort(); /* find the minimum length from first and last string */ let end = Math.min(a[0].length, a[size-1].length); /* find the common prefix between the first and last string */ let i = 0; while (i < end && a[0][i] == a[size-1][i] ) i++; let pre = a[0].substring(0, i); return pre; } /* Driver Function to test other function */ let input=["geeksforgeeks", "geeks", "geek", "geezer"]; document.write( "The longest Common Prefix is : " + longestCommonPrefix(input)); // This code is contributed by rag2127</script> Output: The longest common prefix is : gee Time Complexity: O(MAX * n * log n ) where n is the number of strings in the array and MAX is maximum number of characters in any string. Please note that comparison of two strings would take at most O(MAX) time and for sorting n strings, we would need O(MAX * n * log n ) time.This article is contributed by Saloni Baweja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Sam007 ukasp jrolofmeister nidhi_biet rag2127 Longest Common Prefix Sorting Strings Strings Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. HeapSort std::sort() in C++ STL Time Complexities of all Sorting Algorithms Radix Sort Merge two sorted arrays Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Longest Common Subsequence | DP-4
[ { "code": null, "e": 25833, "s": 25805, "text": "\n27 Apr, 2021" }, { "code": null, "e": 25919, "s": 25833, "text": "Problem Statement: Given a set of strings, find the longest common prefix.Examples: " }, { "code": null, "e": 26032, "s": 25919, "text": "Input: {\"geeksforgeeks\", \"geeks\", \"geek\", \"geezer\"}\nOutput: \"gee\"\n\nInput: {\"apple\", \"ape\", \"april\"}\nOutput: \"ap\"" }, { "code": null, "e": 26394, "s": 26034, "text": "The longest common prefix for an array of strings is the common prefix between 2 most dissimilar strings. For example, in the given array {“apple”, “ape”, “zebra”}, there is no common prefix because the 2 most dissimilar strings of the array “ape” and “zebra” do not share any starting characters. We have discussed five different approaches in below posts. " }, { "code": null, "e": 26490, "s": 26394, "text": "Word by Word MatchingCharacter by Character MatchingDivide and ConquerBinary Search.Using Trie)" }, { "code": null, "e": 26512, "s": 26490, "text": "Word by Word Matching" }, { "code": null, "e": 26544, "s": 26512, "text": "Character by Character Matching" }, { "code": null, "e": 26563, "s": 26544, "text": "Divide and Conquer" }, { "code": null, "e": 26578, "s": 26563, "text": "Binary Search." }, { "code": null, "e": 26590, "s": 26578, "text": "Using Trie)" }, { "code": null, "e": 26768, "s": 26592, "text": "In this post a new method based on sorting is discussed. The idea is to sort the array of strings and find the common prefix of the first and last string of the sorted array. " }, { "code": null, "e": 26772, "s": 26768, "text": "C++" }, { "code": null, "e": 26777, "s": 26772, "text": "Java" }, { "code": null, "e": 26786, "s": 26777, "text": "Python 3" }, { "code": null, "e": 26789, "s": 26786, "text": "C#" }, { "code": null, "e": 26800, "s": 26789, "text": "Javascript" }, { "code": "// C++ program to find longest common prefix// of given array of words.#include<iostream>#include<algorithm> using namespace std; // Function to find the longest common prefixstring longestCommonPrefix(string ar[], int n){ // If size is 0, return empty string if (n == 0) return \"\"; if (n == 1) return ar[0]; // Sort the given array sort(ar, ar + n); // Find the minimum length from // first and last string int en = min(ar[0].size(), ar[n - 1].size()); // Now the common prefix in first and // last string is the longest common prefix string first = ar[0], last = ar[n - 1]; int i = 0; while (i < en && first[i] == last[i]) i++; string pre = first.substr(0, i); return pre;} // Driver Codeint main(){ string ar[] = {\"geeksforgeeks\", \"geeks\", \"geek\", \"geezer\"}; int n = sizeof(ar) / sizeof(ar[0]); cout << \"The longest common prefix is: \" << longestCommonPrefix(ar, n); return 0;} // This code is contributed by jrolofmeister", "e": 27860, "s": 26800, "text": null }, { "code": "// Java program to find longest common prefix of// given array of words.import java.util.*; public class GFG{ public String longestCommonPrefix(String[] a) { int size = a.length; /* if size is 0, return empty string */ if (size == 0) return \"\"; if (size == 1) return a[0]; /* sort the array of strings */ Arrays.sort(a); /* find the minimum length from first and last string */ int end = Math.min(a[0].length(), a[size-1].length()); /* find the common prefix between the first and last string */ int i = 0; while (i < end && a[0].charAt(i) == a[size-1].charAt(i) ) i++; String pre = a[0].substring(0, i); return pre; } /* Driver Function to test other function */ public static void main(String[] args) { GFG gfg = new GFG(); String[] input = {\"geeksforgeeks\", \"geeks\", \"geek\", \"geezer\"}; System.out.println( \"The longest Common Prefix is : \" + gfg.longestCommonPrefix(input)); }}", "e": 28958, "s": 27860, "text": null }, { "code": "# Python 3 program to find longest# common prefix of given array of words.def longestCommonPrefix( a): size = len(a) # if size is 0, return empty string if (size == 0): return \"\" if (size == 1): return a[0] # sort the array of strings a.sort() # find the minimum length from # first and last string end = min(len(a[0]), len(a[size - 1])) # find the common prefix between # the first and last string i = 0 while (i < end and a[0][i] == a[size - 1][i]): i += 1 pre = a[0][0: i] return pre # Driver Codeif __name__ == \"__main__\": input = [\"geeksforgeeks\", \"geeks\", \"geek\", \"geezer\"] print(\"The longest Common Prefix is :\" , longestCommonPrefix(input)) # This code is contributed by ita_c", "e": 29777, "s": 28958, "text": null }, { "code": "// C# program to find longest common prefix of// given array of words.using System; public class GFG { static string longestCommonPrefix(String[] a) { int size = a.Length; /* if size is 0, return empty string */ if (size == 0) return \"\"; if (size == 1) return a[0]; /* sort the array of strings */ Array.Sort(a); /* find the minimum length from first and last string */ int end = Math.Min(a[0].Length, a[size-1].Length); /* find the common prefix between the first and last string */ int i = 0; while (i < end && a[0][i] == a[size-1][i] ) i++; string pre = a[0].Substring(0, i); return pre; } /* Driver Function to test other function */ public static void Main() { string[] input = {\"geeksforgeeks\", \"geeks\", \"geek\", \"geezer\"}; Console.WriteLine( \"The longest Common\" + \" Prefix is : \" + longestCommonPrefix(input)); }} // This code is contributed by Sam007.", "e": 30978, "s": 29777, "text": null }, { "code": "<script>// Javascript program to find longest common prefix of// given array of words. function longestCommonPrefix(a) { let size = a.length; /* if size is 0, return empty string */ if (size == 0) return \"\"; if (size == 1) return a[0]; /* sort the array of strings */ a.sort(); /* find the minimum length from first and last string */ let end = Math.min(a[0].length, a[size-1].length); /* find the common prefix between the first and last string */ let i = 0; while (i < end && a[0][i] == a[size-1][i] ) i++; let pre = a[0].substring(0, i); return pre; } /* Driver Function to test other function */ let input=[\"geeksforgeeks\", \"geeks\", \"geek\", \"geezer\"]; document.write( \"The longest Common Prefix is : \" + longestCommonPrefix(input)); // This code is contributed by rag2127</script>", "e": 31992, "s": 30978, "text": null }, { "code": null, "e": 32002, "s": 31992, "text": "Output: " }, { "code": null, "e": 32037, "s": 32002, "text": "The longest common prefix is : gee" }, { "code": null, "e": 32741, "s": 32037, "text": "Time Complexity: O(MAX * n * log n ) where n is the number of strings in the array and MAX is maximum number of characters in any string. Please note that comparison of two strings would take at most O(MAX) time and for sorting n strings, we would need O(MAX * n * log n ) time.This article is contributed by Saloni Baweja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 32748, "s": 32741, "text": "Sam007" }, { "code": null, "e": 32754, "s": 32748, "text": "ukasp" }, { "code": null, "e": 32768, "s": 32754, "text": "jrolofmeister" }, { "code": null, "e": 32779, "s": 32768, "text": "nidhi_biet" }, { "code": null, "e": 32787, "s": 32779, "text": "rag2127" }, { "code": null, "e": 32809, "s": 32787, "text": "Longest Common Prefix" }, { "code": null, "e": 32817, "s": 32809, "text": "Sorting" }, { "code": null, "e": 32825, "s": 32817, "text": "Strings" }, { "code": null, "e": 32833, "s": 32825, "text": "Strings" }, { "code": null, "e": 32841, "s": 32833, "text": "Sorting" }, { "code": null, "e": 32939, "s": 32841, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32948, "s": 32939, "text": "HeapSort" }, { "code": null, "e": 32971, "s": 32948, "text": "std::sort() in C++ STL" }, { "code": null, "e": 33015, "s": 32971, "text": "Time Complexities of all Sorting Algorithms" }, { "code": null, "e": 33026, "s": 33015, "text": "Radix Sort" }, { "code": null, "e": 33050, "s": 33026, "text": "Merge two sorted arrays" }, { "code": null, "e": 33096, "s": 33050, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 33121, "s": 33096, "text": "Reverse a string in Java" }, { "code": null, "e": 33181, "s": 33121, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 33196, "s": 33181, "text": "C++ Data Types" } ]
Set the innerHTML with JavaScript
The correct syntax to set the innerHTML is as follows − document.getElementById(“yourIdName”).innerHTML=”yourValue”; Let’s now see how to set the innerHTML − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initialscale=1.0"> <title>Document</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/4.7.0/css/font-awesome.min.css"> </head> <body> <label> Username:<input type="text" /> </label> <p id="test"></p> <script> document.getElementById('test').innerHTML = 'Enter Some value into the text box'; </script> </body> </html> To run the above program, save the file name “anyName.html(index.html)” and right click on the file. Select the option “Open with Live Server” in VS Code editor. This will produce the following output −
[ { "code": null, "e": 1118, "s": 1062, "text": "The correct syntax to set the innerHTML is as follows −" }, { "code": null, "e": 1179, "s": 1118, "text": "document.getElementById(“yourIdName”).innerHTML=”yourValue”;" }, { "code": null, "e": 1220, "s": 1179, "text": "Let’s now see how to set the innerHTML −" }, { "code": null, "e": 1231, "s": 1220, "text": " Live Demo" }, { "code": null, "e": 1923, "s": 1231, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initialscale=1.0\">\n<title>Document</title>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/fontawesome/4.7.0/css/font-awesome.min.css\">\n</head>\n<body>\n<label>\nUsername:<input type=\"text\" />\n</label>\n<p id=\"test\"></p>\n<script>\n document.getElementById('test').innerHTML = 'Enter Some value into the text box';\n</script>\n</body>\n</html>" }, { "code": null, "e": 2085, "s": 1923, "text": "To run the above program, save the file name “anyName.html(index.html)” and right click on the\nfile. Select the option “Open with Live Server” in VS Code editor." }, { "code": null, "e": 2126, "s": 2085, "text": "This will produce the following output −" } ]
Fortran - Cycle Statement
The cycle statement causes the loop to skip the remainder of its body, and immediately retest its condition prior to reiterating. program cycle_example implicit none integer :: i do i = 1, 20 if (i == 5) then cycle end if print*, i end do end program cycle_example When the above code is compiled and executed, it produces the following result − 1 2 3 4 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Print Add Notes Bookmark this page
[ { "code": null, "e": 2276, "s": 2146, "text": "The cycle statement causes the loop to skip the remainder of its body, and immediately retest its condition prior to reiterating." }, { "code": null, "e": 2518, "s": 2276, "text": "program cycle_example \nimplicit none \n\n integer :: i \n \n do i = 1, 20 \n \n if (i == 5) then \n cycle \n end if \n \n print*, i \n end do \n \nend program cycle_example" }, { "code": null, "e": 2599, "s": 2518, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 2649, "s": 2599, "text": "1\n2\n3\n4\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n" }, { "code": null, "e": 2656, "s": 2649, "text": " Print" }, { "code": null, "e": 2667, "s": 2656, "text": " Add Notes" } ]
Swap two numbers in C#
To swap two numbers, work with the following logic. Set two variables for swapping − val1 = 100; val2 = 200; Now perform the following operation for swap − val1 = val1 + val2; val2 = val1 - val2; val1 = val1 - val2; The following is the code − using System; namespace Demo { class Program { static void Main(string[] args) { int val1,val2; val1 = 100; val2 = 200; Console.WriteLine("Values before swap..."); Console.WriteLine(val1.ToString()); Console.WriteLine(val2.ToString()); val1 = val1 + val2; val2 = val1 - val2; val1 = val1 - val2; Console.WriteLine("Values after swap..."); Console.WriteLine(val1.ToString()); Console.WriteLine(val2.ToString()); Console.ReadLine(); } } }
[ { "code": null, "e": 1114, "s": 1062, "text": "To swap two numbers, work with the following logic." }, { "code": null, "e": 1147, "s": 1114, "text": "Set two variables for swapping −" }, { "code": null, "e": 1171, "s": 1147, "text": "val1 = 100;\nval2 = 200;" }, { "code": null, "e": 1218, "s": 1171, "text": "Now perform the following operation for swap −" }, { "code": null, "e": 1278, "s": 1218, "text": "val1 = val1 + val2;\nval2 = val1 - val2;\nval1 = val1 - val2;" }, { "code": null, "e": 1306, "s": 1278, "text": "The following is the code −" }, { "code": null, "e": 1885, "s": 1306, "text": "using System;\nnamespace Demo {\n class Program {\n static void Main(string[] args) {\n\n int val1,val2;\n val1 = 100;\n val2 = 200;\n\n Console.WriteLine(\"Values before swap...\");\n Console.WriteLine(val1.ToString());\n Console.WriteLine(val2.ToString());\n\n val1 = val1 + val2;\n val2 = val1 - val2;\n val1 = val1 - val2;\n \n Console.WriteLine(\"Values after swap...\");\n Console.WriteLine(val1.ToString());\n Console.WriteLine(val2.ToString());\n Console.ReadLine();\n }\n }\n}" } ]
Removing Horizontal Lines in image (OpenCV, Python, Matplotlib)
To remove horizontal lines in an image, we can take the following steps − Read a local image. Convert the image from one color space to another. Apply a fixed-level threshold to each array element. Get a structuring element of the specified size and shape for morphological operations. Perform advanced morphological transformations. Find contours in a binary image. Repeat step 4 with different kernel size. Repeat step 5 with a new kernel from step 7. Show the resultant image. import cv2 image = cv2.imread('input_image.png') cv2.imshow('source_image', image) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1] horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (25, 1)) detected_lines = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, horizontal_kernel, iterations=2) cnts = cv2.findContours(detected_lines, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if len(cnts) == 2 else cnts[1] for c in cnts: cv2.drawContours(image, [c], -1, (255, 255, 255), 2) repair_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 6)) result = 255 - cv2.morphologyEx(255 - image, cv2.MORPH_CLOSE, repair_kernel, iterations=1) cv2.imshow('resultant image', result) cv2.waitKey() cv2.destroyAllWindows() Observe that the horizontal lines in our source_image are no longer visible in the resultant_image.
[ { "code": null, "e": 1136, "s": 1062, "text": "To remove horizontal lines in an image, we can take the following steps −" }, { "code": null, "e": 1156, "s": 1136, "text": "Read a local image." }, { "code": null, "e": 1207, "s": 1156, "text": "Convert the image from one color space to another." }, { "code": null, "e": 1260, "s": 1207, "text": "Apply a fixed-level threshold to each array element." }, { "code": null, "e": 1348, "s": 1260, "text": "Get a structuring element of the specified size and shape for morphological operations." }, { "code": null, "e": 1396, "s": 1348, "text": "Perform advanced morphological transformations." }, { "code": null, "e": 1429, "s": 1396, "text": "Find contours in a binary image." }, { "code": null, "e": 1471, "s": 1429, "text": "Repeat step 4 with different kernel size." }, { "code": null, "e": 1516, "s": 1471, "text": "Repeat step 5 with a new kernel from step 7." }, { "code": null, "e": 1542, "s": 1516, "text": "Show the resultant image." }, { "code": null, "e": 2357, "s": 1542, "text": "import cv2\n\nimage = cv2.imread('input_image.png')\ncv2.imshow('source_image', image)\n\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\nthresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]\n\nhorizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (25, 1))\ndetected_lines = cv2.morphologyEx(thresh, cv2.MORPH_OPEN,\nhorizontal_kernel, iterations=2)\n\ncnts = cv2.findContours(detected_lines, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\ncnts = cnts[0] if len(cnts) == 2 else cnts[1]\n\nfor c in cnts:\n cv2.drawContours(image, [c], -1, (255, 255, 255), 2)\n\nrepair_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 6))\n\nresult = 255 - cv2.morphologyEx(255 - image, cv2.MORPH_CLOSE, repair_kernel,\niterations=1)\n\ncv2.imshow('resultant image', result)\ncv2.waitKey()\ncv2.destroyAllWindows()" }, { "code": null, "e": 2457, "s": 2357, "text": "Observe that the horizontal lines in our source_image are no longer visible in the resultant_image." } ]
Edit Distance | DP-5 - GeeksforGeeks
04 Mar, 2022 Given two strings str1 and str2 and below operations that can be performed on str1. Find minimum number of edits (operations) required to convert ‘str1’ into ‘str2’. InsertRemoveReplace Insert Remove Replace All of the above operations are of equal cost. Examples: Input: str1 = "geek", str2 = "gesek" Output: 1 We can convert str1 into str2 by inserting a 's'. Input: str1 = "cat", str2 = "cut" Output: 1 We can convert str1 into str2 by replacing 'a' with 'u'. Input: str1 = "sunday", str2 = "saturday" Output: 3 Last three and first characters are same. We basically need to convert "un" to "atur". This can be done using below three operations. Replace 'n' with 'r', insert t, insert a What are the subproblems in this case? The idea is to process all characters one by one starting from either from left or right sides of both strings. Let us traverse from right corner, there are two possibilities for every pair of character being traversed. m: Length of str1 (first string) n: Length of str2 (second string) If last characters of two strings are same, nothing much to do. Ignore last characters and get count for remaining strings. So we recur for lengths m-1 and n-1.Else (If last characters are not same), we consider all operations on ‘str1’, consider all three operations on last character of first string, recursively compute minimum cost for all three operations and take minimum of three values. Insert: Recur for m and n-1Remove: Recur for m-1 and nReplace: Recur for m-1 and n-1 If last characters of two strings are same, nothing much to do. Ignore last characters and get count for remaining strings. So we recur for lengths m-1 and n-1. Else (If last characters are not same), we consider all operations on ‘str1’, consider all three operations on last character of first string, recursively compute minimum cost for all three operations and take minimum of three values. Insert: Recur for m and n-1Remove: Recur for m-1 and nReplace: Recur for m-1 and n-1 Insert: Recur for m and n-1Remove: Recur for m-1 and nReplace: Recur for m-1 and n-1 Insert: Recur for m and n-1 Remove: Recur for m-1 and n Replace: Recur for m-1 and n-1 Below is implementation of above Naive recursive solution. C++ Java Python3 C# PHP Javascript // A Naive recursive C++ program to find minimum number// operations to convert str1 to str2#include <bits/stdc++.h>using namespace std; // Utility function to find minimum of three numbersint min(int x, int y, int z) { return min(min(x, y), z); } int editDist(string str1, string str2, int m, int n){ // If first string is empty, the only option is to // insert all characters of second string into first if (m == 0) return n; // If second string is empty, the only option is to // remove all characters of first string if (n == 0) return m; // If last characters of two strings are same, nothing // much to do. Ignore last characters and get count for // remaining strings. if (str1[m - 1] == str2[n - 1]) return editDist(str1, str2, m - 1, n - 1); // If last characters are not same, consider all three // operations on last character of first string, // recursively compute minimum cost for all three // operations and take minimum of three values. return 1 + min(editDist(str1, str2, m, n - 1), // Insert editDist(str1, str2, m - 1, n), // Remove editDist(str1, str2, m - 1, n - 1) // Replace );} // Driver codeint main(){ // your code goes here string str1 = "sunday"; string str2 = "saturday"; cout << editDist(str1, str2, str1.length(), str2.length()); return 0;} // A Naive recursive Java program to find minimum number// operations to convert str1 to str2class EDIST { static int min(int x, int y, int z) { if (x <= y && x <= z) return x; if (y <= x && y <= z) return y; else return z; } static int editDist(String str1, String str2, int m, int n) { // If first string is empty, the only option is to // insert all characters of second string into first if (m == 0) return n; // If second string is empty, the only option is to // remove all characters of first string if (n == 0) return m; // If last characters of two strings are same, // nothing much to do. Ignore last characters and // get count for remaining strings. if (str1.charAt(m - 1) == str2.charAt(n - 1)) return editDist(str1, str2, m - 1, n - 1); // If last characters are not same, consider all // three operations on last character of first // string, recursively compute minimum cost for all // three operations and take minimum of three // values. return 1 + min(editDist(str1, str2, m, n - 1), // Insert editDist(str1, str2, m - 1, n), // Remove editDist(str1, str2, m - 1, n - 1) // Replace ); } // Driver Code public static void main(String args[]) { String str1 = "sunday"; String str2 = "saturday"; System.out.println(editDist( str1, str2, str1.length(), str2.length())); }}/*This code is contributed by Rajat Mishra*/ # A Naive recursive Python program to find minimum number# operations to convert str1 to str2 def editDistance(str1, str2, m, n): # If first string is empty, the only option is to # insert all characters of second string into first if m == 0: return n # If second string is empty, the only option is to # remove all characters of first string if n == 0: return m # If last characters of two strings are same, nothing # much to do. Ignore last characters and get count for # remaining strings. if str1[m-1] == str2[n-1]: return editDistance(str1, str2, m-1, n-1) # If last characters are not same, consider all three # operations on last character of first string, recursively # compute minimum cost for all three operations and take # minimum of three values. return 1 + min(editDistance(str1, str2, m, n-1), # Insert editDistance(str1, str2, m-1, n), # Remove editDistance(str1, str2, m-1, n-1) # Replace ) # Driver codestr1 = "sunday"str2 = "saturday"print (editDistance(str1, str2, len(str1), len(str2))) # This code is contributed by Bhavya Jain // A Naive recursive C# program to// find minimum numberoperations// to convert str1 to str2using System; class GFG { static int min(int x, int y, int z) { if (x <= y && x <= z) return x; if (y <= x && y <= z) return y; else return z; } static int editDist(String str1, String str2, int m, int n) { // If first string is empty, the only option is to // insert all characters of second string into first if (m == 0) return n; // If second string is empty, the only option is to // remove all characters of first string if (n == 0) return m; // If last characters of two strings are same, // nothing much to do. Ignore last characters and // get count for remaining strings. if (str1[m - 1] == str2[n - 1]) return editDist(str1, str2, m - 1, n - 1); // If last characters are not same, consider all // three operations on last character of first // string, recursively compute minimum cost for all // three operations and take minimum of three // values. return 1 + min(editDist(str1, str2, m, n - 1), // Insert editDist(str1, str2, m - 1, n), // Remove editDist(str1, str2, m - 1, n - 1) // Replace ); } // Driver code public static void Main() { String str1 = "sunday"; String str2 = "saturday"; Console.WriteLine( editDist(str1, str2, str1.Length, str2.Length)); }} // This Code is Contributed by Sam007 <?php// A Naive recursive Python program // to find minimum number operations// to convert str1 to str2function editDistance($str1, $str2, $m, $n){ // If first string is empty, // the only option is to insert. // all characters of second // string into first if ($m == 0) return $n; // If second string is empty, // the only option is to // remove all characters of // first string if ($n == 0) return $m; // If last characters of two // strings are same, nothing // much to do. Ignore last // characters and get count // for remaining strings. if ($str1[$m - 1] == $str2[$n - 1]) { return editDistance($str1, $str2, $m - 1, $n - 1); } // If last characters are not same, // consider all three operations on // last character of first string, // recursively compute minimum cost // for all three operations and take // minimum of three values. return 1 + min(editDistance($str1, $str2, $m, $n - 1), // Insert editDistance($str1, $str2, $m - 1, $n), // Remove editDistance($str1, $str2, $m - 1, $n - 1)); // Replace} // Driver Code$str1 = "sunday";$str2 = "saturday";echo editDistance($str1, $str2, strlen($str1), strlen($str2)); // This code is contributed// by Shivi_Aggarwal?> <script> // Javascript program to// find minimum numberoperations// to convert str1 to str2function min(x, y, z){ if (x <= y && x <= z) return x; if (y <= x && y <= z) return y; else return z;} function editDist(str1, str2, m, n){ // If first string is empty, the // only option is to insert all // characters of second string into first if (m == 0) return n; // If second string is empty, the only // option is to remove all characters // of first string if (n == 0) return m; // If last characters of two strings are // same, nothing much to do. Ignore last // characters and get count for remaining // strings. if (str1[m - 1] == str2[n - 1]) return editDist(str1, str2, m - 1, n - 1); // If last characters are not same, consider all // three operations on last character of first // string, recursively compute minimum cost for all // three operations and take minimum of three // values. return 1 + min(editDist(str1, str2, m, n - 1), // Insert editDist(str1, str2, m - 1, n), // Remove editDist(str1, str2, m - 1, n - 1)); // Replace} // Driver codelet str1 = "sunday";let str2 = "saturday";document.write(editDist(str1, str2, str1.length, str2.length)); // This code is contributed by target_2 </script> 3 The time complexity of above solution is exponential. In worst case, we may end up doing O(3m) operations. The worst case happens when none of characters of two strings match. Below is a recursive call diagram for worst case. We can see that many subproblems are solved, again and again, for example, eD(2, 2) is called three times. Since same subproblems are called again, this problem has Overlapping Subproblems property. So Edit Distance problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be avoided by constructing a temporary array that stores results of subproblems. C++ Java Python3 C# PHP Javascript // A Dynamic Programming based C++ program to find minimum// number operations to convert str1 to str2#include <bits/stdc++.h>using namespace std; // Utility function to find the minimum of three numbersint min(int x, int y, int z) { return min(min(x, y), z); } int editDistDP(string str1, string str2, int m, int n){ // Create a table to store results of subproblems int dp[m + 1][n + 1]; // Fill d[][] in bottom up manner for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { // If first string is empty, only option is to // insert all characters of second string if (i == 0) dp[i][j] = j; // Min. operations = j // If second string is empty, only option is to // remove all characters of second string else if (j == 0) dp[i][j] = i; // Min. operations = i // If last characters are same, ignore last char // and recur for remaining string else if (str1[i - 1] == str2[j - 1]) dp[i][j] = dp[i - 1][j - 1]; // If the last character is different, consider // all possibilities and find the minimum else dp[i][j] = 1 + min(dp[i][j - 1], // Insert dp[i - 1][j], // Remove dp[i - 1][j - 1]); // Replace } } return dp[m][n];} // Driver codeint main(){ // your code goes here string str1 = "sunday"; string str2 = "saturday"; cout << editDistDP(str1, str2, str1.length(), str2.length()); return 0;} // A Dynamic Programming based Java program to find minimum// number operations to convert str1 to str2class EDIST { static int min(int x, int y, int z) { if (x <= y && x <= z) return x; if (y <= x && y <= z) return y; else return z; } static int editDistDP(String str1, String str2, int m, int n) { // Create a table to store results of subproblems int dp[][] = new int[m + 1][n + 1]; // Fill d[][] in bottom up manner for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { // If first string is empty, only option is // to insert all characters of second string if (i == 0) dp[i][j] = j; // Min. operations = j // If second string is empty, only option is // to remove all characters of second string else if (j == 0) dp[i][j] = i; // Min. operations = i // If last characters are same, ignore last // char and recur for remaining string else if (str1.charAt(i - 1) == str2.charAt(j - 1)) dp[i][j] = dp[i - 1][j - 1]; // If the last character is different, // consider all possibilities and find the // minimum else dp[i][j] = 1 + min(dp[i][j - 1], // Insert dp[i - 1][j], // Remove dp[i - 1] [j - 1]); // Replace } } return dp[m][n]; } // Driver Code public static void main(String args[]) { String str1 = "sunday"; String str2 = "saturday"; System.out.println(editDistDP( str1, str2, str1.length(), str2.length())); }} /*This code is contributed by Rajat Mishra*/ # A Dynamic Programming based Python program for edit# distance problem def editDistDP(str1, str2, m, n): # Create a table to store results of subproblems dp = [[0 for x in range(n + 1)] for x in range(m + 1)] # Fill d[][] in bottom up manner for i in range(m + 1): for j in range(n + 1): # If first string is empty, only option is to # insert all characters of second string if i == 0: dp[i][j] = j # Min. operations = j # If second string is empty, only option is to # remove all characters of second string elif j == 0: dp[i][j] = i # Min. operations = i # If last characters are same, ignore last char # and recur for remaining string elif str1[i-1] == str2[j-1]: dp[i][j] = dp[i-1][j-1] # If last character are different, consider all # possibilities and find minimum else: dp[i][j] = 1 + min(dp[i][j-1], # Insert dp[i-1][j], # Remove dp[i-1][j-1]) # Replace return dp[m][n] # Driver codestr1 = "sunday"str2 = "saturday" print(editDistDP(str1, str2, len(str1), len(str2)))# This code is contributed by Bhavya Jain // A Dynamic Programming based// C# program to find minimum// number operations to// convert str1 to str2using System; class GFG { static int min(int x, int y, int z) { if (x <= y && x <= z) return x; if (y <= x && y <= z) return y; else return z; } static int editDistDP(String str1, String str2, int m, int n) { // Create a table to store // results of subproblems int[, ] dp = new int[m + 1, n + 1]; // Fill d[][] in bottom up manner for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { // If first string is empty, only option is // to insert all characters of second string if (i == 0) // Min. operations = j dp[i, j] = j; // If second string is empty, only option is // to remove all characters of second string else if (j == 0) // Min. operations = i dp[i, j] = i; // If last characters are same, ignore last // char and recur for remaining string else if (str1[i - 1] == str2[j - 1]) dp[i, j] = dp[i - 1, j - 1]; // If the last character is different, // consider all possibilities and find the // minimum else dp[i, j] = 1 + min(dp[i, j - 1], // Insert dp[i - 1, j], // Remove dp[i - 1, j - 1]); // Replace } } return dp[m, n]; } // Driver code public static void Main() { String str1 = "sunday"; String str2 = "saturday"; Console.Write(editDistDP(str1, str2, str1.Length, str2.Length)); }}// This Code is Contributed by Sam007 <?php// A Dynamic Programming based// Python program for edit// distance problemfunction editDistDP($str1, $str2, $m, $n){// Fill d[][] in bottom up mannerfor ($i = 0; $i <= $m; $i++){ for ($j = 0; $j <= $n; $j++) { // If first string is empty, // only option is to insert // all characters of second string if ($i == 0) $dp[$i][$j] = $j ; // Min. operations = j // If second string is empty, // only option is to remove // all characters of second string else if($j == 0) $dp[$i][$j] = $i; // Min. operations = i // If last characters are same, // ignore last char and recur // for remaining string else if($str1[$i - 1] == $str2[$j - 1]) $dp[$i][$j] = $dp[$i - 1][$j - 1]; // If last character are different, // consider all possibilities and // find minimum else { $dp[$i][$j] = 1 + min($dp[$i][$j - 1], // Insert $dp[$i - 1][$j], // Remove $dp[$i - 1][$j - 1]); // Replace } }}return $dp[$m][$n] ;} // Driver Code$str1 = "sunday";$str2 = "saturday"; echo editDistDP($str1, $str2, strlen($str1), strlen($str2)); // This code is contributed// by Shivi_Aggarwal?> <script> // A Dynamic Programming based// Javascript program to find minimum// number operations to convert str1 to str2 function min(x,y,z){ if (x <= y && x <= z) return x; if (y <= x && y <= z) return y; else return z;} function editDistDP(str1,str2,m,n){ // Create a table to store results of subproblems let dp = new Array(m + 1); for(let i=0;i<m+1;i++) { dp[i]=new Array(n+1); for(let j=0;j<n+1;j++) { dp[i][j]=0; } } // Fill d[][] in bottom up manner for (let i = 0; i <= m; i++) { for (let j = 0; j <= n; j++) { // If first string is empty, only option is // to insert all characters of second string if (i == 0) dp[i][j] = j; // Min. operations = j // If second string is empty, only option is // to remove all characters of second string else if (j == 0) dp[i][j] = i; // Min. operations = i // If last characters are same, ignore last // char and recur for remaining string else if (str1[i - 1] == str2[j - 1]) dp[i][j] = dp[i - 1][j - 1]; // If the last character is different, // consider all possibilities and find the // minimum else dp[i][j] = 1 + min(dp[i][j - 1], // Insert dp[i - 1][j], // Remove dp[i - 1] [j - 1]); // Replace } } return dp[m][n];} // Driver Codelet str1 = "sunday";let str2 = "saturday";document.write(editDistDP(str1, str2, str1.length, str2.length)); // This code is contributed by unknown2108 </script> 3 Time Complexity: O(m x n) Auxiliary Space: O(m x n) Space Complex Solution: In the above-given method we require O(m x n) space. This will not be suitable if the length of strings is greater than 2000 as it can only create 2D array of 2000 x 2000. To fill a row in DP array we require only one row the upper row. For example, if we are filling the i = 10 rows in DP array we require only values of 9th row. So we simply create a DP array of 2 x str1 length. This approach reduces the space complexity. Here is the C++ implementation of the above-mentioned problem C++ Java Python3 C# Javascript // A Space efficient Dynamic Programming// based C++ program to find minimum// number operations to convert str1 to str2#include <bits/stdc++.h>using namespace std; void EditDistDP(string str1, string str2){ int len1 = str1.length(); int len2 = str2.length(); // Create a DP array to memoize result // of previous computations int DP[2][len1 + 1]; // To fill the DP array with 0 memset(DP, 0, sizeof DP); // Base condition when second string // is empty then we remove all characters for (int i = 0; i <= len1; i++) DP[0][i] = i; // Start filling the DP // This loop run for every // character in second string for (int i = 1; i <= len2; i++) { // This loop compares the char from // second string with first string // characters for (int j = 0; j <= len1; j++) { // if first string is empty then // we have to perform add character // operation to get second string if (j == 0) DP[i % 2][j] = i; // if character from both string // is same then we do not perform any // operation . here i % 2 is for bound // the row number. else if (str1[j - 1] == str2[i - 1]) { DP[i % 2][j] = DP[(i - 1) % 2][j - 1]; } // if character from both string is // not same then we take the minimum // from three specified operation else { DP[i % 2][j] = 1 + min(DP[(i - 1) % 2][j], min(DP[i % 2][j - 1], DP[(i - 1) % 2][j - 1])); } } } // after complete fill the DP array // if the len2 is even then we end // up in the 0th row else we end up // in the 1th row so we take len2 % 2 // to get row cout << DP[len2 % 2][len1] << endl;} // Driver programint main(){ string str1 = "food"; string str2 = "money"; EditDistDP(str1, str2); return 0;} // A Space efficient Dynamic Programming// based Java program to find minimum// number operations to convert str1 to str2import java.util.*;class GFG{ static void EditDistDP(String str1, String str2){ int len1 = str1.length(); int len2 = str2.length(); // Create a DP array to memoize result // of previous computations int [][]DP = new int[2][len1 + 1]; // Base condition when second String // is empty then we remove all characters for (int i = 0; i <= len1; i++) DP[0][i] = i; // Start filling the DP // This loop run for every // character in second String for (int i = 1; i <= len2; i++) { // This loop compares the char from // second String with first String // characters for (int j = 0; j <= len1; j++) { // if first String is empty then // we have to perform add character // operation to get second String if (j == 0) DP[i % 2][j] = i; // if character from both String // is same then we do not perform any // operation . here i % 2 is for bound // the row number. else if (str1.charAt(j - 1) == str2.charAt(i - 1)) { DP[i % 2][j] = DP[(i - 1) % 2][j - 1]; } // if character from both String is // not same then we take the minimum // from three specified operation else { DP[i % 2][j] = 1 + Math.min(DP[(i - 1) % 2][j], Math.min(DP[i % 2][j - 1], DP[(i - 1) % 2][j - 1])); } } } // after complete fill the DP array // if the len2 is even then we end // up in the 0th row else we end up // in the 1th row so we take len2 % 2 // to get row System.out.print(DP[len2 % 2][len1] +"\n");} // Driver programpublic static void main(String[] args){ String str1 = "food"; String str2 = "money"; EditDistDP(str1, str2);}} // This code is contributed by aashish1995 # A Space efficient Dynamic Programming# based Python3 program to find minimum# number operations to convert str1 to str2def EditDistDP(str1, str2): len1 = len(str1) len2 = len(str2) # Create a DP array to memoize result # of previous computations DP = [[0 for i in range(len1 + 1)] for j in range(2)]; # Base condition when second String # is empty then we remove all characters for i in range(0, len1 + 1): DP[0][i] = i # Start filling the DP # This loop run for every # character in second String for i in range(1, len2 + 1): # This loop compares the char from # second String with first String # characters for j in range(0, len1 + 1): # If first String is empty then # we have to perform add character # operation to get second String if (j == 0): DP[i % 2][j] = i # If character from both String # is same then we do not perform any # operation . here i % 2 is for bound # the row number. else if(str1[j - 1] == str2[i-1]): DP[i % 2][j] = DP[(i - 1) % 2][j - 1] # If character from both String is # not same then we take the minimum # from three specified operation else: DP[i % 2][j] = (1 + min(DP[(i - 1) % 2][j], min(DP[i % 2][j - 1], DP[(i - 1) % 2][j - 1]))) # After complete fill the DP array # if the len2 is even then we end # up in the 0th row else we end up # in the 1th row so we take len2 % 2 # to get row print(DP[len2 % 2][len1], "") # Driver codeif __name__ == '__main__': str1 = "food" str2 = "money" EditDistDP(str1, str2) # This code is contributed by gauravrajput1 // A Space efficient Dynamic Programming// based C# program to find minimum// number operations to convert str1 to str2using System;class GFG{ static void EditDistDP(String str1, String str2){ int len1 = str1.Length; int len2 = str2.Length; // Create a DP array to memoize result // of previous computations int [,]DP = new int[2, len1 + 1]; // Base condition when second String // is empty then we remove all characters for (int i = 0; i <= len1; i++) DP[0, i] = i; // Start filling the DP // This loop run for every // character in second String for (int i = 1; i <= len2; i++) { // This loop compares the char from // second String with first String // characters for (int j = 0; j <= len1; j++) { // if first String is empty then // we have to perform add character // operation to get second String if (j == 0) DP[i % 2, j] = i; // if character from both String // is same then we do not perform any // operation . here i % 2 is for bound // the row number. else if (str1[j - 1] == str2[i - 1]) { DP[i % 2, j] = DP[(i - 1) % 2, j - 1]; } // if character from both String is // not same then we take the minimum // from three specified operation else { DP[i % 2, j] = 1 + Math.Min(DP[(i - 1) % 2, j], Math.Min(DP[i % 2, j - 1], DP[(i - 1) % 2, j - 1])); } } } // after complete fill the DP array // if the len2 is even then we end // up in the 0th row else we end up // in the 1th row so we take len2 % 2 // to get row Console.Write(DP[len2 % 2, len1] +"\n");} // Driver programpublic static void Main(String[] args){ String str1 = "food"; String str2 = "money"; EditDistDP(str1, str2);}} // This code is contributed by aashish1995 <script>// A Space efficient Dynamic Programming// based Javascript program to find minimum// number operations to convert str1 to str2function EditDistDP(str1, str2){ let len1 = str1.length; let len2 = str2.length; // Create a DP array to memoize result // of previous computations let DP = new Array(2); for(let i = 0; i < 2; i++) { DP[i] = new Array(len1+1); for(let j = 0; j < len1 + 1; j++) DP[i][j] = 0; } // Base condition when second String // is empty then we remove all characters for (let i = 0; i <= len1; i++) DP[0][i] = i; // Start filling the DP // This loop run for every // character in second String for (let i = 1; i <= len2; i++) { // This loop compares the char from // second String with first String // characters for (let j = 0; j <= len1; j++) { // if first String is empty then // we have to perform add character // operation to get second String if (j == 0) DP[i % 2][j] = i; // if character from both String // is same then we do not perform any // operation . here i % 2 is for bound // the row number. else if (str1[j-1] == str2[i-1]) { DP[i % 2][j] = DP[(i - 1) % 2][j - 1]; } // if character from both String is // not same then we take the minimum // from three specified operation else { DP[i % 2][j] = 1 + Math.min(DP[(i - 1) % 2][j], Math.min(DP[i % 2][j - 1], DP[(i - 1) % 2][j - 1])); } } } // after complete fill the DP array // if the len2 is even then we end // up in the 0th row else we end up // in the 1th row so we take len2 % 2 // to get row document.write(DP[len2 % 2][len1] +"<br>");} // Driver programlet str1 = "food";let str2 = "money";EditDistDP(str1, str2); // This code is contributed by patel2127.</script> 4 Time Complexity: O(m x n) Auxiliary Space: O( m ) This is a memoized version of recursion i.e. Top-Down DP: C++14 Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std;int minDis(string s1, string s2, int n, int m, vector<vector<int>> &dp){ // If any string is empty, // return the remaining characters of other string if(n==0) return m; if(m==0) return n; // To check if the recursive tree // for given n & m has already been executed if(dp[n][m]!=-1) return dp[n][m]; // If characters are equal, execute // recursive function for n-1, m-1 if(s1[n-1]==s2[m-1]){ if(dp[n-1][m-1]==-1){ return dp[n][m] = minDis(s1, s2, n-1, m-1, dp); } else return dp[n][m] = dp[n-1][m-1]; } // If characters are nt equal, we need to // find the minimum cost out of all 3 operations. else{ int m1, m2, m3; // temp variables if(dp[n-1][m]!=-1){ m1 = dp[n-1][m]; } else{ m1 = minDis(s1, s2, n-1, m, dp); } if(dp[n][m-1]!=-1){ m2 = dp[n][m-1]; } else{ m2 = minDis(s1, s2, n, m-1, dp); } if(dp[n-1][m-1]!=-1){ m3 = dp[n-1][m-1]; } else{ m3 = minDis(s1, s2, n-1, m-1, dp); } return dp[n][m] = 1+min(m1, min(m2, m3)); } } // Driver programint main() { string str1 = "voldemort"; string str2 = "dumbledore"; int n= str1.length(), m = str2.length(); vector<vector<int>> dp(n+1, vector<int>(m+1, -1)); cout<<minDis(str1, str2, n, m, dp); return 0; // This code is a contribution of Bhavneet Singh } import java.util.*;class GFG{ static int minDis(String s1, String s2, int n, int m, int[][]dp){ // If any String is empty, // return the remaining characters of other String if(n == 0) return m; if(m == 0) return n; // To check if the recursive tree // for given n & m has already been executed if(dp[n][m] != -1) return dp[n][m]; // If characters are equal, execute // recursive function for n-1, m-1 if(s1.charAt(n - 1) == s2.charAt(m - 1)) { if(dp[n - 1][m - 1] == -1) { return dp[n][m] = minDis(s1, s2, n - 1, m - 1, dp); } else return dp[n][m] = dp[n - 1][m - 1]; } // If characters are nt equal, we need to // find the minimum cost out of all 3 operations. else { int m1, m2, m3; // temp variables if(dp[n-1][m] != -1) { m1 = dp[n - 1][m]; } else { m1 = minDis(s1, s2, n - 1, m, dp); } if(dp[n][m - 1] != -1) { m2 = dp[n][m - 1]; } else { m2 = minDis(s1, s2, n, m - 1, dp); } if(dp[n - 1][m - 1] != -1) { m3 = dp[n - 1][m - 1]; } else { m3 = minDis(s1, s2, n - 1, m - 1, dp); } return dp[n][m] = 1 + Math.min(m1, Math.min(m2, m3)); }} // Driver programpublic static void main(String[] args){ String str1 = "voldemort"; String str2 = "dumbledore"; int n= str1.length(), m = str2.length(); int[][] dp = new int[n + 1][m + 1]; for(int i = 0; i < n + 1; i++) Arrays.fill(dp[i], -1); System.out.print(minDis(str1, str2, n, m, dp));}} // This code is contributed by gauravrajput1 def minDis(s1, s2, n, m, dp) : # If any string is empty, # return the remaining characters of other string if(n == 0) : return m if(m == 0) : return n # To check if the recursive tree # for given n & m has already been executed if(dp[n][m] != -1) : return dp[n][m]; # If characters are equal, execute # recursive function for n-1, m-1 if(s1[n - 1] == s2[m - 1]) : if(dp[n - 1][m - 1] == -1) : dp[n][m] = minDis(s1, s2, n - 1, m - 1, dp) return dp[n][m] else : dp[n][m] = dp[n - 1][m - 1] return dp[n][m] # If characters are nt equal, we need to # find the minimum cost out of all 3 operations. else : if(dp[n - 1][m] != -1) : m1 = dp[n - 1][m] else : m1 = minDis(s1, s2, n - 1, m, dp) if(dp[n][m - 1] != -1) : m2 = dp[n][m - 1] else : m2 = minDis(s1, s2, n, m - 1, dp) if(dp[n - 1][m - 1] != -1) : m3 = dp[n - 1][m - 1] else : m3 = minDis(s1, s2, n - 1, m - 1, dp) dp[n][m] = 1 + min(m1, min(m2, m3)) return dp[n][m] # Driver codestr1 = "voldemort"str2 = "dumbledore" n = len(str1)m = len(str2)dp = [[-1 for i in range(m + 1)] for j in range(n + 1)] print(minDis(str1, str2, n, m, dp)) # This code is contributed by divyesh072019. using System;using System.Collections.Generic;class GFG { static int minDis(string s1, string s2, int n, int m, List<List<int>> dp) { // If any string is empty, // return the remaining characters of other string if(n == 0) return m; if(m == 0) return n; // To check if the recursive tree // for given n & m has already been executed if(dp[n][m] != -1) return dp[n][m]; // If characters are equal, execute // recursive function for n-1, m-1 if(s1[n - 1] == s2[m - 1]) { if(dp[n - 1][m - 1] == -1) { return dp[n][m] = minDis(s1, s2, n - 1, m - 1, dp); } else return dp[n][m] = dp[n - 1][m - 1]; } // If characters are nt equal, we need to // find the minimum cost out of all 3 operations. else { int m1, m2, m3; // temp variables if(dp[n - 1][m] != -1) { m1 = dp[n - 1][m]; } else { m1 = minDis(s1, s2, n - 1, m, dp); } if(dp[n][m - 1] != -1) { m2 = dp[n][m - 1]; } else { m2 = minDis(s1, s2, n, m - 1, dp); } if(dp[n - 1][m - 1] != -1) { m3 = dp[n - 1][m - 1]; } else { m3 = minDis(s1, s2, n - 1, m - 1, dp); } return dp[n][m] = 1+ Math.Min(m1, Math.Min(m2, m3)); } } // Driver code static void Main() { string str1 = "voldemort"; string str2 = "dumbledore"; int n = str1.Length, m = str2.Length; List<List<int>> dp = new List<List<int>>(); for(int i = 0; i < n + 1; i++) { dp.Add(new List<int>()); for(int j = 0; j < m + 1; j++) { dp[i].Add(-1); } } Console.WriteLine(minDis(str1, str2, n, m, dp)); }} // This code is contributed by divyeshrabadiya07. <script> function minDis(s1,s2,n,m,dp){ // If any String is empty, // return the remaining characters of other String if(n == 0) return m; if(m == 0) return n; // To check if the recursive tree // for given n & m has already been executed if(dp[n][m] != -1) return dp[n][m]; // If characters are equal, execute // recursive function for n-1, m-1 if(s1[n - 1] == s2[m - 1]) { if(dp[n - 1][m - 1] == -1) { return dp[n][m] = minDis(s1, s2, n - 1, m - 1, dp); } else return dp[n][m] = dp[n - 1][m - 1]; } // If characters are nt equal, we need to // find the minimum cost out of all 3 operations. else { let m1, m2, m3; // temp variables if(dp[n-1][m] != -1) { m1 = dp[n - 1][m]; } else { m1 = minDis(s1, s2, n - 1, m, dp); } if(dp[n][m - 1] != -1) { m2 = dp[n][m - 1]; } else { m2 = minDis(s1, s2, n, m - 1, dp); } if(dp[n - 1][m - 1] != -1) { m3 = dp[n - 1][m - 1]; } else { m3 = minDis(s1, s2, n - 1, m - 1, dp); } return dp[n][m] = 1 + Math.min(m1, Math.min(m2, m3)); }} // Driver program let str1 = "voldemort";let str2 = "dumbledore"; let n= str1.length, m = str2.length; let dp = new Array(n + 1);for(let i = 0; i < n + 1; i++){ dp[i]=new Array(m+1); for(let j=0;j<m+1;j++) dp[i][j]=-1;} document.write(minDis(str1, str2, n, m, dp)); // This code is contributed by avanitrachhadiya2155 </script> 7 Applications: There are many practical applications of edit distance algorithm, refer Lucene API for sample. Another example, display all the words in a dictionary that are near proximity to a given wordincorrectly spelled word. YouTubeGeeksforGeeks500K subscribersDynamic Programming | Set 5 (Edit Distance) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:04•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Thv3TfsZVpw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Thanks to Vivek Kumar for suggesting updates.Thanks to Venki for providing initial post. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Shivi_Aggarwal SahilSingh AdarshGupta7 BhardwajNeeraj bhavneet2000 aashish1995 GauravRajput1 divyeshrabadiya07 divyesh072019 target_2 anikakapoor unknown2108 patel2127 avanitrachhadiya2155 akshaysingh98088 arorakashish0911 amartyaghoshgfg sumitgumber28 tathagato surinderdawra388 Amazon edit-distance Dynamic Programming Amazon Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Largest Sum Contiguous Subarray Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Subset Sum Problem | DP-25 Longest Palindromic Substring | Set 1 Efficient program to print all prime factors of a given number Sieve of Eratosthenes Partition a set into two subsets such that the difference of subset sums is minimum Cutting a Rod | DP-13
[ { "code": null, "e": 34205, "s": 34177, "text": "\n04 Mar, 2022" }, { "code": null, "e": 34373, "s": 34205, "text": "Given two strings str1 and str2 and below operations that can be performed on str1. Find minimum number of edits (operations) required to convert ‘str1’ into ‘str2’. " }, { "code": null, "e": 34393, "s": 34373, "text": "InsertRemoveReplace" }, { "code": null, "e": 34400, "s": 34393, "text": "Insert" }, { "code": null, "e": 34407, "s": 34400, "text": "Remove" }, { "code": null, "e": 34415, "s": 34407, "text": "Replace" }, { "code": null, "e": 34463, "s": 34415, "text": "All of the above operations are of equal cost. " }, { "code": null, "e": 34474, "s": 34463, "text": "Examples: " }, { "code": null, "e": 34913, "s": 34474, "text": "Input: str1 = \"geek\", str2 = \"gesek\"\nOutput: 1\nWe can convert str1 into str2 by inserting a 's'.\n\nInput: str1 = \"cat\", str2 = \"cut\"\nOutput: 1\nWe can convert str1 into str2 by replacing 'a' with 'u'.\n\nInput: str1 = \"sunday\", str2 = \"saturday\"\nOutput: 3\nLast three and first characters are same. We basically\nneed to convert \"un\" to \"atur\". This can be done using\nbelow three operations. \nReplace 'n' with 'r', insert t, insert a" }, { "code": null, "e": 35174, "s": 34913, "text": "What are the subproblems in this case? The idea is to process all characters one by one starting from either from left or right sides of both strings. Let us traverse from right corner, there are two possibilities for every pair of character being traversed. " }, { "code": null, "e": 35241, "s": 35174, "text": "m: Length of str1 (first string)\nn: Length of str2 (second string)" }, { "code": null, "e": 35721, "s": 35241, "text": "If last characters of two strings are same, nothing much to do. Ignore last characters and get count for remaining strings. So we recur for lengths m-1 and n-1.Else (If last characters are not same), we consider all operations on ‘str1’, consider all three operations on last character of first string, recursively compute minimum cost for all three operations and take minimum of three values. Insert: Recur for m and n-1Remove: Recur for m-1 and nReplace: Recur for m-1 and n-1" }, { "code": null, "e": 35882, "s": 35721, "text": "If last characters of two strings are same, nothing much to do. Ignore last characters and get count for remaining strings. So we recur for lengths m-1 and n-1." }, { "code": null, "e": 36202, "s": 35882, "text": "Else (If last characters are not same), we consider all operations on ‘str1’, consider all three operations on last character of first string, recursively compute minimum cost for all three operations and take minimum of three values. Insert: Recur for m and n-1Remove: Recur for m-1 and nReplace: Recur for m-1 and n-1" }, { "code": null, "e": 36287, "s": 36202, "text": "Insert: Recur for m and n-1Remove: Recur for m-1 and nReplace: Recur for m-1 and n-1" }, { "code": null, "e": 36315, "s": 36287, "text": "Insert: Recur for m and n-1" }, { "code": null, "e": 36343, "s": 36315, "text": "Remove: Recur for m-1 and n" }, { "code": null, "e": 36374, "s": 36343, "text": "Replace: Recur for m-1 and n-1" }, { "code": null, "e": 36433, "s": 36374, "text": "Below is implementation of above Naive recursive solution." }, { "code": null, "e": 36437, "s": 36433, "text": "C++" }, { "code": null, "e": 36442, "s": 36437, "text": "Java" }, { "code": null, "e": 36450, "s": 36442, "text": "Python3" }, { "code": null, "e": 36453, "s": 36450, "text": "C#" }, { "code": null, "e": 36457, "s": 36453, "text": "PHP" }, { "code": null, "e": 36468, "s": 36457, "text": "Javascript" }, { "code": "// A Naive recursive C++ program to find minimum number// operations to convert str1 to str2#include <bits/stdc++.h>using namespace std; // Utility function to find minimum of three numbersint min(int x, int y, int z) { return min(min(x, y), z); } int editDist(string str1, string str2, int m, int n){ // If first string is empty, the only option is to // insert all characters of second string into first if (m == 0) return n; // If second string is empty, the only option is to // remove all characters of first string if (n == 0) return m; // If last characters of two strings are same, nothing // much to do. Ignore last characters and get count for // remaining strings. if (str1[m - 1] == str2[n - 1]) return editDist(str1, str2, m - 1, n - 1); // If last characters are not same, consider all three // operations on last character of first string, // recursively compute minimum cost for all three // operations and take minimum of three values. return 1 + min(editDist(str1, str2, m, n - 1), // Insert editDist(str1, str2, m - 1, n), // Remove editDist(str1, str2, m - 1, n - 1) // Replace );} // Driver codeint main(){ // your code goes here string str1 = \"sunday\"; string str2 = \"saturday\"; cout << editDist(str1, str2, str1.length(), str2.length()); return 0;}", "e": 37925, "s": 36468, "text": null }, { "code": "// A Naive recursive Java program to find minimum number// operations to convert str1 to str2class EDIST { static int min(int x, int y, int z) { if (x <= y && x <= z) return x; if (y <= x && y <= z) return y; else return z; } static int editDist(String str1, String str2, int m, int n) { // If first string is empty, the only option is to // insert all characters of second string into first if (m == 0) return n; // If second string is empty, the only option is to // remove all characters of first string if (n == 0) return m; // If last characters of two strings are same, // nothing much to do. Ignore last characters and // get count for remaining strings. if (str1.charAt(m - 1) == str2.charAt(n - 1)) return editDist(str1, str2, m - 1, n - 1); // If last characters are not same, consider all // three operations on last character of first // string, recursively compute minimum cost for all // three operations and take minimum of three // values. return 1 + min(editDist(str1, str2, m, n - 1), // Insert editDist(str1, str2, m - 1, n), // Remove editDist(str1, str2, m - 1, n - 1) // Replace ); } // Driver Code public static void main(String args[]) { String str1 = \"sunday\"; String str2 = \"saturday\"; System.out.println(editDist( str1, str2, str1.length(), str2.length())); }}/*This code is contributed by Rajat Mishra*/", "e": 39631, "s": 37925, "text": null }, { "code": "# A Naive recursive Python program to find minimum number# operations to convert str1 to str2 def editDistance(str1, str2, m, n): # If first string is empty, the only option is to # insert all characters of second string into first if m == 0: return n # If second string is empty, the only option is to # remove all characters of first string if n == 0: return m # If last characters of two strings are same, nothing # much to do. Ignore last characters and get count for # remaining strings. if str1[m-1] == str2[n-1]: return editDistance(str1, str2, m-1, n-1) # If last characters are not same, consider all three # operations on last character of first string, recursively # compute minimum cost for all three operations and take # minimum of three values. return 1 + min(editDistance(str1, str2, m, n-1), # Insert editDistance(str1, str2, m-1, n), # Remove editDistance(str1, str2, m-1, n-1) # Replace ) # Driver codestr1 = \"sunday\"str2 = \"saturday\"print (editDistance(str1, str2, len(str1), len(str2))) # This code is contributed by Bhavya Jain", "e": 40816, "s": 39631, "text": null }, { "code": "// A Naive recursive C# program to// find minimum numberoperations// to convert str1 to str2using System; class GFG { static int min(int x, int y, int z) { if (x <= y && x <= z) return x; if (y <= x && y <= z) return y; else return z; } static int editDist(String str1, String str2, int m, int n) { // If first string is empty, the only option is to // insert all characters of second string into first if (m == 0) return n; // If second string is empty, the only option is to // remove all characters of first string if (n == 0) return m; // If last characters of two strings are same, // nothing much to do. Ignore last characters and // get count for remaining strings. if (str1[m - 1] == str2[n - 1]) return editDist(str1, str2, m - 1, n - 1); // If last characters are not same, consider all // three operations on last character of first // string, recursively compute minimum cost for all // three operations and take minimum of three // values. return 1 + min(editDist(str1, str2, m, n - 1), // Insert editDist(str1, str2, m - 1, n), // Remove editDist(str1, str2, m - 1, n - 1) // Replace ); } // Driver code public static void Main() { String str1 = \"sunday\"; String str2 = \"saturday\"; Console.WriteLine( editDist(str1, str2, str1.Length, str2.Length)); }} // This Code is Contributed by Sam007", "e": 42494, "s": 40816, "text": null }, { "code": "<?php// A Naive recursive Python program // to find minimum number operations// to convert str1 to str2function editDistance($str1, $str2, $m, $n){ // If first string is empty, // the only option is to insert. // all characters of second // string into first if ($m == 0) return $n; // If second string is empty, // the only option is to // remove all characters of // first string if ($n == 0) return $m; // If last characters of two // strings are same, nothing // much to do. Ignore last // characters and get count // for remaining strings. if ($str1[$m - 1] == $str2[$n - 1]) { return editDistance($str1, $str2, $m - 1, $n - 1); } // If last characters are not same, // consider all three operations on // last character of first string, // recursively compute minimum cost // for all three operations and take // minimum of three values. return 1 + min(editDistance($str1, $str2, $m, $n - 1), // Insert editDistance($str1, $str2, $m - 1, $n), // Remove editDistance($str1, $str2, $m - 1, $n - 1)); // Replace} // Driver Code$str1 = \"sunday\";$str2 = \"saturday\";echo editDistance($str1, $str2, strlen($str1), strlen($str2)); // This code is contributed// by Shivi_Aggarwal?>", "e": 43985, "s": 42494, "text": null }, { "code": "<script> // Javascript program to// find minimum numberoperations// to convert str1 to str2function min(x, y, z){ if (x <= y && x <= z) return x; if (y <= x && y <= z) return y; else return z;} function editDist(str1, str2, m, n){ // If first string is empty, the // only option is to insert all // characters of second string into first if (m == 0) return n; // If second string is empty, the only // option is to remove all characters // of first string if (n == 0) return m; // If last characters of two strings are // same, nothing much to do. Ignore last // characters and get count for remaining // strings. if (str1[m - 1] == str2[n - 1]) return editDist(str1, str2, m - 1, n - 1); // If last characters are not same, consider all // three operations on last character of first // string, recursively compute minimum cost for all // three operations and take minimum of three // values. return 1 + min(editDist(str1, str2, m, n - 1), // Insert editDist(str1, str2, m - 1, n), // Remove editDist(str1, str2, m - 1, n - 1)); // Replace} // Driver codelet str1 = \"sunday\";let str2 = \"saturday\";document.write(editDist(str1, str2, str1.length, str2.length)); // This code is contributed by target_2 </script>", "e": 45365, "s": 43985, "text": null }, { "code": null, "e": 45370, "s": 45368, "text": "3" }, { "code": null, "e": 45599, "s": 45372, "text": "The time complexity of above solution is exponential. In worst case, we may end up doing O(3m) operations. The worst case happens when none of characters of two strings match. Below is a recursive call diagram for worst case. " }, { "code": null, "e": 46074, "s": 45603, "text": "We can see that many subproblems are solved, again and again, for example, eD(2, 2) is called three times. Since same subproblems are called again, this problem has Overlapping Subproblems property. So Edit Distance problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be avoided by constructing a temporary array that stores results of subproblems." }, { "code": null, "e": 46080, "s": 46076, "text": "C++" }, { "code": null, "e": 46085, "s": 46080, "text": "Java" }, { "code": null, "e": 46093, "s": 46085, "text": "Python3" }, { "code": null, "e": 46096, "s": 46093, "text": "C#" }, { "code": null, "e": 46100, "s": 46096, "text": "PHP" }, { "code": null, "e": 46111, "s": 46100, "text": "Javascript" }, { "code": "// A Dynamic Programming based C++ program to find minimum// number operations to convert str1 to str2#include <bits/stdc++.h>using namespace std; // Utility function to find the minimum of three numbersint min(int x, int y, int z) { return min(min(x, y), z); } int editDistDP(string str1, string str2, int m, int n){ // Create a table to store results of subproblems int dp[m + 1][n + 1]; // Fill d[][] in bottom up manner for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { // If first string is empty, only option is to // insert all characters of second string if (i == 0) dp[i][j] = j; // Min. operations = j // If second string is empty, only option is to // remove all characters of second string else if (j == 0) dp[i][j] = i; // Min. operations = i // If last characters are same, ignore last char // and recur for remaining string else if (str1[i - 1] == str2[j - 1]) dp[i][j] = dp[i - 1][j - 1]; // If the last character is different, consider // all possibilities and find the minimum else dp[i][j] = 1 + min(dp[i][j - 1], // Insert dp[i - 1][j], // Remove dp[i - 1][j - 1]); // Replace } } return dp[m][n];} // Driver codeint main(){ // your code goes here string str1 = \"sunday\"; string str2 = \"saturday\"; cout << editDistDP(str1, str2, str1.length(), str2.length()); return 0;}", "e": 47776, "s": 46111, "text": null }, { "code": "// A Dynamic Programming based Java program to find minimum// number operations to convert str1 to str2class EDIST { static int min(int x, int y, int z) { if (x <= y && x <= z) return x; if (y <= x && y <= z) return y; else return z; } static int editDistDP(String str1, String str2, int m, int n) { // Create a table to store results of subproblems int dp[][] = new int[m + 1][n + 1]; // Fill d[][] in bottom up manner for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { // If first string is empty, only option is // to insert all characters of second string if (i == 0) dp[i][j] = j; // Min. operations = j // If second string is empty, only option is // to remove all characters of second string else if (j == 0) dp[i][j] = i; // Min. operations = i // If last characters are same, ignore last // char and recur for remaining string else if (str1.charAt(i - 1) == str2.charAt(j - 1)) dp[i][j] = dp[i - 1][j - 1]; // If the last character is different, // consider all possibilities and find the // minimum else dp[i][j] = 1 + min(dp[i][j - 1], // Insert dp[i - 1][j], // Remove dp[i - 1] [j - 1]); // Replace } } return dp[m][n]; } // Driver Code public static void main(String args[]) { String str1 = \"sunday\"; String str2 = \"saturday\"; System.out.println(editDistDP( str1, str2, str1.length(), str2.length())); }} /*This code is contributed by Rajat Mishra*/", "e": 49798, "s": 47776, "text": null }, { "code": "# A Dynamic Programming based Python program for edit# distance problem def editDistDP(str1, str2, m, n): # Create a table to store results of subproblems dp = [[0 for x in range(n + 1)] for x in range(m + 1)] # Fill d[][] in bottom up manner for i in range(m + 1): for j in range(n + 1): # If first string is empty, only option is to # insert all characters of second string if i == 0: dp[i][j] = j # Min. operations = j # If second string is empty, only option is to # remove all characters of second string elif j == 0: dp[i][j] = i # Min. operations = i # If last characters are same, ignore last char # and recur for remaining string elif str1[i-1] == str2[j-1]: dp[i][j] = dp[i-1][j-1] # If last character are different, consider all # possibilities and find minimum else: dp[i][j] = 1 + min(dp[i][j-1], # Insert dp[i-1][j], # Remove dp[i-1][j-1]) # Replace return dp[m][n] # Driver codestr1 = \"sunday\"str2 = \"saturday\" print(editDistDP(str1, str2, len(str1), len(str2)))# This code is contributed by Bhavya Jain", "e": 51130, "s": 49798, "text": null }, { "code": "// A Dynamic Programming based// C# program to find minimum// number operations to// convert str1 to str2using System; class GFG { static int min(int x, int y, int z) { if (x <= y && x <= z) return x; if (y <= x && y <= z) return y; else return z; } static int editDistDP(String str1, String str2, int m, int n) { // Create a table to store // results of subproblems int[, ] dp = new int[m + 1, n + 1]; // Fill d[][] in bottom up manner for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { // If first string is empty, only option is // to insert all characters of second string if (i == 0) // Min. operations = j dp[i, j] = j; // If second string is empty, only option is // to remove all characters of second string else if (j == 0) // Min. operations = i dp[i, j] = i; // If last characters are same, ignore last // char and recur for remaining string else if (str1[i - 1] == str2[j - 1]) dp[i, j] = dp[i - 1, j - 1]; // If the last character is different, // consider all possibilities and find the // minimum else dp[i, j] = 1 + min(dp[i, j - 1], // Insert dp[i - 1, j], // Remove dp[i - 1, j - 1]); // Replace } } return dp[m, n]; } // Driver code public static void Main() { String str1 = \"sunday\"; String str2 = \"saturday\"; Console.Write(editDistDP(str1, str2, str1.Length, str2.Length)); }}// This Code is Contributed by Sam007", "e": 53168, "s": 51130, "text": null }, { "code": "<?php// A Dynamic Programming based// Python program for edit// distance problemfunction editDistDP($str1, $str2, $m, $n){// Fill d[][] in bottom up mannerfor ($i = 0; $i <= $m; $i++){ for ($j = 0; $j <= $n; $j++) { // If first string is empty, // only option is to insert // all characters of second string if ($i == 0) $dp[$i][$j] = $j ; // Min. operations = j // If second string is empty, // only option is to remove // all characters of second string else if($j == 0) $dp[$i][$j] = $i; // Min. operations = i // If last characters are same, // ignore last char and recur // for remaining string else if($str1[$i - 1] == $str2[$j - 1]) $dp[$i][$j] = $dp[$i - 1][$j - 1]; // If last character are different, // consider all possibilities and // find minimum else { $dp[$i][$j] = 1 + min($dp[$i][$j - 1], // Insert $dp[$i - 1][$j], // Remove $dp[$i - 1][$j - 1]); // Replace } }}return $dp[$m][$n] ;} // Driver Code$str1 = \"sunday\";$str2 = \"saturday\"; echo editDistDP($str1, $str2, strlen($str1), strlen($str2)); // This code is contributed// by Shivi_Aggarwal?>", "e": 54539, "s": 53168, "text": null }, { "code": "<script> // A Dynamic Programming based// Javascript program to find minimum// number operations to convert str1 to str2 function min(x,y,z){ if (x <= y && x <= z) return x; if (y <= x && y <= z) return y; else return z;} function editDistDP(str1,str2,m,n){ // Create a table to store results of subproblems let dp = new Array(m + 1); for(let i=0;i<m+1;i++) { dp[i]=new Array(n+1); for(let j=0;j<n+1;j++) { dp[i][j]=0; } } // Fill d[][] in bottom up manner for (let i = 0; i <= m; i++) { for (let j = 0; j <= n; j++) { // If first string is empty, only option is // to insert all characters of second string if (i == 0) dp[i][j] = j; // Min. operations = j // If second string is empty, only option is // to remove all characters of second string else if (j == 0) dp[i][j] = i; // Min. operations = i // If last characters are same, ignore last // char and recur for remaining string else if (str1[i - 1] == str2[j - 1]) dp[i][j] = dp[i - 1][j - 1]; // If the last character is different, // consider all possibilities and find the // minimum else dp[i][j] = 1 + min(dp[i][j - 1], // Insert dp[i - 1][j], // Remove dp[i - 1] [j - 1]); // Replace } } return dp[m][n];} // Driver Codelet str1 = \"sunday\";let str2 = \"saturday\";document.write(editDistDP(str1, str2, str1.length, str2.length)); // This code is contributed by unknown2108 </script>", "e": 56517, "s": 54539, "text": null }, { "code": null, "e": 56519, "s": 56517, "text": "3" }, { "code": null, "e": 56571, "s": 56519, "text": "Time Complexity: O(m x n) Auxiliary Space: O(m x n)" }, { "code": null, "e": 57083, "s": 56571, "text": "Space Complex Solution: In the above-given method we require O(m x n) space. This will not be suitable if the length of strings is greater than 2000 as it can only create 2D array of 2000 x 2000. To fill a row in DP array we require only one row the upper row. For example, if we are filling the i = 10 rows in DP array we require only values of 9th row. So we simply create a DP array of 2 x str1 length. This approach reduces the space complexity. Here is the C++ implementation of the above-mentioned problem" }, { "code": null, "e": 57087, "s": 57083, "text": "C++" }, { "code": null, "e": 57092, "s": 57087, "text": "Java" }, { "code": null, "e": 57100, "s": 57092, "text": "Python3" }, { "code": null, "e": 57103, "s": 57100, "text": "C#" }, { "code": null, "e": 57114, "s": 57103, "text": "Javascript" }, { "code": "// A Space efficient Dynamic Programming// based C++ program to find minimum// number operations to convert str1 to str2#include <bits/stdc++.h>using namespace std; void EditDistDP(string str1, string str2){ int len1 = str1.length(); int len2 = str2.length(); // Create a DP array to memoize result // of previous computations int DP[2][len1 + 1]; // To fill the DP array with 0 memset(DP, 0, sizeof DP); // Base condition when second string // is empty then we remove all characters for (int i = 0; i <= len1; i++) DP[0][i] = i; // Start filling the DP // This loop run for every // character in second string for (int i = 1; i <= len2; i++) { // This loop compares the char from // second string with first string // characters for (int j = 0; j <= len1; j++) { // if first string is empty then // we have to perform add character // operation to get second string if (j == 0) DP[i % 2][j] = i; // if character from both string // is same then we do not perform any // operation . here i % 2 is for bound // the row number. else if (str1[j - 1] == str2[i - 1]) { DP[i % 2][j] = DP[(i - 1) % 2][j - 1]; } // if character from both string is // not same then we take the minimum // from three specified operation else { DP[i % 2][j] = 1 + min(DP[(i - 1) % 2][j], min(DP[i % 2][j - 1], DP[(i - 1) % 2][j - 1])); } } } // after complete fill the DP array // if the len2 is even then we end // up in the 0th row else we end up // in the 1th row so we take len2 % 2 // to get row cout << DP[len2 % 2][len1] << endl;} // Driver programint main(){ string str1 = \"food\"; string str2 = \"money\"; EditDistDP(str1, str2); return 0;}", "e": 59150, "s": 57114, "text": null }, { "code": "// A Space efficient Dynamic Programming// based Java program to find minimum// number operations to convert str1 to str2import java.util.*;class GFG{ static void EditDistDP(String str1, String str2){ int len1 = str1.length(); int len2 = str2.length(); // Create a DP array to memoize result // of previous computations int [][]DP = new int[2][len1 + 1]; // Base condition when second String // is empty then we remove all characters for (int i = 0; i <= len1; i++) DP[0][i] = i; // Start filling the DP // This loop run for every // character in second String for (int i = 1; i <= len2; i++) { // This loop compares the char from // second String with first String // characters for (int j = 0; j <= len1; j++) { // if first String is empty then // we have to perform add character // operation to get second String if (j == 0) DP[i % 2][j] = i; // if character from both String // is same then we do not perform any // operation . here i % 2 is for bound // the row number. else if (str1.charAt(j - 1) == str2.charAt(i - 1)) { DP[i % 2][j] = DP[(i - 1) % 2][j - 1]; } // if character from both String is // not same then we take the minimum // from three specified operation else { DP[i % 2][j] = 1 + Math.min(DP[(i - 1) % 2][j], Math.min(DP[i % 2][j - 1], DP[(i - 1) % 2][j - 1])); } } } // after complete fill the DP array // if the len2 is even then we end // up in the 0th row else we end up // in the 1th row so we take len2 % 2 // to get row System.out.print(DP[len2 % 2][len1] +\"\\n\");} // Driver programpublic static void main(String[] args){ String str1 = \"food\"; String str2 = \"money\"; EditDistDP(str1, str2);}} // This code is contributed by aashish1995", "e": 61249, "s": 59150, "text": null }, { "code": "# A Space efficient Dynamic Programming# based Python3 program to find minimum# number operations to convert str1 to str2def EditDistDP(str1, str2): len1 = len(str1) len2 = len(str2) # Create a DP array to memoize result # of previous computations DP = [[0 for i in range(len1 + 1)] for j in range(2)]; # Base condition when second String # is empty then we remove all characters for i in range(0, len1 + 1): DP[0][i] = i # Start filling the DP # This loop run for every # character in second String for i in range(1, len2 + 1): # This loop compares the char from # second String with first String # characters for j in range(0, len1 + 1): # If first String is empty then # we have to perform add character # operation to get second String if (j == 0): DP[i % 2][j] = i # If character from both String # is same then we do not perform any # operation . here i % 2 is for bound # the row number. else if(str1[j - 1] == str2[i-1]): DP[i % 2][j] = DP[(i - 1) % 2][j - 1] # If character from both String is # not same then we take the minimum # from three specified operation else: DP[i % 2][j] = (1 + min(DP[(i - 1) % 2][j], min(DP[i % 2][j - 1], DP[(i - 1) % 2][j - 1]))) # After complete fill the DP array # if the len2 is even then we end # up in the 0th row else we end up # in the 1th row so we take len2 % 2 # to get row print(DP[len2 % 2][len1], \"\") # Driver codeif __name__ == '__main__': str1 = \"food\" str2 = \"money\" EditDistDP(str1, str2) # This code is contributed by gauravrajput1", "e": 63160, "s": 61249, "text": null }, { "code": "// A Space efficient Dynamic Programming// based C# program to find minimum// number operations to convert str1 to str2using System;class GFG{ static void EditDistDP(String str1, String str2){ int len1 = str1.Length; int len2 = str2.Length; // Create a DP array to memoize result // of previous computations int [,]DP = new int[2, len1 + 1]; // Base condition when second String // is empty then we remove all characters for (int i = 0; i <= len1; i++) DP[0, i] = i; // Start filling the DP // This loop run for every // character in second String for (int i = 1; i <= len2; i++) { // This loop compares the char from // second String with first String // characters for (int j = 0; j <= len1; j++) { // if first String is empty then // we have to perform add character // operation to get second String if (j == 0) DP[i % 2, j] = i; // if character from both String // is same then we do not perform any // operation . here i % 2 is for bound // the row number. else if (str1[j - 1] == str2[i - 1]) { DP[i % 2, j] = DP[(i - 1) % 2, j - 1]; } // if character from both String is // not same then we take the minimum // from three specified operation else { DP[i % 2, j] = 1 + Math.Min(DP[(i - 1) % 2, j], Math.Min(DP[i % 2, j - 1], DP[(i - 1) % 2, j - 1])); } } } // after complete fill the DP array // if the len2 is even then we end // up in the 0th row else we end up // in the 1th row so we take len2 % 2 // to get row Console.Write(DP[len2 % 2, len1] +\"\\n\");} // Driver programpublic static void Main(String[] args){ String str1 = \"food\"; String str2 = \"money\"; EditDistDP(str1, str2);}} // This code is contributed by aashish1995", "e": 65240, "s": 63160, "text": null }, { "code": "<script>// A Space efficient Dynamic Programming// based Javascript program to find minimum// number operations to convert str1 to str2function EditDistDP(str1, str2){ let len1 = str1.length; let len2 = str2.length; // Create a DP array to memoize result // of previous computations let DP = new Array(2); for(let i = 0; i < 2; i++) { DP[i] = new Array(len1+1); for(let j = 0; j < len1 + 1; j++) DP[i][j] = 0; } // Base condition when second String // is empty then we remove all characters for (let i = 0; i <= len1; i++) DP[0][i] = i; // Start filling the DP // This loop run for every // character in second String for (let i = 1; i <= len2; i++) { // This loop compares the char from // second String with first String // characters for (let j = 0; j <= len1; j++) { // if first String is empty then // we have to perform add character // operation to get second String if (j == 0) DP[i % 2][j] = i; // if character from both String // is same then we do not perform any // operation . here i % 2 is for bound // the row number. else if (str1[j-1] == str2[i-1]) { DP[i % 2][j] = DP[(i - 1) % 2][j - 1]; } // if character from both String is // not same then we take the minimum // from three specified operation else { DP[i % 2][j] = 1 + Math.min(DP[(i - 1) % 2][j], Math.min(DP[i % 2][j - 1], DP[(i - 1) % 2][j - 1])); } } } // after complete fill the DP array // if the len2 is even then we end // up in the 0th row else we end up // in the 1th row so we take len2 % 2 // to get row document.write(DP[len2 % 2][len1] +\"<br>\");} // Driver programlet str1 = \"food\";let str2 = \"money\";EditDistDP(str1, str2); // This code is contributed by patel2127.</script>", "e": 67370, "s": 65240, "text": null }, { "code": null, "e": 67372, "s": 67370, "text": "4" }, { "code": null, "e": 67422, "s": 67372, "text": "Time Complexity: O(m x n) Auxiliary Space: O( m )" }, { "code": null, "e": 67480, "s": 67422, "text": "This is a memoized version of recursion i.e. Top-Down DP:" }, { "code": null, "e": 67486, "s": 67480, "text": "C++14" }, { "code": null, "e": 67491, "s": 67486, "text": "Java" }, { "code": null, "e": 67499, "s": 67491, "text": "Python3" }, { "code": null, "e": 67502, "s": 67499, "text": "C#" }, { "code": null, "e": 67513, "s": 67502, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std;int minDis(string s1, string s2, int n, int m, vector<vector<int>> &dp){ // If any string is empty, // return the remaining characters of other string if(n==0) return m; if(m==0) return n; // To check if the recursive tree // for given n & m has already been executed if(dp[n][m]!=-1) return dp[n][m]; // If characters are equal, execute // recursive function for n-1, m-1 if(s1[n-1]==s2[m-1]){ if(dp[n-1][m-1]==-1){ return dp[n][m] = minDis(s1, s2, n-1, m-1, dp); } else return dp[n][m] = dp[n-1][m-1]; } // If characters are nt equal, we need to // find the minimum cost out of all 3 operations. else{ int m1, m2, m3; // temp variables if(dp[n-1][m]!=-1){ m1 = dp[n-1][m]; } else{ m1 = minDis(s1, s2, n-1, m, dp); } if(dp[n][m-1]!=-1){ m2 = dp[n][m-1]; } else{ m2 = minDis(s1, s2, n, m-1, dp); } if(dp[n-1][m-1]!=-1){ m3 = dp[n-1][m-1]; } else{ m3 = minDis(s1, s2, n-1, m-1, dp); } return dp[n][m] = 1+min(m1, min(m2, m3)); } } // Driver programint main() { string str1 = \"voldemort\"; string str2 = \"dumbledore\"; int n= str1.length(), m = str2.length(); vector<vector<int>> dp(n+1, vector<int>(m+1, -1)); cout<<minDis(str1, str2, n, m, dp); return 0; // This code is a contribution of Bhavneet Singh }", "e": 69276, "s": 67513, "text": null }, { "code": "import java.util.*;class GFG{ static int minDis(String s1, String s2, int n, int m, int[][]dp){ // If any String is empty, // return the remaining characters of other String if(n == 0) return m; if(m == 0) return n; // To check if the recursive tree // for given n & m has already been executed if(dp[n][m] != -1) return dp[n][m]; // If characters are equal, execute // recursive function for n-1, m-1 if(s1.charAt(n - 1) == s2.charAt(m - 1)) { if(dp[n - 1][m - 1] == -1) { return dp[n][m] = minDis(s1, s2, n - 1, m - 1, dp); } else return dp[n][m] = dp[n - 1][m - 1]; } // If characters are nt equal, we need to // find the minimum cost out of all 3 operations. else { int m1, m2, m3; // temp variables if(dp[n-1][m] != -1) { m1 = dp[n - 1][m]; } else { m1 = minDis(s1, s2, n - 1, m, dp); } if(dp[n][m - 1] != -1) { m2 = dp[n][m - 1]; } else { m2 = minDis(s1, s2, n, m - 1, dp); } if(dp[n - 1][m - 1] != -1) { m3 = dp[n - 1][m - 1]; } else { m3 = minDis(s1, s2, n - 1, m - 1, dp); } return dp[n][m] = 1 + Math.min(m1, Math.min(m2, m3)); }} // Driver programpublic static void main(String[] args){ String str1 = \"voldemort\"; String str2 = \"dumbledore\"; int n= str1.length(), m = str2.length(); int[][] dp = new int[n + 1][m + 1]; for(int i = 0; i < n + 1; i++) Arrays.fill(dp[i], -1); System.out.print(minDis(str1, str2, n, m, dp));}} // This code is contributed by gauravrajput1", "e": 71142, "s": 69276, "text": null }, { "code": "def minDis(s1, s2, n, m, dp) : # If any string is empty, # return the remaining characters of other string if(n == 0) : return m if(m == 0) : return n # To check if the recursive tree # for given n & m has already been executed if(dp[n][m] != -1) : return dp[n][m]; # If characters are equal, execute # recursive function for n-1, m-1 if(s1[n - 1] == s2[m - 1]) : if(dp[n - 1][m - 1] == -1) : dp[n][m] = minDis(s1, s2, n - 1, m - 1, dp) return dp[n][m] else : dp[n][m] = dp[n - 1][m - 1] return dp[n][m] # If characters are nt equal, we need to # find the minimum cost out of all 3 operations. else : if(dp[n - 1][m] != -1) : m1 = dp[n - 1][m] else : m1 = minDis(s1, s2, n - 1, m, dp) if(dp[n][m - 1] != -1) : m2 = dp[n][m - 1] else : m2 = minDis(s1, s2, n, m - 1, dp) if(dp[n - 1][m - 1] != -1) : m3 = dp[n - 1][m - 1] else : m3 = minDis(s1, s2, n - 1, m - 1, dp) dp[n][m] = 1 + min(m1, min(m2, m3)) return dp[n][m] # Driver codestr1 = \"voldemort\"str2 = \"dumbledore\" n = len(str1)m = len(str2)dp = [[-1 for i in range(m + 1)] for j in range(n + 1)] print(minDis(str1, str2, n, m, dp)) # This code is contributed by divyesh072019.", "e": 72608, "s": 71142, "text": null }, { "code": "using System;using System.Collections.Generic;class GFG { static int minDis(string s1, string s2, int n, int m, List<List<int>> dp) { // If any string is empty, // return the remaining characters of other string if(n == 0) return m; if(m == 0) return n; // To check if the recursive tree // for given n & m has already been executed if(dp[n][m] != -1) return dp[n][m]; // If characters are equal, execute // recursive function for n-1, m-1 if(s1[n - 1] == s2[m - 1]) { if(dp[n - 1][m - 1] == -1) { return dp[n][m] = minDis(s1, s2, n - 1, m - 1, dp); } else return dp[n][m] = dp[n - 1][m - 1]; } // If characters are nt equal, we need to // find the minimum cost out of all 3 operations. else { int m1, m2, m3; // temp variables if(dp[n - 1][m] != -1) { m1 = dp[n - 1][m]; } else { m1 = minDis(s1, s2, n - 1, m, dp); } if(dp[n][m - 1] != -1) { m2 = dp[n][m - 1]; } else { m2 = minDis(s1, s2, n, m - 1, dp); } if(dp[n - 1][m - 1] != -1) { m3 = dp[n - 1][m - 1]; } else { m3 = minDis(s1, s2, n - 1, m - 1, dp); } return dp[n][m] = 1+ Math.Min(m1, Math.Min(m2, m3)); } } // Driver code static void Main() { string str1 = \"voldemort\"; string str2 = \"dumbledore\"; int n = str1.Length, m = str2.Length; List<List<int>> dp = new List<List<int>>(); for(int i = 0; i < n + 1; i++) { dp.Add(new List<int>()); for(int j = 0; j < m + 1; j++) { dp[i].Add(-1); } } Console.WriteLine(minDis(str1, str2, n, m, dp)); }} // This code is contributed by divyeshrabadiya07.", "e": 74606, "s": 72608, "text": null }, { "code": "<script> function minDis(s1,s2,n,m,dp){ // If any String is empty, // return the remaining characters of other String if(n == 0) return m; if(m == 0) return n; // To check if the recursive tree // for given n & m has already been executed if(dp[n][m] != -1) return dp[n][m]; // If characters are equal, execute // recursive function for n-1, m-1 if(s1[n - 1] == s2[m - 1]) { if(dp[n - 1][m - 1] == -1) { return dp[n][m] = minDis(s1, s2, n - 1, m - 1, dp); } else return dp[n][m] = dp[n - 1][m - 1]; } // If characters are nt equal, we need to // find the minimum cost out of all 3 operations. else { let m1, m2, m3; // temp variables if(dp[n-1][m] != -1) { m1 = dp[n - 1][m]; } else { m1 = minDis(s1, s2, n - 1, m, dp); } if(dp[n][m - 1] != -1) { m2 = dp[n][m - 1]; } else { m2 = minDis(s1, s2, n, m - 1, dp); } if(dp[n - 1][m - 1] != -1) { m3 = dp[n - 1][m - 1]; } else { m3 = minDis(s1, s2, n - 1, m - 1, dp); } return dp[n][m] = 1 + Math.min(m1, Math.min(m2, m3)); }} // Driver program let str1 = \"voldemort\";let str2 = \"dumbledore\"; let n= str1.length, m = str2.length; let dp = new Array(n + 1);for(let i = 0; i < n + 1; i++){ dp[i]=new Array(m+1); for(let j=0;j<m+1;j++) dp[i][j]=-1;} document.write(minDis(str1, str2, n, m, dp)); // This code is contributed by avanitrachhadiya2155 </script>", "e": 76317, "s": 74606, "text": null }, { "code": null, "e": 76319, "s": 76317, "text": "7" }, { "code": null, "e": 76548, "s": 76319, "text": "Applications: There are many practical applications of edit distance algorithm, refer Lucene API for sample. Another example, display all the words in a dictionary that are near proximity to a given wordincorrectly spelled word." }, { "code": null, "e": 77390, "s": 76548, "text": "YouTubeGeeksforGeeks500K subscribersDynamic Programming | Set 5 (Edit Distance) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:04•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Thv3TfsZVpw\" 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": 77604, "s": 77390, "text": "Thanks to Vivek Kumar for suggesting updates.Thanks to Venki for providing initial post. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 77619, "s": 77604, "text": "Shivi_Aggarwal" }, { "code": null, "e": 77630, "s": 77619, "text": "SahilSingh" }, { "code": null, "e": 77643, "s": 77630, "text": "AdarshGupta7" }, { "code": null, "e": 77658, "s": 77643, "text": "BhardwajNeeraj" }, { "code": null, "e": 77671, "s": 77658, "text": "bhavneet2000" }, { "code": null, "e": 77683, "s": 77671, "text": "aashish1995" }, { "code": null, "e": 77697, "s": 77683, "text": "GauravRajput1" }, { "code": null, "e": 77715, "s": 77697, "text": "divyeshrabadiya07" }, { "code": null, "e": 77729, "s": 77715, "text": "divyesh072019" }, { "code": null, "e": 77738, "s": 77729, "text": "target_2" }, { "code": null, "e": 77750, "s": 77738, "text": "anikakapoor" }, { "code": null, "e": 77762, "s": 77750, "text": "unknown2108" }, { "code": null, "e": 77772, "s": 77762, "text": "patel2127" }, { "code": null, "e": 77793, "s": 77772, "text": "avanitrachhadiya2155" }, { "code": null, "e": 77810, "s": 77793, "text": "akshaysingh98088" }, { "code": null, "e": 77827, "s": 77810, "text": "arorakashish0911" }, { "code": null, "e": 77843, "s": 77827, "text": "amartyaghoshgfg" }, { "code": null, "e": 77857, "s": 77843, "text": "sumitgumber28" }, { "code": null, "e": 77867, "s": 77857, "text": "tathagato" }, { "code": null, "e": 77884, "s": 77867, "text": "surinderdawra388" }, { "code": null, "e": 77891, "s": 77884, "text": "Amazon" }, { "code": null, "e": 77905, "s": 77891, "text": "edit-distance" }, { "code": null, "e": 77925, "s": 77905, "text": "Dynamic Programming" }, { "code": null, "e": 77932, "s": 77925, "text": "Amazon" }, { "code": null, "e": 77952, "s": 77932, "text": "Dynamic Programming" }, { "code": null, "e": 78050, "s": 77952, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 78059, "s": 78050, "text": "Comments" }, { "code": null, "e": 78072, "s": 78059, "text": "Old Comments" }, { "code": null, "e": 78103, "s": 78072, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 78136, "s": 78103, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 78168, "s": 78136, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 78236, "s": 78168, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 78263, "s": 78236, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 78301, "s": 78263, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 78364, "s": 78301, "text": "Efficient program to print all prime factors of a given number" }, { "code": null, "e": 78386, "s": 78364, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 78470, "s": 78386, "text": "Partition a set into two subsets such that the difference of subset sums is minimum" } ]
How to check if a character is upper-case in Python?
To check if a character is upper-case, we can simply use isupper() function call on the said character. print( 'Z'.isupper()) print( 'u'.isupper()) True False We can also check it using range based if conditions. def check_upper(c): if c >= 'A' and c <= 'Z': return True else: return False print check_upper('A') print check_upper('a') This will give us the output: True False
[ { "code": null, "e": 1167, "s": 1062, "text": "To check if a character is upper-case, we can simply use isupper() function call on the said character. " }, { "code": null, "e": 1211, "s": 1167, "text": "print( 'Z'.isupper())\nprint( 'u'.isupper())" }, { "code": null, "e": 1222, "s": 1211, "text": "True\nFalse" }, { "code": null, "e": 1277, "s": 1222, "text": "We can also check it using range based if conditions. " }, { "code": null, "e": 1424, "s": 1277, "text": "def check_upper(c):\n if c >= 'A' and c <= 'Z':\n return True\n else:\n return False\nprint check_upper('A')\nprint check_upper('a')" }, { "code": null, "e": 1454, "s": 1424, "text": "This will give us the output:" }, { "code": null, "e": 1465, "s": 1454, "text": "True\nFalse" } ]
Difference between HashTable and ConcurrentHashMap in Java
Concurrent Hashmap is a class that was introduced in jdk1.5. Concurrent hash map applies locks only at bucket level called fragment while adding or updating the map. So, a concurrent hash map allows concurrent read and write operations to the map. HashTable is a thread-safe legacy class introduced in the Jdk1.1. It is a base implementation of Map interface. It doesn't allow null keys and values. It is synchronized in nature so two different threads can’t access simultaneously. Hashtable does not maintain any order. 1 Basic ConcurrentHashmap is a class that was introduced in jdk1.5 2 Locking It applies lock on the entire collection ConcurrentHashMap apply locks only at bucket level called fragment while adding or updating the map 3 Performance It is better than HashTable 4. Null It doesn't allow null key and value It allows null key and value import java.util.ArrayList; import java.util.EnumMap; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; public class HashtableExample { public static void main(String[] args) { // create Hashtable Hashtable map = new Hashtable(); map.put("HCL", "100"); map.put("DELL", "200"); map.put("IBM", "300"); // print the map for (Map.Entry m : map.entrySet()) { System.out.println(m.getKey() + " " + m.getValue()); } } } import java.util.ArrayList; import java.util.EnumMap; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class ConcurrentHashMapExample { public static void main(String[] args) { // ConcurrentHashMap Map myMap = new ConcurrentHashMap(); myMap.put("HCL", "1"); myMap.put("DELL", "1"); // print the map for (Map.Entry m : map.entrySet()) { System.out.println(m.getKey() + " " + m.getValue()); } } }
[ { "code": null, "e": 1312, "s": 1062, "text": "Concurrent Hashmap is a class that was introduced in jdk1.5. Concurrent hash map applies locks only at bucket level called fragment while adding or updating the map. So, a concurrent hash map allows concurrent read and write operations to the map. " }, { "code": null, "e": 1585, "s": 1312, "text": "HashTable is a thread-safe legacy class introduced in the Jdk1.1. It is a base implementation of Map interface. It doesn't allow null keys and values. It is synchronized in nature so two different threads can’t access simultaneously. Hashtable does not maintain any order." }, { "code": null, "e": 1587, "s": 1585, "text": "1" }, { "code": null, "e": 1594, "s": 1587, "text": "Basic " }, { "code": null, "e": 1654, "s": 1594, "text": " ConcurrentHashmap is a class that was introduced in jdk1.5" }, { "code": null, "e": 1656, "s": 1654, "text": "2" }, { "code": null, "e": 1664, "s": 1656, "text": "Locking" }, { "code": null, "e": 1706, "s": 1664, "text": "It applies lock on the entire collection " }, { "code": null, "e": 1807, "s": 1706, "text": "ConcurrentHashMap apply locks only at bucket level called fragment while adding or updating the map" }, { "code": null, "e": 1809, "s": 1807, "text": "3" }, { "code": null, "e": 1822, "s": 1809, "text": "Performance " }, { "code": null, "e": 1850, "s": 1822, "text": "It is better than HashTable" }, { "code": null, "e": 1853, "s": 1850, "text": "4." }, { "code": null, "e": 1858, "s": 1853, "text": "Null" }, { "code": null, "e": 1894, "s": 1858, "text": "It doesn't allow null key and value" }, { "code": null, "e": 1923, "s": 1894, "text": "It allows null key and value" }, { "code": null, "e": 2448, "s": 1923, "text": "import java.util.ArrayList;\nimport java.util.EnumMap;\nimport java.util.HashMap;\nimport java.util.Hashtable;\nimport java.util.List;\nimport java.util.Map;\npublic class HashtableExample {\n public static void main(String[] args) {\n // create Hashtable\n Hashtable map = new Hashtable();\n map.put(\"HCL\", \"100\");\n map.put(\"DELL\", \"200\");\n map.put(\"IBM\", \"300\");\n // print the map\n for (Map.Entry m : map.entrySet()) {\n System.out.println(m.getKey() + \" \" + m.getValue());\n }\n }\n}" }, { "code": null, "e": 3004, "s": 2448, "text": "import java.util.ArrayList;\nimport java.util.EnumMap;\nimport java.util.HashMap;\nimport java.util.Hashtable;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\npublic class ConcurrentHashMapExample {\n public static void main(String[] args) {\n // ConcurrentHashMap\n Map myMap = new ConcurrentHashMap();\n myMap.put(\"HCL\", \"1\");\n myMap.put(\"DELL\", \"1\");\n // print the map\n for (Map.Entry m : map.entrySet()) {\n System.out.println(m.getKey() + \" \" + m.getValue());\n }\n }\n}" } ]