title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Maximum items that can be bought from the cost Array based on given conditions
|
18 Feb, 2022
Given an array arr[] of size N where every index in the array represents the cost of buying an item and two numbers P, K. The task is to find the maximum number of items which can be bought such that:
If some i-th object is bought from the array, the remaining amount becomes P – arr[i].We can buy K items, not necessarily consecutive, at a time by paying only for the item whose cost is maximum among them. Now, the remaining amount would be P – max(cost of K items).
If some i-th object is bought from the array, the remaining amount becomes P – arr[i].
We can buy K items, not necessarily consecutive, at a time by paying only for the item whose cost is maximum among them. Now, the remaining amount would be P – max(cost of K items).
Examples:
Input: arr[] = {2, 4, 3, 5, 7}, P = 6, K = 2Output: 3 Explanation: We can buy the first item whose cost is 2. So, the remaining amount is P = 6 – 2 = 4. Now, we can choose the second and third item and pay for the maximum one which is max(4, 3) = 4, and the remaining amount is 4 – 4 = 0. Therefore, the total number of items bought is 3.
Input: arr[] = {2, 4, 3, 5, 7}, P = 11, K = 2Output: 4 Explanation: We can buy the first and third item together and pay for only the maximum one which is max(2, 3) = 3. The remaining amount is P = 11 – 3 = 8. Now, we can buy the second and fourth item and pay for the maximum one which is max(4, 5) = 5. The remaining amount is P = 8 – 5 = 3. Now, we cant buy any item further.
Approach: The idea is to use the concept of sorting and prefix sum array.
Sort the given array arr[].
Find the prefix sum for the array arr[].
The idea behind sorting is that the maximum number of items can be bought only when we buy the items with less cost. This type of algorithm is known as a greedy algorithm.
And, we use the prefix sum array to find the cost of buying the items.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find the// maximum number of items// that can be bought from// the given cost array #include <bits/stdc++.h>using namespace std; // Function to find the// maximum number of items// that can be bought from// the given cost arrayint number(int a[], int n, int p, int k){ // Sort the given array sort(a, a + n); // Variables to store the prefix // sum, answer and the counter // variables int pre[n] = { 0 }, val, i, j, ans = 0; // Initializing the first element // of the prefix array pre[0] = a[0]; // If we can buy at least one item if (pre[0] <= p) ans = 1; // Iterating through the first // K items and finding the // prefix sum for (i = 1; i < k - 1; i++) { pre[i] = pre[i - 1] + a[i]; // Check the number of items // that can be bought if (pre[i] <= p) ans = i + 1; } pre[k - 1] = a[k - 1]; // Finding the prefix sum for // the remaining elements for (i = k - 1; i < n; i++) { if (i >= k) { pre[i] += pre[i - k] + a[i]; } // Check the number of items // that can be bought if (pre[i] <= p) ans = i + 1; } return ans;} // Driver codeint main(){ int n = 5; int arr[] = { 2, 4, 3, 5, 7 }; int p = 11; int k = 2; cout << number(arr, n, p, k) << endl; return 0;}
// Java program to find the maximum// number of items that can be bought// from the given cost arrayimport java.io.*;import java.util.*; class GFG{ // Function to find the// maximum number of items// that can be bought from// the given cost arraystatic int number(int[] a, int n, int p, int k){ // Sort the given array Arrays.sort(a); // Variables to store the prefix // sum, answer and the counter // variables int[] pre = new int[n]; int val, i, j, ans = 0; // Initializing the first element // of the prefix array pre[0] = a[0]; // If we can buy at least one item if (pre[0] <= p) ans = 1; // Iterating through the first // K items and finding the // prefix sum for(i = 1; i < k - 1; i++) { pre[i] = pre[i - 1] + a[i]; // Check the number of items // that can be bought if (pre[i] <= p) ans = i + 1; } pre[k - 1] = a[k - 1]; // Finding the prefix sum for // the remaining elements for(i = k - 1; i < n; i++) { if (i >= k) { pre[i] += pre[i - k] + a[i]; } // Check the number of items // that can be bought if (pre[i] <= p) ans = i + 1; } return ans;} // Driver codepublic static void main(String[] args){ int n = 5; int[] arr = { 2, 4, 3, 5, 7 }; int p = 11; int k = 2; System.out.println(number(arr, n, p, k));}} // This code is contributed by akhilsaini
# Python3 program to find the maximum# number of items that can be bought# from the given cost array # Function to find the maximum# number of items that can be# bought from the given cost arraydef number(a, n, p, k): # Sort the given array a.sort() # Variables to store the prefix # sum, answer and the counter # variables pre = [ ] for i in range(n): pre.append(0) ans = 0 val = 0 i = 0 j = 0 # Initializing the first element # of the prefix array pre[0] = a[0] # If we can buy at least one item if pre[0] <= p: ans = 1 # Iterating through the first # K items and finding the # prefix sum for i in range(1, k - 1): pre[i] = pre[i - 1] + a[i] # Check the number of items # that can be bought if pre[i] <= p: ans = i + 1 pre[k - 1] = a[k - 1] # Finding the prefix sum for # the remaining elements for i in range(k - 1, n): if i >= k: pre[i] += pre[i - k] + a[i] # Check the number of items # that can be bought if pre[i] <= p: ans = i+ 1 return ans # Driver coden = 5arr = [ 2, 4, 3, 5, 7 ]p = 11k = 2 print(number(arr, n, p, k)) # This code is contributed by ishayadav181
// C# program to find the maximum// number of items that can be// bought from the given cost arrayusing System;using System.Collections; class GFG{ // Function to find the// maximum number of items// that can be bought from// the given cost arraystatic int number(int[] a, int n, int p, int k){ // Sort the given array Array.Sort(a); // Variables to store the prefix // sum, answer and the counter // variables int[] pre = new int[n]; int i, ans = 0; // Initializing the first element // of the prefix array pre[0] = a[0]; // If we can buy at least one item if (pre[0] <= p) ans = 1; // Iterating through the first // K items and finding the // prefix sum for(i = 1; i < k - 1; i++) { pre[i] = pre[i - 1] + a[i]; // Check the number of items // that can be bought if (pre[i] <= p) ans = i + 1; } pre[k - 1] = a[k - 1]; // Finding the prefix sum for // the remaining elements for(i = k - 1; i < n; i++) { if (i >= k) { pre[i] += pre[i - k] + a[i]; } // Check the number of items // that can be bought if (pre[i] <= p) ans = i + 1; } return ans;} // Driver codestatic public void Main (){ int n = 5; int[] arr = { 2, 4, 3, 5, 7 }; int p = 11; int k = 2; Console.WriteLine(number(arr, n, p, k));}} // This code is contributed by akhilsaini
<script> // Javascript program to find the// maximum number of items// that can be bought from// the given cost array // Function to find the// maximum number of items// that can be bought from// the given cost arrayfunction number(a, n, p, k){ // Sort the given array a.sort(); // Variables to store the prefix // sum, answer and the counter // variables var pre = Array(n).fill(0), val, i, j, ans = 0; // Initializing the first element // of the prefix array pre[0] = a[0]; // If we can buy at least one item if (pre[0] <= p) ans = 1; // Iterating through the first // K items and finding the // prefix sum for (i = 1; i < k - 1; i++) { pre[i] = pre[i - 1] + a[i]; // Check the number of items // that can be bought if (pre[i] <= p) ans = i + 1; } pre[k - 1] = a[k - 1]; // Finding the prefix sum for // the remaining elements for (i = k - 1; i < n; i++) { if (i >= k) { pre[i] += pre[i - k] + a[i]; } // Check the number of items // that can be bought if (pre[i] <= p) ans = i + 1; } return ans;} // Driver codevar n = 5;var arr = [2, 4, 3, 5, 7];var p = 11;var k = 2;document.write( number(arr, n, p, k)); </script>
4
Time Complexity: O(N*logN)
Auxiliary Space: O(N)
ishayadav181
akhilsaini
rutvik_56
rohan07
simranarora5sos
prefix-sum
Arrays
Greedy
Sorting
prefix-sum
Arrays
Greedy
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Multidimensional Arrays in Java
Introduction to Arrays
Dijkstra's shortest path algorithm | Greedy Algo-7
Write a program to print all permutations of a given string
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Activity Selection Problem | Greedy Algo-1
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Feb, 2022"
},
{
"code": null,
"e": 230,
"s": 28,
"text": "Given an array arr[] of size N where every index in the array represents the cost of buying an item and two numbers P, K. The task is to find the maximum number of items which can be bought such that: "
},
{
"code": null,
"e": 498,
"s": 230,
"text": "If some i-th object is bought from the array, the remaining amount becomes P – arr[i].We can buy K items, not necessarily consecutive, at a time by paying only for the item whose cost is maximum among them. Now, the remaining amount would be P – max(cost of K items)."
},
{
"code": null,
"e": 585,
"s": 498,
"text": "If some i-th object is bought from the array, the remaining amount becomes P – arr[i]."
},
{
"code": null,
"e": 767,
"s": 585,
"text": "We can buy K items, not necessarily consecutive, at a time by paying only for the item whose cost is maximum among them. Now, the remaining amount would be P – max(cost of K items)."
},
{
"code": null,
"e": 778,
"s": 767,
"text": "Examples: "
},
{
"code": null,
"e": 1118,
"s": 778,
"text": "Input: arr[] = {2, 4, 3, 5, 7}, P = 6, K = 2Output: 3 Explanation: We can buy the first item whose cost is 2. So, the remaining amount is P = 6 – 2 = 4. Now, we can choose the second and third item and pay for the maximum one which is max(4, 3) = 4, and the remaining amount is 4 – 4 = 0. Therefore, the total number of items bought is 3. "
},
{
"code": null,
"e": 1498,
"s": 1118,
"text": "Input: arr[] = {2, 4, 3, 5, 7}, P = 11, K = 2Output: 4 Explanation: We can buy the first and third item together and pay for only the maximum one which is max(2, 3) = 3. The remaining amount is P = 11 – 3 = 8. Now, we can buy the second and fourth item and pay for the maximum one which is max(4, 5) = 5. The remaining amount is P = 8 – 5 = 3. Now, we cant buy any item further. "
},
{
"code": null,
"e": 1573,
"s": 1498,
"text": "Approach: The idea is to use the concept of sorting and prefix sum array. "
},
{
"code": null,
"e": 1601,
"s": 1573,
"text": "Sort the given array arr[]."
},
{
"code": null,
"e": 1642,
"s": 1601,
"text": "Find the prefix sum for the array arr[]."
},
{
"code": null,
"e": 1814,
"s": 1642,
"text": "The idea behind sorting is that the maximum number of items can be bought only when we buy the items with less cost. This type of algorithm is known as a greedy algorithm."
},
{
"code": null,
"e": 1885,
"s": 1814,
"text": "And, we use the prefix sum array to find the cost of buying the items."
},
{
"code": null,
"e": 1937,
"s": 1885,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1941,
"s": 1937,
"text": "C++"
},
{
"code": null,
"e": 1946,
"s": 1941,
"text": "Java"
},
{
"code": null,
"e": 1954,
"s": 1946,
"text": "Python3"
},
{
"code": null,
"e": 1957,
"s": 1954,
"text": "C#"
},
{
"code": null,
"e": 1968,
"s": 1957,
"text": "Javascript"
},
{
"code": "// C++ program to find the// maximum number of items// that can be bought from// the given cost array #include <bits/stdc++.h>using namespace std; // Function to find the// maximum number of items// that can be bought from// the given cost arrayint number(int a[], int n, int p, int k){ // Sort the given array sort(a, a + n); // Variables to store the prefix // sum, answer and the counter // variables int pre[n] = { 0 }, val, i, j, ans = 0; // Initializing the first element // of the prefix array pre[0] = a[0]; // If we can buy at least one item if (pre[0] <= p) ans = 1; // Iterating through the first // K items and finding the // prefix sum for (i = 1; i < k - 1; i++) { pre[i] = pre[i - 1] + a[i]; // Check the number of items // that can be bought if (pre[i] <= p) ans = i + 1; } pre[k - 1] = a[k - 1]; // Finding the prefix sum for // the remaining elements for (i = k - 1; i < n; i++) { if (i >= k) { pre[i] += pre[i - k] + a[i]; } // Check the number of items // that can be bought if (pre[i] <= p) ans = i + 1; } return ans;} // Driver codeint main(){ int n = 5; int arr[] = { 2, 4, 3, 5, 7 }; int p = 11; int k = 2; cout << number(arr, n, p, k) << endl; return 0;}",
"e": 3353,
"s": 1968,
"text": null
},
{
"code": "// Java program to find the maximum// number of items that can be bought// from the given cost arrayimport java.io.*;import java.util.*; class GFG{ // Function to find the// maximum number of items// that can be bought from// the given cost arraystatic int number(int[] a, int n, int p, int k){ // Sort the given array Arrays.sort(a); // Variables to store the prefix // sum, answer and the counter // variables int[] pre = new int[n]; int val, i, j, ans = 0; // Initializing the first element // of the prefix array pre[0] = a[0]; // If we can buy at least one item if (pre[0] <= p) ans = 1; // Iterating through the first // K items and finding the // prefix sum for(i = 1; i < k - 1; i++) { pre[i] = pre[i - 1] + a[i]; // Check the number of items // that can be bought if (pre[i] <= p) ans = i + 1; } pre[k - 1] = a[k - 1]; // Finding the prefix sum for // the remaining elements for(i = k - 1; i < n; i++) { if (i >= k) { pre[i] += pre[i - k] + a[i]; } // Check the number of items // that can be bought if (pre[i] <= p) ans = i + 1; } return ans;} // Driver codepublic static void main(String[] args){ int n = 5; int[] arr = { 2, 4, 3, 5, 7 }; int p = 11; int k = 2; System.out.println(number(arr, n, p, k));}} // This code is contributed by akhilsaini",
"e": 4842,
"s": 3353,
"text": null
},
{
"code": "# Python3 program to find the maximum# number of items that can be bought# from the given cost array # Function to find the maximum# number of items that can be# bought from the given cost arraydef number(a, n, p, k): # Sort the given array a.sort() # Variables to store the prefix # sum, answer and the counter # variables pre = [ ] for i in range(n): pre.append(0) ans = 0 val = 0 i = 0 j = 0 # Initializing the first element # of the prefix array pre[0] = a[0] # If we can buy at least one item if pre[0] <= p: ans = 1 # Iterating through the first # K items and finding the # prefix sum for i in range(1, k - 1): pre[i] = pre[i - 1] + a[i] # Check the number of items # that can be bought if pre[i] <= p: ans = i + 1 pre[k - 1] = a[k - 1] # Finding the prefix sum for # the remaining elements for i in range(k - 1, n): if i >= k: pre[i] += pre[i - k] + a[i] # Check the number of items # that can be bought if pre[i] <= p: ans = i+ 1 return ans # Driver coden = 5arr = [ 2, 4, 3, 5, 7 ]p = 11k = 2 print(number(arr, n, p, k)) # This code is contributed by ishayadav181",
"e": 6180,
"s": 4842,
"text": null
},
{
"code": "// C# program to find the maximum// number of items that can be// bought from the given cost arrayusing System;using System.Collections; class GFG{ // Function to find the// maximum number of items// that can be bought from// the given cost arraystatic int number(int[] a, int n, int p, int k){ // Sort the given array Array.Sort(a); // Variables to store the prefix // sum, answer and the counter // variables int[] pre = new int[n]; int i, ans = 0; // Initializing the first element // of the prefix array pre[0] = a[0]; // If we can buy at least one item if (pre[0] <= p) ans = 1; // Iterating through the first // K items and finding the // prefix sum for(i = 1; i < k - 1; i++) { pre[i] = pre[i - 1] + a[i]; // Check the number of items // that can be bought if (pre[i] <= p) ans = i + 1; } pre[k - 1] = a[k - 1]; // Finding the prefix sum for // the remaining elements for(i = k - 1; i < n; i++) { if (i >= k) { pre[i] += pre[i - k] + a[i]; } // Check the number of items // that can be bought if (pre[i] <= p) ans = i + 1; } return ans;} // Driver codestatic public void Main (){ int n = 5; int[] arr = { 2, 4, 3, 5, 7 }; int p = 11; int k = 2; Console.WriteLine(number(arr, n, p, k));}} // This code is contributed by akhilsaini",
"e": 7658,
"s": 6180,
"text": null
},
{
"code": "<script> // Javascript program to find the// maximum number of items// that can be bought from// the given cost array // Function to find the// maximum number of items// that can be bought from// the given cost arrayfunction number(a, n, p, k){ // Sort the given array a.sort(); // Variables to store the prefix // sum, answer and the counter // variables var pre = Array(n).fill(0), val, i, j, ans = 0; // Initializing the first element // of the prefix array pre[0] = a[0]; // If we can buy at least one item if (pre[0] <= p) ans = 1; // Iterating through the first // K items and finding the // prefix sum for (i = 1; i < k - 1; i++) { pre[i] = pre[i - 1] + a[i]; // Check the number of items // that can be bought if (pre[i] <= p) ans = i + 1; } pre[k - 1] = a[k - 1]; // Finding the prefix sum for // the remaining elements for (i = k - 1; i < n; i++) { if (i >= k) { pre[i] += pre[i - k] + a[i]; } // Check the number of items // that can be bought if (pre[i] <= p) ans = i + 1; } return ans;} // Driver codevar n = 5;var arr = [2, 4, 3, 5, 7];var p = 11;var k = 2;document.write( number(arr, n, p, k)); </script>",
"e": 8963,
"s": 7658,
"text": null
},
{
"code": null,
"e": 8965,
"s": 8963,
"text": "4"
},
{
"code": null,
"e": 8994,
"s": 8967,
"text": "Time Complexity: O(N*logN)"
},
{
"code": null,
"e": 9016,
"s": 8994,
"text": "Auxiliary Space: O(N)"
},
{
"code": null,
"e": 9029,
"s": 9016,
"text": "ishayadav181"
},
{
"code": null,
"e": 9040,
"s": 9029,
"text": "akhilsaini"
},
{
"code": null,
"e": 9050,
"s": 9040,
"text": "rutvik_56"
},
{
"code": null,
"e": 9058,
"s": 9050,
"text": "rohan07"
},
{
"code": null,
"e": 9074,
"s": 9058,
"text": "simranarora5sos"
},
{
"code": null,
"e": 9085,
"s": 9074,
"text": "prefix-sum"
},
{
"code": null,
"e": 9092,
"s": 9085,
"text": "Arrays"
},
{
"code": null,
"e": 9099,
"s": 9092,
"text": "Greedy"
},
{
"code": null,
"e": 9107,
"s": 9099,
"text": "Sorting"
},
{
"code": null,
"e": 9118,
"s": 9107,
"text": "prefix-sum"
},
{
"code": null,
"e": 9125,
"s": 9118,
"text": "Arrays"
},
{
"code": null,
"e": 9132,
"s": 9125,
"text": "Greedy"
},
{
"code": null,
"e": 9140,
"s": 9132,
"text": "Sorting"
},
{
"code": null,
"e": 9238,
"s": 9140,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9306,
"s": 9238,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 9350,
"s": 9306,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 9398,
"s": 9350,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 9430,
"s": 9398,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 9453,
"s": 9430,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 9504,
"s": 9453,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 9564,
"s": 9504,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 9615,
"s": 9564,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 9673,
"s": 9615,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
}
] |
How to Read and Print an Integer value in C
|
05 Dec, 2018
The given task is to take an integer as input from the user and print that integer in C language.
In below program, the syntax and procedures to take the integer as input from the user is shown in C language.
Steps:
The user enters an integer value when asked.This value is taken from the user with the help of scanf() method. The scanf() method, in C, reads the value from the console as per the type specified.Syntax:scanf("%X", &variableOfXType);
where %X is the format specifier in C
It is a way to tell the compiler
what type of data is in a variable
and
& is the address operator in C,
which tells the compiler to change the
real value of this variable, stored at this
address in the memory.
For an integer value, the X is replaced with type int. The syntax of scanf() method becomes as follows then:Syntax:scanf("%d", &variableOfIntType);
This entered value is now stored in the variableOfIntType.Now to print this value, printf() method is used. The printf() method, in C, prints the value passed as the parameter to it, on the console screen.Syntax:printf("%X", variableOfXType);
For an integer value, the X is replaced with type int. The syntax of printf() method becomes as follows then:Syntax:printf("%d", variableOfIntType);
Hence, the integer value is successfully read and printed.
The user enters an integer value when asked.
This value is taken from the user with the help of scanf() method. The scanf() method, in C, reads the value from the console as per the type specified.Syntax:scanf("%X", &variableOfXType);
where %X is the format specifier in C
It is a way to tell the compiler
what type of data is in a variable
and
& is the address operator in C,
which tells the compiler to change the
real value of this variable, stored at this
address in the memory.
Syntax:
scanf("%X", &variableOfXType);
where %X is the format specifier in C
It is a way to tell the compiler
what type of data is in a variable
and
& is the address operator in C,
which tells the compiler to change the
real value of this variable, stored at this
address in the memory.
For an integer value, the X is replaced with type int. The syntax of scanf() method becomes as follows then:Syntax:scanf("%d", &variableOfIntType);
Syntax:
scanf("%d", &variableOfIntType);
This entered value is now stored in the variableOfIntType.
Now to print this value, printf() method is used. The printf() method, in C, prints the value passed as the parameter to it, on the console screen.Syntax:printf("%X", variableOfXType);
Syntax:
printf("%X", variableOfXType);
For an integer value, the X is replaced with type int. The syntax of printf() method becomes as follows then:Syntax:printf("%d", variableOfIntType);
Syntax:
printf("%d", variableOfIntType);
Hence, the integer value is successfully read and printed.
Program:
C
// C program to take an integer// as input and print it #include <stdio.h> int main(){ // Declare the variables int num; // Input the integer printf("Enter the integer: "); scanf("%d", &num); // Display the integer printf("Entered integer is: %d", num); return 0;}
Output:
Enter the integer: 10
Entered integer is: 10
C Basics
C Language
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Python Dictionary
Reverse a string in Java
Introduction To PYTHON
Interfaces in Java
Inheritance in C++
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n05 Dec, 2018"
},
{
"code": null,
"e": 152,
"s": 54,
"text": "The given task is to take an integer as input from the user and print that integer in C language."
},
{
"code": null,
"e": 263,
"s": 152,
"text": "In below program, the syntax and procedures to take the integer as input from the user is shown in C language."
},
{
"code": null,
"e": 270,
"s": 263,
"text": "Steps:"
},
{
"code": null,
"e": 1358,
"s": 270,
"text": "The user enters an integer value when asked.This value is taken from the user with the help of scanf() method. The scanf() method, in C, reads the value from the console as per the type specified.Syntax:scanf(\"%X\", &variableOfXType);\n\nwhere %X is the format specifier in C\nIt is a way to tell the compiler \nwhat type of data is in a variable \n\nand\n\n& is the address operator in C,\nwhich tells the compiler to change the \nreal value of this variable, stored at this \naddress in the memory.\nFor an integer value, the X is replaced with type int. The syntax of scanf() method becomes as follows then:Syntax:scanf(\"%d\", &variableOfIntType);\nThis entered value is now stored in the variableOfIntType.Now to print this value, printf() method is used. The printf() method, in C, prints the value passed as the parameter to it, on the console screen.Syntax:printf(\"%X\", variableOfXType);\nFor an integer value, the X is replaced with type int. The syntax of printf() method becomes as follows then:Syntax:printf(\"%d\", variableOfIntType);\nHence, the integer value is successfully read and printed."
},
{
"code": null,
"e": 1403,
"s": 1358,
"text": "The user enters an integer value when asked."
},
{
"code": null,
"e": 1849,
"s": 1403,
"text": "This value is taken from the user with the help of scanf() method. The scanf() method, in C, reads the value from the console as per the type specified.Syntax:scanf(\"%X\", &variableOfXType);\n\nwhere %X is the format specifier in C\nIt is a way to tell the compiler \nwhat type of data is in a variable \n\nand\n\n& is the address operator in C,\nwhich tells the compiler to change the \nreal value of this variable, stored at this \naddress in the memory.\n"
},
{
"code": null,
"e": 1857,
"s": 1849,
"text": "Syntax:"
},
{
"code": null,
"e": 2144,
"s": 1857,
"text": "scanf(\"%X\", &variableOfXType);\n\nwhere %X is the format specifier in C\nIt is a way to tell the compiler \nwhat type of data is in a variable \n\nand\n\n& is the address operator in C,\nwhich tells the compiler to change the \nreal value of this variable, stored at this \naddress in the memory.\n"
},
{
"code": null,
"e": 2293,
"s": 2144,
"text": "For an integer value, the X is replaced with type int. The syntax of scanf() method becomes as follows then:Syntax:scanf(\"%d\", &variableOfIntType);\n"
},
{
"code": null,
"e": 2301,
"s": 2293,
"text": "Syntax:"
},
{
"code": null,
"e": 2335,
"s": 2301,
"text": "scanf(\"%d\", &variableOfIntType);\n"
},
{
"code": null,
"e": 2394,
"s": 2335,
"text": "This entered value is now stored in the variableOfIntType."
},
{
"code": null,
"e": 2580,
"s": 2394,
"text": "Now to print this value, printf() method is used. The printf() method, in C, prints the value passed as the parameter to it, on the console screen.Syntax:printf(\"%X\", variableOfXType);\n"
},
{
"code": null,
"e": 2588,
"s": 2580,
"text": "Syntax:"
},
{
"code": null,
"e": 2620,
"s": 2588,
"text": "printf(\"%X\", variableOfXType);\n"
},
{
"code": null,
"e": 2770,
"s": 2620,
"text": "For an integer value, the X is replaced with type int. The syntax of printf() method becomes as follows then:Syntax:printf(\"%d\", variableOfIntType);\n"
},
{
"code": null,
"e": 2778,
"s": 2770,
"text": "Syntax:"
},
{
"code": null,
"e": 2812,
"s": 2778,
"text": "printf(\"%d\", variableOfIntType);\n"
},
{
"code": null,
"e": 2871,
"s": 2812,
"text": "Hence, the integer value is successfully read and printed."
},
{
"code": null,
"e": 2880,
"s": 2871,
"text": "Program:"
},
{
"code": null,
"e": 2882,
"s": 2880,
"text": "C"
},
{
"code": "// C program to take an integer// as input and print it #include <stdio.h> int main(){ // Declare the variables int num; // Input the integer printf(\"Enter the integer: \"); scanf(\"%d\", &num); // Display the integer printf(\"Entered integer is: %d\", num); return 0;}",
"e": 3181,
"s": 2882,
"text": null
},
{
"code": null,
"e": 3189,
"s": 3181,
"text": "Output:"
},
{
"code": null,
"e": 3235,
"s": 3189,
"text": "Enter the integer: 10\nEntered integer is: 10\n"
},
{
"code": null,
"e": 3244,
"s": 3235,
"text": "C Basics"
},
{
"code": null,
"e": 3255,
"s": 3244,
"text": "C Language"
},
{
"code": null,
"e": 3274,
"s": 3255,
"text": "School Programming"
},
{
"code": null,
"e": 3372,
"s": 3274,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3389,
"s": 3372,
"text": "Substring in C++"
},
{
"code": null,
"e": 3411,
"s": 3389,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 3457,
"s": 3411,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 3502,
"s": 3457,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 3527,
"s": 3502,
"text": "std::string class in C++"
},
{
"code": null,
"e": 3545,
"s": 3527,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3570,
"s": 3545,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 3593,
"s": 3570,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3612,
"s": 3593,
"text": "Interfaces in Java"
}
] |
How to get the standard deviation of an array of numbers using JavaScript ?
|
15 Jul, 2021
Given an array and the task is to calculate the standard deviation of it.
Example:
Input: [1, 2, 3, 4, 5]
Output: 1.4142135623730951
Input: [23, 4, 6, 457, 65, 7, 45, 8]
Output: 145.13565852332775
Please refer to Mean, Variance, and Standard Deviation for details.
Mean is average of element. Where 0 <= i < n
Mean of arr[0..n-1] = ∑(arr[i]) / n
Variance is the sum of squared differences from the mean divided by a number of elements.
Variance = ∑(arr[i] – mean)2 / n
Standard Deviation is the square root of the variance.
Standard Deviation = variance ^ 1/2
Approach: To calculate the standard deviation first we calculate the mean and then variance and then deviation. To calculate the mean we use Array.reduce() method and calculate the sum of all the array items and then divide the array with the length of the array.
To calculate the variance we use the map() method and mutate the array by assigning (value – mean) ^ 2 to every array item, and then we calculate the sum of the array, and then we divide the sum with the length of the array. To calculate the standard deviation we calculate the square root of the array.
Example:
Javascript
<script>// Javascript program to calculate the standered deviation of an arrayfunction dev(arr){ // Creating the mean with Array.reduce let mean = arr.reduce((acc, curr)=>{ return acc + curr }, 0) / arr.length; // Assigning (value - mean) ^ 2 to every array item arr = arr.map((k)=>{ return (k - mean) ** 2 }) // Calculating the sum of updated array let sum = arr.reduce((acc, curr)=> acc + curr, 0); // Calculating the variance let variance = sum / arr.length // Returning the Standered deviation return Math.sqrt(sum / arr.length)} console.log(dev([1, 2, 3, 4, 5]))console.log(dev([23, 4, 6, 457, 65, 7, 45, 8]))</script>
Output:
1.4142135623730951
145.13565852332775
singghakshay
javascript-array
javascript-math
JavaScript-Questions
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
How to append HTML code to a div using JavaScript ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Jul, 2021"
},
{
"code": null,
"e": 102,
"s": 28,
"text": "Given an array and the task is to calculate the standard deviation of it."
},
{
"code": null,
"e": 111,
"s": 102,
"text": "Example:"
},
{
"code": null,
"e": 228,
"s": 111,
"text": "Input: [1, 2, 3, 4, 5]\nOutput: 1.4142135623730951\n\nInput: [23, 4, 6, 457, 65, 7, 45, 8]\nOutput: 145.13565852332775"
},
{
"code": null,
"e": 296,
"s": 228,
"text": "Please refer to Mean, Variance, and Standard Deviation for details."
},
{
"code": null,
"e": 341,
"s": 296,
"text": "Mean is average of element. Where 0 <= i < n"
},
{
"code": null,
"e": 377,
"s": 341,
"text": "Mean of arr[0..n-1] = ∑(arr[i]) / n"
},
{
"code": null,
"e": 467,
"s": 377,
"text": "Variance is the sum of squared differences from the mean divided by a number of elements."
},
{
"code": null,
"e": 500,
"s": 467,
"text": "Variance = ∑(arr[i] – mean)2 / n"
},
{
"code": null,
"e": 555,
"s": 500,
"text": "Standard Deviation is the square root of the variance."
},
{
"code": null,
"e": 591,
"s": 555,
"text": "Standard Deviation = variance ^ 1/2"
},
{
"code": null,
"e": 855,
"s": 591,
"text": "Approach: To calculate the standard deviation first we calculate the mean and then variance and then deviation. To calculate the mean we use Array.reduce() method and calculate the sum of all the array items and then divide the array with the length of the array."
},
{
"code": null,
"e": 1159,
"s": 855,
"text": "To calculate the variance we use the map() method and mutate the array by assigning (value – mean) ^ 2 to every array item, and then we calculate the sum of the array, and then we divide the sum with the length of the array. To calculate the standard deviation we calculate the square root of the array."
},
{
"code": null,
"e": 1168,
"s": 1159,
"text": "Example:"
},
{
"code": null,
"e": 1179,
"s": 1168,
"text": "Javascript"
},
{
"code": "<script>// Javascript program to calculate the standered deviation of an arrayfunction dev(arr){ // Creating the mean with Array.reduce let mean = arr.reduce((acc, curr)=>{ return acc + curr }, 0) / arr.length; // Assigning (value - mean) ^ 2 to every array item arr = arr.map((k)=>{ return (k - mean) ** 2 }) // Calculating the sum of updated array let sum = arr.reduce((acc, curr)=> acc + curr, 0); // Calculating the variance let variance = sum / arr.length // Returning the Standered deviation return Math.sqrt(sum / arr.length)} console.log(dev([1, 2, 3, 4, 5]))console.log(dev([23, 4, 6, 457, 65, 7, 45, 8]))</script>",
"e": 1827,
"s": 1179,
"text": null
},
{
"code": null,
"e": 1835,
"s": 1827,
"text": "Output:"
},
{
"code": null,
"e": 1873,
"s": 1835,
"text": "1.4142135623730951\n145.13565852332775"
},
{
"code": null,
"e": 1886,
"s": 1873,
"text": "singghakshay"
},
{
"code": null,
"e": 1903,
"s": 1886,
"text": "javascript-array"
},
{
"code": null,
"e": 1919,
"s": 1903,
"text": "javascript-math"
},
{
"code": null,
"e": 1940,
"s": 1919,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 1951,
"s": 1940,
"text": "JavaScript"
},
{
"code": null,
"e": 1968,
"s": 1951,
"text": "Web Technologies"
},
{
"code": null,
"e": 2066,
"s": 1968,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2127,
"s": 2066,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2199,
"s": 2127,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2239,
"s": 2199,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2292,
"s": 2239,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 2344,
"s": 2292,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 2406,
"s": 2344,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2439,
"s": 2406,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2500,
"s": 2439,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2550,
"s": 2500,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How does a vector work in C++?
|
08 Oct, 2021
A Vectors in C++ can resize itself when more elements are added. It also allows deletion of elements. Below is a very basic idea when array becomes full and user wishes to add an item. 1) Create a bigger sized memory on heap memory (for example memory of double size). 2) Copy current memory elements to the new memory. 3) New item is added now as there is bigger memory available now. 4) Delete the old memory.However the actual library implementation may be more complex. If we create a new double sized array whenever current array becomes full (or it is about to become full), and copy current elements to new double sized array, we get amortized time complexity as O(1). So a particular insert operation may be costly, but overall time complexity remains O(1). Please refer Analysis of Algorithm | Set 5 (Amortized Analysis Introduction) for proof. So time complexity of push_back() is O(1).
CPP
// CPP program to illustrate push_back()#include <iostream>#include <vector>using namespace std; int main(){ vector<int> myvector{ 1, 2, 3, 4, 5 }; myvector.push_back(6); // Vector becomes 1, 2, 3, 4, 5, 6 for (auto x : myvector) cout << x << " ";}
Output :
1 2 3 4 5 6
What is the time complexity of erase() in vector()? Since erasing an element requires moving other elements (to ensure random access), time complexity of erase is O(n).
CPP
// CPP program to illustrate// working of erase() function#include <iostream>#include <vector>using namespace std; int main(){ vector<int> myvector{ 1, 2, 3, 4, 5 }; auto it = myvector.begin(); myvector.erase(it); // Printing the Vector for (auto x : myvector) cout << x << " "; return 0;}
Output :
2 3 4 5
atharvautekar99
cpp-vector
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 951,
"s": 53,
"text": "A Vectors in C++ can resize itself when more elements are added. It also allows deletion of elements. Below is a very basic idea when array becomes full and user wishes to add an item. 1) Create a bigger sized memory on heap memory (for example memory of double size). 2) Copy current memory elements to the new memory. 3) New item is added now as there is bigger memory available now. 4) Delete the old memory.However the actual library implementation may be more complex. If we create a new double sized array whenever current array becomes full (or it is about to become full), and copy current elements to new double sized array, we get amortized time complexity as O(1). So a particular insert operation may be costly, but overall time complexity remains O(1). Please refer Analysis of Algorithm | Set 5 (Amortized Analysis Introduction) for proof. So time complexity of push_back() is O(1). "
},
{
"code": null,
"e": 955,
"s": 951,
"text": "CPP"
},
{
"code": "// CPP program to illustrate push_back()#include <iostream>#include <vector>using namespace std; int main(){ vector<int> myvector{ 1, 2, 3, 4, 5 }; myvector.push_back(6); // Vector becomes 1, 2, 3, 4, 5, 6 for (auto x : myvector) cout << x << \" \";}",
"e": 1229,
"s": 955,
"text": null
},
{
"code": null,
"e": 1239,
"s": 1229,
"text": "Output : "
},
{
"code": null,
"e": 1252,
"s": 1239,
"text": "1 2 3 4 5 6 "
},
{
"code": null,
"e": 1422,
"s": 1252,
"text": "What is the time complexity of erase() in vector()? Since erasing an element requires moving other elements (to ensure random access), time complexity of erase is O(n). "
},
{
"code": null,
"e": 1426,
"s": 1422,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// working of erase() function#include <iostream>#include <vector>using namespace std; int main(){ vector<int> myvector{ 1, 2, 3, 4, 5 }; auto it = myvector.begin(); myvector.erase(it); // Printing the Vector for (auto x : myvector) cout << x << \" \"; return 0;}",
"e": 1743,
"s": 1426,
"text": null
},
{
"code": null,
"e": 1753,
"s": 1743,
"text": "Output : "
},
{
"code": null,
"e": 1762,
"s": 1753,
"text": "2 3 4 5 "
},
{
"code": null,
"e": 1780,
"s": 1764,
"text": "atharvautekar99"
},
{
"code": null,
"e": 1791,
"s": 1780,
"text": "cpp-vector"
},
{
"code": null,
"e": 1795,
"s": 1791,
"text": "C++"
},
{
"code": null,
"e": 1799,
"s": 1795,
"text": "CPP"
}
] |
Turtle programming in Python
|
Turtle is a special feathers of Python. Using Turtle, we can easily draw in a drawing board.
First we import the turtle module. Then create a window, next we create turtle object and using turtle method we can draw in the drawing board.
# import turtle library
import turtle
my_window = turtle.Screen()
my_window.bgcolor("blue") # creates a graphics window
my_pen = turtle.Turtle()
my_pen.forward(150)
my_pen.left(90)
my_pen.forward(75)
my_pen.color("white")
my_pen.pensize(12)
# import turtle library
import turtle
my_pen = turtle.Turtle()
for i in range(4):
my_pen.forward(50)
my_pen.right(90)
turtle.done()
# import turtle library
import turtle
my_pen = turtle.Turtle()
for i in range(50):
my_pen.forward(50)
my_pen.right(144)
turtle.done()
# import turtle library
import turtle
polygon = turtle.Turtle()
my_num_sides = 6
my_side_length = 70
my_angle = 360.0 / my_num_sides
for i in range(my_num_sides):
polygon.forward(my_side_length)
polygon.right(my_angle)
turtle.done()
# import turtle library
import turtle
my_wn = turtle.Screen()
my_wn.bgcolor("light blue")
my_wn.title("Turtle")
my_pen = turtle.Turtle()
my_pen.color("black")
def my_sqrfunc(size):
for i in range(4):
my_pen.fd(size)
my_pen.left(90)
size = size - 5
my_sqrfunc(146)
my_sqrfunc(126)
my_sqrfunc(106)
my_sqrfunc(86)
my_sqrfunc(66)
my_sqrfunc(46)
my_sqrfunc(26)
# import turtle library
import turtle
my_wn = turtle.Screen()
turtle.speed(2)
for i in range(30):
turtle.circle(5*i)
turtle.circle(-5*i)
turtle.left(i)
turtle.exitonclick()
# import turtle library
import turtle
colors = [ "red","purple","blue","green","orange","yellow"]
my_pen = turtle.Pen()
turtle.bgcolor("black")
for x in range(360):
my_pen.pencolor(colors[x % 6])
my_pen.width(x/100 + 1)
my_pen.forward(x)
my_pen.left(59)
|
[
{
"code": null,
"e": 1280,
"s": 1187,
"text": "Turtle is a special feathers of Python. Using Turtle, we can easily draw in a drawing board."
},
{
"code": null,
"e": 1424,
"s": 1280,
"text": "First we import the turtle module. Then create a window, next we create turtle object and using turtle method we can draw in the drawing board."
},
{
"code": null,
"e": 1717,
"s": 1424,
"text": "# import turtle library\nimport turtle \nmy_window = turtle.Screen() \nmy_window.bgcolor(\"blue\") # creates a graphics window\nmy_pen = turtle.Turtle() \nmy_pen.forward(150) \nmy_pen.left(90) \nmy_pen.forward(75)\nmy_pen.color(\"white\")\nmy_pen.pensize(12)"
},
{
"code": null,
"e": 1900,
"s": 1717,
"text": "# import turtle library\nimport turtle \nmy_pen = turtle.Turtle() \nfor i in range(4):\n my_pen.forward(50) \n my_pen.right(90) \nturtle.done()"
},
{
"code": null,
"e": 2085,
"s": 1900,
"text": "# import turtle library\nimport turtle \nmy_pen = turtle.Turtle() \nfor i in range(50):\n my_pen.forward(50) \n my_pen.right(144) \nturtle.done()"
},
{
"code": null,
"e": 2349,
"s": 2085,
"text": "# import turtle library\nimport turtle \npolygon = turtle.Turtle()\nmy_num_sides = 6\nmy_side_length = 70\nmy_angle = 360.0 / my_num_sides\nfor i in range(my_num_sides):\n polygon.forward(my_side_length) \n polygon.right(my_angle) \nturtle.done()"
},
{
"code": null,
"e": 2739,
"s": 2349,
"text": "# import turtle library\nimport turtle \nmy_wn = turtle.Screen()\nmy_wn.bgcolor(\"light blue\")\nmy_wn.title(\"Turtle\")\nmy_pen = turtle.Turtle()\nmy_pen.color(\"black\")\ndef my_sqrfunc(size):\n for i in range(4):\n my_pen.fd(size)\n my_pen.left(90)\n size = size - 5\nmy_sqrfunc(146)\nmy_sqrfunc(126)\nmy_sqrfunc(106)\nmy_sqrfunc(86)\nmy_sqrfunc(66)\nmy_sqrfunc(46)\nmy_sqrfunc(26)"
},
{
"code": null,
"e": 2934,
"s": 2739,
"text": "# import turtle library\nimport turtle \nmy_wn = turtle.Screen()\nturtle.speed(2)\nfor i in range(30):\n turtle.circle(5*i)\n turtle.circle(-5*i)\n turtle.left(i)\nturtle.exitonclick()"
},
{
"code": null,
"e": 3213,
"s": 2934,
"text": "# import turtle library\nimport turtle \ncolors = [ \"red\",\"purple\",\"blue\",\"green\",\"orange\",\"yellow\"]\nmy_pen = turtle.Pen()\nturtle.bgcolor(\"black\")\nfor x in range(360):\n my_pen.pencolor(colors[x % 6])\n my_pen.width(x/100 + 1)\n my_pen.forward(x)\n my_pen.left(59)"
}
] |
Click-Through Window in ElectronJS
|
03 Aug, 2020
ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.
In a complex desktop application, a situation might occur wherein the developers may have to freeze the current window or a region of the current window which is being shown to the user. In such cases, the window becomes static and the user will not be able to perform any window operations such as close, minimize, maximize, etc on the window and it will remain open on the screen. This means that the window or the region of the window becomes oblivious to any Mouse Events which might occur on it. This behaviour might seem familiar to disabling button clicks using HTML, CSS, and JavaScript but the crucial difference here is that the window or the region of the window becomes unresponsive to all Mouse Events including mouse movements over that region. Such a window is known as a Click-Through Window. Electron provides us with a way by which we can create or make an existing window a Click-Through window using the Instance methods of the BrowserWindow object. This tutorial will demonstrate how to create a Click-Through Window in Electron.
We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system.
Project Structure:
Example: Follow the Steps given in How to Find Text on Page in ElectronJS ? to set up the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also, perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. The basic steps required to set up the Electron application remain the same. package.json:
{
"name": "electron-clickthrough",
"version": "1.0.0",
"description": "Click-Through Window in Electron",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"keywords": [
"electron"
],
"author": "Radhesh Khanna",
"license": "ISC",
"dependencies": {
"electron": "^8.3.0"
}
}
Output:
Click-Through Window in Electron: The BrowserWindow Instance is part of the Main Process. To import and use BrowserWindow in the Renderer Process, we will be using Electron remote module. As mentioned above, a Click-Through window ignores all Mouse Events which occur on it. In order to exit the Click-Through window, we need to terminate the BrowserWindow Instance or close the task.
index.html: Add the following snippet in that file.
html
<h3>Click-Through Window in Electron</h3> <button id="disable"> Disable Mouse Events on Current Window </button> <br><br> <button id="forward"> Forwarding Mouse Events </button><!-- Adding Individual Renderer Process Script File --> <script src="index.js"></script>
index.js: The Disable Mouse Events on Current Window and Forwarding Mouse Events buttons do not have any functionality associated with them yet. To change this, add the following code in the index.js file
javascript
const electron = require('electron')// Import BrowserWindow using Electron remoteconst BrowserWindow = electron.remote.BrowserWindow; const win = BrowserWindow.getFocusedWindow();// let win = BrowserWindow.getAllWindows()[0]; var disable = document.getElementById('disable')disable.addEventListener('click', (event) => { win.setIgnoreMouseEvents(true);}); var forward = document.getElementById('forward');forward.addEventListener('mouseenter', () => { console.log('Mouse Entered the Region...Disabling Click') win.setIgnoreMouseEvents(true, { forward: true });}); forward.addEventListener('mouseleave', () => { console.log('Mouse Left the Region...Event Emitted') win.setIgnoreMouseEvents(false);});
Explanation: To create a simple Click-Through window in Electron, we use the win.setIgnoreMouseEvents(ignore, options) Instance method of the BrowserWindow object. Calling this Instance method on the BrowserWindow object makes the window oblivious to all mouse EventEmitters. This method does not have a return type. All mouse events which happen in this window will now be passed to the window or the contents which lie below this window, but if this Click-Through window has focus, it will still receive the keyboard events which occur on it. Before we look into the parameters that are passed to this Instance method, there is an additional feature for the Click-Through window which is only supported in the Windows operating system. As mentioned above, a Click-Through window is oblivious to all mouse events including mouse movements over that window or that region of the Window. In Windows OS, we can pass an additional options: Object parameter to this Instance method which can be used to Forward mouse messages to the webpage, therefore, allowing mouse Movement Events such as the mouseleave and the mouseenter to be emitted on the BrowserWindow Instance. This concept is known as Forwarding and it becomes useful in a situation where we want to make only a portion of the window Click-Through and not the entire BrowserWindow Instance. This helps the developers have more granular control over the window or regions of the window. In this tutorial, we have applied Forwarding to the Forwarding Mouse Events button. Hence, the mouse movement events will be applicable over this button but the button itself will still be unresponsive to mouseClick. In simpler words, this makes the webpage Click-Through when over the HTML Button but returns to normal outside it. Refer to the Output for a better understanding. On clicking the Disable Mouse Events on Current Window button, the current BrowserWindow Instance becomes a Click-Through window. The win.setIgnoreMouseEvents(ignore, options) Instance method of the BrowserWindow object takes in the following parameters.
ignore: Boolean This parameter makes the window a Click-Through Window.
options: Object (Optional) This parameter is supported in Windows only. This parameter is an optional parameter and is responsible for Forwarding as discussed above. It takes in the following parameters.forward: Boolean (Optional) This parameter is set to true, forwards mouse move messages to Chromium, enabling mouse movement-related events such as mouseenter and mouseleave to be emitted. This parameter can only be used when the ignore parameter is set to true. If the ignore parameter is false, forwarding is always disabled regardless of this value.
forward: Boolean (Optional) This parameter is set to true, forwards mouse move messages to Chromium, enabling mouse movement-related events such as mouseenter and mouseleave to be emitted. This parameter can only be used when the ignore parameter is set to true. If the ignore parameter is false, forwarding is always disabled regardless of this value.
To get the current BrowserWindow Instance in the Renderer Process, we can use some Static Methods provided by the BrowserWindow object.
BrowserWindow.getAllWindows(): This method returns an Array of active/opened BrowserWindow Instances. In this application, we have only one active BrowserWindow Instance and it can be directly referred from the Array as shown in the code.
BrowserWindow.getFocusedWindow(): This method returns the BrowserWindow Instance which is focused in the Application. If no current BrowserWindow Instance is found, it returns null. In this application, we only have one active BrowserWindow Instance and it can be directly referred to using this method as shown in the code.
Output:
ElectronJS
CSS
HTML
JavaScript
Node.js
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of CSS (Cascading Style Sheet)
How to set space between the flexbox ?
Design a Tribute Page using HTML & CSS
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
Types of CSS (Cascading Style Sheet)
HTTP headers | Content-Type
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Aug, 2020"
},
{
"code": null,
"e": 328,
"s": 28,
"text": "ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime."
},
{
"code": null,
"e": 1380,
"s": 328,
"text": "In a complex desktop application, a situation might occur wherein the developers may have to freeze the current window or a region of the current window which is being shown to the user. In such cases, the window becomes static and the user will not be able to perform any window operations such as close, minimize, maximize, etc on the window and it will remain open on the screen. This means that the window or the region of the window becomes oblivious to any Mouse Events which might occur on it. This behaviour might seem familiar to disabling button clicks using HTML, CSS, and JavaScript but the crucial difference here is that the window or the region of the window becomes unresponsive to all Mouse Events including mouse movements over that region. Such a window is known as a Click-Through Window. Electron provides us with a way by which we can create or make an existing window a Click-Through window using the Instance methods of the BrowserWindow object. This tutorial will demonstrate how to create a Click-Through Window in Electron. "
},
{
"code": null,
"e": 1550,
"s": 1380,
"text": "We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system."
},
{
"code": null,
"e": 1571,
"s": 1550,
"text": "Project Structure: "
},
{
"code": null,
"e": 2056,
"s": 1571,
"text": "Example: Follow the Steps given in How to Find Text on Page in ElectronJS ? to set up the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also, perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. The basic steps required to set up the Electron application remain the same. package.json: "
},
{
"code": null,
"e": 2373,
"s": 2056,
"text": "{\n \"name\": \"electron-clickthrough\",\n \"version\": \"1.0.0\",\n \"description\": \"Click-Through Window in Electron\",\n \"main\": \"main.js\",\n \"scripts\": {\n \"start\": \"electron .\"\n },\n \"keywords\": [\n \"electron\"\n ],\n \"author\": \"Radhesh Khanna\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"electron\": \"^8.3.0\"\n }\n}\n"
},
{
"code": null,
"e": 2381,
"s": 2373,
"text": "Output:"
},
{
"code": null,
"e": 2767,
"s": 2381,
"text": "Click-Through Window in Electron: The BrowserWindow Instance is part of the Main Process. To import and use BrowserWindow in the Renderer Process, we will be using Electron remote module. As mentioned above, a Click-Through window ignores all Mouse Events which occur on it. In order to exit the Click-Through window, we need to terminate the BrowserWindow Instance or close the task. "
},
{
"code": null,
"e": 2820,
"s": 2767,
"text": "index.html: Add the following snippet in that file. "
},
{
"code": null,
"e": 2825,
"s": 2820,
"text": "html"
},
{
"code": "<h3>Click-Through Window in Electron</h3> <button id=\"disable\"> Disable Mouse Events on Current Window </button> <br><br> <button id=\"forward\"> Forwarding Mouse Events </button><!-- Adding Individual Renderer Process Script File --> <script src=\"index.js\"></script>",
"e": 3109,
"s": 2825,
"text": null
},
{
"code": null,
"e": 3314,
"s": 3109,
"text": "index.js: The Disable Mouse Events on Current Window and Forwarding Mouse Events buttons do not have any functionality associated with them yet. To change this, add the following code in the index.js file"
},
{
"code": null,
"e": 3325,
"s": 3314,
"text": "javascript"
},
{
"code": "const electron = require('electron')// Import BrowserWindow using Electron remoteconst BrowserWindow = electron.remote.BrowserWindow; const win = BrowserWindow.getFocusedWindow();// let win = BrowserWindow.getAllWindows()[0]; var disable = document.getElementById('disable')disable.addEventListener('click', (event) => { win.setIgnoreMouseEvents(true);}); var forward = document.getElementById('forward');forward.addEventListener('mouseenter', () => { console.log('Mouse Entered the Region...Disabling Click') win.setIgnoreMouseEvents(true, { forward: true });}); forward.addEventListener('mouseleave', () => { console.log('Mouse Left the Region...Event Emitted') win.setIgnoreMouseEvents(false);});",
"e": 4044,
"s": 3325,
"text": null
},
{
"code": null,
"e": 6123,
"s": 4044,
"text": "Explanation: To create a simple Click-Through window in Electron, we use the win.setIgnoreMouseEvents(ignore, options) Instance method of the BrowserWindow object. Calling this Instance method on the BrowserWindow object makes the window oblivious to all mouse EventEmitters. This method does not have a return type. All mouse events which happen in this window will now be passed to the window or the contents which lie below this window, but if this Click-Through window has focus, it will still receive the keyboard events which occur on it. Before we look into the parameters that are passed to this Instance method, there is an additional feature for the Click-Through window which is only supported in the Windows operating system. As mentioned above, a Click-Through window is oblivious to all mouse events including mouse movements over that window or that region of the Window. In Windows OS, we can pass an additional options: Object parameter to this Instance method which can be used to Forward mouse messages to the webpage, therefore, allowing mouse Movement Events such as the mouseleave and the mouseenter to be emitted on the BrowserWindow Instance. This concept is known as Forwarding and it becomes useful in a situation where we want to make only a portion of the window Click-Through and not the entire BrowserWindow Instance. This helps the developers have more granular control over the window or regions of the window. In this tutorial, we have applied Forwarding to the Forwarding Mouse Events button. Hence, the mouse movement events will be applicable over this button but the button itself will still be unresponsive to mouseClick. In simpler words, this makes the webpage Click-Through when over the HTML Button but returns to normal outside it. Refer to the Output for a better understanding. On clicking the Disable Mouse Events on Current Window button, the current BrowserWindow Instance becomes a Click-Through window. The win.setIgnoreMouseEvents(ignore, options) Instance method of the BrowserWindow object takes in the following parameters. "
},
{
"code": null,
"e": 6195,
"s": 6123,
"text": "ignore: Boolean This parameter makes the window a Click-Through Window."
},
{
"code": null,
"e": 6751,
"s": 6195,
"text": "options: Object (Optional) This parameter is supported in Windows only. This parameter is an optional parameter and is responsible for Forwarding as discussed above. It takes in the following parameters.forward: Boolean (Optional) This parameter is set to true, forwards mouse move messages to Chromium, enabling mouse movement-related events such as mouseenter and mouseleave to be emitted. This parameter can only be used when the ignore parameter is set to true. If the ignore parameter is false, forwarding is always disabled regardless of this value."
},
{
"code": null,
"e": 7104,
"s": 6751,
"text": "forward: Boolean (Optional) This parameter is set to true, forwards mouse move messages to Chromium, enabling mouse movement-related events such as mouseenter and mouseleave to be emitted. This parameter can only be used when the ignore parameter is set to true. If the ignore parameter is false, forwarding is always disabled regardless of this value."
},
{
"code": null,
"e": 7241,
"s": 7104,
"text": "To get the current BrowserWindow Instance in the Renderer Process, we can use some Static Methods provided by the BrowserWindow object. "
},
{
"code": null,
"e": 7480,
"s": 7241,
"text": "BrowserWindow.getAllWindows(): This method returns an Array of active/opened BrowserWindow Instances. In this application, we have only one active BrowserWindow Instance and it can be directly referred from the Array as shown in the code."
},
{
"code": null,
"e": 7807,
"s": 7480,
"text": "BrowserWindow.getFocusedWindow(): This method returns the BrowserWindow Instance which is focused in the Application. If no current BrowserWindow Instance is found, it returns null. In this application, we only have one active BrowserWindow Instance and it can be directly referred to using this method as shown in the code. "
},
{
"code": null,
"e": 7816,
"s": 7807,
"text": "Output: "
},
{
"code": null,
"e": 7827,
"s": 7816,
"text": "ElectronJS"
},
{
"code": null,
"e": 7831,
"s": 7827,
"text": "CSS"
},
{
"code": null,
"e": 7836,
"s": 7831,
"text": "HTML"
},
{
"code": null,
"e": 7847,
"s": 7836,
"text": "JavaScript"
},
{
"code": null,
"e": 7855,
"s": 7847,
"text": "Node.js"
},
{
"code": null,
"e": 7872,
"s": 7855,
"text": "Web Technologies"
},
{
"code": null,
"e": 7877,
"s": 7872,
"text": "HTML"
},
{
"code": null,
"e": 7975,
"s": 7877,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8012,
"s": 7975,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 8051,
"s": 8012,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 8090,
"s": 8051,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 8154,
"s": 8090,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 8215,
"s": 8154,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 8239,
"s": 8215,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 8292,
"s": 8239,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 8352,
"s": 8292,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 8389,
"s": 8352,
"text": "Types of CSS (Cascading Style Sheet)"
}
] |
Pivot and Unpivot in SQL
|
24 Jul, 2019
In SQL, Pivot and Unpivot are relational operators that are used to transform one table into another in order to achieve more simpler view of table. Conventionally we can say that Pivot operator converts the rows data of the table into the column data. The Unpivot operator does the opposite that is it transform the column based data into rows.
Syntax:
1. Pivot:
SELECT (ColumnNames)
FROM (TableName)
PIVOT
(
AggregateFunction(ColumnToBeAggregated)
FOR PivotColumn IN (PivotColumnValues)
) AS (Alias) //Alias is a temporary name for a table
2. Unpivot:
SELECT (ColumnNames)
FROM (TableName)
UNPIVOT
(
AggregateFunction(ColumnToBeAggregated)
FOR PivotColumn IN (PivotColumnValues)
) AS (Alias)
Example-1:We have created a simple table named “geeksforgeeks” with values like Course name, course category and price and inserted the respective values.
Create Table geeksforgeeks
(
CourseName nvarchar(50),
CourseCategory nvarchar(50),
Price int
)
Insert into geeksforgeeks values('C', 'PROGRAMMING', 5000)
Insert into geeksforgeeks values('JAVA', 'PROGRAMMING', 6000)
Insert into geeksforgeeks values('PYTHON', 'PROGRAMMING', 8000)
Insert into geeksforgeeks values('PLACEMENT 100', 'INTERVIEWPREPARATION', 5000)
SELECT * FROM geeksforgeeks
The output we get is :
Now, applying PIVOT operator to this data:
SELECT CourseName, PROGRAMMING, INTERVIEWPREPARATION
FROM geeksforgeeks
PIVOT
(
SUM(Price) FOR CourseCategory IN (PROGRAMMING, INTERVIEWPREPARATION )
) AS PivotTable
After using Pivot operator we get the following result:
Example-2:Now, we use the same table “geeksforgeeks” created in the above example and apply the Unpivot operator to our Pivoted table.
Applying UNPIVOT operator:
SELECT CourseName, CourseCategory, Price
FROM
(
SELECT CourseName, PROGRAMMING, INTERVIEWPREPARATION FROM geeksforgeeks
PIVOT
(
SUM(Price) FOR CourseCategory IN (PROGRAMMING, INTERVIEWPREPARATION)
) AS PivotTable
) P
UNPIVOT
(
Price FOR CourseCategory IN (PROGRAMMING, INTERVIEWPREPARATION)
)
AS UnpivotTable
After using Unpivot operator we get our original table back as we have successfully transformed the columns of the table back to rows:
Picked
SQL-Clauses-Operators
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
SQL Interview Questions
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Views
Difference between DELETE, DROP and TRUNCATE
Window functions in SQL
SQL | GROUP BY
Difference between DELETE and TRUNCATE
Difference between DDL and DML in DBMS
MySQL | Group_CONCAT() Function
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Jul, 2019"
},
{
"code": null,
"e": 400,
"s": 54,
"text": "In SQL, Pivot and Unpivot are relational operators that are used to transform one table into another in order to achieve more simpler view of table. Conventionally we can say that Pivot operator converts the rows data of the table into the column data. The Unpivot operator does the opposite that is it transform the column based data into rows."
},
{
"code": null,
"e": 408,
"s": 400,
"text": "Syntax:"
},
{
"code": null,
"e": 418,
"s": 408,
"text": "1. Pivot:"
},
{
"code": null,
"e": 608,
"s": 418,
"text": "SELECT (ColumnNames) \nFROM (TableName) \nPIVOT\n ( \n AggregateFunction(ColumnToBeAggregated)\n FOR PivotColumn IN (PivotColumnValues)\n ) AS (Alias) //Alias is a temporary name for a table\n"
},
{
"code": null,
"e": 620,
"s": 608,
"text": "2. Unpivot:"
},
{
"code": null,
"e": 772,
"s": 620,
"text": "SELECT (ColumnNames) \nFROM (TableName) \nUNPIVOT\n ( \n AggregateFunction(ColumnToBeAggregated)\n FOR PivotColumn IN (PivotColumnValues)\n ) AS (Alias)\n"
},
{
"code": null,
"e": 927,
"s": 772,
"text": "Example-1:We have created a simple table named “geeksforgeeks” with values like Course name, course category and price and inserted the respective values."
},
{
"code": null,
"e": 1332,
"s": 927,
"text": "Create Table geeksforgeeks \n( \nCourseName nvarchar(50), \nCourseCategory nvarchar(50),\nPrice int \n) \n\nInsert into geeksforgeeks values('C', 'PROGRAMMING', 5000) \nInsert into geeksforgeeks values('JAVA', 'PROGRAMMING', 6000) \nInsert into geeksforgeeks values('PYTHON', 'PROGRAMMING', 8000) \nInsert into geeksforgeeks values('PLACEMENT 100', 'INTERVIEWPREPARATION', 5000) \n\nSELECT * FROM geeksforgeeks "
},
{
"code": null,
"e": 1355,
"s": 1332,
"text": "The output we get is :"
},
{
"code": null,
"e": 1398,
"s": 1355,
"text": "Now, applying PIVOT operator to this data:"
},
{
"code": null,
"e": 1570,
"s": 1398,
"text": "SELECT CourseName, PROGRAMMING, INTERVIEWPREPARATION\nFROM geeksforgeeks \nPIVOT \n( \nSUM(Price) FOR CourseCategory IN (PROGRAMMING, INTERVIEWPREPARATION ) \n) AS PivotTable \n"
},
{
"code": null,
"e": 1626,
"s": 1570,
"text": "After using Pivot operator we get the following result:"
},
{
"code": null,
"e": 1761,
"s": 1626,
"text": "Example-2:Now, we use the same table “geeksforgeeks” created in the above example and apply the Unpivot operator to our Pivoted table."
},
{
"code": null,
"e": 1788,
"s": 1761,
"text": "Applying UNPIVOT operator:"
},
{
"code": null,
"e": 2108,
"s": 1788,
"text": "SELECT CourseName, CourseCategory, Price \nFROM \n(\nSELECT CourseName, PROGRAMMING, INTERVIEWPREPARATION FROM geeksforgeeks \nPIVOT \n( \nSUM(Price) FOR CourseCategory IN (PROGRAMMING, INTERVIEWPREPARATION) \n) AS PivotTable\n) P \nUNPIVOT \n( \nPrice FOR CourseCategory IN (PROGRAMMING, INTERVIEWPREPARATION)\n) \nAS UnpivotTable\n"
},
{
"code": null,
"e": 2243,
"s": 2108,
"text": "After using Unpivot operator we get our original table back as we have successfully transformed the columns of the table back to rows:"
},
{
"code": null,
"e": 2250,
"s": 2243,
"text": "Picked"
},
{
"code": null,
"e": 2272,
"s": 2250,
"text": "SQL-Clauses-Operators"
},
{
"code": null,
"e": 2276,
"s": 2272,
"text": "SQL"
},
{
"code": null,
"e": 2280,
"s": 2276,
"text": "SQL"
},
{
"code": null,
"e": 2378,
"s": 2280,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2389,
"s": 2378,
"text": "CTE in SQL"
},
{
"code": null,
"e": 2413,
"s": 2389,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 2479,
"s": 2413,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 2491,
"s": 2479,
"text": "SQL | Views"
},
{
"code": null,
"e": 2536,
"s": 2491,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 2560,
"s": 2536,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 2575,
"s": 2560,
"text": "SQL | GROUP BY"
},
{
"code": null,
"e": 2614,
"s": 2575,
"text": "Difference between DELETE and TRUNCATE"
},
{
"code": null,
"e": 2653,
"s": 2614,
"text": "Difference between DDL and DML in DBMS"
}
] |
SAS - Frequency Distributions
|
A frequency distribution is a table showing the frequency of the data points in a data set. Each entry in the table contains the frequency or count of the occurrences of values within a particular group or interval, and in this way, the table summarizes the distribution of values in the sample.
SAS provides a procedure called PROC FREQ to calculate the frequency distribution of data points in a data set.
The basic syntax for calculating frequency distribution in SAS is −
PROC FREQ DATA = Dataset ;
TABLES Variable_1 ;
BY Variable_2 ;
Following is the description of the parameters used −
Dataset is the name of the dataset.
Dataset is the name of the dataset.
Variables_1 is the variable names of the dataset whose frequency distribution needs to be calculated.
Variables_1 is the variable names of the dataset whose frequency distribution needs to be calculated.
Variables_2 is the variables which categorised the frequency distribution result.
Variables_2 is the variables which categorised the frequency distribution result.
We can determine the frequency distribution of a single variable by using PROC FREQ. In this case the result will show the frequency of each value of the variable. The result also shows the percentage distribution, cumulative frequency and cumulative percentage.
In the below example we find the frequency distribution of the variable horsepower for the dataset named CARS1 which is created form the library SASHELP.CARS. We can see the result divided into two categories of results. One for each make of the car.
PROC SQL;
create table CARS1 as
SELECT make, model, type, invoice, horsepower, length, weight
FROM
SASHELP.CARS
WHERE make in ('Audi','BMW')
;
RUN;
proc FREQ data = CARS1 ;
tables horsepower;
by make;
run;
When the above code is executed, we get the following result −
We can find the frequency distributions for multiple variables which groups them into all possible combinations.
In the below example we calculate the frequency distribution for the make of a car for grouped by car type and also the frequency distribution of each type of car grouped by each make.
proc FREQ data = CARS1 ;
tables make type;
run;
When the above code is executed, we get the following result −
With the weight option we can calculate the frequency distribution biased with the weight of the variable. Here the value of the variable is taken as the number of observations instead of the count of value.
In the below example we calculate the frequency distribution of the variables make and type with weight assigned to horsepower.
proc FREQ data = CARS1 ;
tables make type;
weight horsepower;
run;
When the above code is executed, we get the following result −
|
[
{
"code": null,
"e": 3013,
"s": 2717,
"text": "A frequency distribution is a table showing the frequency of the data points in a data set. Each entry in the table contains the frequency or count of the occurrences of values within a particular group or interval, and in this way, the table summarizes the distribution of values in the sample."
},
{
"code": null,
"e": 3125,
"s": 3013,
"text": "SAS provides a procedure called PROC FREQ to calculate the frequency distribution of data points in a data set."
},
{
"code": null,
"e": 3193,
"s": 3125,
"text": "The basic syntax for calculating frequency distribution in SAS is −"
},
{
"code": null,
"e": 3257,
"s": 3193,
"text": "PROC FREQ DATA = Dataset ;\nTABLES Variable_1 ;\nBY Variable_2 ;\n"
},
{
"code": null,
"e": 3311,
"s": 3257,
"text": "Following is the description of the parameters used −"
},
{
"code": null,
"e": 3347,
"s": 3311,
"text": "Dataset is the name of the dataset."
},
{
"code": null,
"e": 3383,
"s": 3347,
"text": "Dataset is the name of the dataset."
},
{
"code": null,
"e": 3485,
"s": 3383,
"text": "Variables_1 is the variable names of the dataset whose frequency distribution needs to be calculated."
},
{
"code": null,
"e": 3587,
"s": 3485,
"text": "Variables_1 is the variable names of the dataset whose frequency distribution needs to be calculated."
},
{
"code": null,
"e": 3669,
"s": 3587,
"text": "Variables_2 is the variables which categorised the frequency distribution result."
},
{
"code": null,
"e": 3751,
"s": 3669,
"text": "Variables_2 is the variables which categorised the frequency distribution result."
},
{
"code": null,
"e": 4014,
"s": 3751,
"text": "We can determine the frequency distribution of a single variable by using PROC FREQ. In this case the result will show the frequency of each value of the variable. The result also shows the percentage distribution, cumulative frequency and cumulative percentage."
},
{
"code": null,
"e": 4265,
"s": 4014,
"text": "In the below example we find the frequency distribution of the variable horsepower for the dataset named CARS1 which is created form the library SASHELP.CARS. We can see the result divided into two categories of results. One for each make of the car."
},
{
"code": null,
"e": 4484,
"s": 4265,
"text": "PROC SQL;\ncreate table CARS1 as\nSELECT make, model, type, invoice, horsepower, length, weight\n FROM \n SASHELP.CARS\n WHERE make in ('Audi','BMW')\n;\nRUN;\n\nproc FREQ data = CARS1 ;\ntables horsepower; \nby make;\nrun;\n"
},
{
"code": null,
"e": 4547,
"s": 4484,
"text": "When the above code is executed, we get the following result −"
},
{
"code": null,
"e": 4660,
"s": 4547,
"text": "We can find the frequency distributions for multiple variables which groups them into all possible combinations."
},
{
"code": null,
"e": 4845,
"s": 4660,
"text": "In the below example we calculate the frequency distribution for the make of a car for grouped by car type and also the frequency distribution of each type of car grouped by each make."
},
{
"code": null,
"e": 4895,
"s": 4845,
"text": "proc FREQ data = CARS1 ;\ntables make type; \nrun;\n"
},
{
"code": null,
"e": 4958,
"s": 4895,
"text": "When the above code is executed, we get the following result −"
},
{
"code": null,
"e": 5166,
"s": 4958,
"text": "With the weight option we can calculate the frequency distribution biased with the weight of the variable. Here the value of the variable is taken as the number of observations instead of the count of value."
},
{
"code": null,
"e": 5295,
"s": 5166,
"text": "In the below example we calculate the frequency distribution of the variables make and type with weight assigned to horsepower."
},
{
"code": null,
"e": 5364,
"s": 5295,
"text": "proc FREQ data = CARS1 ;\ntables make type; \nweight horsepower;\nrun;\n"
}
] |
String formatting in Python
|
16 Aug, 2021
In this article, we will discuss how to format string Python. String formatting is the process of infusing things in the string dynamically and presenting the string. There are four different ways to perform string formatting:-
Formatting with % Operator.
Formatting with format() string method.
Formatting with string literals, called f-strings.
Formatting with String Template Class
So we will see the entirety of the above-mentioned ways, and we will also focus on which string formatting strategy is the best.
It is the oldest method of string formatting. Here we use the modulo % operator. The modulo % is also known as the “string-formatting operator”.
Example: Formatting string using % operator
Python3
print("The mangy, scrawny stray dog %s gobbled down" + "the grain-free, organic dog food." %'hurriedly')
Output:
The mangy, scrawny stray dog hurriedly gobbled down the grain-free, organic dog food.
You can also inject multiple strings at a time and can also use variables to insert objects in the string.
Example: Injecting multiple strings using % operator
Python3
x = 'looked' print("Misha %s and %s around"%('walked',x))
Output:
Misha walked and looked around.
‘%s’ is used to inject strings similarly ‘%d’ for integers, ‘%f’ for floating-point values, ‘%b’ for binary format. For all formats, conversion methods visit the official documentation.
Example:
Python3
print('Joe stood up and %s to the crowd.' %'spoke') print('There are %d dogs.' %4)
Output:
Joe stood up and spoke to the crowd.
There are 4 dogs.
Floating-point numbers use the format %a.bf. Here, a would be the minimum number of digits to be present in the string; these might be padded with white space if the whole number doesn’t have this many digits. Close to this, bf represents how many digits are to be displayed after the decimal point.
Let us see a few examples:
Example 1: Float point precision using % operator
Python3
print('The value of pi is: %5.4f' %(3.141592))
Output:
The value of pi is: 3.1416
Example 2:
Python3
print('Floating point numbers: %1.0f' %(13.144))
Output:
Floating point numbers: 13
Example 3: You can use multiple format conversion types in a single print statement
Python3
variable = 12 string = "Variable as integer = %d \n\Variable as float = %f" %(variable, variable) print (string)
Variable as integer = 12
Variable as float = 12.000000
Note: To know more about %-formatting, refer to String Formatting in Python using %
Format() method was introduced with Python3 for handling complex string formatting more efficiently. Formatters work by putting in one or more replacement fields and placeholders defined by a pair of curly braces { } into a string and calling the str.format(). The value we wish to put into the placeholders and concatenate with the string passed as parameters into the format function.
Syntax: ‘String here {} then also {}’.format(‘something1′,’something2’)
Example: Formatting string using format() method
Python3
print('We all are {}.'.format('equal'))
Output:
We all are equal.
The.format() method has many advantages over the placeholder method:
We can insert object by using index-based position:
Python3
print('{2} {1} {0}'.format('directions', 'the', 'Read'))
Output:
Read the directions.
We can insert objects by using assigned keywords:
Python3
print('a: {a}, b: {b}, c: {c}'.format(a = 1, b = 'Two', c = 12.3))
Output:
a: 1, b: Two, c: 12.3
We can reuse the inserted objects to avoid duplication:
Python3
print('The first {p} was alright, but the {p} {p} was tough.'.format(p = 'second'))
Output:
The first second was alright, but the second second was tough.
Float precision with the.format() method:
Syntax: {[index]:[width][.precision][type]}
The type can be used with format codes:
‘d’ for integers
‘f’ for floating-point numbers
‘b’ for binary numbers
‘o’ for octal numbers
‘x’ for octal hexadecimal numbers
‘s’ for string
‘e’ for floating-point in an exponent format
Example:
Python3
print('The valueof pi is: %1.5f' %3.141592) # vs. print('The valueof pi is: {0:1.5f}'.format(3.141592))
Output:
The valueof pi is: 3.14159
The valueof pi is: 3.14159
Note: To know more about str.format(), refer to format() function in Python
PEP 498 introduced a new string formatting mechanism known as Literal String Interpolation or more commonly as F-strings (because of the leading f character preceding the string literal). The idea behind f-strings is to make string interpolation simpler.
To create an f-string, prefix the string with the letter “ f ”. The string itself can be formatted in much the same way that you would with str.format(). F-strings provide a concise and convenient way to embed python expressions inside string literals for formatting.
Example: Formatting string with F-Strings
Python3
name = 'Ele' print(f"My name is {name}.")
Output:
My name is Ele.
This new formatting syntax is very powerful and easy. You can also insert arbitrary Python expressions and you can even do arithmetic operations in it.
Example: Arithmetic operations using F-strings
Python3
a = 5 b = 10 print(f"He said his age is {2 * (a + b)}.")
Output:
He said his age is 30.
We can also use lambda expressions in f-string formatting.
Example: Lambda Expressions using F-strings
Python3
print(f"He said his age is {(lambda x: x*2)(3)}")
Output:
He said his age is 6
Float precision in the f-String method:
Syntax: {value:{width}.{precision}}
Example: Float Precision using F-strings
Python3
num = 3.14159 print(f"The valueof pi is: {num:{1}.{5}}")
Output:
The valueof pi is: 3.1416
Note: To know more about f-strings, refer to f-strings in Python
In the String module, Template Class allows us to create simplified syntax for output specification. The format uses placeholder names formed by $ with valid Python identifiers (alphanumeric characters and underscores). Surrounding the placeholder with braces allows it to be followed by more alphanumeric letters with no intervening spaces. Writing $$ creates a single escaped $:
Example: Formatting string using Template Class
Python3
# Python program to demonstrate# string interpolation from string import Template n1 = 'Hello'n2 = 'GeeksforGeeks' # made a template which we used to# pass two variable so n3 and n4# formal and n1 and n2 actualn = Template('$n3 ! This is $n4.') # and pass the parameters into the# template string.print(n.substitute(n3=n1, n4=n2))
Note: To know more about String Template class, refer to String Template Class in Python
f-strings are faster and better than both %-formatting and str.format(). f-strings expressions are evaluated are at runtime, and we can also embed expressions inside f-string, using a very simple and easy syntax. The expressions inside the braces are evaluated in runtime and then put together with the string part of the f-string and then the final string is returned.
Note: Use f-Strings if you are on Python 3.6+, and.format() method if you are not.
nikhilaggarwal3
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Aug, 2021"
},
{
"code": null,
"e": 280,
"s": 52,
"text": "In this article, we will discuss how to format string Python. String formatting is the process of infusing things in the string dynamically and presenting the string. There are four different ways to perform string formatting:-"
},
{
"code": null,
"e": 308,
"s": 280,
"text": "Formatting with % Operator."
},
{
"code": null,
"e": 348,
"s": 308,
"text": "Formatting with format() string method."
},
{
"code": null,
"e": 399,
"s": 348,
"text": "Formatting with string literals, called f-strings."
},
{
"code": null,
"e": 437,
"s": 399,
"text": "Formatting with String Template Class"
},
{
"code": null,
"e": 566,
"s": 437,
"text": "So we will see the entirety of the above-mentioned ways, and we will also focus on which string formatting strategy is the best."
},
{
"code": null,
"e": 711,
"s": 566,
"text": "It is the oldest method of string formatting. Here we use the modulo % operator. The modulo % is also known as the “string-formatting operator”."
},
{
"code": null,
"e": 755,
"s": 711,
"text": "Example: Formatting string using % operator"
},
{
"code": null,
"e": 763,
"s": 755,
"text": "Python3"
},
{
"code": "print(\"The mangy, scrawny stray dog %s gobbled down\" + \"the grain-free, organic dog food.\" %'hurriedly')",
"e": 873,
"s": 763,
"text": null
},
{
"code": null,
"e": 881,
"s": 873,
"text": "Output:"
},
{
"code": null,
"e": 968,
"s": 881,
"text": "The mangy, scrawny stray dog hurriedly gobbled down the grain-free, organic dog food. "
},
{
"code": null,
"e": 1075,
"s": 968,
"text": "You can also inject multiple strings at a time and can also use variables to insert objects in the string."
},
{
"code": null,
"e": 1128,
"s": 1075,
"text": "Example: Injecting multiple strings using % operator"
},
{
"code": null,
"e": 1136,
"s": 1128,
"text": "Python3"
},
{
"code": "x = 'looked' print(\"Misha %s and %s around\"%('walked',x))",
"e": 1194,
"s": 1136,
"text": null
},
{
"code": null,
"e": 1202,
"s": 1194,
"text": "Output:"
},
{
"code": null,
"e": 1234,
"s": 1202,
"text": "Misha walked and looked around."
},
{
"code": null,
"e": 1420,
"s": 1234,
"text": "‘%s’ is used to inject strings similarly ‘%d’ for integers, ‘%f’ for floating-point values, ‘%b’ for binary format. For all formats, conversion methods visit the official documentation."
},
{
"code": null,
"e": 1429,
"s": 1420,
"text": "Example:"
},
{
"code": null,
"e": 1437,
"s": 1429,
"text": "Python3"
},
{
"code": "print('Joe stood up and %s to the crowd.' %'spoke') print('There are %d dogs.' %4)",
"e": 1520,
"s": 1437,
"text": null
},
{
"code": null,
"e": 1528,
"s": 1520,
"text": "Output:"
},
{
"code": null,
"e": 1583,
"s": 1528,
"text": "Joe stood up and spoke to the crowd.\nThere are 4 dogs."
},
{
"code": null,
"e": 1884,
"s": 1583,
"text": "Floating-point numbers use the format %a.bf. Here, a would be the minimum number of digits to be present in the string; these might be padded with white space if the whole number doesn’t have this many digits. Close to this, bf represents how many digits are to be displayed after the decimal point. "
},
{
"code": null,
"e": 1911,
"s": 1884,
"text": "Let us see a few examples:"
},
{
"code": null,
"e": 1961,
"s": 1911,
"text": "Example 1: Float point precision using % operator"
},
{
"code": null,
"e": 1969,
"s": 1961,
"text": "Python3"
},
{
"code": "print('The value of pi is: %5.4f' %(3.141592))",
"e": 2016,
"s": 1969,
"text": null
},
{
"code": null,
"e": 2024,
"s": 2016,
"text": "Output:"
},
{
"code": null,
"e": 2051,
"s": 2024,
"text": "The value of pi is: 3.1416"
},
{
"code": null,
"e": 2062,
"s": 2051,
"text": "Example 2:"
},
{
"code": null,
"e": 2070,
"s": 2062,
"text": "Python3"
},
{
"code": "print('Floating point numbers: %1.0f' %(13.144))",
"e": 2119,
"s": 2070,
"text": null
},
{
"code": null,
"e": 2127,
"s": 2119,
"text": "Output:"
},
{
"code": null,
"e": 2154,
"s": 2127,
"text": "Floating point numbers: 13"
},
{
"code": null,
"e": 2238,
"s": 2154,
"text": "Example 3: You can use multiple format conversion types in a single print statement"
},
{
"code": null,
"e": 2246,
"s": 2238,
"text": "Python3"
},
{
"code": "variable = 12 string = \"Variable as integer = %d \\n\\Variable as float = %f\" %(variable, variable) print (string)",
"e": 2359,
"s": 2246,
"text": null
},
{
"code": null,
"e": 2415,
"s": 2359,
"text": "Variable as integer = 12 \nVariable as float = 12.000000"
},
{
"code": null,
"e": 2499,
"s": 2415,
"text": "Note: To know more about %-formatting, refer to String Formatting in Python using %"
},
{
"code": null,
"e": 2887,
"s": 2499,
"text": "Format() method was introduced with Python3 for handling complex string formatting more efficiently. Formatters work by putting in one or more replacement fields and placeholders defined by a pair of curly braces { } into a string and calling the str.format(). The value we wish to put into the placeholders and concatenate with the string passed as parameters into the format function. "
},
{
"code": null,
"e": 2959,
"s": 2887,
"text": "Syntax: ‘String here {} then also {}’.format(‘something1′,’something2’)"
},
{
"code": null,
"e": 3008,
"s": 2959,
"text": "Example: Formatting string using format() method"
},
{
"code": null,
"e": 3016,
"s": 3008,
"text": "Python3"
},
{
"code": "print('We all are {}.'.format('equal'))",
"e": 3056,
"s": 3016,
"text": null
},
{
"code": null,
"e": 3064,
"s": 3056,
"text": "Output:"
},
{
"code": null,
"e": 3082,
"s": 3064,
"text": "We all are equal."
},
{
"code": null,
"e": 3151,
"s": 3082,
"text": "The.format() method has many advantages over the placeholder method:"
},
{
"code": null,
"e": 3203,
"s": 3151,
"text": "We can insert object by using index-based position:"
},
{
"code": null,
"e": 3211,
"s": 3203,
"text": "Python3"
},
{
"code": "print('{2} {1} {0}'.format('directions', 'the', 'Read'))",
"e": 3294,
"s": 3211,
"text": null
},
{
"code": null,
"e": 3302,
"s": 3294,
"text": "Output:"
},
{
"code": null,
"e": 3323,
"s": 3302,
"text": "Read the directions."
},
{
"code": null,
"e": 3373,
"s": 3323,
"text": "We can insert objects by using assigned keywords:"
},
{
"code": null,
"e": 3381,
"s": 3373,
"text": "Python3"
},
{
"code": "print('a: {a}, b: {b}, c: {c}'.format(a = 1, b = 'Two', c = 12.3))",
"e": 3522,
"s": 3381,
"text": null
},
{
"code": null,
"e": 3530,
"s": 3522,
"text": "Output:"
},
{
"code": null,
"e": 3552,
"s": 3530,
"text": "a: 1, b: Two, c: 12.3"
},
{
"code": null,
"e": 3608,
"s": 3552,
"text": "We can reuse the inserted objects to avoid duplication:"
},
{
"code": null,
"e": 3616,
"s": 3608,
"text": "Python3"
},
{
"code": "print('The first {p} was alright, but the {p} {p} was tough.'.format(p = 'second'))",
"e": 3700,
"s": 3616,
"text": null
},
{
"code": null,
"e": 3708,
"s": 3700,
"text": "Output:"
},
{
"code": null,
"e": 3772,
"s": 3708,
"text": "The first second was alright, but the second second was tough. "
},
{
"code": null,
"e": 3814,
"s": 3772,
"text": "Float precision with the.format() method:"
},
{
"code": null,
"e": 3858,
"s": 3814,
"text": "Syntax: {[index]:[width][.precision][type]}"
},
{
"code": null,
"e": 3898,
"s": 3858,
"text": "The type can be used with format codes:"
},
{
"code": null,
"e": 3915,
"s": 3898,
"text": "‘d’ for integers"
},
{
"code": null,
"e": 3946,
"s": 3915,
"text": "‘f’ for floating-point numbers"
},
{
"code": null,
"e": 3969,
"s": 3946,
"text": "‘b’ for binary numbers"
},
{
"code": null,
"e": 3991,
"s": 3969,
"text": "‘o’ for octal numbers"
},
{
"code": null,
"e": 4025,
"s": 3991,
"text": "‘x’ for octal hexadecimal numbers"
},
{
"code": null,
"e": 4040,
"s": 4025,
"text": "‘s’ for string"
},
{
"code": null,
"e": 4085,
"s": 4040,
"text": "‘e’ for floating-point in an exponent format"
},
{
"code": null,
"e": 4094,
"s": 4085,
"text": "Example:"
},
{
"code": null,
"e": 4102,
"s": 4094,
"text": "Python3"
},
{
"code": "print('The valueof pi is: %1.5f' %3.141592) # vs. print('The valueof pi is: {0:1.5f}'.format(3.141592))",
"e": 4206,
"s": 4102,
"text": null
},
{
"code": null,
"e": 4214,
"s": 4206,
"text": "Output:"
},
{
"code": null,
"e": 4268,
"s": 4214,
"text": "The valueof pi is: 3.14159\nThe valueof pi is: 3.14159"
},
{
"code": null,
"e": 4344,
"s": 4268,
"text": "Note: To know more about str.format(), refer to format() function in Python"
},
{
"code": null,
"e": 4599,
"s": 4344,
"text": "PEP 498 introduced a new string formatting mechanism known as Literal String Interpolation or more commonly as F-strings (because of the leading f character preceding the string literal). The idea behind f-strings is to make string interpolation simpler."
},
{
"code": null,
"e": 4867,
"s": 4599,
"text": "To create an f-string, prefix the string with the letter “ f ”. The string itself can be formatted in much the same way that you would with str.format(). F-strings provide a concise and convenient way to embed python expressions inside string literals for formatting."
},
{
"code": null,
"e": 4909,
"s": 4867,
"text": "Example: Formatting string with F-Strings"
},
{
"code": null,
"e": 4917,
"s": 4909,
"text": "Python3"
},
{
"code": "name = 'Ele' print(f\"My name is {name}.\")",
"e": 4959,
"s": 4917,
"text": null
},
{
"code": null,
"e": 4967,
"s": 4959,
"text": "Output:"
},
{
"code": null,
"e": 4983,
"s": 4967,
"text": "My name is Ele."
},
{
"code": null,
"e": 5135,
"s": 4983,
"text": "This new formatting syntax is very powerful and easy. You can also insert arbitrary Python expressions and you can even do arithmetic operations in it."
},
{
"code": null,
"e": 5182,
"s": 5135,
"text": "Example: Arithmetic operations using F-strings"
},
{
"code": null,
"e": 5190,
"s": 5182,
"text": "Python3"
},
{
"code": "a = 5 b = 10 print(f\"He said his age is {2 * (a + b)}.\")",
"e": 5247,
"s": 5190,
"text": null
},
{
"code": null,
"e": 5255,
"s": 5247,
"text": "Output:"
},
{
"code": null,
"e": 5278,
"s": 5255,
"text": "He said his age is 30."
},
{
"code": null,
"e": 5337,
"s": 5278,
"text": "We can also use lambda expressions in f-string formatting."
},
{
"code": null,
"e": 5381,
"s": 5337,
"text": "Example: Lambda Expressions using F-strings"
},
{
"code": null,
"e": 5389,
"s": 5381,
"text": "Python3"
},
{
"code": "print(f\"He said his age is {(lambda x: x*2)(3)}\")",
"e": 5439,
"s": 5389,
"text": null
},
{
"code": null,
"e": 5448,
"s": 5439,
"text": " Output:"
},
{
"code": null,
"e": 5469,
"s": 5448,
"text": "He said his age is 6"
},
{
"code": null,
"e": 5509,
"s": 5469,
"text": "Float precision in the f-String method:"
},
{
"code": null,
"e": 5545,
"s": 5509,
"text": "Syntax: {value:{width}.{precision}}"
},
{
"code": null,
"e": 5586,
"s": 5545,
"text": "Example: Float Precision using F-strings"
},
{
"code": null,
"e": 5594,
"s": 5586,
"text": "Python3"
},
{
"code": "num = 3.14159 print(f\"The valueof pi is: {num:{1}.{5}}\")",
"e": 5651,
"s": 5594,
"text": null
},
{
"code": null,
"e": 5659,
"s": 5651,
"text": "Output:"
},
{
"code": null,
"e": 5685,
"s": 5659,
"text": "The valueof pi is: 3.1416"
},
{
"code": null,
"e": 5750,
"s": 5685,
"text": "Note: To know more about f-strings, refer to f-strings in Python"
},
{
"code": null,
"e": 6131,
"s": 5750,
"text": "In the String module, Template Class allows us to create simplified syntax for output specification. The format uses placeholder names formed by $ with valid Python identifiers (alphanumeric characters and underscores). Surrounding the placeholder with braces allows it to be followed by more alphanumeric letters with no intervening spaces. Writing $$ creates a single escaped $:"
},
{
"code": null,
"e": 6179,
"s": 6131,
"text": "Example: Formatting string using Template Class"
},
{
"code": null,
"e": 6187,
"s": 6179,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# string interpolation from string import Template n1 = 'Hello'n2 = 'GeeksforGeeks' # made a template which we used to# pass two variable so n3 and n4# formal and n1 and n2 actualn = Template('$n3 ! This is $n4.') # and pass the parameters into the# template string.print(n.substitute(n3=n1, n4=n2))",
"e": 6519,
"s": 6187,
"text": null
},
{
"code": null,
"e": 6608,
"s": 6519,
"text": "Note: To know more about String Template class, refer to String Template Class in Python"
},
{
"code": null,
"e": 6978,
"s": 6608,
"text": "f-strings are faster and better than both %-formatting and str.format(). f-strings expressions are evaluated are at runtime, and we can also embed expressions inside f-string, using a very simple and easy syntax. The expressions inside the braces are evaluated in runtime and then put together with the string part of the f-string and then the final string is returned."
},
{
"code": null,
"e": 7061,
"s": 6978,
"text": "Note: Use f-Strings if you are on Python 3.6+, and.format() method if you are not."
},
{
"code": null,
"e": 7077,
"s": 7061,
"text": "nikhilaggarwal3"
},
{
"code": null,
"e": 7091,
"s": 7077,
"text": "python-string"
},
{
"code": null,
"e": 7098,
"s": 7091,
"text": "Python"
}
] |
Shortest substring of a string containing all given words
|
01 Apr, 2019
Print the shortest sub-string of a string containing all the given words.
In the first example, two solutions are possible: “world is here. this is a life full of ups” and “ups and downs. life is world”.
Initialize HashMap with all the given words which are required to be searched and assign their values as -1.Maintain a counter.Traverse the entire String word by word and do following for each sentence wordIf the sentence word exists in the list of words you’re looking for, update the last position of that word.Increase the total count if the updated last position was not initialized.If the total count is equal to count of all given words, loop through the last positions and find the smallest one. The distance between the current position and that value will be the length of the substring. Record these values and find the best one over all positions
Initialize HashMap with all the given words which are required to be searched and assign their values as -1.
Maintain a counter.
Traverse the entire String word by word and do following for each sentence wordIf the sentence word exists in the list of words you’re looking for, update the last position of that word.Increase the total count if the updated last position was not initialized.If the total count is equal to count of all given words, loop through the last positions and find the smallest one. The distance between the current position and that value will be the length of the substring. Record these values and find the best one over all positions
If the sentence word exists in the list of words you’re looking for, update the last position of that word.
Increase the total count if the updated last position was not initialized.
If the total count is equal to count of all given words, loop through the last positions and find the smallest one. The distance between the current position and that value will be the length of the substring. Record these values and find the best one over all positions
Below is Java implementation of above steps.
// Java program to find the shortest substring of a// string containing all given words using HashMapimport java.io.*;import java.util.*;import java.util.HashMap; class Shortest { public static void findShortest(String sentence, String[] words) { // Make an array of words from given sentence // We remove punctuations before splitting. String replicate = sentence.replace(".", ""); replicate = replicate.replace(", ", ""); replicate = replicate.replace("!", ""); String sent_words[] = replicate.split(" "); // hashmap to store given words in a map. HashMap<String, Integer> map = new HashMap<>(); int length = words.length; for (int i = 0; i < length; i++) map.put(words[i], -1); // Traverse through all sentence words // and if they match with given words // then mark their appearances in map. int len_sub = Integer.MAX_VALUE; int count = 0; int local_start = 0, local_end = 0; for (int i = 0; i < sent_words.length; i++) { if (map.containsKey(sent_words[i]) == true) { // If this is the first occurrence int index = map.get(sent_words[i]); if (index == -1) count++; // Store latest index map.put(sent_words[i], i); // If all words matched if (count == length) { // Find smallest index int min = Integer.MAX_VALUE; for (Map.Entry<String, Integer> m : map.entrySet()) { int val = m.getValue(); if (val < min) min = val; } // Check if current length is smaller // then length so far int s = i - min; if (s < len_sub) { local_start = min; local_end = i; len_sub=s; } } } } // Printing original substring (with punctuations) // using resultant local_start and local_end. String[] original_parts = sentence.split(" "); for (int i = local_start; i <=local_end; i++) System.out.print(original_parts[i] + " "); } // Driver code public static void main(String args[]) { String sentence = "The world is here. this is a" + " life full of ups and downs. life is world."; String[] words = { "life", "ups", "is", "world" }; findShortest(sentence, words); }}
Output :
ups and downs. life is
This article is contributed by Shifa Khan. 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.
shubh_123ab
Hash
Strings
Hash
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Hashing | A Complete Tutorial
Real-time application of Data Structures
Find k numbers with most occurrences in the given array
set vs unordered_set in C++ STL
Find the length of largest subarray with 0 sum
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
Different Methods to Reverse a String in C++
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Apr, 2019"
},
{
"code": null,
"e": 126,
"s": 52,
"text": "Print the shortest sub-string of a string containing all the given words."
},
{
"code": null,
"e": 256,
"s": 126,
"text": "In the first example, two solutions are possible: “world is here. this is a life full of ups” and “ups and downs. life is world”."
},
{
"code": null,
"e": 914,
"s": 256,
"text": "Initialize HashMap with all the given words which are required to be searched and assign their values as -1.Maintain a counter.Traverse the entire String word by word and do following for each sentence wordIf the sentence word exists in the list of words you’re looking for, update the last position of that word.Increase the total count if the updated last position was not initialized.If the total count is equal to count of all given words, loop through the last positions and find the smallest one. The distance between the current position and that value will be the length of the substring. Record these values and find the best one over all positions"
},
{
"code": null,
"e": 1023,
"s": 914,
"text": "Initialize HashMap with all the given words which are required to be searched and assign their values as -1."
},
{
"code": null,
"e": 1043,
"s": 1023,
"text": "Maintain a counter."
},
{
"code": null,
"e": 1574,
"s": 1043,
"text": "Traverse the entire String word by word and do following for each sentence wordIf the sentence word exists in the list of words you’re looking for, update the last position of that word.Increase the total count if the updated last position was not initialized.If the total count is equal to count of all given words, loop through the last positions and find the smallest one. The distance between the current position and that value will be the length of the substring. Record these values and find the best one over all positions"
},
{
"code": null,
"e": 1682,
"s": 1574,
"text": "If the sentence word exists in the list of words you’re looking for, update the last position of that word."
},
{
"code": null,
"e": 1757,
"s": 1682,
"text": "Increase the total count if the updated last position was not initialized."
},
{
"code": null,
"e": 2028,
"s": 1757,
"text": "If the total count is equal to count of all given words, loop through the last positions and find the smallest one. The distance between the current position and that value will be the length of the substring. Record these values and find the best one over all positions"
},
{
"code": null,
"e": 2073,
"s": 2028,
"text": "Below is Java implementation of above steps."
},
{
"code": "// Java program to find the shortest substring of a// string containing all given words using HashMapimport java.io.*;import java.util.*;import java.util.HashMap; class Shortest { public static void findShortest(String sentence, String[] words) { // Make an array of words from given sentence // We remove punctuations before splitting. String replicate = sentence.replace(\".\", \"\"); replicate = replicate.replace(\", \", \"\"); replicate = replicate.replace(\"!\", \"\"); String sent_words[] = replicate.split(\" \"); // hashmap to store given words in a map. HashMap<String, Integer> map = new HashMap<>(); int length = words.length; for (int i = 0; i < length; i++) map.put(words[i], -1); // Traverse through all sentence words // and if they match with given words // then mark their appearances in map. int len_sub = Integer.MAX_VALUE; int count = 0; int local_start = 0, local_end = 0; for (int i = 0; i < sent_words.length; i++) { if (map.containsKey(sent_words[i]) == true) { // If this is the first occurrence int index = map.get(sent_words[i]); if (index == -1) count++; // Store latest index map.put(sent_words[i], i); // If all words matched if (count == length) { // Find smallest index int min = Integer.MAX_VALUE; for (Map.Entry<String, Integer> m : map.entrySet()) { int val = m.getValue(); if (val < min) min = val; } // Check if current length is smaller // then length so far int s = i - min; if (s < len_sub) { local_start = min; local_end = i; len_sub=s; } } } } // Printing original substring (with punctuations) // using resultant local_start and local_end. String[] original_parts = sentence.split(\" \"); for (int i = local_start; i <=local_end; i++) System.out.print(original_parts[i] + \" \"); } // Driver code public static void main(String args[]) { String sentence = \"The world is here. this is a\" + \" life full of ups and downs. life is world.\"; String[] words = { \"life\", \"ups\", \"is\", \"world\" }; findShortest(sentence, words); }}",
"e": 4816,
"s": 2073,
"text": null
},
{
"code": null,
"e": 4825,
"s": 4816,
"text": "Output :"
},
{
"code": null,
"e": 4849,
"s": 4825,
"text": "ups and downs. life is "
},
{
"code": null,
"e": 5147,
"s": 4849,
"text": "This article is contributed by Shifa Khan. 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": 5272,
"s": 5147,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 5284,
"s": 5272,
"text": "shubh_123ab"
},
{
"code": null,
"e": 5289,
"s": 5284,
"text": "Hash"
},
{
"code": null,
"e": 5297,
"s": 5289,
"text": "Strings"
},
{
"code": null,
"e": 5302,
"s": 5297,
"text": "Hash"
},
{
"code": null,
"e": 5310,
"s": 5302,
"text": "Strings"
},
{
"code": null,
"e": 5408,
"s": 5310,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5446,
"s": 5408,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 5487,
"s": 5446,
"text": "Real-time application of Data Structures"
},
{
"code": null,
"e": 5543,
"s": 5487,
"text": "Find k numbers with most occurrences in the given array"
},
{
"code": null,
"e": 5575,
"s": 5543,
"text": "set vs unordered_set in C++ STL"
},
{
"code": null,
"e": 5622,
"s": 5575,
"text": "Find the length of largest subarray with 0 sum"
},
{
"code": null,
"e": 5668,
"s": 5622,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 5693,
"s": 5668,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 5753,
"s": 5693,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 5768,
"s": 5753,
"text": "C++ Data Types"
}
] |
How to count rows in MySQL table in PHP ?
|
26 May, 2021
PHP stands for hypertext preprocessor. MySQL is a database query language used to manage databases.
In this article, we are going to discuss how to get the count of rows in a particular table present in the database using PHP and MySQL.
Requirements:
XAMPP
Approach: By using PHP and MySQL, one can perform database operations. We can get the total number of rows in a table by using the MySQL mysqli_num_rows() function.
Syntax:
mysqli_num_rows( result );
The result is to specify the result set identifier returned by mysqli_query() function.
Example: The following table has 5 rows.
To count the number of rows in the building table, the following code snippet is used.
$sql = "SELECT * from building";
if ($result = mysqli_query($con, $sql)) {
// Return the number of rows in result set
$rowcount = mysqli_num_rows( $result );
// Display result
printf("Total rows in this table : %d\n", $rowcount);
}
Output: The expected result is as follows.
Total rows in this table : 5
Steps for the approach:
Create a database named database.
Create a table named building inside the database.
Insert records into it.
Write PHP code to count rows.
Steps:
Start XAMPP server.
XAMPP server
Create a database named database and create a table named building inside the database.
Insert records into it
building table
Write PHP code to count rows.
PHP code:
PHP
<?php // localhost is localhost// servername is root// password is empty// database name is database$con = mysqli_connect("localhost","root","","database"); // SQL query to display row count // in building table $sql = "SELECT * from building"; if ($result = mysqli_query($con, $sql)) { // Return the number of rows in result set $rowcount = mysqli_num_rows( $result ); // Display result printf("Total rows in this table : %d\n", $rowcount);} // Close the connectionmysqli_close($con); ?>
Output: After running the above PHP file in localhost, the following result is achieved.
Total rows in this table : 5
Example 2: In the following example, we count the table rows using MySQL count() function. It’s an aggregate function used to count rows.
Syntax:
select count(*) from table;
Consider the table.
PHP code:
PHP
<?php // Servername$servername = "localhost"; // Username$username = "root"; // Empty password$password = ""; // Database name $dbname = "database"; // Create connection by passing these// connection parameters$conn = new mysqli($servername, $username, $password, $dbname); // SQL query to find total count// of college_data table$sql = "SELECT count(*) FROM college_data ";$result = $conn->query($sql); // Display data on web pagewhile($row = mysqli_fetch_array($result)) { echo "Total Rows is ". $row['count(*)']; echo "<br />";} // Close the connection$conn->close(); ?>
Output:
Total Rows is 8
PHP-function
PHP-Questions
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 May, 2021"
},
{
"code": null,
"e": 152,
"s": 52,
"text": "PHP stands for hypertext preprocessor. MySQL is a database query language used to manage databases."
},
{
"code": null,
"e": 289,
"s": 152,
"text": "In this article, we are going to discuss how to get the count of rows in a particular table present in the database using PHP and MySQL."
},
{
"code": null,
"e": 303,
"s": 289,
"text": "Requirements:"
},
{
"code": null,
"e": 309,
"s": 303,
"text": "XAMPP"
},
{
"code": null,
"e": 474,
"s": 309,
"text": "Approach: By using PHP and MySQL, one can perform database operations. We can get the total number of rows in a table by using the MySQL mysqli_num_rows() function."
},
{
"code": null,
"e": 482,
"s": 474,
"text": "Syntax:"
},
{
"code": null,
"e": 509,
"s": 482,
"text": "mysqli_num_rows( result );"
},
{
"code": null,
"e": 597,
"s": 509,
"text": "The result is to specify the result set identifier returned by mysqli_query() function."
},
{
"code": null,
"e": 638,
"s": 597,
"text": "Example: The following table has 5 rows."
},
{
"code": null,
"e": 725,
"s": 638,
"text": "To count the number of rows in the building table, the following code snippet is used."
},
{
"code": null,
"e": 982,
"s": 725,
"text": "$sql = \"SELECT * from building\";\n\nif ($result = mysqli_query($con, $sql)) {\n\n // Return the number of rows in result set\n $rowcount = mysqli_num_rows( $result );\n \n // Display result\n printf(\"Total rows in this table : %d\\n\", $rowcount);\n }"
},
{
"code": null,
"e": 1025,
"s": 982,
"text": "Output: The expected result is as follows."
},
{
"code": null,
"e": 1054,
"s": 1025,
"text": "Total rows in this table : 5"
},
{
"code": null,
"e": 1078,
"s": 1054,
"text": "Steps for the approach:"
},
{
"code": null,
"e": 1112,
"s": 1078,
"text": "Create a database named database."
},
{
"code": null,
"e": 1163,
"s": 1112,
"text": "Create a table named building inside the database."
},
{
"code": null,
"e": 1187,
"s": 1163,
"text": "Insert records into it."
},
{
"code": null,
"e": 1217,
"s": 1187,
"text": "Write PHP code to count rows."
},
{
"code": null,
"e": 1226,
"s": 1219,
"text": "Steps:"
},
{
"code": null,
"e": 1246,
"s": 1226,
"text": "Start XAMPP server."
},
{
"code": null,
"e": 1259,
"s": 1246,
"text": "XAMPP server"
},
{
"code": null,
"e": 1347,
"s": 1259,
"text": "Create a database named database and create a table named building inside the database."
},
{
"code": null,
"e": 1370,
"s": 1347,
"text": "Insert records into it"
},
{
"code": null,
"e": 1385,
"s": 1370,
"text": "building table"
},
{
"code": null,
"e": 1415,
"s": 1385,
"text": "Write PHP code to count rows."
},
{
"code": null,
"e": 1425,
"s": 1415,
"text": "PHP code:"
},
{
"code": null,
"e": 1429,
"s": 1425,
"text": "PHP"
},
{
"code": "<?php // localhost is localhost// servername is root// password is empty// database name is database$con = mysqli_connect(\"localhost\",\"root\",\"\",\"database\"); // SQL query to display row count // in building table $sql = \"SELECT * from building\"; if ($result = mysqli_query($con, $sql)) { // Return the number of rows in result set $rowcount = mysqli_num_rows( $result ); // Display result printf(\"Total rows in this table : %d\\n\", $rowcount);} // Close the connectionmysqli_close($con); ?>",
"e": 1957,
"s": 1429,
"text": null
},
{
"code": null,
"e": 2046,
"s": 1957,
"text": "Output: After running the above PHP file in localhost, the following result is achieved."
},
{
"code": null,
"e": 2075,
"s": 2046,
"text": "Total rows in this table : 5"
},
{
"code": null,
"e": 2213,
"s": 2075,
"text": "Example 2: In the following example, we count the table rows using MySQL count() function. It’s an aggregate function used to count rows."
},
{
"code": null,
"e": 2221,
"s": 2213,
"text": "Syntax:"
},
{
"code": null,
"e": 2249,
"s": 2221,
"text": "select count(*) from table;"
},
{
"code": null,
"e": 2269,
"s": 2249,
"text": "Consider the table."
},
{
"code": null,
"e": 2279,
"s": 2269,
"text": "PHP code:"
},
{
"code": null,
"e": 2283,
"s": 2279,
"text": "PHP"
},
{
"code": "<?php // Servername$servername = \"localhost\"; // Username$username = \"root\"; // Empty password$password = \"\"; // Database name $dbname = \"database\"; // Create connection by passing these// connection parameters$conn = new mysqli($servername, $username, $password, $dbname); // SQL query to find total count// of college_data table$sql = \"SELECT count(*) FROM college_data \";$result = $conn->query($sql); // Display data on web pagewhile($row = mysqli_fetch_array($result)) { echo \"Total Rows is \". $row['count(*)']; echo \"<br />\";} // Close the connection$conn->close(); ?>",
"e": 2879,
"s": 2283,
"text": null
},
{
"code": null,
"e": 2887,
"s": 2879,
"text": "Output:"
},
{
"code": null,
"e": 2903,
"s": 2887,
"text": "Total Rows is 8"
},
{
"code": null,
"e": 2916,
"s": 2903,
"text": "PHP-function"
},
{
"code": null,
"e": 2930,
"s": 2916,
"text": "PHP-Questions"
},
{
"code": null,
"e": 2937,
"s": 2930,
"text": "Picked"
},
{
"code": null,
"e": 2941,
"s": 2937,
"text": "PHP"
},
{
"code": null,
"e": 2958,
"s": 2941,
"text": "Web Technologies"
},
{
"code": null,
"e": 2962,
"s": 2958,
"text": "PHP"
}
] |
Working With Text In Python .docx Module - GeeksforGeeks
|
03 Jan, 2021
Prerequisite: Working with .docx module
Word documents contain formatted text wrapped within three object levels. The Lowest level-run objects, middle level-paragraph objects, and highest level-document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module. Pip command to install this module is:
pip install python-docx
Python docx module allows user to manipulate docs by either manipulating the existing one or creating a new empty document and manipulating it. It is a powerful tool as it helps you to manipulate the document to a very large extend. You can also manipulate the font size, colour and its style using this module.
To increase/decrease the font size of the text you have to first create a paragraph object then you have to use add_run() method to add content. You can directly use add_paragraph() method to add paragraph but if you want to increase/decrease the font size of the text you have to use add_run() as all the block-level formatting is done by using add_paragraph() method while all the character-level formatting is done by using add_run().
Now to set a new font size we will use .font.size method. This is the method of the font object and is used to set the new font size of the text.
Syntax: para.font.size = Length
Parameter:
Length: It defines the size of the font. It can be in inches, pt or cm.
Example 1: Setting the font size of the text in a paragraph.
Python3
# Import docx NOT python-docximport docxfrom docx.shared import Pt # Create an instance of a word documentdoc = docx.Document() # Add a Title to the document doc.add_heading('GeeksForGeeks', 0) # Adding paragraph with Increased font sizedoc.add_heading('Increased Font Size Paragraph:', 3)para = doc.add_paragraph().add_run( 'GeeksforGeeks is a Computer Science portal for geeks.')# Increasing size of the fontpara.font.size = Pt(12) # Adding paragraph with normal font sizedoc.add_heading('Normal Font Size Paragraph:', 3)doc.add_paragraph( 'GeeksforGeeks is a Computer Science portal for geeks.') # Now save the document to a location doc.save('gfg.docx')
Output:
To apply a font colour to the text you have to first create a paragraph object then you have to use add_run() method to add content. You can directly use add_paragraph() method to add paragraph but if you want to apply a font colour to a text you have to use add_run() as all the block-level formatting is done by using add_paragraph() method while all the character-level formatting is done by using add_run().
To set the colour to the font we will make us of the RGBColor() object which takes hexadecimal input of the colour and sets the same colour to the text.
Syntax: para.font.color.rgb = RGBColor([RGB Colour Value in Hexadecimal])
Parameter:
RGB Colour Value: It is the hexadecimal value of the colour you want to set. It is given in the form of R, G, B as input.
Note: You have to add ‘from docx.shared import RGBColor‘ import statement before calling RGBColor() function in your code.
Example 2: Adding colour to the text in the paragraph.
Python3
# Import docx NOT python-docximport docxfrom docx.shared import RGBColor # Create an instance of a word documentdoc = docx.Document() # Add a Title to the document doc.add_heading('GeeksForGeeks', 0) # Adding paragraph doc.add_heading('Font Colour:', 3)para = doc.add_paragraph().add_run( 'GeeksforGeeks is a Computer Science portal for geeks.') # Adding forest green colour to the text# RGBColor(R, G, B)para.font.color.rgb = RGBColor(0x22, 0x8b, 0x22) # Now save the document to a location doc.save('gfg.docx')
Output:
To set a new font style for the text you have to first create a paragraph object then you have to use add_run() method to add content. You can directly use add_paragraph() method to add paragraph but if you want to set a new font style of the text you have to use add_run() as all the block-level formatting is done by using add_paragraph() method while all the character-level formatting is done by using add_run().
Now to set a new font name we will use .font.name method. This is the method of the font object and is used to set the new font name for the text.
Syntax: para.font.name = String s
Parameter:
String s: It is the name of the new font style. If you give any random name as input string then default style is adopted for the text.
Example 3: Setting a new font name for a paragraph.
Python3
# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Add a Title to the document doc.add_heading('GeeksForGeeks', 0) # Adding paragraph with new font Styledoc.add_heading('Font Style: Roboto', 3)para = doc.add_paragraph().add_run( 'GeeksforGeeks is a Computer Science portal for geeks.')# Setting new font stylepara.font.name = 'Roboto' # Adding paragraph with default font Styledoc.add_heading('Font Style: Default [Cambria]', 3)doc.add_paragraph( 'GeeksforGeeks is a Computer Science portal for geeks.') # Now save the document to a location doc.save('gfg.docx')
Output:
To set the text to bold you have to set it true.
doc.bold = True
To highlight a specific word the bold needs to be set True along with its add_run() statement.
add_run(" text ").bold=True
Example 1: Applying bold to a complete paragraph.
Python3
# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Creating paragraphpara = doc.add_paragraph() # Adding content to paragraphbold_para = para.add_run( '''GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles, quizzes etc.''') # Setting bold to truebold_para.bold = True # Now save the document to a locationdoc.save('gfg.docx')
Output:
Document gfg.docx
Example 2: Applying bold to a specific word or phrase.
Python3
# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Creating paragraph with some contentpara = doc.add_paragraph( '''GeeksforGeeks is a Computer Science portal for geeks.''') # Adding more content to paragraph and Setting bold to truepara.add_run( ''' It contains well written, well thought and well-explained ''').bold = True # Adding more content to paragraphpara.add_run('''computer science and programming articles, quizzes etc.''') # Now save the document to a locationdoc.save('gfg.docx')
Output:
Document gfg.docx
To set the text to italics you have to set it true.
doc.italic = True
To make some specific word(s) italics, it needs to be set True along with its add_run() statement.
add_run(" text ").italic=True
Example 3: Applying italics to a complete paragraph.
Python3
# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Creating paragraphpara = doc.add_paragraph() # Adding content to paragraphitalic_para = para.add_run( '''GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles, quizzes etc.''') # Applying italics to trueitalic_para.italic = True # Now save the document to a locationdoc.save('gfg.docx')
Output:
Document gfg.docx
Example 4: Applying italics to a specific word or phrase.
Python3
# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Creating paragraph with some contentpara = doc.add_paragraph( '''GeeksforGeeks is a Computer Science portal for geeks.''') # Adding more content to paragraph and applying italics to truepara.add_run( ''' It contains well written, well thought and well-explained ''').italic = True # Adding more content to paragraphpara.add_run('''computer science and programming articles, quizzes etc.''') # Now save the document to a locationdoc.save('gfg.docx')
Output:
Document gfg.docx
To apply to underline to a text you have to set it true.
doc.underline = True
To underline a specific part, underline needs to set a True along with its add_run() function
add_run("text").underline=True
Example 5: Applying underline to a complete paragraph.
Python3
# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Creating paragraphpara = doc.add_paragraph() # Adding content to paragraphunderline_para = para.add_run( '''GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles, quizzes etc.''') # Applying undeline to trueunderline_para.underline = True # Now save the document to a locationdoc.save('gfg.docx')
Output:
Document gfg.docx
Example 6: Applying underline to a specific word or phrase.
Python3
# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Creating paragraph with some contentpara = doc.add_paragraph( '''GeeksforGeeks is a Computer Science portal for geeks.''') # Adding more content to paragraph and applying underline to thempara.add_run( ''' It contains well written, well thought and well-explained ''').underline = True # Adding more content to paragraphpara.add_run('''computer science and programming articles, quizzes etc.''') # Now save the document to a locationdoc.save('gfg.docx')
Output:
Document gfg.docx
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24317,
"s": 24289,
"text": "\n03 Jan, 2021"
},
{
"code": null,
"e": 24357,
"s": 24317,
"text": "Prerequisite: Working with .docx module"
},
{
"code": null,
"e": 24718,
"s": 24357,
"text": "Word documents contain formatted text wrapped within three object levels. The Lowest level-run objects, middle level-paragraph objects, and highest level-document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module. Pip command to install this module is:"
},
{
"code": null,
"e": 24742,
"s": 24718,
"text": "pip install python-docx"
},
{
"code": null,
"e": 25054,
"s": 24742,
"text": "Python docx module allows user to manipulate docs by either manipulating the existing one or creating a new empty document and manipulating it. It is a powerful tool as it helps you to manipulate the document to a very large extend. You can also manipulate the font size, colour and its style using this module."
},
{
"code": null,
"e": 25492,
"s": 25054,
"text": "To increase/decrease the font size of the text you have to first create a paragraph object then you have to use add_run() method to add content. You can directly use add_paragraph() method to add paragraph but if you want to increase/decrease the font size of the text you have to use add_run() as all the block-level formatting is done by using add_paragraph() method while all the character-level formatting is done by using add_run()."
},
{
"code": null,
"e": 25638,
"s": 25492,
"text": "Now to set a new font size we will use .font.size method. This is the method of the font object and is used to set the new font size of the text."
},
{
"code": null,
"e": 25670,
"s": 25638,
"text": "Syntax: para.font.size = Length"
},
{
"code": null,
"e": 25682,
"s": 25670,
"text": "Parameter: "
},
{
"code": null,
"e": 25754,
"s": 25682,
"text": "Length: It defines the size of the font. It can be in inches, pt or cm."
},
{
"code": null,
"e": 25815,
"s": 25754,
"text": "Example 1: Setting the font size of the text in a paragraph."
},
{
"code": null,
"e": 25823,
"s": 25815,
"text": "Python3"
},
{
"code": "# Import docx NOT python-docximport docxfrom docx.shared import Pt # Create an instance of a word documentdoc = docx.Document() # Add a Title to the document doc.add_heading('GeeksForGeeks', 0) # Adding paragraph with Increased font sizedoc.add_heading('Increased Font Size Paragraph:', 3)para = doc.add_paragraph().add_run( 'GeeksforGeeks is a Computer Science portal for geeks.')# Increasing size of the fontpara.font.size = Pt(12) # Adding paragraph with normal font sizedoc.add_heading('Normal Font Size Paragraph:', 3)doc.add_paragraph( 'GeeksforGeeks is a Computer Science portal for geeks.') # Now save the document to a location doc.save('gfg.docx')",
"e": 26492,
"s": 25823,
"text": null
},
{
"code": null,
"e": 26500,
"s": 26492,
"text": "Output:"
},
{
"code": null,
"e": 26912,
"s": 26500,
"text": "To apply a font colour to the text you have to first create a paragraph object then you have to use add_run() method to add content. You can directly use add_paragraph() method to add paragraph but if you want to apply a font colour to a text you have to use add_run() as all the block-level formatting is done by using add_paragraph() method while all the character-level formatting is done by using add_run()."
},
{
"code": null,
"e": 27065,
"s": 26912,
"text": "To set the colour to the font we will make us of the RGBColor() object which takes hexadecimal input of the colour and sets the same colour to the text."
},
{
"code": null,
"e": 27140,
"s": 27065,
"text": "Syntax: para.font.color.rgb = RGBColor([RGB Colour Value in Hexadecimal])"
},
{
"code": null,
"e": 27151,
"s": 27140,
"text": "Parameter:"
},
{
"code": null,
"e": 27273,
"s": 27151,
"text": "RGB Colour Value: It is the hexadecimal value of the colour you want to set. It is given in the form of R, G, B as input."
},
{
"code": null,
"e": 27396,
"s": 27273,
"text": "Note: You have to add ‘from docx.shared import RGBColor‘ import statement before calling RGBColor() function in your code."
},
{
"code": null,
"e": 27451,
"s": 27396,
"text": "Example 2: Adding colour to the text in the paragraph."
},
{
"code": null,
"e": 27459,
"s": 27451,
"text": "Python3"
},
{
"code": "# Import docx NOT python-docximport docxfrom docx.shared import RGBColor # Create an instance of a word documentdoc = docx.Document() # Add a Title to the document doc.add_heading('GeeksForGeeks', 0) # Adding paragraph doc.add_heading('Font Colour:', 3)para = doc.add_paragraph().add_run( 'GeeksforGeeks is a Computer Science portal for geeks.') # Adding forest green colour to the text# RGBColor(R, G, B)para.font.color.rgb = RGBColor(0x22, 0x8b, 0x22) # Now save the document to a location doc.save('gfg.docx')",
"e": 27980,
"s": 27459,
"text": null
},
{
"code": null,
"e": 27988,
"s": 27980,
"text": "Output:"
},
{
"code": null,
"e": 28405,
"s": 27988,
"text": "To set a new font style for the text you have to first create a paragraph object then you have to use add_run() method to add content. You can directly use add_paragraph() method to add paragraph but if you want to set a new font style of the text you have to use add_run() as all the block-level formatting is done by using add_paragraph() method while all the character-level formatting is done by using add_run()."
},
{
"code": null,
"e": 28552,
"s": 28405,
"text": "Now to set a new font name we will use .font.name method. This is the method of the font object and is used to set the new font name for the text."
},
{
"code": null,
"e": 28586,
"s": 28552,
"text": "Syntax: para.font.name = String s"
},
{
"code": null,
"e": 28597,
"s": 28586,
"text": "Parameter:"
},
{
"code": null,
"e": 28733,
"s": 28597,
"text": "String s: It is the name of the new font style. If you give any random name as input string then default style is adopted for the text."
},
{
"code": null,
"e": 28785,
"s": 28733,
"text": "Example 3: Setting a new font name for a paragraph."
},
{
"code": null,
"e": 28793,
"s": 28785,
"text": "Python3"
},
{
"code": "# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Add a Title to the document doc.add_heading('GeeksForGeeks', 0) # Adding paragraph with new font Styledoc.add_heading('Font Style: Roboto', 3)para = doc.add_paragraph().add_run( 'GeeksforGeeks is a Computer Science portal for geeks.')# Setting new font stylepara.font.name = 'Roboto' # Adding paragraph with default font Styledoc.add_heading('Font Style: Default [Cambria]', 3)doc.add_paragraph( 'GeeksforGeeks is a Computer Science portal for geeks.') # Now save the document to a location doc.save('gfg.docx')",
"e": 29420,
"s": 28793,
"text": null
},
{
"code": null,
"e": 29428,
"s": 29420,
"text": "Output:"
},
{
"code": null,
"e": 29477,
"s": 29428,
"text": "To set the text to bold you have to set it true."
},
{
"code": null,
"e": 29493,
"s": 29477,
"text": "doc.bold = True"
},
{
"code": null,
"e": 29588,
"s": 29493,
"text": "To highlight a specific word the bold needs to be set True along with its add_run() statement."
},
{
"code": null,
"e": 29616,
"s": 29588,
"text": "add_run(\" text \").bold=True"
},
{
"code": null,
"e": 29666,
"s": 29616,
"text": "Example 1: Applying bold to a complete paragraph."
},
{
"code": null,
"e": 29674,
"s": 29666,
"text": "Python3"
},
{
"code": "# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Creating paragraphpara = doc.add_paragraph() # Adding content to paragraphbold_para = para.add_run( '''GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles, quizzes etc.''') # Setting bold to truebold_para.bold = True # Now save the document to a locationdoc.save('gfg.docx')",
"e": 30229,
"s": 29674,
"text": null
},
{
"code": null,
"e": 30237,
"s": 30229,
"text": "Output:"
},
{
"code": null,
"e": 30255,
"s": 30237,
"text": "Document gfg.docx"
},
{
"code": null,
"e": 30310,
"s": 30255,
"text": "Example 2: Applying bold to a specific word or phrase."
},
{
"code": null,
"e": 30318,
"s": 30310,
"text": "Python3"
},
{
"code": "# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Creating paragraph with some contentpara = doc.add_paragraph( '''GeeksforGeeks is a Computer Science portal for geeks.''') # Adding more content to paragraph and Setting bold to truepara.add_run( ''' It contains well written, well thought and well-explained ''').bold = True # Adding more content to paragraphpara.add_run('''computer science and programming articles, quizzes etc.''') # Now save the document to a locationdoc.save('gfg.docx')",
"e": 30942,
"s": 30318,
"text": null
},
{
"code": null,
"e": 30950,
"s": 30942,
"text": "Output:"
},
{
"code": null,
"e": 30968,
"s": 30950,
"text": "Document gfg.docx"
},
{
"code": null,
"e": 31020,
"s": 30968,
"text": "To set the text to italics you have to set it true."
},
{
"code": null,
"e": 31038,
"s": 31020,
"text": "doc.italic = True"
},
{
"code": null,
"e": 31137,
"s": 31038,
"text": "To make some specific word(s) italics, it needs to be set True along with its add_run() statement."
},
{
"code": null,
"e": 31167,
"s": 31137,
"text": "add_run(\" text \").italic=True"
},
{
"code": null,
"e": 31220,
"s": 31167,
"text": "Example 3: Applying italics to a complete paragraph."
},
{
"code": null,
"e": 31228,
"s": 31220,
"text": "Python3"
},
{
"code": "# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Creating paragraphpara = doc.add_paragraph() # Adding content to paragraphitalic_para = para.add_run( '''GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles, quizzes etc.''') # Applying italics to trueitalic_para.italic = True # Now save the document to a locationdoc.save('gfg.docx')",
"e": 31793,
"s": 31228,
"text": null
},
{
"code": null,
"e": 31801,
"s": 31793,
"text": "Output:"
},
{
"code": null,
"e": 31819,
"s": 31801,
"text": "Document gfg.docx"
},
{
"code": null,
"e": 31877,
"s": 31819,
"text": "Example 4: Applying italics to a specific word or phrase."
},
{
"code": null,
"e": 31885,
"s": 31877,
"text": "Python3"
},
{
"code": "# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Creating paragraph with some contentpara = doc.add_paragraph( '''GeeksforGeeks is a Computer Science portal for geeks.''') # Adding more content to paragraph and applying italics to truepara.add_run( ''' It contains well written, well thought and well-explained ''').italic = True # Adding more content to paragraphpara.add_run('''computer science and programming articles, quizzes etc.''') # Now save the document to a locationdoc.save('gfg.docx')",
"e": 32515,
"s": 31885,
"text": null
},
{
"code": null,
"e": 32523,
"s": 32515,
"text": "Output:"
},
{
"code": null,
"e": 32541,
"s": 32523,
"text": "Document gfg.docx"
},
{
"code": null,
"e": 32598,
"s": 32541,
"text": "To apply to underline to a text you have to set it true."
},
{
"code": null,
"e": 32619,
"s": 32598,
"text": "doc.underline = True"
},
{
"code": null,
"e": 32713,
"s": 32619,
"text": "To underline a specific part, underline needs to set a True along with its add_run() function"
},
{
"code": null,
"e": 32744,
"s": 32713,
"text": "add_run(\"text\").underline=True"
},
{
"code": null,
"e": 32799,
"s": 32744,
"text": "Example 5: Applying underline to a complete paragraph."
},
{
"code": null,
"e": 32807,
"s": 32799,
"text": "Python3"
},
{
"code": "# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Creating paragraphpara = doc.add_paragraph() # Adding content to paragraphunderline_para = para.add_run( '''GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles, quizzes etc.''') # Applying undeline to trueunderline_para.underline = True # Now save the document to a locationdoc.save('gfg.docx')",
"e": 33382,
"s": 32807,
"text": null
},
{
"code": null,
"e": 33390,
"s": 33382,
"text": "Output:"
},
{
"code": null,
"e": 33408,
"s": 33390,
"text": "Document gfg.docx"
},
{
"code": null,
"e": 33468,
"s": 33408,
"text": "Example 6: Applying underline to a specific word or phrase."
},
{
"code": null,
"e": 33476,
"s": 33468,
"text": "Python3"
},
{
"code": "# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Creating paragraph with some contentpara = doc.add_paragraph( '''GeeksforGeeks is a Computer Science portal for geeks.''') # Adding more content to paragraph and applying underline to thempara.add_run( ''' It contains well written, well thought and well-explained ''').underline = True # Adding more content to paragraphpara.add_run('''computer science and programming articles, quizzes etc.''') # Now save the document to a locationdoc.save('gfg.docx')",
"e": 34111,
"s": 33476,
"text": null
},
{
"code": null,
"e": 34119,
"s": 34111,
"text": "Output:"
},
{
"code": null,
"e": 34137,
"s": 34119,
"text": "Document gfg.docx"
},
{
"code": null,
"e": 34161,
"s": 34137,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 34168,
"s": 34161,
"text": "Python"
},
{
"code": null,
"e": 34187,
"s": 34168,
"text": "Technical Scripter"
},
{
"code": null,
"e": 34285,
"s": 34187,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34317,
"s": 34285,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 34359,
"s": 34317,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 34415,
"s": 34359,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 34457,
"s": 34415,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 34488,
"s": 34457,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 34543,
"s": 34488,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 34565,
"s": 34543,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 34604,
"s": 34565,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 34633,
"s": 34604,
"text": "Create a directory in Python"
}
] |
Perl Interview Questions
|
Dear readers, these Perl Programming Language Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of Perl Programming Language. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer −
Perl is a stable, cross platform programming language.
Perl is a stable, cross platform programming language.
Though Perl is not officially an acronym but few people used it as Practical Extraction and Report Language.
Though Perl is not officially an acronym but few people used it as Practical Extraction and Report Language.
It is used for mission critical projects in the public and private sectors.
It is used for mission critical projects in the public and private sectors.
Perl is an Open Source software, licensed under its Artistic License, or the GNU General Public License (GPL).
Perl is an Open Source software, licensed under its Artistic License, or the GNU General Public License (GPL).
Perl was created by Larry Wall.
Perl was created by Larry Wall.
Perl 1.0 was released to usenet's alt.comp.sources in 1987
Perl 1.0 was released to usenet's alt.comp.sources in 1987
At the time of writing this tutorial, the latest version of perl is 5.16.2
At the time of writing this tutorial, the latest version of perl is 5.16.2
Perl is listed in the Oxford English Dictionary.
Perl is listed in the Oxford English Dictionary.
Perl takes the best features from other languages, such as C, awk, sed, sh, and BASIC, among others.
Perl takes the best features from other languages, such as C, awk, sed, sh, and BASIC, among others.
Perls database integration interface DBI supports third-party databases including Oracle, Sybase, Postgres, MySQL and others.
Perls database integration interface DBI supports third-party databases including Oracle, Sybase, Postgres, MySQL and others.
Perl works with HTML, XML, and other mark-up languages.
Perl works with HTML, XML, and other mark-up languages.
Perl supports Unicode.
Perl supports Unicode.
Perl is Y2K compliant.
Perl is Y2K compliant.
Perl supports both procedural and object-oriented programming.
Perl supports both procedural and object-oriented programming.
Perl interfaces with external C/C++ libraries through XS or SWIG.
Perl interfaces with external C/C++ libraries through XS or SWIG.
Perl is extensible. There are over 20,000 third party modules available from the Comprehensive Perl Archive Network (CPAN).
Perl is extensible. There are over 20,000 third party modules available from the Comprehensive Perl Archive Network (CPAN).
The Perl interpreter can be embedded into other systems.
The Perl interpreter can be embedded into other systems.
Perl used to be the most popular web programming language due to its text manipulation capabilities and rapid development cycle.
Perl used to be the most popular web programming language due to its text manipulation capabilities and rapid development cycle.
Perl is widely known as " the duct-tape of the Internet".
Perl is widely known as " the duct-tape of the Internet".
Perl can handle encrypted Web data, including e-commerce transactions.
Perl can handle encrypted Web data, including e-commerce transactions.
Perl can be embedded into web servers to speed up processing by as much as 2000%.
Perl can be embedded into web servers to speed up processing by as much as 2000%.
Perl's mod_perl allows the Apache web server to embed a Perl interpreter.
Perl's mod_perl allows the Apache web server to embed a Perl interpreter.
Perl's DBI package makes web-database integration easy.
Perl's DBI package makes web-database integration easy.
Yes! Perl is a case sensitive programming language.
A Perl identifier is a name used to identify a variable, function, class, module, or other object. A Perl variable name starts with either $, @ or % followed by zero or more letters, underscores, and digits (0 to 9).
Perl has three basic data types − scalars, arrays of scalars, and hashes of scalars, also known as associative arrays.
Scalars are simple variables. They are preceded by a dollar sign ($). A scalar is either a number, a string, or a reference. A reference is actually an address of a variable, which we will see in the upcoming chapters.
Arrays are ordered lists of scalars that you access with a numeric index which starts with 0. They are preceded by an "at" sign (@).
Hashes are unordered sets of key/value pairs that you access using the keys as subscripts. They are preceded by a percent sign (%).
Perl variables do not have to be explicitly declared to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.
Perl treats same variable differently based on Context, i.e. situation where a variable is being used.
Assignment to a scalar variable evaluates the right-hand side in a scalar context.
Assignment to an array or a hash evaluates the right-hand side in a list context.
Boolean context is simply any place where an expression is being evaluated to see whether it's true or false.
This context not only doesn't care what the return value is, it doesn't even want a return value.
This context only happens inside quotes, or things that work like quotes.
Single quoted string prints the perl variable as a string whereas double quoted string evaluates the variable and used to get the variable's value.
#!/usr/bin/perl
$var = "This is string scalar!";
$quote = 'I m inside single quote - $var';
$double = "This is inside double quote - $var";
$escape = "This example of escape -\tHello, World!";
print "var = $var\n";
print "quote = $quote\n";
print "double = $double\n";
print "escape = $escape\n";
This will produce the following result −
var = This is string scalar!
quote = I m inside single quote - $var
double = This is inside double quote - This is string scalar!
escape = This example of escape - Hello, World!
A literal of the form v1.20.300.4000 is parsed as a string composed of characters with the specified ordinals. This form is known as v-strings.
A v-string provides an alternative and more readable way to construct strings, rather than use the somewhat less readable interpolation form "\x{1}\x{14}\x{12c}\x{fa0}".
It is used to get the current file name.
It is used to get the current line number.
It is used to get the current package name.
To refer to a single element of an array, you will use the dollar sign ($) with the variable name followed by the index of the element in square brackets.
Here is a simple example of using the array variables −
#!/usr/bin/perl
@ages = (25, 30, 40);
@names = ("John Paul", "Lisa", "Kumar");
print "\$ages[0] = $ages[0]\n";
print "\$ages[1] = $ages[1]\n";
print "\$ages[2] = $ages[2]\n";
print "\$names[0] = $names[0]\n";
print "\$names[1] = $names[1]\n";
print "\$names[2] = $names[2]\n";
When exected, this will produce the following result −
$ages[0] = 25
$ages[1] = 30
$ages[2] = 40
$names[0] = John Paul
$names[1] = Lisa
$names[2] = Kumar
range operator (..) is used to create sequential arrays.
#!/usr/bin/perl
@var_10 = (1..10);
@var_20 = (10..20);
@var_abc = (a..z);
print "@var_10\n"; # Prints number from 1 to 10
print "@var_20\n"; # Prints number from 10 to 20
print "@var_abc\n"; # Prints number from a to z
Here double dot (..) is called range operator. This will produce the following result −
1 2 3 4 5 6 7 8 9 10
10 11 12 13 14 15 16 17 18 19 20
a b c d e f g h i j k l m n o p q r s t u v w x y z
The size of an array can be determined using the scalar context on the array - the returned value will be the number of elements in the array −
@array = (1,2,3);
print "Size: ",scalar @array,"\n";
The value returned will always be the physical size of the array, not the number of valid elements.
push @ARRAY, LIST - Pushes the values of the list onto the end of the array.
#!/usr/bin/perl
# create a simple array
@coins = ("Quarter","Dime","Nickel");
print "1. \@coins = @coins\n";
# add one element at the end of the array
push(@coins, "Penny");
print "2. \@coins = @coins\n";
This will produce the following result −
1. @coins = Quarter Dime Nickel
2. @coins = Quarter Dime Nickel Penny
unshift @ARRAY, LIST - Prepends list to the front of the array, and returns the number of elements in the new array.
#!/usr/bin/perl
# create a simple array
@coins = ("Quarter","Dime","Nickel");
print "1. \@coins = @coins\n";
# add one element at the beginning of the array
unshift(@coins, "Dollar");
print "2. \@coins = @coins\n";
This will produce the following result −
1. @coins = Quarter Dime Nickel
2. @coins = Dollar Quarter Dime Nickel
pop @ARRAY − Pops off and returns the last value of the array.
#!/usr/bin/perl
# create a simple array
@coins = ("Quarter","Dime","Nickel");
print "1. \@coins = @coins\n";
# remove one element from the last of the array.
pop(@coins);
print "2. \@coins = @coins\n";
This will produce the following result −
1. @coins = Quarter Dime Nickel
2. @coins = Quarter Dime
shift @ARRAY − Shifts the first value of the array off and returns it, shortening the array by 1 and moving everything down.
#!/usr/bin/perl
# create a simple array
@coins = ("Quarter","Dime","Nickel");
print "1. \@coins = @coins\n";
# remove one element from the beginning of the array.
shift(@coins);
print "2. \@coins = @coins\n";
This will produce the following result −
1. @coins = Quarter Dime Nickel
2. @coins = Dime Nickel
You can also extract a "slice" from an array − that is, you can select more than one item from an array in order to produce another array.
#!/usr/bin/perl
@days = qw/Mon Tue Wed Thu Fri Sat Sun/;
@weekdays = @days[3,4,5];
print "@weekdays\n";
This will produce the following result -
Thu Fri Sat
splice() function will remove the elements of @ARRAY designated by OFFSET and LENGTH, and replaces them with LIST, if specified. Finally, it returns the elements removed from the array.
splice @ARRAY, OFFSET [ , LENGTH [ , LIST ] ]
Following is the example −
#!/usr/bin/perl
@nums = (1..20);
print "Before - @nums\n";
splice(@nums, 5, 5, 21..25);
print "After - @nums\n";
This will produce the following result −
Before − 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
After − 1 2 3 4 5 21 22 23 24 25 11 12 13 14 15 16 17 18 19 20
split() splits a string into an array of strings, and returns it. If LIMIT is specified, splits into at most that number of fields. If PATTERN is omitted, splits on whitespace.
split [ PATTERN [ , EXPR [ , LIMIT ] ] ]
Following is the example −
#!/usr/bin/perl
# define Strings
$var_string = "Rain-Drops-On-Roses-And-Whiskers-On-Kittens";
$var_names = "Larry,David,Roger,Ken,Michael,Tom";
# transform above strings into arrays.
@string = split('-', $var_string);
@names = split(',', $var_names);
print "$string[3]\n"; # This will print Roses
print "$names[4]\n"; # This will print Michael
This will produce the following result −
Roses
Michael
join() function joins the separate strings of LIST into a single string with fields separated by the value of EXPR, and returns the string.
join EXPR, LIST
Following is the example −
#!/usr/bin/perl
# define Strings
$var_string = "Rain-Drops-On-Roses-And-Whiskers-On-Kittens";
$var_names = "Larry,David,Roger,Ken,Michael,Tom";
# transform above strings into arrays.
@string = split('-', $var_string);
@names = split(',', $var_names);
$string1 = join( '-', @string );
$string2 = join( ',', @names );
print "$string1\n";
print "$string2\n";
print "$string[3]\n"; # This will print Roses
print "$names[4]\n"; # This will print Michael
This will produce the following result −
Rain-Drops-On-Roses-And-Whiskers-On-Kittens
Larry,David,Roger,Ken,Michael,Tom
The sort() function sorts each element of an array according to the ASCII Numeric standards. This function has the following syntax −
sort [ SUBROUTINE ] LIST
This function sorts the LIST and returns the sorted array value. If SUBROUTINE is specified then specified logic inside the SUBTROUTINE is applied while sorting the elements.
#!/usr/bin/perl
# define an array
@foods = qw(pizza steak chicken burgers);
print "Before: @foods\n";
# sort this array
@foods = sort(@foods);
print "After: @foods\n";
This will produce the following result −
Before: pizza steak chicken burgers
After: burgers chicken pizza steak
This special variable is a scalar containing the first index of all arrays. Because Perl arrays have zero-based indexing, $[ will almost always be 0. But if you set $[ to 1 then all your arrays will use on-based indexing. It is recommended not to use any other indexing other than zero. However, let's take one example to show the usage of $[ variable −
#!/usr/bin/perl
# define an array
@foods = qw(pizza steak chicken burgers);
print "Foods: @foods\n";
# Let's reset first index of all the arrays.
$[ = 1;
print "Food at \@foods[1]: $foods[1]\n";
print "Food at \@foods[2]: $foods[2]\n";
This will produce the following result −
Foods: pizza steak chicken burgers
Food at @foods[1]: pizza
Food at @foods[2]: steak
Because an array is just a comma-separated sequence of values, you can combine them together as shown below.
#!/usr/bin/perl
@numbers = (1,3,(4,5,6));
print "numbers = @numbers\n";
This will produce the following result −
numbers = 1 3 4 5 6
Hashes are created in one of the two following ways. In the first method, you assign a value to a named key on a one-by-one basis −
$data{'John Paul'} = 45;
$data{'Lisa'} = 30;
$data{'Kumar'} = 40;
In the second case, you use a list, which is converted by taking individual pairs from the list: the first element of the pair is used as the key, and the second, as the value. For example −
%data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40);
When accessing individual elements from a hash, you must prefix the variable with a dollar sign ($) and then append the element key within curly brackets after the name of the variable. For example −
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
print "$data{'John Paul'}\n";
print "$data{'Lisa'}\n";
print "$data{'Kumar'}\n";
This will produce the following result −
45
30
40
You can get a list of all of the keys from a hash by using keys function, which has the following syntax −
keys %HASH
This function returns an array of all the keys of the named hash. Following is the example −
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
@names = keys %data;
print "$names[0]\n";
print "$names[1]\n";
print "$names[2]\n";
This will produce the following result −
Lisa
John Paul
Kumar
You can get a list of all of the values from a hash by using values function, which has the following syntax −
values %HASH
This function returns an array of all the values of the named hash. Following is the example −
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
@ages = values %data;
print "$ages[0]\n";
print "$ages[1]\n";
print "$ages[2]\n";
This will produce the following result −
30
45
40
Using the exists function, which returns true if the named key exists, irrespective of what its value might be −
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
if( exists($data{'Lisa'} ) ){
print "Lisa is $data{'Lisa'} years old\n";
}
else{
print "I don't know age of Lisa\n";
}
Here we have introduced the IF...ELSE statement, which we will study in a separate chapter. For now you just assume that if( condition ) part will be executed only when the given condition is true otherwise else part will be executed. So when we execute the above program, it produces the following result because here the given condition exists($data{'Lisa'} returns true −
Lisa is 30 years old
You can get the size - that is, the number of elements from a hash by using the scalar context on either keys or values. Simply saying first you have to get an array of either the keys or values and then you can get the size of array as follows −
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
@keys = keys %data;
$size = @keys;
print "1 - Hash size: is $size\n";
@values = values %data;
$size = @values;
print "2 - Hash size: is $size\n";
This will produce the following result −
1 - Hash size: is 3
2 - Hash size: is 3
Adding a new key/value pair can be done with one line of code using simple assignment operator.
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
@keys = keys %data;
$size = @keys;
print "1 - Hash size: is $size\n";
# adding an element to the hash;
$data{'Ali'} = 55;
@keys = keys %data;
$size = @keys;
print "2 - Hash size: is $size\n";
This will produce the following result −
1 - Hash size: is 3
2 - Hash size: is 4
To remove an element from the hash you need to use delete function as shown below in the example−
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
@keys = keys %data;
$size = @keys;
print "1 - Hash size: is $size\n";
# delete the same element from the hash;
delete $data{'John Paul'};
@keys = keys %data;
$size = @keys;
print "2 - Hash size: is $size\n";
This will produce the following result −
1 - Hash size: is 3
2 - Hash size: is 2
It causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
last statement.
It terminates the loop statement and transfers execution to the statement immediately following the loop.
continue statement.
A continue BLOCK, it is always executed just before the conditional is about to be evaluated again.
The redo command restarts the loop block without evaluating the conditional again. The continue block, if any, is not executed.
The goto LABEL form jumps to the statement labeled with LABEL and resumes execution from there.
The goto EXPR form is just a generalization of goto LABEL. It expects the expression to return a label name and then jumps to that labeled statement.
It substitutes a call to the named subroutine for the currently running subroutine.
Exponent − Performs exponential (power) calculation on operators. Assume variable $a holds 10 and variable $b holds 20 then $a**$b will give 10 to the power 20.
It checks if the value of two operands are equal or not, and returns -1, 0, or 1 depending on whether the left argument is numerically less than, equal to, or greater than the right argument. Assume variable $a holds 10 and variable $b holds 20 then ($a <=> $b) returns -1.
It returns true if the left argument is stringwise less than the right argument. Assume variable $a holds "abc" and variable $b holds "xyz" then ($a lt $b) is true.
It returns true if the left argument is stringwise greater than the right argument. Assume variable $a holds "abc" and variable $b holds "xyz" then ($a gt $b) is false.
It returns true if the left argument is stringwise less than or equal to the right argument. Assume variable $a holds "abc" and variable $b holds "xyz" then ($a le $b) is true.
It returns true if the left argument is stringwise greater than or equal to the right argument. Assume variable $a holds "abc" and variable $b holds "xyz" then ($a ge $b) is false.
It returns true if the left argument is stringwise equal to the right argument. Assume variable $a holds "abc" and variable $b holds "xyz" then ($a eq $b) is false.
It returns true if the left argument is stringwise not equal to the right argument. Assume variable $a holds "abc" and variable $b holds "xyz" then ($a ne $b) is true.
It returns -1, 0, or 1 depending on whether the left argument is stringwise less than, equal to, or greater than the right argument. Assume variable $a holds "abc" and variable $b holds "xyz" then ($a cmp $b) is -1.
Exponent AND assignment operator, Performs exponential (power) calculation on operators and assign value to the left operand. $c **= $a is equivalent to $c = $c ** $a
It encloses a string with-in single quotes. q{abcd} gives 'abcd'
It encloses a string with-in double quotes. qq{abcd} gives "abcd"
It encloses a string with-in invert quotes. qx{abcd} gives `abcd`
Binary operator dot (.) concatenates two strings. If $a="abc", $b="def" then $a.$b will give "abcdef"
The repetition operator x returns a string consisting of the left operand repeated the number of times specified by the right operand. ('-' x 3) will give ---.
The range operator .. returns a list of values counting (up by ones) from the left value to the right value. (2..5) will give (2, 3, 4, 5).
Auto Increment operator increases integer value by one. $a++ will give 11.
Auto Decrement operator decreases integer value by one. $a−− will give 9
The arrow operator is mostly used in dereferencing a method or variable from an object or a class name. $obj−>$a is an example to access variable $a from object $obj.
localtime() function, which returns values for the current date and time if given no arguments.
#!/usr/local/bin/perl
@months = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );
@days = qw(Sun Mon Tue Wed Thu Fri Sat Sun);
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
print "$mday $months[$mon] $days[$wday]\n";
When the above code is executed, it produces the following result −
16 Feb Sat
The function gmtime() works just like localtime() function but the returned values are localized for the standard Greenwich time zone. When called in list context, $isdst, the last value returned by gmtime, is always 0 . There is no Daylight Saving Time in GMT.
localtime() will return the current local time on the machine that runs the script and gmtime() will return the universal Greenwich Mean Time, or GMT (or UTC).
You can use the time() function to get epoch time, i.e. the numbers of seconds that have elapsed since a given date, in Unix is January 1, 1970.
You can use the POSIX function strftime() to format date and time.
The general form of a subroutine definition in Perl programming language is as follows −
sub subroutine_name{
body of the subroutine
}
The typical way of calling that Perl subroutine is as follows −
subroutine_name( list of arguments );
they can be acessed inside the function using the special array @_. Thus the first argument to the function is in $_[0], the second is in $_[1], and so on.
using scalar(@_), we can get the total number of arguments passed.
The my operator confines a variable to a particular region of code in which it can be used and accessed. Outside that region, this variable cannot be used or accessed.
By default, all variables in Perl are global variables, which means they can be accessed from anywhere in the program.
Lexical variables are private variables created using my operator.
The local is used when the current value of a variable must be visible to called subroutines.
A local just gives temporary values to global (meaning package) variables. This is known as dynamic scoping.
Lexical scoping is done with my operator. A lexical scope is usually a block of code with a set of braces around it, such as those defining the body of the subroutine or those marking the code blocks of if, while, for, foreach, and eval statements. The my operator confines a variable to a particular region of code in which it can be used and accessed. Outside that region, this variable cannot be used or accessed.
There are another type of lexical variables, which are similar to private variables but they maintain their state and they do not get reinitialized upon multiple calls of the subroutines. These variables are defined using the state operator and available starting from Perl 5.9.4.
The context of a subroutine or statement is defined as the type of return value that is expected. This allows you to use a single function that returns different values based on what the user is expecting to receive. For example, the following localtime() returns a string when it is called in scalar context, but it returns a list when it is called in list context.
my $datestring = localtime( time );
In this example, the value of $timestr is now a string made up of the current date and time, for example, Thu Nov 30 15:21:33 2000. Conversely −
($sec,$min,$hour,$mday,$mon, $year,$wday,$yday,$isdst) = localtime(time);
Now the individual variables contain the corresponding values returned by localtime() subroutine.
A Perl reference is a scalar data type that holds the location of another value which could be scalar, arrays, or hashes. Because of its scalar nature, a reference can be used anywhere, a scalar can be used.
You can create a reference for any variable by prefixing it with a backslash as follows −
$scalarref = \$foo;
You can create a reference for any array by prefixing it with a backslash as follows −
$arrayref = \@ARGV;
You can create a reference for any hash by prefixing it with a backslash as follows −
$hashref = \%ENV;
You can create a reference for any subrouting by prefixing it with a backslash as follows −
$cref = \&PrintHash;
Dereferencing returns the value from a reference point to the location.
To dereference a reference simply use $, @ or % as prefix of the reference variable depending on whether the reference is pointing to a scalar, array, or hash.
A circular reference occurs when two references contain a reference to each other. You have to be careful while creating references otherwise a circular reference can lead to memory leaks. Following is an example −
#!/usr/bin/perl
my $foo = 100;
$foo = \$foo;
print "Value of foo is : ", $$foo, "\n";
When above program is executed, it produces the following result −
Value of foo is : REF(0x9aae38)
Following is the syntax to open file.txt in read-only mode. Here less than < sign indicates that file has to be opend in read-only mode.
open(DATA, "<file.txt");
Here DATA is the file handle which will be used to read the file.
Following is the syntax to open file.txt in writing mode. Here less than > sign indicates that file has to be opend in the writing mode.
open(DATA, ">file.txt") or die "Couldn't open file file.txt, $!";
Following is the syntax to open file.txt in writing mode without truncating it. Here less than +< sign indicates that file has to be opend in the writing mode without truncating it.
open(DATA, "+<file.txt") or die "Couldn't open file file.txt, $!";
To close a filehandle, and therefore disassociate the filehandle from the corresponding file, you use the close function. This flushes the filehandle's buffers and closes the system's file descriptor.
The getc function returns a single character from the specified FILEHANDLE, or STDIN if none is specified.
The read function reads a block of information from the buffered filehandle: This function is used to read binary data from the file.
Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong.
Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)
46 Lectures
4.5 hours
Devi Killada
11 Lectures
1.5 hours
Harshit Srivastava
30 Lectures
6 hours
TELCOMA Global
24 Lectures
2 hours
Mohammad Nauman
68 Lectures
7 hours
Stone River ELearning
58 Lectures
6.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2695,
"s": 2220,
"text": "Dear readers, these Perl Programming Language Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of Perl Programming Language. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer −"
},
{
"code": null,
"e": 2750,
"s": 2695,
"text": "Perl is a stable, cross platform programming language."
},
{
"code": null,
"e": 2805,
"s": 2750,
"text": "Perl is a stable, cross platform programming language."
},
{
"code": null,
"e": 2914,
"s": 2805,
"text": "Though Perl is not officially an acronym but few people used it as Practical Extraction and Report Language."
},
{
"code": null,
"e": 3023,
"s": 2914,
"text": "Though Perl is not officially an acronym but few people used it as Practical Extraction and Report Language."
},
{
"code": null,
"e": 3099,
"s": 3023,
"text": "It is used for mission critical projects in the public and private sectors."
},
{
"code": null,
"e": 3175,
"s": 3099,
"text": "It is used for mission critical projects in the public and private sectors."
},
{
"code": null,
"e": 3286,
"s": 3175,
"text": "Perl is an Open Source software, licensed under its Artistic License, or the GNU General Public License (GPL)."
},
{
"code": null,
"e": 3397,
"s": 3286,
"text": "Perl is an Open Source software, licensed under its Artistic License, or the GNU General Public License (GPL)."
},
{
"code": null,
"e": 3429,
"s": 3397,
"text": "Perl was created by Larry Wall."
},
{
"code": null,
"e": 3461,
"s": 3429,
"text": "Perl was created by Larry Wall."
},
{
"code": null,
"e": 3520,
"s": 3461,
"text": "Perl 1.0 was released to usenet's alt.comp.sources in 1987"
},
{
"code": null,
"e": 3579,
"s": 3520,
"text": "Perl 1.0 was released to usenet's alt.comp.sources in 1987"
},
{
"code": null,
"e": 3654,
"s": 3579,
"text": "At the time of writing this tutorial, the latest version of perl is 5.16.2"
},
{
"code": null,
"e": 3729,
"s": 3654,
"text": "At the time of writing this tutorial, the latest version of perl is 5.16.2"
},
{
"code": null,
"e": 3778,
"s": 3729,
"text": "Perl is listed in the Oxford English Dictionary."
},
{
"code": null,
"e": 3827,
"s": 3778,
"text": "Perl is listed in the Oxford English Dictionary."
},
{
"code": null,
"e": 3928,
"s": 3827,
"text": "Perl takes the best features from other languages, such as C, awk, sed, sh, and BASIC, among others."
},
{
"code": null,
"e": 4029,
"s": 3928,
"text": "Perl takes the best features from other languages, such as C, awk, sed, sh, and BASIC, among others."
},
{
"code": null,
"e": 4155,
"s": 4029,
"text": "Perls database integration interface DBI supports third-party databases including Oracle, Sybase, Postgres, MySQL and others."
},
{
"code": null,
"e": 4281,
"s": 4155,
"text": "Perls database integration interface DBI supports third-party databases including Oracle, Sybase, Postgres, MySQL and others."
},
{
"code": null,
"e": 4337,
"s": 4281,
"text": "Perl works with HTML, XML, and other mark-up languages."
},
{
"code": null,
"e": 4393,
"s": 4337,
"text": "Perl works with HTML, XML, and other mark-up languages."
},
{
"code": null,
"e": 4416,
"s": 4393,
"text": "Perl supports Unicode."
},
{
"code": null,
"e": 4439,
"s": 4416,
"text": "Perl supports Unicode."
},
{
"code": null,
"e": 4462,
"s": 4439,
"text": "Perl is Y2K compliant."
},
{
"code": null,
"e": 4485,
"s": 4462,
"text": "Perl is Y2K compliant."
},
{
"code": null,
"e": 4548,
"s": 4485,
"text": "Perl supports both procedural and object-oriented programming."
},
{
"code": null,
"e": 4611,
"s": 4548,
"text": "Perl supports both procedural and object-oriented programming."
},
{
"code": null,
"e": 4677,
"s": 4611,
"text": "Perl interfaces with external C/C++ libraries through XS or SWIG."
},
{
"code": null,
"e": 4743,
"s": 4677,
"text": "Perl interfaces with external C/C++ libraries through XS or SWIG."
},
{
"code": null,
"e": 4867,
"s": 4743,
"text": "Perl is extensible. There are over 20,000 third party modules available from the Comprehensive Perl Archive Network (CPAN)."
},
{
"code": null,
"e": 4991,
"s": 4867,
"text": "Perl is extensible. There are over 20,000 third party modules available from the Comprehensive Perl Archive Network (CPAN)."
},
{
"code": null,
"e": 5048,
"s": 4991,
"text": "The Perl interpreter can be embedded into other systems."
},
{
"code": null,
"e": 5105,
"s": 5048,
"text": "The Perl interpreter can be embedded into other systems."
},
{
"code": null,
"e": 5234,
"s": 5105,
"text": "Perl used to be the most popular web programming language due to its text manipulation capabilities and rapid development cycle."
},
{
"code": null,
"e": 5363,
"s": 5234,
"text": "Perl used to be the most popular web programming language due to its text manipulation capabilities and rapid development cycle."
},
{
"code": null,
"e": 5421,
"s": 5363,
"text": "Perl is widely known as \" the duct-tape of the Internet\"."
},
{
"code": null,
"e": 5479,
"s": 5421,
"text": "Perl is widely known as \" the duct-tape of the Internet\"."
},
{
"code": null,
"e": 5550,
"s": 5479,
"text": "Perl can handle encrypted Web data, including e-commerce transactions."
},
{
"code": null,
"e": 5621,
"s": 5550,
"text": "Perl can handle encrypted Web data, including e-commerce transactions."
},
{
"code": null,
"e": 5703,
"s": 5621,
"text": "Perl can be embedded into web servers to speed up processing by as much as 2000%."
},
{
"code": null,
"e": 5785,
"s": 5703,
"text": "Perl can be embedded into web servers to speed up processing by as much as 2000%."
},
{
"code": null,
"e": 5859,
"s": 5785,
"text": "Perl's mod_perl allows the Apache web server to embed a Perl interpreter."
},
{
"code": null,
"e": 5933,
"s": 5859,
"text": "Perl's mod_perl allows the Apache web server to embed a Perl interpreter."
},
{
"code": null,
"e": 5989,
"s": 5933,
"text": "Perl's DBI package makes web-database integration easy."
},
{
"code": null,
"e": 6045,
"s": 5989,
"text": "Perl's DBI package makes web-database integration easy."
},
{
"code": null,
"e": 6097,
"s": 6045,
"text": "Yes! Perl is a case sensitive programming language."
},
{
"code": null,
"e": 6314,
"s": 6097,
"text": "A Perl identifier is a name used to identify a variable, function, class, module, or other object. A Perl variable name starts with either $, @ or % followed by zero or more letters, underscores, and digits (0 to 9)."
},
{
"code": null,
"e": 6433,
"s": 6314,
"text": "Perl has three basic data types − scalars, arrays of scalars, and hashes of scalars, also known as associative arrays."
},
{
"code": null,
"e": 6652,
"s": 6433,
"text": "Scalars are simple variables. They are preceded by a dollar sign ($). A scalar is either a number, a string, or a reference. A reference is actually an address of a variable, which we will see in the upcoming chapters."
},
{
"code": null,
"e": 6785,
"s": 6652,
"text": "Arrays are ordered lists of scalars that you access with a numeric index which starts with 0. They are preceded by an \"at\" sign (@)."
},
{
"code": null,
"e": 6917,
"s": 6785,
"text": "Hashes are unordered sets of key/value pairs that you access using the keys as subscripts. They are preceded by a percent sign (%)."
},
{
"code": null,
"e": 7130,
"s": 6917,
"text": "Perl variables do not have to be explicitly declared to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables."
},
{
"code": null,
"e": 7233,
"s": 7130,
"text": "Perl treats same variable differently based on Context, i.e. situation where a variable is being used."
},
{
"code": null,
"e": 7316,
"s": 7233,
"text": "Assignment to a scalar variable evaluates the right-hand side in a scalar context."
},
{
"code": null,
"e": 7398,
"s": 7316,
"text": "Assignment to an array or a hash evaluates the right-hand side in a list context."
},
{
"code": null,
"e": 7508,
"s": 7398,
"text": "Boolean context is simply any place where an expression is being evaluated to see whether it's true or false."
},
{
"code": null,
"e": 7606,
"s": 7508,
"text": "This context not only doesn't care what the return value is, it doesn't even want a return value."
},
{
"code": null,
"e": 7680,
"s": 7606,
"text": "This context only happens inside quotes, or things that work like quotes."
},
{
"code": null,
"e": 7828,
"s": 7680,
"text": "Single quoted string prints the perl variable as a string whereas double quoted string evaluates the variable and used to get the variable's value."
},
{
"code": null,
"e": 8128,
"s": 7828,
"text": "#!/usr/bin/perl\n\n$var = \"This is string scalar!\";\n$quote = 'I m inside single quote - $var';\n$double = \"This is inside double quote - $var\";\n\n$escape = \"This example of escape -\\tHello, World!\";\n\nprint \"var = $var\\n\";\nprint \"quote = $quote\\n\";\nprint \"double = $double\\n\";\nprint \"escape = $escape\\n\";"
},
{
"code": null,
"e": 8169,
"s": 8128,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 8347,
"s": 8169,
"text": "var = This is string scalar!\nquote = I m inside single quote - $var\ndouble = This is inside double quote - This is string scalar!\nescape = This example of escape - Hello, World!"
},
{
"code": null,
"e": 8491,
"s": 8347,
"text": "A literal of the form v1.20.300.4000 is parsed as a string composed of characters with the specified ordinals. This form is known as v-strings."
},
{
"code": null,
"e": 8661,
"s": 8491,
"text": "A v-string provides an alternative and more readable way to construct strings, rather than use the somewhat less readable interpolation form \"\\x{1}\\x{14}\\x{12c}\\x{fa0}\"."
},
{
"code": null,
"e": 8702,
"s": 8661,
"text": "It is used to get the current file name."
},
{
"code": null,
"e": 8745,
"s": 8702,
"text": "It is used to get the current line number."
},
{
"code": null,
"e": 8789,
"s": 8745,
"text": "It is used to get the current package name."
},
{
"code": null,
"e": 8945,
"s": 8789,
"text": " To refer to a single element of an array, you will use the dollar sign ($) with the variable name followed by the index of the element in square brackets."
},
{
"code": null,
"e": 9001,
"s": 8945,
"text": "Here is a simple example of using the array variables −"
},
{
"code": null,
"e": 9293,
"s": 9001,
"text": "#!/usr/bin/perl\n\n@ages = (25, 30, 40); \n@names = (\"John Paul\", \"Lisa\", \"Kumar\");\n\nprint \"\\$ages[0] = $ages[0]\\n\";\nprint \"\\$ages[1] = $ages[1]\\n\";\nprint \"\\$ages[2] = $ages[2]\\n\";\nprint \"\\$names[0] = $names[0]\\n\";\nprint \"\\$names[1] = $names[1]\\n\";\nprint \"\\$names[2] = $names[2]\\n\";"
},
{
"code": null,
"e": 9348,
"s": 9293,
"text": "When exected, this will produce the following result −"
},
{
"code": null,
"e": 9447,
"s": 9348,
"text": "$ages[0] = 25\n$ages[1] = 30\n$ages[2] = 40\n$names[0] = John Paul\n$names[1] = Lisa\n$names[2] = Kumar"
},
{
"code": null,
"e": 9504,
"s": 9447,
"text": "range operator (..) is used to create sequential arrays."
},
{
"code": null,
"e": 9730,
"s": 9504,
"text": "#!/usr/bin/perl\n\n@var_10 = (1..10);\n@var_20 = (10..20);\n@var_abc = (a..z);\n\nprint \"@var_10\\n\"; # Prints number from 1 to 10\nprint \"@var_20\\n\"; # Prints number from 10 to 20\nprint \"@var_abc\\n\"; # Prints number from a to z"
},
{
"code": null,
"e": 9819,
"s": 9730,
"text": "Here double dot (..) is called range operator. This will produce the following result − "
},
{
"code": null,
"e": 9925,
"s": 9819,
"text": "1 2 3 4 5 6 7 8 9 10\n10 11 12 13 14 15 16 17 18 19 20\na b c d e f g h i j k l m n o p q r s t u v w x y z"
},
{
"code": null,
"e": 10069,
"s": 9925,
"text": "The size of an array can be determined using the scalar context on the array - the returned value will be the number of elements in the array −"
},
{
"code": null,
"e": 10122,
"s": 10069,
"text": "@array = (1,2,3);\nprint \"Size: \",scalar @array,\"\\n\";"
},
{
"code": null,
"e": 10222,
"s": 10122,
"text": "The value returned will always be the physical size of the array, not the number of valid elements."
},
{
"code": null,
"e": 10299,
"s": 10222,
"text": "push @ARRAY, LIST - Pushes the values of the list onto the end of the array."
},
{
"code": null,
"e": 10508,
"s": 10299,
"text": "#!/usr/bin/perl\n\n# create a simple array\n@coins = (\"Quarter\",\"Dime\",\"Nickel\");\nprint \"1. \\@coins = @coins\\n\";\n\n# add one element at the end of the array\npush(@coins, \"Penny\");\nprint \"2. \\@coins = @coins\\n\";"
},
{
"code": null,
"e": 10549,
"s": 10508,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 10619,
"s": 10549,
"text": "1. @coins = Quarter Dime Nickel\n2. @coins = Quarter Dime Nickel Penny"
},
{
"code": null,
"e": 10736,
"s": 10619,
"text": "unshift @ARRAY, LIST - Prepends list to the front of the array, and returns the number of elements in the new array."
},
{
"code": null,
"e": 10955,
"s": 10736,
"text": "#!/usr/bin/perl\n\n# create a simple array\n@coins = (\"Quarter\",\"Dime\",\"Nickel\");\nprint \"1. \\@coins = @coins\\n\";\n\n# add one element at the beginning of the array\nunshift(@coins, \"Dollar\");\nprint \"2. \\@coins = @coins\\n\";"
},
{
"code": null,
"e": 10996,
"s": 10955,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 11067,
"s": 10996,
"text": "1. @coins = Quarter Dime Nickel\n2. @coins = Dollar Quarter Dime Nickel"
},
{
"code": null,
"e": 11130,
"s": 11067,
"text": "pop @ARRAY − Pops off and returns the last value of the array."
},
{
"code": null,
"e": 11336,
"s": 11130,
"text": "#!/usr/bin/perl\n\n# create a simple array\n@coins = (\"Quarter\",\"Dime\",\"Nickel\");\nprint \"1. \\@coins = @coins\\n\";\n\n# remove one element from the last of the array.\npop(@coins);\nprint \"2. \\@coins = @coins\\n\";"
},
{
"code": null,
"e": 11377,
"s": 11336,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 11434,
"s": 11377,
"text": "1. @coins = Quarter Dime Nickel\n2. @coins = Quarter Dime"
},
{
"code": null,
"e": 11559,
"s": 11434,
"text": "shift @ARRAY − Shifts the first value of the array off and returns it, shortening the array by 1 and moving everything down."
},
{
"code": null,
"e": 11772,
"s": 11559,
"text": "#!/usr/bin/perl\n\n# create a simple array\n@coins = (\"Quarter\",\"Dime\",\"Nickel\");\nprint \"1. \\@coins = @coins\\n\";\n\n# remove one element from the beginning of the array.\nshift(@coins);\nprint \"2. \\@coins = @coins\\n\";"
},
{
"code": null,
"e": 11813,
"s": 11772,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 11869,
"s": 11813,
"text": "1. @coins = Quarter Dime Nickel\n2. @coins = Dime Nickel"
},
{
"code": null,
"e": 12008,
"s": 11869,
"text": "You can also extract a \"slice\" from an array − that is, you can select more than one item from an array in order to produce another array."
},
{
"code": null,
"e": 12115,
"s": 12008,
"text": "#!/usr/bin/perl\n\n@days = qw/Mon Tue Wed Thu Fri Sat Sun/;\n\n@weekdays = @days[3,4,5];\n\nprint \"@weekdays\\n\";"
},
{
"code": null,
"e": 12156,
"s": 12115,
"text": "This will produce the following result -"
},
{
"code": null,
"e": 12168,
"s": 12156,
"text": "Thu Fri Sat"
},
{
"code": null,
"e": 12355,
"s": 12168,
"text": "splice() function will remove the elements of @ARRAY designated by OFFSET and LENGTH, and replaces them with LIST, if specified. Finally, it returns the elements removed from the array. "
},
{
"code": null,
"e": 12401,
"s": 12355,
"text": "splice @ARRAY, OFFSET [ , LENGTH [ , LIST ] ]"
},
{
"code": null,
"e": 12428,
"s": 12401,
"text": "Following is the example −"
},
{
"code": null,
"e": 12544,
"s": 12428,
"text": "#!/usr/bin/perl\n\n@nums = (1..20);\nprint \"Before - @nums\\n\";\n\nsplice(@nums, 5, 5, 21..25); \nprint \"After - @nums\\n\";"
},
{
"code": null,
"e": 12585,
"s": 12544,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 12708,
"s": 12585,
"text": "Before − 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20\nAfter − 1 2 3 4 5 21 22 23 24 25 11 12 13 14 15 16 17 18 19 20"
},
{
"code": null,
"e": 12886,
"s": 12708,
"text": "split() splits a string into an array of strings, and returns it. If LIMIT is specified, splits into at most that number of fields. If PATTERN is omitted, splits on whitespace. "
},
{
"code": null,
"e": 12927,
"s": 12886,
"text": "split [ PATTERN [ , EXPR [ , LIMIT ] ] ]"
},
{
"code": null,
"e": 12954,
"s": 12927,
"text": "Following is the example −"
},
{
"code": null,
"e": 13305,
"s": 12954,
"text": "#!/usr/bin/perl\n\n# define Strings\n$var_string = \"Rain-Drops-On-Roses-And-Whiskers-On-Kittens\";\n$var_names = \"Larry,David,Roger,Ken,Michael,Tom\";\n\n# transform above strings into arrays.\n@string = split('-', $var_string);\n@names = split(',', $var_names);\n\nprint \"$string[3]\\n\"; # This will print Roses\nprint \"$names[4]\\n\"; # This will print Michael"
},
{
"code": null,
"e": 13346,
"s": 13305,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 13360,
"s": 13346,
"text": "Roses\nMichael"
},
{
"code": null,
"e": 13500,
"s": 13360,
"text": "join() function joins the separate strings of LIST into a single string with fields separated by the value of EXPR, and returns the string."
},
{
"code": null,
"e": 13516,
"s": 13500,
"text": "join EXPR, LIST"
},
{
"code": null,
"e": 13543,
"s": 13516,
"text": "Following is the example −"
},
{
"code": null,
"e": 14000,
"s": 13543,
"text": "#!/usr/bin/perl\n\n# define Strings\n$var_string = \"Rain-Drops-On-Roses-And-Whiskers-On-Kittens\";\n$var_names = \"Larry,David,Roger,Ken,Michael,Tom\";\n\n# transform above strings into arrays.\n@string = split('-', $var_string);\n@names = split(',', $var_names);\n\n$string1 = join( '-', @string );\n$string2 = join( ',', @names );\n\nprint \"$string1\\n\";\nprint \"$string2\\n\";\nprint \"$string[3]\\n\"; # This will print Roses\nprint \"$names[4]\\n\"; # This will print Michael"
},
{
"code": null,
"e": 14041,
"s": 14000,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 14119,
"s": 14041,
"text": "Rain-Drops-On-Roses-And-Whiskers-On-Kittens\nLarry,David,Roger,Ken,Michael,Tom"
},
{
"code": null,
"e": 14253,
"s": 14119,
"text": "The sort() function sorts each element of an array according to the ASCII Numeric standards. This function has the following syntax −"
},
{
"code": null,
"e": 14278,
"s": 14253,
"text": "sort [ SUBROUTINE ] LIST"
},
{
"code": null,
"e": 14453,
"s": 14278,
"text": "This function sorts the LIST and returns the sorted array value. If SUBROUTINE is specified then specified logic inside the SUBTROUTINE is applied while sorting the elements."
},
{
"code": null,
"e": 14623,
"s": 14453,
"text": "#!/usr/bin/perl\n\n# define an array\n@foods = qw(pizza steak chicken burgers);\nprint \"Before: @foods\\n\";\n\n# sort this array\n@foods = sort(@foods);\nprint \"After: @foods\\n\";"
},
{
"code": null,
"e": 14664,
"s": 14623,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 14735,
"s": 14664,
"text": "Before: pizza steak chicken burgers\nAfter: burgers chicken pizza steak"
},
{
"code": null,
"e": 15089,
"s": 14735,
"text": "This special variable is a scalar containing the first index of all arrays. Because Perl arrays have zero-based indexing, $[ will almost always be 0. But if you set $[ to 1 then all your arrays will use on-based indexing. It is recommended not to use any other indexing other than zero. However, let's take one example to show the usage of $[ variable −"
},
{
"code": null,
"e": 15328,
"s": 15089,
"text": "#!/usr/bin/perl\n\n# define an array\n@foods = qw(pizza steak chicken burgers);\nprint \"Foods: @foods\\n\";\n\n# Let's reset first index of all the arrays.\n$[ = 1;\n\nprint \"Food at \\@foods[1]: $foods[1]\\n\";\nprint \"Food at \\@foods[2]: $foods[2]\\n\";"
},
{
"code": null,
"e": 15369,
"s": 15328,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 15454,
"s": 15369,
"text": "Foods: pizza steak chicken burgers\nFood at @foods[1]: pizza\nFood at @foods[2]: steak"
},
{
"code": null,
"e": 15563,
"s": 15454,
"text": "Because an array is just a comma-separated sequence of values, you can combine them together as shown below."
},
{
"code": null,
"e": 15637,
"s": 15563,
"text": "#!/usr/bin/perl\n\n@numbers = (1,3,(4,5,6));\n\nprint \"numbers = @numbers\\n\";"
},
{
"code": null,
"e": 15678,
"s": 15637,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 15698,
"s": 15678,
"text": "numbers = 1 3 4 5 6"
},
{
"code": null,
"e": 15830,
"s": 15698,
"text": "Hashes are created in one of the two following ways. In the first method, you assign a value to a named key on a one-by-one basis −"
},
{
"code": null,
"e": 15896,
"s": 15830,
"text": "$data{'John Paul'} = 45;\n$data{'Lisa'} = 30;\n$data{'Kumar'} = 40;"
},
{
"code": null,
"e": 16087,
"s": 15896,
"text": "In the second case, you use a list, which is converted by taking individual pairs from the list: the first element of the pair is used as the key, and the second, as the value. For example −"
},
{
"code": null,
"e": 16139,
"s": 16087,
"text": "%data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40);"
},
{
"code": null,
"e": 16339,
"s": 16139,
"text": "When accessing individual elements from a hash, you must prefix the variable with a dollar sign ($) and then append the element key within curly brackets after the name of the variable. For example −"
},
{
"code": null,
"e": 16496,
"s": 16339,
"text": "#!/usr/bin/perl\n\n%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);\n\nprint \"$data{'John Paul'}\\n\";\nprint \"$data{'Lisa'}\\n\";\nprint \"$data{'Kumar'}\\n\";"
},
{
"code": null,
"e": 16537,
"s": 16496,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 16546,
"s": 16537,
"text": "45\n30\n40"
},
{
"code": null,
"e": 16653,
"s": 16546,
"text": "You can get a list of all of the keys from a hash by using keys function, which has the following syntax −"
},
{
"code": null,
"e": 16664,
"s": 16653,
"text": "keys %HASH"
},
{
"code": null,
"e": 16757,
"s": 16664,
"text": "This function returns an array of all the keys of the named hash. Following is the example −"
},
{
"code": null,
"e": 16919,
"s": 16757,
"text": "#!/usr/bin/perl \n\n%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);\n\n@names = keys %data;\n\nprint \"$names[0]\\n\";\nprint \"$names[1]\\n\";\nprint \"$names[2]\\n\";"
},
{
"code": null,
"e": 16960,
"s": 16919,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 16981,
"s": 16960,
"text": "Lisa\nJohn Paul\nKumar"
},
{
"code": null,
"e": 17092,
"s": 16981,
"text": "You can get a list of all of the values from a hash by using values function, which has the following syntax −"
},
{
"code": null,
"e": 17105,
"s": 17092,
"text": "values %HASH"
},
{
"code": null,
"e": 17200,
"s": 17105,
"text": "This function returns an array of all the values of the named hash. Following is the example −"
},
{
"code": null,
"e": 17360,
"s": 17200,
"text": "#!/usr/bin/perl \n\n%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);\n\n@ages = values %data;\n\nprint \"$ages[0]\\n\";\nprint \"$ages[1]\\n\";\nprint \"$ages[2]\\n\";"
},
{
"code": null,
"e": 17401,
"s": 17360,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 17410,
"s": 17401,
"text": "30\n45\n40"
},
{
"code": null,
"e": 17523,
"s": 17410,
"text": "Using the exists function, which returns true if the named key exists, irrespective of what its value might be −"
},
{
"code": null,
"e": 17724,
"s": 17523,
"text": "#!/usr/bin/perl\n\n%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);\n\nif( exists($data{'Lisa'} ) ){\n print \"Lisa is $data{'Lisa'} years old\\n\";\n}\nelse{\n print \"I don't know age of Lisa\\n\";\n}"
},
{
"code": null,
"e": 18099,
"s": 17724,
"text": "Here we have introduced the IF...ELSE statement, which we will study in a separate chapter. For now you just assume that if( condition ) part will be executed only when the given condition is true otherwise else part will be executed. So when we execute the above program, it produces the following result because here the given condition exists($data{'Lisa'} returns true −"
},
{
"code": null,
"e": 18120,
"s": 18099,
"text": "Lisa is 30 years old"
},
{
"code": null,
"e": 18367,
"s": 18120,
"text": "You can get the size - that is, the number of elements from a hash by using the scalar context on either keys or values. Simply saying first you have to get an array of either the keys or values and then you can get the size of array as follows −"
},
{
"code": null,
"e": 18592,
"s": 18367,
"text": "#!/usr/bin/perl\n\n%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);\n\n@keys = keys %data;\n$size = @keys;\nprint \"1 - Hash size: is $size\\n\";\n\n@values = values %data;\n$size = @values;\nprint \"2 - Hash size: is $size\\n\";"
},
{
"code": null,
"e": 18633,
"s": 18592,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 18673,
"s": 18633,
"text": "1 - Hash size: is 3\n2 - Hash size: is 3"
},
{
"code": null,
"e": 18769,
"s": 18673,
"text": "Adding a new key/value pair can be done with one line of code using simple assignment operator."
},
{
"code": null,
"e": 19039,
"s": 18769,
"text": "#!/usr/bin/perl\n\n%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);\n@keys = keys %data;\n$size = @keys;\nprint \"1 - Hash size: is $size\\n\";\n\n# adding an element to the hash;\n$data{'Ali'} = 55;\n@keys = keys %data;\n$size = @keys;\nprint \"2 - Hash size: is $size\\n\";"
},
{
"code": null,
"e": 19080,
"s": 19039,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 19120,
"s": 19080,
"text": "1 - Hash size: is 3\n2 - Hash size: is 4"
},
{
"code": null,
"e": 19218,
"s": 19120,
"text": "To remove an element from the hash you need to use delete function as shown below in the example−"
},
{
"code": null,
"e": 19504,
"s": 19218,
"text": "#!/usr/bin/perl\n\n%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);\n@keys = keys %data;\n$size = @keys;\nprint \"1 - Hash size: is $size\\n\";\n\n# delete the same element from the hash;\ndelete $data{'John Paul'};\n@keys = keys %data;\n$size = @keys;\nprint \"2 - Hash size: is $size\\n\";"
},
{
"code": null,
"e": 19545,
"s": 19504,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 19585,
"s": 19545,
"text": "1 - Hash size: is 3\n2 - Hash size: is 2"
},
{
"code": null,
"e": 19713,
"s": 19585,
"text": "It causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.\nlast statement."
},
{
"code": null,
"e": 19839,
"s": 19713,
"text": "It terminates the loop statement and transfers execution to the statement immediately following the loop.\ncontinue statement."
},
{
"code": null,
"e": 19939,
"s": 19839,
"text": "A continue BLOCK, it is always executed just before the conditional is about to be evaluated again."
},
{
"code": null,
"e": 20067,
"s": 19939,
"text": "The redo command restarts the loop block without evaluating the conditional again. The continue block, if any, is not executed."
},
{
"code": null,
"e": 20163,
"s": 20067,
"text": "The goto LABEL form jumps to the statement labeled with LABEL and resumes execution from there."
},
{
"code": null,
"e": 20313,
"s": 20163,
"text": "The goto EXPR form is just a generalization of goto LABEL. It expects the expression to return a label name and then jumps to that labeled statement."
},
{
"code": null,
"e": 20397,
"s": 20313,
"text": "It substitutes a call to the named subroutine for the currently running subroutine."
},
{
"code": null,
"e": 20558,
"s": 20397,
"text": "Exponent − Performs exponential (power) calculation on operators. Assume variable $a holds 10 and variable $b holds 20 then $a**$b will give 10 to the power 20."
},
{
"code": null,
"e": 20832,
"s": 20558,
"text": "It checks if the value of two operands are equal or not, and returns -1, 0, or 1 depending on whether the left argument is numerically less than, equal to, or greater than the right argument. Assume variable $a holds 10 and variable $b holds 20 then ($a <=> $b) returns -1."
},
{
"code": null,
"e": 20997,
"s": 20832,
"text": "It returns true if the left argument is stringwise less than the right argument. Assume variable $a holds \"abc\" and variable $b holds \"xyz\" then ($a lt $b) is true."
},
{
"code": null,
"e": 21166,
"s": 20997,
"text": "It returns true if the left argument is stringwise greater than the right argument. Assume variable $a holds \"abc\" and variable $b holds \"xyz\" then ($a gt $b) is false."
},
{
"code": null,
"e": 21343,
"s": 21166,
"text": "It returns true if the left argument is stringwise less than or equal to the right argument. Assume variable $a holds \"abc\" and variable $b holds \"xyz\" then ($a le $b) is true."
},
{
"code": null,
"e": 21524,
"s": 21343,
"text": "It returns true if the left argument is stringwise greater than or equal to the right argument. Assume variable $a holds \"abc\" and variable $b holds \"xyz\" then ($a ge $b) is false."
},
{
"code": null,
"e": 21689,
"s": 21524,
"text": "It returns true if the left argument is stringwise equal to the right argument. Assume variable $a holds \"abc\" and variable $b holds \"xyz\" then ($a eq $b) is false."
},
{
"code": null,
"e": 21857,
"s": 21689,
"text": "It returns true if the left argument is stringwise not equal to the right argument. Assume variable $a holds \"abc\" and variable $b holds \"xyz\" then ($a ne $b) is true."
},
{
"code": null,
"e": 22073,
"s": 21857,
"text": "It returns -1, 0, or 1 depending on whether the left argument is stringwise less than, equal to, or greater than the right argument. Assume variable $a holds \"abc\" and variable $b holds \"xyz\" then ($a cmp $b) is -1."
},
{
"code": null,
"e": 22240,
"s": 22073,
"text": "Exponent AND assignment operator, Performs exponential (power) calculation on operators and assign value to the left operand. $c **= $a is equivalent to $c = $c ** $a"
},
{
"code": null,
"e": 22305,
"s": 22240,
"text": "It encloses a string with-in single quotes. q{abcd} gives 'abcd'"
},
{
"code": null,
"e": 22371,
"s": 22305,
"text": "It encloses a string with-in double quotes. qq{abcd} gives \"abcd\""
},
{
"code": null,
"e": 22437,
"s": 22371,
"text": "It encloses a string with-in invert quotes. qx{abcd} gives `abcd`"
},
{
"code": null,
"e": 22539,
"s": 22437,
"text": "Binary operator dot (.) concatenates two strings. If $a=\"abc\", $b=\"def\" then $a.$b will give \"abcdef\""
},
{
"code": null,
"e": 22699,
"s": 22539,
"text": "The repetition operator x returns a string consisting of the left operand repeated the number of times specified by the right operand. ('-' x 3) will give ---."
},
{
"code": null,
"e": 22839,
"s": 22699,
"text": "The range operator .. returns a list of values counting (up by ones) from the left value to the right value.\t(2..5) will give (2, 3, 4, 5)."
},
{
"code": null,
"e": 22914,
"s": 22839,
"text": "Auto Increment operator increases integer value by one.\t$a++ will give 11."
},
{
"code": null,
"e": 22987,
"s": 22914,
"text": "Auto Decrement operator decreases integer value by one.\t$a−− will give 9"
},
{
"code": null,
"e": 23154,
"s": 22987,
"text": "The arrow operator is mostly used in dereferencing a method or variable from an object or a class name. $obj−>$a is an example to access variable $a from object $obj."
},
{
"code": null,
"e": 23250,
"s": 23154,
"text": "localtime() function, which returns values for the current date and time if given no arguments."
},
{
"code": null,
"e": 23498,
"s": 23250,
"text": "#!/usr/local/bin/perl\n \n@months = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );\n@days = qw(Sun Mon Tue Wed Thu Fri Sat Sun);\n\n($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();\nprint \"$mday $months[$mon] $days[$wday]\\n\";"
},
{
"code": null,
"e": 23566,
"s": 23498,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 23577,
"s": 23566,
"text": "16 Feb Sat"
},
{
"code": null,
"e": 23840,
"s": 23577,
"text": " The function gmtime() works just like localtime() function but the returned values are localized for the standard Greenwich time zone. When called in list context, $isdst, the last value returned by gmtime, is always 0 . There is no Daylight Saving Time in GMT."
},
{
"code": null,
"e": 24001,
"s": 23840,
"text": " localtime() will return the current local time on the machine that runs the script and gmtime() will return the universal Greenwich Mean Time, or GMT (or UTC)."
},
{
"code": null,
"e": 24147,
"s": 24001,
"text": " You can use the time() function to get epoch time, i.e. the numbers of seconds that have elapsed since a given date, in Unix is January 1, 1970."
},
{
"code": null,
"e": 24215,
"s": 24147,
"text": " You can use the POSIX function strftime() to format date and time."
},
{
"code": null,
"e": 24305,
"s": 24215,
"text": " The general form of a subroutine definition in Perl programming language is as follows −"
},
{
"code": null,
"e": 24354,
"s": 24305,
"text": "sub subroutine_name{\n body of the subroutine\n}"
},
{
"code": null,
"e": 24419,
"s": 24354,
"text": " The typical way of calling that Perl subroutine is as follows −"
},
{
"code": null,
"e": 24457,
"s": 24419,
"text": "subroutine_name( list of arguments );"
},
{
"code": null,
"e": 24614,
"s": 24457,
"text": " they can be acessed inside the function using the special array @_. Thus the first argument to the function is in $_[0], the second is in $_[1], and so on."
},
{
"code": null,
"e": 24682,
"s": 24614,
"text": " using scalar(@_), we can get the total number of arguments passed."
},
{
"code": null,
"e": 24852,
"s": 24682,
"text": " The my operator confines a variable to a particular region of code in which it can be used and accessed. Outside that region, this variable cannot be used or accessed. "
},
{
"code": null,
"e": 24972,
"s": 24852,
"text": " By default, all variables in Perl are global variables, which means they can be accessed from anywhere in the program."
},
{
"code": null,
"e": 25040,
"s": 24972,
"text": " Lexical variables are private variables created using my operator."
},
{
"code": null,
"e": 25136,
"s": 25040,
"text": " The local is used when the current value of a variable must be visible to called subroutines. "
},
{
"code": null,
"e": 25246,
"s": 25136,
"text": " A local just gives temporary values to global (meaning package) variables. This is known as dynamic scoping."
},
{
"code": null,
"e": 25665,
"s": 25246,
"text": " Lexical scoping is done with my operator. A lexical scope is usually a block of code with a set of braces around it, such as those defining the body of the subroutine or those marking the code blocks of if, while, for, foreach, and eval statements. The my operator confines a variable to a particular region of code in which it can be used and accessed. Outside that region, this variable cannot be used or accessed. "
},
{
"code": null,
"e": 25947,
"s": 25665,
"text": " There are another type of lexical variables, which are similar to private variables but they maintain their state and they do not get reinitialized upon multiple calls of the subroutines. These variables are defined using the state operator and available starting from Perl 5.9.4."
},
{
"code": null,
"e": 26315,
"s": 25947,
"text": " The context of a subroutine or statement is defined as the type of return value that is expected. This allows you to use a single function that returns different values based on what the user is expecting to receive. For example, the following localtime() returns a string when it is called in scalar context, but it returns a list when it is called in list context."
},
{
"code": null,
"e": 26351,
"s": 26315,
"text": "my $datestring = localtime( time );"
},
{
"code": null,
"e": 26496,
"s": 26351,
"text": "In this example, the value of $timestr is now a string made up of the current date and time, for example, Thu Nov 30 15:21:33 2000. Conversely −"
},
{
"code": null,
"e": 26570,
"s": 26496,
"text": "($sec,$min,$hour,$mday,$mon, $year,$wday,$yday,$isdst) = localtime(time);"
},
{
"code": null,
"e": 26668,
"s": 26570,
"text": "Now the individual variables contain the corresponding values returned by localtime() subroutine."
},
{
"code": null,
"e": 26877,
"s": 26668,
"text": " A Perl reference is a scalar data type that holds the location of another value which could be scalar, arrays, or hashes. Because of its scalar nature, a reference can be used anywhere, a scalar can be used."
},
{
"code": null,
"e": 26968,
"s": 26877,
"text": " You can create a reference for any variable by prefixing it with a backslash as follows −"
},
{
"code": null,
"e": 26988,
"s": 26968,
"text": "$scalarref = \\$foo;"
},
{
"code": null,
"e": 27076,
"s": 26988,
"text": " You can create a reference for any array by prefixing it with a backslash as follows −"
},
{
"code": null,
"e": 27097,
"s": 27076,
"text": "$arrayref = \\@ARGV;"
},
{
"code": null,
"e": 27184,
"s": 27097,
"text": " You can create a reference for any hash by prefixing it with a backslash as follows −"
},
{
"code": null,
"e": 27204,
"s": 27184,
"text": "$hashref = \\%ENV;"
},
{
"code": null,
"e": 27297,
"s": 27204,
"text": " You can create a reference for any subrouting by prefixing it with a backslash as follows −"
},
{
"code": null,
"e": 27318,
"s": 27297,
"text": "$cref = \\&PrintHash;"
},
{
"code": null,
"e": 27392,
"s": 27318,
"text": " Dereferencing returns the value from a reference point to the location. "
},
{
"code": null,
"e": 27553,
"s": 27392,
"text": " To dereference a reference simply use $, @ or % as prefix of the reference variable depending on whether the reference is pointing to a scalar, array, or hash."
},
{
"code": null,
"e": 27769,
"s": 27553,
"text": " A circular reference occurs when two references contain a reference to each other. You have to be careful while creating references otherwise a circular reference can lead to memory leaks. Following is an example −"
},
{
"code": null,
"e": 27857,
"s": 27769,
"text": "#!/usr/bin/perl\nmy $foo = 100;\n$foo = \\$foo;\n \nprint \"Value of foo is : \", $$foo, \"\\n\";"
},
{
"code": null,
"e": 27924,
"s": 27857,
"text": "When above program is executed, it produces the following result −"
},
{
"code": null,
"e": 27956,
"s": 27924,
"text": "Value of foo is : REF(0x9aae38)"
},
{
"code": null,
"e": 28094,
"s": 27956,
"text": " Following is the syntax to open file.txt in read-only mode. Here less than < sign indicates that file has to be opend in read-only mode."
},
{
"code": null,
"e": 28119,
"s": 28094,
"text": "open(DATA, \"<file.txt\");"
},
{
"code": null,
"e": 28186,
"s": 28119,
"text": "Here DATA is the file handle which will be used to read the file. "
},
{
"code": null,
"e": 28324,
"s": 28186,
"text": " Following is the syntax to open file.txt in writing mode. Here less than > sign indicates that file has to be opend in the writing mode."
},
{
"code": null,
"e": 28390,
"s": 28324,
"text": "open(DATA, \">file.txt\") or die \"Couldn't open file file.txt, $!\";"
},
{
"code": null,
"e": 28574,
"s": 28390,
"text": " Following is the syntax to open file.txt in writing mode without truncating it. Here less than +< sign indicates that file has to be opend in the writing mode without truncating it."
},
{
"code": null,
"e": 28641,
"s": 28574,
"text": "open(DATA, \"+<file.txt\") or die \"Couldn't open file file.txt, $!\";"
},
{
"code": null,
"e": 28843,
"s": 28641,
"text": " To close a filehandle, and therefore disassociate the filehandle from the corresponding file, you use the close function. This flushes the filehandle's buffers and closes the system's file descriptor."
},
{
"code": null,
"e": 28951,
"s": 28843,
"text": " The getc function returns a single character from the specified FILEHANDLE, or STDIN if none is specified."
},
{
"code": null,
"e": 29086,
"s": 28951,
"text": " The read function reads a block of information from the buffered filehandle: This function is used to read binary data from the file."
},
{
"code": null,
"e": 29373,
"s": 29086,
"text": "Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong."
},
{
"code": null,
"e": 29703,
"s": 29373,
"text": "Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)"
},
{
"code": null,
"e": 29738,
"s": 29703,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 29752,
"s": 29738,
"text": " Devi Killada"
},
{
"code": null,
"e": 29787,
"s": 29752,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 29807,
"s": 29787,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 29840,
"s": 29807,
"text": "\n 30 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 29856,
"s": 29840,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 29889,
"s": 29856,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 29906,
"s": 29889,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 29939,
"s": 29906,
"text": "\n 68 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 29962,
"s": 29939,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 29997,
"s": 29962,
"text": "\n 58 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 30020,
"s": 29997,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 30027,
"s": 30020,
"text": " Print"
},
{
"code": null,
"e": 30038,
"s": 30027,
"text": " Add Notes"
}
] |
Python os.removedirs() Method
|
Python method removedirs() removes dirs recursively. If the leaf directory is succesfully removed, removedirs tries to successively remove every parent directory displayed in path.
Following is the syntax for removedirs() method −
os.removedirs(path)
path − This is the path of the directory, which needs to be removed.
path − This is the path of the directory, which needs to be removed.
This method does not return any value.
The following example shows the usage of removedirs() method.
# !/usr/bin/python
import os, sys
# listing directories
print "The dir is: %s" %os.listdir(os.getcwd())
# removing
os.removedirs("/tutorialsdir")
# listing directories after removing directory
print "The dir after removal is:" %os.listdir(os.getcwd())
When we run above program, it produces following result −
The dir is:
[ 'a1.txt','resume.doc','a3.py','tutorialsdir','amrood.admin' ]
The dir after removal is:
[ 'a1.txt','resume.doc','a3.py','amrood.admin' ]
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": 2425,
"s": 2244,
"text": "Python method removedirs() removes dirs recursively. If the leaf directory is succesfully removed, removedirs tries to successively remove every parent directory displayed in path."
},
{
"code": null,
"e": 2475,
"s": 2425,
"text": "Following is the syntax for removedirs() method −"
},
{
"code": null,
"e": 2496,
"s": 2475,
"text": "os.removedirs(path)\n"
},
{
"code": null,
"e": 2565,
"s": 2496,
"text": "path − This is the path of the directory, which needs to be removed."
},
{
"code": null,
"e": 2634,
"s": 2565,
"text": "path − This is the path of the directory, which needs to be removed."
},
{
"code": null,
"e": 2673,
"s": 2634,
"text": "This method does not return any value."
},
{
"code": null,
"e": 2735,
"s": 2673,
"text": "The following example shows the usage of removedirs() method."
},
{
"code": null,
"e": 2991,
"s": 2735,
"text": "# !/usr/bin/python\n\nimport os, sys\n\n# listing directories\nprint \"The dir is: %s\" %os.listdir(os.getcwd())\n\n# removing\nos.removedirs(\"/tutorialsdir\")\n\n# listing directories after removing directory\nprint \"The dir after removal is:\" %os.listdir(os.getcwd())"
},
{
"code": null,
"e": 3049,
"s": 2991,
"text": "When we run above program, it produces following result −"
},
{
"code": null,
"e": 3203,
"s": 3049,
"text": "The dir is:\n[ 'a1.txt','resume.doc','a3.py','tutorialsdir','amrood.admin' ]\nThe dir after removal is:\n[ 'a1.txt','resume.doc','a3.py','amrood.admin' ]\n"
},
{
"code": null,
"e": 3240,
"s": 3203,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3256,
"s": 3240,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3289,
"s": 3256,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3308,
"s": 3289,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3343,
"s": 3308,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3365,
"s": 3343,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3399,
"s": 3365,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3427,
"s": 3399,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3462,
"s": 3427,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3476,
"s": 3462,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3509,
"s": 3476,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3526,
"s": 3509,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3533,
"s": 3526,
"text": " Print"
},
{
"code": null,
"e": 3544,
"s": 3533,
"text": " Add Notes"
}
] |
How to input multiple values from user in one line in C#?
|
Use a while loop to input multiple values from the user in one line.
Let’s say you need to get the elements of a matrix. Get it using Console.ReadLine() as shown below −
Console.Write("\nEnter elements - Matrix 1 : ");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
arr1[i, j] = Convert.ToInt16(Console.ReadLine());
}
}
The following is an example showing how we can input multiple values from user −
Live Demo
using System;
namespace Demo {
public class Program {
public static void Main(string[] args) {
int[,] arr1 = new int[10, 10];
int i, j;
Console.Write("\nEnter Matrix elements: ");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
arr1[i, j] = Convert.ToInt16(Console.ReadLine());
}
}
}
}
}
Enter Matrix elements:
|
[
{
"code": null,
"e": 1131,
"s": 1062,
"text": "Use a while loop to input multiple values from the user in one line."
},
{
"code": null,
"e": 1232,
"s": 1131,
"text": "Let’s say you need to get the elements of a matrix. Get it using Console.ReadLine() as shown below −"
},
{
"code": null,
"e": 1399,
"s": 1232,
"text": "Console.Write(\"\\nEnter elements - Matrix 1 : \");\nfor (i = 0; i < m; i++) {\n for (j = 0; j < n; j++) {\n arr1[i, j] = Convert.ToInt16(Console.ReadLine());\n }\n}"
},
{
"code": null,
"e": 1480,
"s": 1399,
"text": "The following is an example showing how we can input multiple values from user −"
},
{
"code": null,
"e": 1491,
"s": 1480,
"text": " Live Demo"
},
{
"code": null,
"e": 1888,
"s": 1491,
"text": "using System;\n\nnamespace Demo {\n public class Program {\n public static void Main(string[] args) {\n int[,] arr1 = new int[10, 10];\n int i, j;\n\n Console.Write(\"\\nEnter Matrix elements: \");\n for (i = 0; i < 3; i++) {\n for (j = 0; j < 3; j++) {\n arr1[i, j] = Convert.ToInt16(Console.ReadLine());\n }\n }\n\n }\n }\n}"
},
{
"code": null,
"e": 1911,
"s": 1888,
"text": "Enter Matrix elements:"
}
] |
Dart Programming - If Else Statement
|
An if can be followed by an optional else block. The else block will execute if the Boolean expression tested by the if block evaluates to false.
Following is the syntax.
if(boolean_expression){
// statement(s) will execute if the Boolean expression is true.
} else {
// statement(s) will execute if the Boolean expression is false.
}
If the Boolean expression evaluates to be true, then the if block of code will be executed, otherwise else block of code will be executed.
The following illustration shows the flowchart of the if...else statement.
The if block guards the conditional expression. The block associated with the if statement is executed if the Boolean expression evaluates to true. The if block may be followed by an optional else statement. The instruction block associated with the else block is executed if the expression evaluates to false.
The following example prints whether the value in a variable is even or odd. The if block checks the divisibility of the value by 2 to determine the same.
void main() {
var num = 12;
if (num % 2==0) {
print("Even");
} else {
print("Odd");
}
}
The following output is displayed on successful execution of the above code.
Even
44 Lectures
4.5 hours
Sriyank Siddhartha
34 Lectures
4 hours
Sriyank Siddhartha
69 Lectures
4 hours
Frahaan Hussain
117 Lectures
10 hours
Frahaan Hussain
22 Lectures
1.5 hours
Pranjal Srivastava
34 Lectures
3 hours
Pranjal Srivastava
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2671,
"s": 2525,
"text": "An if can be followed by an optional else block. The else block will execute if the Boolean expression tested by the if block evaluates to false."
},
{
"code": null,
"e": 2696,
"s": 2671,
"text": "Following is the syntax."
},
{
"code": null,
"e": 2872,
"s": 2696,
"text": "if(boolean_expression){ \n // statement(s) will execute if the Boolean expression is true. \n} else { \n // statement(s) will execute if the Boolean expression is false. \n} \n"
},
{
"code": null,
"e": 3011,
"s": 2872,
"text": "If the Boolean expression evaluates to be true, then the if block of code will be executed, otherwise else block of code will be executed."
},
{
"code": null,
"e": 3086,
"s": 3011,
"text": "The following illustration shows the flowchart of the if...else statement."
},
{
"code": null,
"e": 3397,
"s": 3086,
"text": "The if block guards the conditional expression. The block associated with the if statement is executed if the Boolean expression evaluates to true. The if block may be followed by an optional else statement. The instruction block associated with the else block is executed if the expression evaluates to false."
},
{
"code": null,
"e": 3552,
"s": 3397,
"text": "The following example prints whether the value in a variable is even or odd. The if block checks the divisibility of the value by 2 to determine the same."
},
{
"code": null,
"e": 3671,
"s": 3552,
"text": "void main() { \n var num = 12; \n if (num % 2==0) { \n print(\"Even\"); \n } else { \n print(\"Odd\"); \n } \n}"
},
{
"code": null,
"e": 3748,
"s": 3671,
"text": "The following output is displayed on successful execution of the above code."
},
{
"code": null,
"e": 3754,
"s": 3748,
"text": "Even\n"
},
{
"code": null,
"e": 3789,
"s": 3754,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3809,
"s": 3789,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 3842,
"s": 3809,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3862,
"s": 3842,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 3895,
"s": 3862,
"text": "\n 69 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3912,
"s": 3895,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3947,
"s": 3912,
"text": "\n 117 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3964,
"s": 3947,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3999,
"s": 3964,
"text": "\n 22 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4019,
"s": 3999,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 4052,
"s": 4019,
"text": "\n 34 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4072,
"s": 4052,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 4079,
"s": 4072,
"text": " Print"
},
{
"code": null,
"e": 4090,
"s": 4079,
"text": " Add Notes"
}
] |
WPF - Mouse
|
There are different types of mouse inputs such as MouseDown, MouseEnter, MouseLeave, etc. In the following example, we will handle some of the mouse inputs.
Let’s create a new WPF project with the name WPFMouseInput.
Let’s create a new WPF project with the name WPFMouseInput.
Drag a rectangle and three Text blocks to a stack panel and set the following properties and events as shown in the following XAML file.
Drag a rectangle and three Text blocks to a stack panel and set the following properties and events as shown in the following XAML file.
<Window x:Class = "WPFMouseInput.MainWindow"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local = "clr-namespace:WPFMouseInput"
mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604">
<StackPanel>
<Rectangle x:Name = "mrRec" Fill = "AliceBlue"
MouseEnter = "OnMouseEnter" MouseLeave = "OnMouseLeave"
MouseMove = "OnMouseMove" MouseDown = "OnMouseDown" Height = "100" Margin = "20">
</Rectangle>
<TextBlock x:Name = "txt1" Height = "31" HorizontalAlignment = "Right"
Width = "250" Margin = "0,0,294,0" />
<TextBlock x:Name = "txt2" Height = "31" HorizontalAlignment = "Right"
Width = "250" Margin = "0,0,294,0" />
<TextBlock x:Name = "txt3" Height = "31" HorizontalAlignment = "Right"
Width = "250" Margin = "0,0,294,0" />
</StackPanel>
</Window>
Here is the C# code in which different mouse events are handled.
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
namespace WPFMouseInput {
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
}
private void OnMouseEnter(object sender, MouseEventArgs e) {
Rectangle source = e.Source as Rectangle;
if (source != null) {
source.Fill = Brushes.SlateGray;
}
txt1.Text = "Mouse Entered";
}
private void OnMouseLeave(object sender, MouseEventArgs e) {
// Cast the source of the event to a Button.
Rectangle source = e.Source as Rectangle;
// If source is a Button.
if (source != null) {
source.Fill = Brushes.AliceBlue;
}
txt1.Text = "Mouse Leave";
txt2.Text = "";
txt3.Text = "";
}
private void OnMouseMove(object sender, MouseEventArgs e) {
Point pnt = e.GetPosition(mrRec);
txt2.Text = "Mouse Move: " + pnt.ToString();
}
private void OnMouseDown(object sender, MouseButtonEventArgs e) {
Rectangle source = e.Source as Rectangle;
Point pnt = e.GetPosition(mrRec);
txt3.Text = "Mouse Click: " + pnt.ToString();
if (source != null) {
source.Fill = Brushes.Beige;
}
}
}
}
When you compile and execute the above code, it will produce the following window −
When the mouse enters inside the rectangle, the color of the rectangle will automatically change. In addition, you will get a message that the mouse has entered along with its coordinates.
When you click inside the rectangle, it will change color and show the coordinates at which mouse has been clicked.
When the mouse leaves the rectangle, it will show a message that mouse has left and the rectangle will change to its default color.
31 Lectures
2.5 hours
Anadi Sharma
30 Lectures
2.5 hours
Taurius Litvinavicius
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2177,
"s": 2020,
"text": "There are different types of mouse inputs such as MouseDown, MouseEnter, MouseLeave, etc. In the following example, we will handle some of the mouse inputs."
},
{
"code": null,
"e": 2237,
"s": 2177,
"text": "Let’s create a new WPF project with the name WPFMouseInput."
},
{
"code": null,
"e": 2297,
"s": 2237,
"text": "Let’s create a new WPF project with the name WPFMouseInput."
},
{
"code": null,
"e": 2434,
"s": 2297,
"text": "Drag a rectangle and three Text blocks to a stack panel and set the following properties and events as shown in the following XAML file."
},
{
"code": null,
"e": 2571,
"s": 2434,
"text": "Drag a rectangle and three Text blocks to a stack panel and set the following properties and events as shown in the following XAML file."
},
{
"code": null,
"e": 3684,
"s": 2571,
"text": "<Window x:Class = \"WPFMouseInput.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n xmlns:local = \"clr-namespace:WPFMouseInput\" \n mc:Ignorable = \"d\" Title = \"MainWindow\" Height = \"350\" Width = \"604\">\n\t\n <StackPanel> \n <Rectangle x:Name = \"mrRec\" Fill = \"AliceBlue\" \n MouseEnter = \"OnMouseEnter\" MouseLeave = \"OnMouseLeave\" \n MouseMove = \"OnMouseMove\" MouseDown = \"OnMouseDown\" Height = \"100\" Margin = \"20\"> \n </Rectangle> \n\t\t\n <TextBlock x:Name = \"txt1\" Height = \"31\" HorizontalAlignment = \"Right\" \n Width = \"250\" Margin = \"0,0,294,0\" /> \n <TextBlock x:Name = \"txt2\" Height = \"31\" HorizontalAlignment = \"Right\" \n Width = \"250\" Margin = \"0,0,294,0\" /> \n <TextBlock x:Name = \"txt3\" Height = \"31\" HorizontalAlignment = \"Right\" \n Width = \"250\" Margin = \"0,0,294,0\" /> \n\t\t\t\n </StackPanel> \n\t\n</Window>"
},
{
"code": null,
"e": 3749,
"s": 3684,
"text": "Here is the C# code in which different mouse events are handled."
},
{
"code": null,
"e": 5207,
"s": 3749,
"text": "using System.Windows; \nusing System.Windows.Input; \nusing System.Windows.Media; \nusing System.Windows.Shapes; \n \nnamespace WPFMouseInput { \n\n public partial class MainWindow : Window {\n\t\n public MainWindow() { \n InitializeComponent(); \n } \n\t\t\n private void OnMouseEnter(object sender, MouseEventArgs e) { \n Rectangle source = e.Source as Rectangle; \n\t\t\t\n if (source != null) { \n source.Fill = Brushes.SlateGray; \n } \n\t\t\t\n txt1.Text = \"Mouse Entered\"; \n } \n\t\t\n private void OnMouseLeave(object sender, MouseEventArgs e) { \n\t\t\n // Cast the source of the event to a Button. \n Rectangle source = e.Source as Rectangle;\n\t\t\t\n // If source is a Button. \n if (source != null) { \n source.Fill = Brushes.AliceBlue; \n } \n\t\t\t\n txt1.Text = \"Mouse Leave\"; \n txt2.Text = \"\"; \n txt3.Text = \"\"; \n } \n\t\t\n private void OnMouseMove(object sender, MouseEventArgs e) { \n Point pnt = e.GetPosition(mrRec); \n txt2.Text = \"Mouse Move: \" + pnt.ToString(); \n } \n\t\t\n private void OnMouseDown(object sender, MouseButtonEventArgs e) { \n Rectangle source = e.Source as Rectangle; \n Point pnt = e.GetPosition(mrRec); \n txt3.Text = \"Mouse Click: \" + pnt.ToString(); \n\t\t\t\n if (source != null) { \n source.Fill = Brushes.Beige; \n } \n } \n\t\t\n } \n} "
},
{
"code": null,
"e": 5291,
"s": 5207,
"text": "When you compile and execute the above code, it will produce the following window −"
},
{
"code": null,
"e": 5480,
"s": 5291,
"text": "When the mouse enters inside the rectangle, the color of the rectangle will automatically change. In addition, you will get a message that the mouse has entered along with its coordinates."
},
{
"code": null,
"e": 5596,
"s": 5480,
"text": "When you click inside the rectangle, it will change color and show the coordinates at which mouse has been clicked."
},
{
"code": null,
"e": 5728,
"s": 5596,
"text": "When the mouse leaves the rectangle, it will show a message that mouse has left and the rectangle will change to its default color."
},
{
"code": null,
"e": 5763,
"s": 5728,
"text": "\n 31 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5777,
"s": 5763,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5812,
"s": 5777,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5835,
"s": 5812,
"text": " Taurius Litvinavicius"
},
{
"code": null,
"e": 5842,
"s": 5835,
"text": " Print"
},
{
"code": null,
"e": 5853,
"s": 5842,
"text": " Add Notes"
}
] |
Smallest alphabet greater than a given character - GeeksforGeeks
|
27 May, 2021
Given a list of sorted characters consisting of both Uppercase and Lowercase Alphabets and a particular target value, say K, the task is to find the smallest element in the list that is larger than K. Letters also wrap around. For example, if K = ‘z’ and letters = [‘A’, ‘r’, ‘z’], then the answer would be ‘A’.
Examples:
Input : Letters = ["D", "J", "K"]
K = "B"
Output: 'D'
Explanation:
The Next greater character of "B" is 'D'
since it is the smallest element from the
set of given letters, greater than "B".
Input: Letters = ["h", "n", "s"]
K = "t"
Output: 'h'
Prerequisites: Binary Search
Approach: Binary Search can be applied to find the index of the smallest character in the given Set of Letters such that the character at that index is greater than K. If the element at the current mid is smaller than or equal to K, binary search is applied on the Right half, else it is applied on the left half.
C++
Java
Python 3
C#
Javascript
/* C++ Program to find the smallest characterfrom the given set of letter, which is greaterthan the target element */#include <bits/stdc++.h>using namespace std; /* Returns the smallest character from the givenset of letters that is greater than K */ // In this code we consider only uppercase characters or only lowercase characters// Incase if we have mixed characters then we//convert all either into lowercase or uppercasechar nextGreatestAlphabet(vector<char>& alphabets, char K){ int n= alphabets.size(); if(K>=alphabets[n-1]) return alphabets[0]; int l = 0, r = alphabets.size() - 1; // Take the first element as l and // the rightmost element as r int ans = -1; while (l <= r) { // if this while condition does not satisfy // simply return the first element. int mid = (l + r) / 2; if (alphabets[mid] > K) { r = mid - 1; ans = mid; } else l = mid + 1; } // Return the smallest element return alphabets[ans];} // Driver Codeint main(){ vector<char> letters{ 'A', 'K', 'S' }; char K = 'L'; // Function call char result = nextGreatestAlphabet(letters, K); cout << result << endl; return 0;}
/* Java Program to find the smallest characterfrom the given set of letter, which is greaterthan the target element */ class GFG{ /* Returns the smallest character from the given set of letters that is greater than K */ static char nextGreatestAlphabet(char alphabets[], char K) { int n = alphabets.length; if(K>=alphabets[n-1]) return alphabets[0]; int l = 0, r = alphabets.length - 1; int ans = -1; // Take the first element as l and // the rightmost element as r while (l <= r) { // if this while condition does not // satisfy simply return the first // element. int mid = (l + r) / 2; if (alphabets[mid] > K) { r = mid - 1; ans = mid; } else l = mid + 1; } // Return the smallest element return alphabets[ans]; } // Driver Code public static void main(String[] args) { char letters[] = { 'A', 'r', 'z' }; char K = 'z'; char result = nextGreatestAlphabet(letters, K); // Function call System.out.println(result); }} // This code is contributed by Smitha.
# Python 3 Program to find the smallest# character from the given set of letter,# which is greater than the target# element */ # Returns the smallest character from# the given set of letters that is# greater than K def nextGreatestAlphabet(alphabets, K): n = len(alphabets) if(K >= alphabets[n-1]): return alphabets[0] l = 0 r = len(alphabets) - 1 ans = -1 # Take the first element as l and # the rightmost element as r while (l <= r): # if this while condition does # not satisfy simply return the # first element. mid = int((l + r) / 2) if (alphabets[mid] > K): r = mid - 1 ans = mid else: l = mid + 1 # Return the smallest element if (alphabets[ans] < K): return alphabets[0] else: return alphabets[ans] # Driver Codeletters = ['A', 'r', 'z']K = 'z' # Function callresult = nextGreatestAlphabet(letters, K)print(result) # This code is contributed by Smitha
/* C# Program to find the smallest characterfrom the given set of letter, which is greaterthan the target element */using System; class GFG { /* Returns the smallest character from the given set of letters that is greater than K */ static char nextGreatestAlphabet(char[] alphabets, char K) { int n= alphabets.Length; if(K >= alphabets[n-1]) return alphabets[0]; int l = 0, r = alphabets.Length - 1; int ans = -1; // Take the first element as l and // the rightmost element as r while (l <= r) { // if this while condition does not // satisfy simply return the first // element. int mid = (l + r) / 2; if (alphabets[mid] > K) { ans = mid; r = mid - 1; } else l = mid + 1; } // Return the smallest element return alphabets[ans]; } // Driver Code public static void Main() { char[] letters = { 'A', 'r', 'z' }; char K = 'z'; // Function call char result = nextGreatestAlphabet(letters, K); Console.Write(result); }} // This code is contributed by Smitha
<script> /* JavaScript Program to find the smallest characterfrom the given set of letter, which is greaterthan the target element */ /* Returns the smallest character from the given set of letters that is greater than K */ function nextGreatestAlphabet(alphabets, K) { var l = 0, r = alphabets.length - 1; var ans = -1; // Take the first element as l and // the rightmost element as r while (l <= r) { // if this while condition does not // satisfy simply return the first // element. var mid = (l + r) / 2; if (alphabets[mid] > K) { ans = mid; r = mid - 1; } else l = mid + 1; } // Return the smallest element return alphabets[ans]; } // Driver Code var letters = ["A", "K", "S"]; var K = "L"; // Function call document.write(nextGreatestAlphabet(letters, K)); </script>
S
The Time Complexity of the above approach is, O(log N) where N is the number of characters in the given set of Letters.
Smitha Dinesh Semwal
ankitaankit1311
adityamishra120799
ferryrules
rdtank
bss12
Binary Search
Strings
Strings
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 String Coding Problems for Interviews
Hill Cipher
Naive algorithm for Pattern Searching
Vigenère Cipher
How to Append a Character to a String in C
Convert character array to string in C++
Print all subsequences of a string
Converting Roman Numerals to Decimal lying between 1 to 3999
sprintf() in C
Find frequency of each word in a string in Python
|
[
{
"code": null,
"e": 24854,
"s": 24826,
"text": "\n27 May, 2021"
},
{
"code": null,
"e": 25166,
"s": 24854,
"text": "Given a list of sorted characters consisting of both Uppercase and Lowercase Alphabets and a particular target value, say K, the task is to find the smallest element in the list that is larger than K. Letters also wrap around. For example, if K = ‘z’ and letters = [‘A’, ‘r’, ‘z’], then the answer would be ‘A’."
},
{
"code": null,
"e": 25178,
"s": 25166,
"text": "Examples: "
},
{
"code": null,
"e": 25440,
"s": 25178,
"text": "Input : Letters = [\"D\", \"J\", \"K\"]\n K = \"B\"\nOutput: 'D'\nExplanation:\nThe Next greater character of \"B\" is 'D'\nsince it is the smallest element from the \nset of given letters, greater than \"B\".\n\nInput: Letters = [\"h\", \"n\", \"s\"]\n K = \"t\"\nOutput: 'h'"
},
{
"code": null,
"e": 25469,
"s": 25440,
"text": "Prerequisites: Binary Search"
},
{
"code": null,
"e": 25784,
"s": 25469,
"text": "Approach: Binary Search can be applied to find the index of the smallest character in the given Set of Letters such that the character at that index is greater than K. If the element at the current mid is smaller than or equal to K, binary search is applied on the Right half, else it is applied on the left half. "
},
{
"code": null,
"e": 25788,
"s": 25784,
"text": "C++"
},
{
"code": null,
"e": 25793,
"s": 25788,
"text": "Java"
},
{
"code": null,
"e": 25802,
"s": 25793,
"text": "Python 3"
},
{
"code": null,
"e": 25805,
"s": 25802,
"text": "C#"
},
{
"code": null,
"e": 25816,
"s": 25805,
"text": "Javascript"
},
{
"code": "/* C++ Program to find the smallest characterfrom the given set of letter, which is greaterthan the target element */#include <bits/stdc++.h>using namespace std; /* Returns the smallest character from the givenset of letters that is greater than K */ // In this code we consider only uppercase characters or only lowercase characters// Incase if we have mixed characters then we//convert all either into lowercase or uppercasechar nextGreatestAlphabet(vector<char>& alphabets, char K){ int n= alphabets.size(); if(K>=alphabets[n-1]) return alphabets[0]; int l = 0, r = alphabets.size() - 1; // Take the first element as l and // the rightmost element as r int ans = -1; while (l <= r) { // if this while condition does not satisfy // simply return the first element. int mid = (l + r) / 2; if (alphabets[mid] > K) { r = mid - 1; ans = mid; } else l = mid + 1; } // Return the smallest element return alphabets[ans];} // Driver Codeint main(){ vector<char> letters{ 'A', 'K', 'S' }; char K = 'L'; // Function call char result = nextGreatestAlphabet(letters, K); cout << result << endl; return 0;}",
"e": 27052,
"s": 25816,
"text": null
},
{
"code": "/* Java Program to find the smallest characterfrom the given set of letter, which is greaterthan the target element */ class GFG{ /* Returns the smallest character from the given set of letters that is greater than K */ static char nextGreatestAlphabet(char alphabets[], char K) { int n = alphabets.length; if(K>=alphabets[n-1]) return alphabets[0]; int l = 0, r = alphabets.length - 1; int ans = -1; // Take the first element as l and // the rightmost element as r while (l <= r) { // if this while condition does not // satisfy simply return the first // element. int mid = (l + r) / 2; if (alphabets[mid] > K) { r = mid - 1; ans = mid; } else l = mid + 1; } // Return the smallest element return alphabets[ans]; } // Driver Code public static void main(String[] args) { char letters[] = { 'A', 'r', 'z' }; char K = 'z'; char result = nextGreatestAlphabet(letters, K); // Function call System.out.println(result); }} // This code is contributed by Smitha.",
"e": 28332,
"s": 27052,
"text": null
},
{
"code": "# Python 3 Program to find the smallest# character from the given set of letter,# which is greater than the target# element */ # Returns the smallest character from# the given set of letters that is# greater than K def nextGreatestAlphabet(alphabets, K): n = len(alphabets) if(K >= alphabets[n-1]): return alphabets[0] l = 0 r = len(alphabets) - 1 ans = -1 # Take the first element as l and # the rightmost element as r while (l <= r): # if this while condition does # not satisfy simply return the # first element. mid = int((l + r) / 2) if (alphabets[mid] > K): r = mid - 1 ans = mid else: l = mid + 1 # Return the smallest element if (alphabets[ans] < K): return alphabets[0] else: return alphabets[ans] # Driver Codeletters = ['A', 'r', 'z']K = 'z' # Function callresult = nextGreatestAlphabet(letters, K)print(result) # This code is contributed by Smitha",
"e": 29326,
"s": 28332,
"text": null
},
{
"code": "/* C# Program to find the smallest characterfrom the given set of letter, which is greaterthan the target element */using System; class GFG { /* Returns the smallest character from the given set of letters that is greater than K */ static char nextGreatestAlphabet(char[] alphabets, char K) { int n= alphabets.Length; if(K >= alphabets[n-1]) return alphabets[0]; int l = 0, r = alphabets.Length - 1; int ans = -1; // Take the first element as l and // the rightmost element as r while (l <= r) { // if this while condition does not // satisfy simply return the first // element. int mid = (l + r) / 2; if (alphabets[mid] > K) { ans = mid; r = mid - 1; } else l = mid + 1; } // Return the smallest element return alphabets[ans]; } // Driver Code public static void Main() { char[] letters = { 'A', 'r', 'z' }; char K = 'z'; // Function call char result = nextGreatestAlphabet(letters, K); Console.Write(result); }} // This code is contributed by Smitha",
"e": 30609,
"s": 29326,
"text": null
},
{
"code": "<script> /* JavaScript Program to find the smallest characterfrom the given set of letter, which is greaterthan the target element */ /* Returns the smallest character from the given set of letters that is greater than K */ function nextGreatestAlphabet(alphabets, K) { var l = 0, r = alphabets.length - 1; var ans = -1; // Take the first element as l and // the rightmost element as r while (l <= r) { // if this while condition does not // satisfy simply return the first // element. var mid = (l + r) / 2; if (alphabets[mid] > K) { ans = mid; r = mid - 1; } else l = mid + 1; } // Return the smallest element return alphabets[ans]; } // Driver Code var letters = [\"A\", \"K\", \"S\"]; var K = \"L\"; // Function call document.write(nextGreatestAlphabet(letters, K)); </script>",
"e": 31598,
"s": 30609,
"text": null
},
{
"code": null,
"e": 31600,
"s": 31598,
"text": "S"
},
{
"code": null,
"e": 31721,
"s": 31600,
"text": " The Time Complexity of the above approach is, O(log N) where N is the number of characters in the given set of Letters."
},
{
"code": null,
"e": 31742,
"s": 31721,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 31758,
"s": 31742,
"text": "ankitaankit1311"
},
{
"code": null,
"e": 31777,
"s": 31758,
"text": "adityamishra120799"
},
{
"code": null,
"e": 31788,
"s": 31777,
"text": "ferryrules"
},
{
"code": null,
"e": 31795,
"s": 31788,
"text": "rdtank"
},
{
"code": null,
"e": 31801,
"s": 31795,
"text": "bss12"
},
{
"code": null,
"e": 31815,
"s": 31801,
"text": "Binary Search"
},
{
"code": null,
"e": 31823,
"s": 31815,
"text": "Strings"
},
{
"code": null,
"e": 31831,
"s": 31823,
"text": "Strings"
},
{
"code": null,
"e": 31845,
"s": 31831,
"text": "Binary Search"
},
{
"code": null,
"e": 31943,
"s": 31845,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31952,
"s": 31943,
"text": "Comments"
},
{
"code": null,
"e": 31965,
"s": 31952,
"text": "Old Comments"
},
{
"code": null,
"e": 32010,
"s": 31965,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 32022,
"s": 32010,
"text": "Hill Cipher"
},
{
"code": null,
"e": 32060,
"s": 32022,
"text": "Naive algorithm for Pattern Searching"
},
{
"code": null,
"e": 32077,
"s": 32060,
"text": "Vigenère Cipher"
},
{
"code": null,
"e": 32120,
"s": 32077,
"text": "How to Append a Character to a String in C"
},
{
"code": null,
"e": 32161,
"s": 32120,
"text": "Convert character array to string in C++"
},
{
"code": null,
"e": 32196,
"s": 32161,
"text": "Print all subsequences of a string"
},
{
"code": null,
"e": 32257,
"s": 32196,
"text": "Converting Roman Numerals to Decimal lying between 1 to 3999"
},
{
"code": null,
"e": 32272,
"s": 32257,
"text": "sprintf() in C"
}
] |
Check if a number can be expressed as power | Set 2 (Using Log) - GeeksforGeeks
|
14 Jun, 2021
Check if a number can be expressed as x^y (x raised to power y) Given a positive integer n, find if it can be expressed as x^y where y > 1 and x > 0. x and y both are integers.Examples :
Input: n = 8
Output: true
8 can be expressed as 2^3
Input: n = 49
Output: true
49 can be expressed as 7^2
Input: n = 48
Output: false
48 can't be expressed as x^y
We have discussed two different approaches in below post.Check if a number can be expressed as x^y (x raised to power y).The idea is find Log n in different bases from 2 to square root of n. If Log n for a base becomes integer then result is true, else result is false.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find if a number// can be expressed as x raised to// power y.#include <bits/stdc++.h>using namespace std; bool isPower(unsigned int n){ // Find Log n in different bases // and check if the value is an // integer for (int x=2; x<=sqrt(n); x++) { float f = log(n) / log(x); if ((f - (int)f) == 0.0) return true; } return false;} // Driver codeint main(){ for (int i = 2; i < 100; i++) if (isPower(i)) cout << i << " "; return 0;}
// Java program to find if a number// can be expressed as x raised to// power y.class GFG { static boolean isPower(int n) { // Find Log n in different // bases and check if the // value is an integer for (int x = 2; x <= (int)Math.sqrt(n); x++) { float f = (float)Math.log(n) / (float) Math.log(x); if ((f - (int)f) == 0.0) return true; } return false; } // Driver code public static void main(String args[]) { for (int i = 2; i < 100; i++) if (isPower(i)) System.out.print( i + " "); }} // This code is contributed by Sam007
# Python3 program to find if a number# can be expressed as x raised to# power y.import math def isPower(n): # Find Log n in different # bases and check if the # value is an integer for x in range(2,int(math.sqrt(n)) + 1): f = math.log(n) / math.log(x); if ((f - int(f)) == 0.0): return True; return False; # Driver codefor i in range(2, 100): if (isPower(i)): print(i, end = " "); # This code is contributed by mits
// C# program to find if a number// can be expressed as x raised to// power y.using System; class GFG{ static bool isPower(int n) { // Find Log n in different // bases and check if the // value is an integer for (int x = 2; x <= (int)Math.Sqrt(n); x++) { float f = (float)Math.Log(n) / (float) Math.Log(x); if ((f - (int)f) == 0.0) return true; } return false; } // Driver Code public static void Main() { for (int i = 2; i < 100; i++) if (isPower(i)) Console.Write( i + " "); }} // This code is contributed by Sam007
<?php// PHP program to find if a number// can be expressed as x raised to// power y. function isPower($n){ // Find Log n in different // bases and check if the // value is an integer for ($x = 2; $x <= sqrt($n); $x++) { $f = log($n) / log($x); if (($f - (int)$f) == 0.0) return true; } return false;} // Driver codefor ($i = 2; $i < 100; $i++) if (isPower((int)$i)) echo $i." "; // This code is contributed by Sam007?>
<script> // javascript program to find if a number// can be expressed as x raised to// power y.function isPower(n) { // Find Log n in different // bases and check if the // value is an integer for (x = 2; x <= parseInt( Math.sqrt(n)); x++) { var f = Math.log(n) / Math.log(x); if ((f - parseInt( f)) == 0.0) return true; } return false; } // Driver code for (i = 2; i < 100; i++) if (isPower(i)) document.write(i + " "); // This code contributed by Rajput-Ji </script>
4 8 9 16 25 27 32 36 49 64 81
Sam007
Mithun Kumar
Rajput-Ji
bunnyram19
maths-log
number-theory
Mathematical
number-theory
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to find GCD or HCF of two numbers
Modulo Operator (%) in C/C++ with Examples
Merge two sorted arrays
Prime Numbers
Program to find sum of elements in a given array
Program for factorial of a number
Operators in C / C++
Euclidean algorithms (Basic and Extended)
Sieve of Eratosthenes
Program for Decimal to Binary Conversion
|
[
{
"code": null,
"e": 25282,
"s": 25254,
"text": "\n14 Jun, 2021"
},
{
"code": null,
"e": 25471,
"s": 25282,
"text": "Check if a number can be expressed as x^y (x raised to power y) Given a positive integer n, find if it can be expressed as x^y where y > 1 and x > 0. x and y both are integers.Examples : "
},
{
"code": null,
"e": 25639,
"s": 25471,
"text": "Input: n = 8\nOutput: true\n8 can be expressed as 2^3\n\nInput: n = 49\nOutput: true\n49 can be expressed as 7^2\n\nInput: n = 48\nOutput: false\n48 can't be expressed as x^y"
},
{
"code": null,
"e": 25913,
"s": 25641,
"text": "We have discussed two different approaches in below post.Check if a number can be expressed as x^y (x raised to power y).The idea is find Log n in different bases from 2 to square root of n. If Log n for a base becomes integer then result is true, else result is false. "
},
{
"code": null,
"e": 25917,
"s": 25913,
"text": "C++"
},
{
"code": null,
"e": 25922,
"s": 25917,
"text": "Java"
},
{
"code": null,
"e": 25930,
"s": 25922,
"text": "Python3"
},
{
"code": null,
"e": 25933,
"s": 25930,
"text": "C#"
},
{
"code": null,
"e": 25937,
"s": 25933,
"text": "PHP"
},
{
"code": null,
"e": 25948,
"s": 25937,
"text": "Javascript"
},
{
"code": "// CPP program to find if a number// can be expressed as x raised to// power y.#include <bits/stdc++.h>using namespace std; bool isPower(unsigned int n){ // Find Log n in different bases // and check if the value is an // integer for (int x=2; x<=sqrt(n); x++) { float f = log(n) / log(x); if ((f - (int)f) == 0.0) return true; } return false;} // Driver codeint main(){ for (int i = 2; i < 100; i++) if (isPower(i)) cout << i << \" \"; return 0;}",
"e": 26469,
"s": 25948,
"text": null
},
{
"code": "// Java program to find if a number// can be expressed as x raised to// power y.class GFG { static boolean isPower(int n) { // Find Log n in different // bases and check if the // value is an integer for (int x = 2; x <= (int)Math.sqrt(n); x++) { float f = (float)Math.log(n) / (float) Math.log(x); if ((f - (int)f) == 0.0) return true; } return false; } // Driver code public static void main(String args[]) { for (int i = 2; i < 100; i++) if (isPower(i)) System.out.print( i + \" \"); }} // This code is contributed by Sam007",
"e": 27207,
"s": 26469,
"text": null
},
{
"code": "# Python3 program to find if a number# can be expressed as x raised to# power y.import math def isPower(n): # Find Log n in different # bases and check if the # value is an integer for x in range(2,int(math.sqrt(n)) + 1): f = math.log(n) / math.log(x); if ((f - int(f)) == 0.0): return True; return False; # Driver codefor i in range(2, 100): if (isPower(i)): print(i, end = \" \"); # This code is contributed by mits",
"e": 27688,
"s": 27207,
"text": null
},
{
"code": "// C# program to find if a number// can be expressed as x raised to// power y.using System; class GFG{ static bool isPower(int n) { // Find Log n in different // bases and check if the // value is an integer for (int x = 2; x <= (int)Math.Sqrt(n); x++) { float f = (float)Math.Log(n) / (float) Math.Log(x); if ((f - (int)f) == 0.0) return true; } return false; } // Driver Code public static void Main() { for (int i = 2; i < 100; i++) if (isPower(i)) Console.Write( i + \" \"); }} // This code is contributed by Sam007",
"e": 28387,
"s": 27688,
"text": null
},
{
"code": "<?php// PHP program to find if a number// can be expressed as x raised to// power y. function isPower($n){ // Find Log n in different // bases and check if the // value is an integer for ($x = 2; $x <= sqrt($n); $x++) { $f = log($n) / log($x); if (($f - (int)$f) == 0.0) return true; } return false;} // Driver codefor ($i = 2; $i < 100; $i++) if (isPower((int)$i)) echo $i.\" \"; // This code is contributed by Sam007?>",
"e": 28866,
"s": 28387,
"text": null
},
{
"code": "<script> // javascript program to find if a number// can be expressed as x raised to// power y.function isPower(n) { // Find Log n in different // bases and check if the // value is an integer for (x = 2; x <= parseInt( Math.sqrt(n)); x++) { var f = Math.log(n) / Math.log(x); if ((f - parseInt( f)) == 0.0) return true; } return false; } // Driver code for (i = 2; i < 100; i++) if (isPower(i)) document.write(i + \" \"); // This code contributed by Rajput-Ji </script>",
"e": 29469,
"s": 28866,
"text": null
},
{
"code": null,
"e": 29509,
"s": 29469,
"text": "4 8 9 16 25 27 32 36 49 64 81"
},
{
"code": null,
"e": 29518,
"s": 29511,
"text": "Sam007"
},
{
"code": null,
"e": 29531,
"s": 29518,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 29541,
"s": 29531,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 29552,
"s": 29541,
"text": "bunnyram19"
},
{
"code": null,
"e": 29562,
"s": 29552,
"text": "maths-log"
},
{
"code": null,
"e": 29576,
"s": 29562,
"text": "number-theory"
},
{
"code": null,
"e": 29589,
"s": 29576,
"text": "Mathematical"
},
{
"code": null,
"e": 29603,
"s": 29589,
"text": "number-theory"
},
{
"code": null,
"e": 29616,
"s": 29603,
"text": "Mathematical"
},
{
"code": null,
"e": 29714,
"s": 29616,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29756,
"s": 29714,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 29799,
"s": 29756,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 29823,
"s": 29799,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 29837,
"s": 29823,
"text": "Prime Numbers"
},
{
"code": null,
"e": 29886,
"s": 29837,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 29920,
"s": 29886,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 29941,
"s": 29920,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 29983,
"s": 29941,
"text": "Euclidean algorithms (Basic and Extended)"
},
{
"code": null,
"e": 30005,
"s": 29983,
"text": "Sieve of Eratosthenes"
}
] |
C++ Program to Convert Hexadecimal Number to Binary
|
Given with hexadecimal number as an input, the task is to convert that hexadecimal number into a binary number.
Hexadecimal number in computers is represented with base 16 and binary number is represented with base 2 as it has only two binary digits 0 and 1 whereas hexadecimal number have digits starting from 0 – 15 in which 10 is represented as A, 11 as B, 12 as C, 13 as D, 14 as E and 15 as F.
To convert hexadecimal number into binary number every number is converted into its binary equivalent of 4 bits and after that these numbers are combined to form one corresponding binary number.
Input-: 123B
1 will have binary equivalent of 4 digit -: 0001
2 will have binary equivalent of 4 digit -: 0010
3 will have binary equivalent of 4 digit -: 0011
B(11) will have binary equivalent of 4 digit -: 1011
Output-: 0001001000111011
Start
Step 1 -> declare function to convert Hexadecimal to Binary Number
void convert(string hexa)
Declare variable as long int i = 0
Loop While(hexa[i])
Use Switch (hexa[i])
case '0':
print "0000"
break;
case '1':
print "0001"
break;
case '2':
print "0010"
break;
case '3':
print "0011"
break;
case '4':
print "0100”
break;
case '5':
print "0101"
break;
case '6':
print "0110"
break;
case '7':
print "0111"
break;
case '8':
print "1000"
break;
case '9':
print "1001"
break;
case 'A':
case 'a':
print "1010"
break;
case 'B':
case 'b':
print "1011"
break;
case 'C':
case 'c':
print "1100"
break;
case 'D':
case 'd':
print "1101"
break;
case 'E':
case 'e':
print "1110"
break;
case 'F':
case 'f':
print "111"
break;
default:
print please enter valid hexadecimal digit
End
i++
End
Step 2 -> In main()
Declare string hexa = "123B"
Print convert(hexa);
Stop
#include <bits/stdc++.h>
#include<string.h>
using namespace std;
// convert Hexadecimal to Binary Number
void convert(string hexa){
long int i = 0;
while (hexa[i]){
switch (hexa[i]){
case '0':
cout << "0000";
break;
case '1':
cout << "0001";
break;
case '2':
cout << "0010";
break;
case '3':
cout << "0011";
break;
case '4':
cout << "0100";
break;
case '5':
cout << "0101";
break;
case '6':
cout << "0110";
break;
case '7':
cout << "0111";
break;
case '8':
cout << "1000";
break;
case '9':
cout << "1001";
break;
case 'A':
case 'a':
cout << "1010";
break;
case 'B':
case 'b':
cout << "1011";
break;
case 'C':
case 'c':
cout << "1100";
break;
case 'D':
case 'd':
cout << "1101";
break;
case 'E':
case 'e':
cout << "1110";
break;
case 'F':
case 'f':
cout << "1111";
break;
default:
cout << "\please enter valid hexadecimal digit "<< hexa[i];
}
i++;
}
}
int main(){
string hexa = "123B";
cout << "\nEquivalent Binary value is : ";
convert(hexa);
return 0;
}
Equivalent Binary value is : 0001001000111011
|
[
{
"code": null,
"e": 1174,
"s": 1062,
"text": "Given with hexadecimal number as an input, the task is to convert that hexadecimal number into a binary number."
},
{
"code": null,
"e": 1461,
"s": 1174,
"text": "Hexadecimal number in computers is represented with base 16 and binary number is represented with base 2 as it has only two binary digits 0 and 1 whereas hexadecimal number have digits starting from 0 – 15 in which 10 is represented as A, 11 as B, 12 as C, 13 as D, 14 as E and 15 as F."
},
{
"code": null,
"e": 1656,
"s": 1461,
"text": "To convert hexadecimal number into binary number every number is converted into its binary equivalent of 4 bits and after that these numbers are combined to form one corresponding binary number."
},
{
"code": null,
"e": 1907,
"s": 1656,
"text": "Input-: 123B\n 1 will have binary equivalent of 4 digit -: 0001\n 2 will have binary equivalent of 4 digit -: 0010\n 3 will have binary equivalent of 4 digit -: 0011\n B(11) will have binary equivalent of 4 digit -: 1011\nOutput-: 0001001000111011"
},
{
"code": null,
"e": 3402,
"s": 1907,
"text": "Start\nStep 1 -> declare function to convert Hexadecimal to Binary Number\n void convert(string hexa)\n Declare variable as long int i = 0\n Loop While(hexa[i])\n Use Switch (hexa[i])\n case '0':\n print \"0000\"\n break;\n case '1':\n print \"0001\"\n break;\n case '2':\n print \"0010\"\n break;\n case '3':\n print \"0011\"\n break;\n case '4':\n print \"0100”\n break;\n case '5':\n print \"0101\"\n break;\n case '6':\n print \"0110\"\n break;\n case '7':\n print \"0111\"\n break;\n case '8':\n print \"1000\"\n break;\n case '9':\n print \"1001\"\n break;\n case 'A':\n case 'a':\n print \"1010\"\n break;\n case 'B':\n case 'b':\n print \"1011\"\n break;\n case 'C':\n case 'c':\n print \"1100\"\n break;\n case 'D':\n case 'd':\n print \"1101\"\n break;\n case 'E':\n case 'e':\n print \"1110\"\n break;\n case 'F':\n case 'f':\n print \"111\"\n break;\n default:\n print please enter valid hexadecimal digit\n End\n i++\n End\nStep 2 -> In main()\n Declare string hexa = \"123B\"\n Print convert(hexa);\nStop"
},
{
"code": null,
"e": 4831,
"s": 3402,
"text": "#include <bits/stdc++.h>\n#include<string.h>\nusing namespace std;\n// convert Hexadecimal to Binary Number\nvoid convert(string hexa){\n long int i = 0;\n while (hexa[i]){\n switch (hexa[i]){\n case '0':\n cout << \"0000\";\n break;\n case '1':\n cout << \"0001\";\n break;\n case '2':\n cout << \"0010\";\n break;\n case '3':\n cout << \"0011\";\n break;\n case '4':\n cout << \"0100\";\n break;\n case '5':\n cout << \"0101\";\n break;\n case '6':\n cout << \"0110\";\n break;\n case '7':\n cout << \"0111\";\n break;\n case '8':\n cout << \"1000\";\n break;\n case '9':\n cout << \"1001\";\n break;\n case 'A':\n case 'a':\n cout << \"1010\";\n break;\n case 'B':\n case 'b':\n cout << \"1011\";\n break;\n case 'C':\n case 'c':\n cout << \"1100\";\n break;\n case 'D':\n case 'd':\n cout << \"1101\";\n break;\n case 'E':\n case 'e':\n cout << \"1110\";\n break;\n case 'F':\n case 'f':\n cout << \"1111\";\n break;\n default:\n cout << \"\\please enter valid hexadecimal digit \"<< hexa[i];\n }\n i++;\n }\n}\nint main(){\n string hexa = \"123B\";\n cout << \"\\nEquivalent Binary value is : \";\n convert(hexa);\n return 0;\n}"
},
{
"code": null,
"e": 4877,
"s": 4831,
"text": "Equivalent Binary value is : 0001001000111011"
}
] |
Format TimeSpan in C#
|
You can format a TimeSpan in the hh: mm: ss format in C#.
Firstly, set the TimeSpan −
TimeSpan ts = new TimeSpan(9, 15, 30);
To format TimeSpan −
{0:hh\\:mm\\:ss}
The following is the code −
Live Demo
using System;
using System.Linq;
public class Demo {
public static void Main() {
TimeSpan ts = new TimeSpan(9, 15, 30);
Console.WriteLine("{0:hh\\:mm\\:ss}", ts);
}
}
09:15:30
|
[
{
"code": null,
"e": 1120,
"s": 1062,
"text": "You can format a TimeSpan in the hh: mm: ss format in C#."
},
{
"code": null,
"e": 1148,
"s": 1120,
"text": "Firstly, set the TimeSpan −"
},
{
"code": null,
"e": 1187,
"s": 1148,
"text": "TimeSpan ts = new TimeSpan(9, 15, 30);"
},
{
"code": null,
"e": 1208,
"s": 1187,
"text": "To format TimeSpan −"
},
{
"code": null,
"e": 1225,
"s": 1208,
"text": "{0:hh\\\\:mm\\\\:ss}"
},
{
"code": null,
"e": 1253,
"s": 1225,
"text": "The following is the code −"
},
{
"code": null,
"e": 1264,
"s": 1253,
"text": " Live Demo"
},
{
"code": null,
"e": 1449,
"s": 1264,
"text": "using System;\nusing System.Linq;\npublic class Demo {\n public static void Main() {\n TimeSpan ts = new TimeSpan(9, 15, 30);\n Console.WriteLine(\"{0:hh\\\\:mm\\\\:ss}\", ts);\n }\n}"
},
{
"code": null,
"e": 1458,
"s": 1449,
"text": "09:15:30"
}
] |
Debugging in TensorFlow. How to Debug a TensorFlow Training... | by Chaim Rand | Towards Data Science
|
If debugging is the process of removing software bugs, then programming must be the process of putting them in.Edsger Dijkstra. From https://www.azquotes.com/quote/561997
In some of my previous posts (here, here, and here), I told you a bit about how my team at Mobileye, (officially known as Mobileye, an Intel Company), uses TensorFlow, the Amazon SageMaker and Amazon s3 to train our deep neural networks on large quantities of data. In this post, I want to talk about debugging in TensorFlow.
It is well known, that program debugging is an integral part of software development, and that the time that is spent debugging, often eclipses the time that it takes to write the original program.
Debugging is hard, and much has been written about how to design and implement one's program in order to increase the reproducibility of bugs, and ease the process of root cause analysis.
In machine learning, the task of debugging is complicated by the stochasticity that is inherent to machine learning algorithms, and by the fact that the algorithms are run on dedicated HW accelerators often on remote machines.
Debugging in TensorFlow is further complicated due to the use of symbolic execution (a.k.a. graph mode), that boosts the runtime performance of the training session, but, at the same time, limits the ability to freely read arbitrary tensors in the graph, a capability that is important for debugging.
In this post, I will expand on the difficulties of debugging TensorFlow training programs, and provide some suggestions for how to address those difficulties.
For legal purposes, I want to clarify that despite my carefully chosen subtitle, I provide no guarantees that anything I write here will prevent you from losing your mind. On the contrary, I think that I can all but guarantee that you probably will lose your mind when debugging your TensorFlow program, despite anything I write. But, perhaps, you will lose your mind just a little bit less.
Before we begin, let's clarify the scope of our discussion.
In the context of this post, debugging refers to the art of identifying a bug, either in your code, or in your data, that causes your training session to abruptly break down.
A different kind of debugging, that is out of the scope of this post, refers to the task of fixing, or tuning, a model that is not converging, or that is producing unsatisfactory predictions on a certain class of inputs (e.g. a vehicle detection model that is failing to identify pink cars). This procedure might involve defining and evaluating model metrics, collection and statistical analysis of the model artifacts (such as gradients, activations and weights), using tools such as TensorBoard and Amazon Sagemaker Debugger, hyperparameter tuning, rearchitecting, or modifying your data input using techniques such as augmentation and boosting. Tuning a model can be an extremely challenging, time consuming and often frustrating task.
Within the realm of solving bugs in one's code or data, I like to make the distinction between two categories of bugs: bugs and monster bugs.
By bugs I refer to issues that are relatively easy to reproduce. Examples of bugs are models with an assumption on the sizes of the input tensors that doesn't match the training data, trying to concatenate mismatched tensors, or performing a tf operation on an invalid data type. These usually don't depend on specific model states and data and are typically relatively easy to reproduce. They aren't necessarily easy to fix, but they are child's play compared to monster bugs.
Monster bugs are bugs that occur sporadically and unpredictably. Bugs that reproduce only on a specific state of the model, a specific data sample, or a specific combination of the model state and data input, could pose a serious challenge and might constitute a monster bug.
Here is an example of a scenario, based on true events, that is certain to increase your blood pressure:
It's Friday afternoon and your model has been training successfully for a couple of days. The loss appears to be converging nicely, and you are starting to picture a relaxing, post-release, weekend vacation, in a getaway location of your choosing. You glance back at your screen for a moment and notice that, all of a sudden, without any warning, your loss has become NaN. "Surely", you think to yourself, "this must have been due to some totally random, momentary, macrocosmic glitch", and you immediately resume training from your last valid model checkpoint. A few more hours pass, and it happens again, and then again. Now you start to panic, the dreamy pictures of your weekend paradise now replaced with thoughts of the tantalizing effort of needing to solve a monster bug.
We will come back to this sorrowful example in a short while. But first, let's check off some mandatory "debugging" check-boxes.
Much ink has been spilled on the art of debugging and, more importantly, the art of developing debuggable code. In this section, I will mention a few techniques, as they pertain to TensorFlow applications. This list is, by no means, comprehensive.
This is probably the most important thing I will write in this post. Always configure your training session such that it periodically saves snapshots of your model.
Programming bugs are not the only reason why your training might break down... If you are running in the cloud, you might get a spot instance termination, or hit an internal server error. If you are running locally, there might be a power outage, or your GPU might explode. If you have been training for days, without storing intermediate checkpoints, the damage could be extreme. If you saved a checkpoint every hour, then all you lost is, at most, an hour. TensorFlow offers utilities for storing checkpoints, such as the keras model checkpoint callback. All you need to do, is to decide how frequently to capture such snapshots, by weighing the overhead of storing checkpoints, against the cost of an unplanned break down in the training session.
I apologize to my Covid19 contemporaries for my choice of title for this subsection, I just couldn't resist. By contact tracing, I am referring to the ability to keep track of the training data that is being entered into the training pipeline.
Suppose your training data is divided into 100,000 in tfrecord files, and that one of these files has a formatting error that crashes, or stalls, your program. One way to narrow down your search for the problematic file, is to record each file that is entered into the pipeline. Once you hit the crash you can look back at your log to see what the most recent files to be entered, were. As I have mentioned in previous posts, we train using the Amazon SageMaker pipe mode feature. A fairly recent addition to pipe mode, is a, pipe mode server side log that records the files that are being entered into the pipe.
Recording the data that enters into pipeline can assist in one's ability to reproduce bugs, which brings us to our next point.
The ease at which a bug can be reproduced directly impacts how easily it can be solved. We always want to write our code so as to ensure reproducibity. This is not easy in TensorFlow programs. Machine learning applications, often include reliance on the use of random variables. We randomly initialize model weights, we randomly augment data, we randomly shard our data for distributed training, we randomly apply dropouts, we shuffle our input data before each epoch, and then shuffle it again (using tf.dataset.shuffle) before creating batches. We could seed all of the pseudo-random operations with pseudo-random seeds that we record, but keep in mind that there could be many different places that introduce randomization, and keeping track of all of these could easily become a bookkeeping nightmare. I can't tell you how many times I have thought I had removed all elements of randomization, only to find that I missed one. Additionally, there are some random processes that cannot be seeded. If you use multiple processes to import your training data, you might not have any control over the order in which the data records are actually fed (e.g. if experimental_deterministic is set to false in tf.data.Options()). Of course, you could record each sample as it is entered into the pipe, but that would come at a steep, and likely prohibitive, overhead.
The bottom line is that while it is definitely possible to build reproducible training programs, I think it's wiser to embrace the non-determinism, accept the irreproducible nature of training, and find ways to overcome this debugging limitation.
A key technique in creating debuggable programs, is to build your application in a modular fashion. Applied to a TensorFlow training loop, this would imply the ability to test different subsets of the training pipeline, such as the dataset, the loss function, different model layers, and callbacks, separately. This is not always easy to do, as some of the training modules (such as the loss function) are pretty dependent on the other modules. But there is a lot of room for creativity. For example, one can test different functions on the input pipeline by simply iterating over the dataset while applying a subset of the dataset operations. One can test a loss function, or a callback, by creating an application that runs just the loss function or callback. One can neutralize the loss function, by replacing it with a dummy loss function. I like to build my models with multiple points of output, i.e. with the ability to easily modify the number of layers in the model so as to test the impact of different layers.
The more thought you put in to the modularity and debuggability of your program when you are building it, the less you will suffer later on.
If you are a regular TensorFlow user, you have probably encountered terms such as "eager execution mode", "graph mode", and the "tf function qualifier". You may have heard some (somewhat misleading) statements such as "debugging in eager execution mode is a piece of cake", or "tensorflow 2 runs in eager execution mode". You may, like me, have ardently dove into the tensorflow source code, trying to make sense of the different execution modes, only to have broken down in sobs, your self-esteem shattered for life. To get a full understanding of how it all works, I refer you to the TensorFlow documentation, and wish you luck. Here we will mention just the gist of it as it pertains to debugging. The most optimal way to run TensorFlow training is to run it in graph mode. Graph mode is a symbolic execution mode, which means that we don't have arbitrary access to the graph tensors. Functions that are wrapped with the tf.function qualifier, will be run in graph mode. When you train with tf.keras.model.fit, by default, the training step is executed in graph mode. Of course, the inability to access arbitrary graph tensors, makes debugging in graph mode difficult. In eager execution mode you can access arbitrary tensors, and even debug with a debugger, (provided that you place your breakpoint in the appropriate place in the model.call() function). Of course, when you run in eager execution mode, your training will run much slower. To program your model to train in eager execution mode, you need to call the model.compile() function with with the run_eagerly flag set to true.
The bottom line is, when you are training, run in graph mode, when you are debugging, run in eager execution mode. Unfortunately, it is not uncommon for certain bugs to reproduce only in graph mode and not in eager execution mode, which is a real bummer. Also, eager execution is helpful when you are debugging in a local environment, less so in the cloud. It is often not very useful in debugging monster bugs... Unless you first find a way to reproduce the bug in your local environment, (more on this down below).
Try to make the most of the TensorFlow logger. When you are debugging an issue, set the logger to the most informative level.
The tf.debugging module offers a bunch of assertion utilities as well as numeric checking functions. In particular, the tf.debugging.enable_check_numerics utility can be helpful in pinpointing problematic functions.
The tf.print function, which enables printing out arbitrary graph tensors, is an additional utility that I have found extremely useful for debugging.
And, last but not least, add your own print logs, (in the non-graph portions of the code), to get a better feel for where your program breaks down.
Sometimes, you will be lucky enough to get an TensorFlow error message. Unfortunately, it is not always immediately clear how to use them. I often get emails from colleagues with cryptic TensorFlow messages, begging for help. When I see messages, such as:
tensorflow.python.framework.errors_impl.InvalidArgumentError: ConcatOp : Dimensions of inputs should match: shape[0] = [5,229376] vs. shape[2] = [3,1]
or
node DatasetToGraphV2 (defined at main.py:152) (1) Failed precondition: Failed to serialize the input pipeline graph: Conversion to GraphDef is not supported.
or
ValueError: slice index -1 of dimension 0 out of bounds. for 'loss/strided_slice' (op: 'StridedSlice') with input shapes: [0], [1], [1], [1] and with computed input tensors: input[1] = <-1>, input[2] = <0>, input[3] = <1>.
I ask myself (slightly modified to make the post child friendly) "What the bleepitybeep am I supposed to with that?" or "Why couldn't the friendly-loving TensorFlow engineers give me something more to work with?". But I quickly calm myself, (sometimes with the help of an alcoholic beverage), and say, "Chaim, stop being so spoiled. Get back to work and be thankful that you got any message at all." The first thing you should do, is to try to reproduce the bug in eager execution mode, and/or with a debugger. Unfortunately, as mentioned above, this doesn't always help.
There is no arguing the fact that messages such as the ones above are not very helpful. But don't despair. Sometimes, with the help of some investigative work, you will find clues that might lead you in the right direction. Go through the call stack to see if it provides any hints. If the message includes shape sizes, try to match these up against tensors in your graph that might be of the same shape. And, of course, search online to see if others have encountered similar issues and in what scenarios. Don't despair.
Naturally, debugging in your local environment is easier than debugging on a remote machine, or in the cloud. This is particularly true when you first create your model. Your goal should be to work through as many issues as possible in your local environment before starting to train remotely. Otherwise, you are likely to end up wasting a lot of time and money.
To increase reproducibility, you should try to make your local environment as similar as possible to the remote environment. If you are using a docker image or virtual environment in your remote environment, try to use the same one locally. (If your remote training is on Amazon SageMaker, you can pull the docker image used.)
Of course, there may be some elements of the remote training environment that cannot be reproduced locally. For example, you might have encountered a bug that only reproduces when using Amazon SageMaker pipe mode, which is currently only supported when running in the cloud. (In this case you might consider alternative methods for accessing your data from s3.)
I wish I could tell you that the techniques described here will solve all your problems. But alas, such is not the case. In the next section we will return to the monster bug scenario we illustrated above, and introduce one last debugging technique.
In the scenario we described above, after days of training, a combination of the particular state of the model and a particular training batch sample, suddenly caused the loss to become NaN.
Let's evaluate how we can use the debugging techniques above to debug this issue.
If we kept meticulous track of the seeds that were used for all the random operations, and there were no uncontrolled non-deterministic events, we could in theory reproduce the bug by training from scratch... but that would take days.
Reproducing in a local environment or in eager execution mode would likely take weeks.
We could resume from a recent checkpoint, but we would only be able to reproduce the same model state and batch sample if we can resume from the exact same sample and with the exact same state of all the pseudo-random generators.
Adding tf.prints would help, but introduce tremendous overhead
Adding tf.debugging.enable_check_numerics would be very helpful in pinpointing the function in which it fails. This might be sufficient if there is an obvious bug in the function. But it does not enable us to reproduce the bug.
Ideally, we would be able to capture the input and model state right before the loss goes bananas. Then we could reproduce the issue in a controlled (local) environment, in eager execution mode and with a debugger.
The problem is that we don't know that problem is about to happen, until it actually happens. By the time the loss is reported as NaN, the model has already been updated with NaN weights, and the batch sample that caused the error has already been iterated over.
The solution I'd like to propose is to customize the training loop such that we record the current sample at every step, and only update the model weights if the gradients are valid. If the gradients are invalid, we will halt training and dump out the last batch sample along with the current model snapshot. This can be carried over to your local environment, where you load the model, and enter the captured data sample in eager execution mode in order to reproduce (and solve) the bug.
We will get to the code in a moment, but first, a few words about the pros and cons of using custom training loops.
There is an age-old dispute amongst TensorFlow users as to whether to write custom training loops or rely on high level APIs such as tf.keras.model.fit().
Proponents of the custom training loop, herald the ability to have line by line control over how the training is performed, and the freedom to be creative. Supporters of the high level API call out the many conveniences it offers, most notably the built-in callback utilities, and distributed strategy support. Using the high level API is also presumed to ensure that you are using a bug-free, and highly optimized implementation of the training loop.
Starting from version 2.2, TensorFlow introduced the ability to override the train_step and make_train_function routines of the tf.keras.model class. This enables one to introduce some level of customization while continuing to enjoy the conveniences of model.fit(). We will demonstrate how to override these function in such a way that enables us to capture a problematic sample input and model state for local debugging.
In the code block below, we extend the tf.keras.models.Model object with customized implementations of the train_step and make_train_functions routines. To get a full understanding of the implementation, I recommend that you compare it to the default implementations of the routines in github. You'll notice that I have removed all of the logic relating to metrics calculation and to strategy support in order to make the code more readable. The main changes to note are:
Before applying the gradients to the model weights, we test the gradients for NaN. The gradients will be applied to the weights, only if NaN does not appear. Otherwise, a signal is sent to the training loop that an error was encountered. An example of a signal can be setting the loss to a predetermined value such as zero or NaN.
The train loop stores the data features and labels (x and y) at each step. Note that in order to do that, we have moved the dataset traversal (next(iterator) call) outside of the @tf.function scope.
The class has a boolean "crash" flag to signal to the main function whether an error was encountered.
class CustomKerasModel(tf.keras.models.Model): def __init__(self, **kwargs): super(CustomKerasModel, self).__init__(**kwargs) # boolean flag that will signal to main function that # an error was encountered self.crash = False @tf.function def train_step(self, data): x, y = data with tf.GradientTape() as tape: y_pred = self(x, training=True) # Forward pass # Compute the loss value # (the loss function is configured in `compile()`) loss = self.compiled_loss( y, y_pred, regularization_losses=self.losses) res = {'loss':loss} # Compute gradients trainable_vars = self.trainable_variables gradients = tape.gradient(loss, trainable_vars) # concatenate the gradients into a single tensor for testing concat_grads = tf.concat([tf.reshape(g,[-1]) for g in gradients],0) # In this example, we test for NaNs, # but we can include other tests if tf.reduce_any(tf.math.is_nan(concat_grads)): # if any of the gradients are NaN, send a signal to the # outer loop and halt the training. We choose to signal # to the outer loop by setting the loss to 0. return {'loss': 0.} else: # Update weights self.optimizer.apply_gradients( zip(gradients, trainable_vars)) return {'loss': loss} def make_train_function(self): if self.train_function is not None: return self.train_function def train_function(iterator): data = next(iterator) # records the current sample self.x, self.y = data res = self.train_step(data) if res['loss'] == 0.: self.crash = True raise Exception() return res self.train_function = train_function return self.train_functionif __name__ == '__main__': # train_ds = # inputs = # outputs = # optimizer = # loss = # epochs = # steps_per_epoch = model = CustomKerasModel(inputs=inputs, outputs=outputs) opt = tf.keras.optimizers.Adadelta(1.0) model.compile(loss=loss, optimizer=optimizer) try: model.fit(train_ds, epochs=epochs, steps_per_epoch=steps_per_epoch) except Exception as e: # check for signal if model.crash: model.save_weights('model_weights.ckpt') # pickle dump model.x and model.y features_dict = {} for n, v in model.x.items(): features_dict[n] = v.numpy() with open('features.pkl','wb') as f: pickle.dump(features_dict,f) labels_dict = {} for n, v in model.y.items(): labels_dict[n] = v.numpy() with open('labels.pkl', 'wb') as f: pickle.dump(labels_dict, f) raise e
It is important to note, that there is a small training runtime cost to this technique that comes from reading the data from the dataset in eager execution mode, rather than graph mode. (There are no free lunches.) The precise cost will depend on the size of the model; the larger the model, the less this change will be felt. You should evaluate the overhead of this technique on your own model, and then decide whether, and how, to employ it.
So long as us humans are involved in the development of AI applications, the prevalence of programming bugs is just about guaranteed. Designing your code with debuggability in mind, and acquiring tools and techniques for solving bugs, may prevent some serious torture down the line.
Most importantly, don't despair.
|
[
{
"code": null,
"e": 342,
"s": 171,
"text": "If debugging is the process of removing software bugs, then programming must be the process of putting them in.Edsger Dijkstra. From https://www.azquotes.com/quote/561997"
},
{
"code": null,
"e": 668,
"s": 342,
"text": "In some of my previous posts (here, here, and here), I told you a bit about how my team at Mobileye, (officially known as Mobileye, an Intel Company), uses TensorFlow, the Amazon SageMaker and Amazon s3 to train our deep neural networks on large quantities of data. In this post, I want to talk about debugging in TensorFlow."
},
{
"code": null,
"e": 866,
"s": 668,
"text": "It is well known, that program debugging is an integral part of software development, and that the time that is spent debugging, often eclipses the time that it takes to write the original program."
},
{
"code": null,
"e": 1054,
"s": 866,
"text": "Debugging is hard, and much has been written about how to design and implement one's program in order to increase the reproducibility of bugs, and ease the process of root cause analysis."
},
{
"code": null,
"e": 1281,
"s": 1054,
"text": "In machine learning, the task of debugging is complicated by the stochasticity that is inherent to machine learning algorithms, and by the fact that the algorithms are run on dedicated HW accelerators often on remote machines."
},
{
"code": null,
"e": 1582,
"s": 1281,
"text": "Debugging in TensorFlow is further complicated due to the use of symbolic execution (a.k.a. graph mode), that boosts the runtime performance of the training session, but, at the same time, limits the ability to freely read arbitrary tensors in the graph, a capability that is important for debugging."
},
{
"code": null,
"e": 1741,
"s": 1582,
"text": "In this post, I will expand on the difficulties of debugging TensorFlow training programs, and provide some suggestions for how to address those difficulties."
},
{
"code": null,
"e": 2133,
"s": 1741,
"text": "For legal purposes, I want to clarify that despite my carefully chosen subtitle, I provide no guarantees that anything I write here will prevent you from losing your mind. On the contrary, I think that I can all but guarantee that you probably will lose your mind when debugging your TensorFlow program, despite anything I write. But, perhaps, you will lose your mind just a little bit less."
},
{
"code": null,
"e": 2193,
"s": 2133,
"text": "Before we begin, let's clarify the scope of our discussion."
},
{
"code": null,
"e": 2368,
"s": 2193,
"text": "In the context of this post, debugging refers to the art of identifying a bug, either in your code, or in your data, that causes your training session to abruptly break down."
},
{
"code": null,
"e": 3107,
"s": 2368,
"text": "A different kind of debugging, that is out of the scope of this post, refers to the task of fixing, or tuning, a model that is not converging, or that is producing unsatisfactory predictions on a certain class of inputs (e.g. a vehicle detection model that is failing to identify pink cars). This procedure might involve defining and evaluating model metrics, collection and statistical analysis of the model artifacts (such as gradients, activations and weights), using tools such as TensorBoard and Amazon Sagemaker Debugger, hyperparameter tuning, rearchitecting, or modifying your data input using techniques such as augmentation and boosting. Tuning a model can be an extremely challenging, time consuming and often frustrating task."
},
{
"code": null,
"e": 3249,
"s": 3107,
"text": "Within the realm of solving bugs in one's code or data, I like to make the distinction between two categories of bugs: bugs and monster bugs."
},
{
"code": null,
"e": 3727,
"s": 3249,
"text": "By bugs I refer to issues that are relatively easy to reproduce. Examples of bugs are models with an assumption on the sizes of the input tensors that doesn't match the training data, trying to concatenate mismatched tensors, or performing a tf operation on an invalid data type. These usually don't depend on specific model states and data and are typically relatively easy to reproduce. They aren't necessarily easy to fix, but they are child's play compared to monster bugs."
},
{
"code": null,
"e": 4003,
"s": 3727,
"text": "Monster bugs are bugs that occur sporadically and unpredictably. Bugs that reproduce only on a specific state of the model, a specific data sample, or a specific combination of the model state and data input, could pose a serious challenge and might constitute a monster bug."
},
{
"code": null,
"e": 4108,
"s": 4003,
"text": "Here is an example of a scenario, based on true events, that is certain to increase your blood pressure:"
},
{
"code": null,
"e": 4888,
"s": 4108,
"text": "It's Friday afternoon and your model has been training successfully for a couple of days. The loss appears to be converging nicely, and you are starting to picture a relaxing, post-release, weekend vacation, in a getaway location of your choosing. You glance back at your screen for a moment and notice that, all of a sudden, without any warning, your loss has become NaN. \"Surely\", you think to yourself, \"this must have been due to some totally random, momentary, macrocosmic glitch\", and you immediately resume training from your last valid model checkpoint. A few more hours pass, and it happens again, and then again. Now you start to panic, the dreamy pictures of your weekend paradise now replaced with thoughts of the tantalizing effort of needing to solve a monster bug."
},
{
"code": null,
"e": 5017,
"s": 4888,
"text": "We will come back to this sorrowful example in a short while. But first, let's check off some mandatory \"debugging\" check-boxes."
},
{
"code": null,
"e": 5265,
"s": 5017,
"text": "Much ink has been spilled on the art of debugging and, more importantly, the art of developing debuggable code. In this section, I will mention a few techniques, as they pertain to TensorFlow applications. This list is, by no means, comprehensive."
},
{
"code": null,
"e": 5430,
"s": 5265,
"text": "This is probably the most important thing I will write in this post. Always configure your training session such that it periodically saves snapshots of your model."
},
{
"code": null,
"e": 6180,
"s": 5430,
"text": "Programming bugs are not the only reason why your training might break down... If you are running in the cloud, you might get a spot instance termination, or hit an internal server error. If you are running locally, there might be a power outage, or your GPU might explode. If you have been training for days, without storing intermediate checkpoints, the damage could be extreme. If you saved a checkpoint every hour, then all you lost is, at most, an hour. TensorFlow offers utilities for storing checkpoints, such as the keras model checkpoint callback. All you need to do, is to decide how frequently to capture such snapshots, by weighing the overhead of storing checkpoints, against the cost of an unplanned break down in the training session."
},
{
"code": null,
"e": 6424,
"s": 6180,
"text": "I apologize to my Covid19 contemporaries for my choice of title for this subsection, I just couldn't resist. By contact tracing, I am referring to the ability to keep track of the training data that is being entered into the training pipeline."
},
{
"code": null,
"e": 7037,
"s": 6424,
"text": "Suppose your training data is divided into 100,000 in tfrecord files, and that one of these files has a formatting error that crashes, or stalls, your program. One way to narrow down your search for the problematic file, is to record each file that is entered into the pipeline. Once you hit the crash you can look back at your log to see what the most recent files to be entered, were. As I have mentioned in previous posts, we train using the Amazon SageMaker pipe mode feature. A fairly recent addition to pipe mode, is a, pipe mode server side log that records the files that are being entered into the pipe."
},
{
"code": null,
"e": 7164,
"s": 7037,
"text": "Recording the data that enters into pipeline can assist in one's ability to reproduce bugs, which brings us to our next point."
},
{
"code": null,
"e": 8525,
"s": 7164,
"text": "The ease at which a bug can be reproduced directly impacts how easily it can be solved. We always want to write our code so as to ensure reproducibity. This is not easy in TensorFlow programs. Machine learning applications, often include reliance on the use of random variables. We randomly initialize model weights, we randomly augment data, we randomly shard our data for distributed training, we randomly apply dropouts, we shuffle our input data before each epoch, and then shuffle it again (using tf.dataset.shuffle) before creating batches. We could seed all of the pseudo-random operations with pseudo-random seeds that we record, but keep in mind that there could be many different places that introduce randomization, and keeping track of all of these could easily become a bookkeeping nightmare. I can't tell you how many times I have thought I had removed all elements of randomization, only to find that I missed one. Additionally, there are some random processes that cannot be seeded. If you use multiple processes to import your training data, you might not have any control over the order in which the data records are actually fed (e.g. if experimental_deterministic is set to false in tf.data.Options()). Of course, you could record each sample as it is entered into the pipe, but that would come at a steep, and likely prohibitive, overhead."
},
{
"code": null,
"e": 8772,
"s": 8525,
"text": "The bottom line is that while it is definitely possible to build reproducible training programs, I think it's wiser to embrace the non-determinism, accept the irreproducible nature of training, and find ways to overcome this debugging limitation."
},
{
"code": null,
"e": 9793,
"s": 8772,
"text": "A key technique in creating debuggable programs, is to build your application in a modular fashion. Applied to a TensorFlow training loop, this would imply the ability to test different subsets of the training pipeline, such as the dataset, the loss function, different model layers, and callbacks, separately. This is not always easy to do, as some of the training modules (such as the loss function) are pretty dependent on the other modules. But there is a lot of room for creativity. For example, one can test different functions on the input pipeline by simply iterating over the dataset while applying a subset of the dataset operations. One can test a loss function, or a callback, by creating an application that runs just the loss function or callback. One can neutralize the loss function, by replacing it with a dummy loss function. I like to build my models with multiple points of output, i.e. with the ability to easily modify the number of layers in the model so as to test the impact of different layers."
},
{
"code": null,
"e": 9934,
"s": 9793,
"text": "The more thought you put in to the modularity and debuggability of your program when you are building it, the less you will suffer later on."
},
{
"code": null,
"e": 11524,
"s": 9934,
"text": "If you are a regular TensorFlow user, you have probably encountered terms such as \"eager execution mode\", \"graph mode\", and the \"tf function qualifier\". You may have heard some (somewhat misleading) statements such as \"debugging in eager execution mode is a piece of cake\", or \"tensorflow 2 runs in eager execution mode\". You may, like me, have ardently dove into the tensorflow source code, trying to make sense of the different execution modes, only to have broken down in sobs, your self-esteem shattered for life. To get a full understanding of how it all works, I refer you to the TensorFlow documentation, and wish you luck. Here we will mention just the gist of it as it pertains to debugging. The most optimal way to run TensorFlow training is to run it in graph mode. Graph mode is a symbolic execution mode, which means that we don't have arbitrary access to the graph tensors. Functions that are wrapped with the tf.function qualifier, will be run in graph mode. When you train with tf.keras.model.fit, by default, the training step is executed in graph mode. Of course, the inability to access arbitrary graph tensors, makes debugging in graph mode difficult. In eager execution mode you can access arbitrary tensors, and even debug with a debugger, (provided that you place your breakpoint in the appropriate place in the model.call() function). Of course, when you run in eager execution mode, your training will run much slower. To program your model to train in eager execution mode, you need to call the model.compile() function with with the run_eagerly flag set to true."
},
{
"code": null,
"e": 12041,
"s": 11524,
"text": "The bottom line is, when you are training, run in graph mode, when you are debugging, run in eager execution mode. Unfortunately, it is not uncommon for certain bugs to reproduce only in graph mode and not in eager execution mode, which is a real bummer. Also, eager execution is helpful when you are debugging in a local environment, less so in the cloud. It is often not very useful in debugging monster bugs... Unless you first find a way to reproduce the bug in your local environment, (more on this down below)."
},
{
"code": null,
"e": 12167,
"s": 12041,
"text": "Try to make the most of the TensorFlow logger. When you are debugging an issue, set the logger to the most informative level."
},
{
"code": null,
"e": 12383,
"s": 12167,
"text": "The tf.debugging module offers a bunch of assertion utilities as well as numeric checking functions. In particular, the tf.debugging.enable_check_numerics utility can be helpful in pinpointing problematic functions."
},
{
"code": null,
"e": 12533,
"s": 12383,
"text": "The tf.print function, which enables printing out arbitrary graph tensors, is an additional utility that I have found extremely useful for debugging."
},
{
"code": null,
"e": 12681,
"s": 12533,
"text": "And, last but not least, add your own print logs, (in the non-graph portions of the code), to get a better feel for where your program breaks down."
},
{
"code": null,
"e": 12937,
"s": 12681,
"text": "Sometimes, you will be lucky enough to get an TensorFlow error message. Unfortunately, it is not always immediately clear how to use them. I often get emails from colleagues with cryptic TensorFlow messages, begging for help. When I see messages, such as:"
},
{
"code": null,
"e": 13088,
"s": 12937,
"text": "tensorflow.python.framework.errors_impl.InvalidArgumentError: ConcatOp : Dimensions of inputs should match: shape[0] = [5,229376] vs. shape[2] = [3,1]"
},
{
"code": null,
"e": 13091,
"s": 13088,
"text": "or"
},
{
"code": null,
"e": 13250,
"s": 13091,
"text": "node DatasetToGraphV2 (defined at main.py:152) (1) Failed precondition: Failed to serialize the input pipeline graph: Conversion to GraphDef is not supported."
},
{
"code": null,
"e": 13253,
"s": 13250,
"text": "or"
},
{
"code": null,
"e": 13476,
"s": 13253,
"text": "ValueError: slice index -1 of dimension 0 out of bounds. for 'loss/strided_slice' (op: 'StridedSlice') with input shapes: [0], [1], [1], [1] and with computed input tensors: input[1] = <-1>, input[2] = <0>, input[3] = <1>."
},
{
"code": null,
"e": 14048,
"s": 13476,
"text": "I ask myself (slightly modified to make the post child friendly) \"What the bleepitybeep am I supposed to with that?\" or \"Why couldn't the friendly-loving TensorFlow engineers give me something more to work with?\". But I quickly calm myself, (sometimes with the help of an alcoholic beverage), and say, \"Chaim, stop being so spoiled. Get back to work and be thankful that you got any message at all.\" The first thing you should do, is to try to reproduce the bug in eager execution mode, and/or with a debugger. Unfortunately, as mentioned above, this doesn't always help."
},
{
"code": null,
"e": 14570,
"s": 14048,
"text": "There is no arguing the fact that messages such as the ones above are not very helpful. But don't despair. Sometimes, with the help of some investigative work, you will find clues that might lead you in the right direction. Go through the call stack to see if it provides any hints. If the message includes shape sizes, try to match these up against tensors in your graph that might be of the same shape. And, of course, search online to see if others have encountered similar issues and in what scenarios. Don't despair."
},
{
"code": null,
"e": 14933,
"s": 14570,
"text": "Naturally, debugging in your local environment is easier than debugging on a remote machine, or in the cloud. This is particularly true when you first create your model. Your goal should be to work through as many issues as possible in your local environment before starting to train remotely. Otherwise, you are likely to end up wasting a lot of time and money."
},
{
"code": null,
"e": 15260,
"s": 14933,
"text": "To increase reproducibility, you should try to make your local environment as similar as possible to the remote environment. If you are using a docker image or virtual environment in your remote environment, try to use the same one locally. (If your remote training is on Amazon SageMaker, you can pull the docker image used.)"
},
{
"code": null,
"e": 15622,
"s": 15260,
"text": "Of course, there may be some elements of the remote training environment that cannot be reproduced locally. For example, you might have encountered a bug that only reproduces when using Amazon SageMaker pipe mode, which is currently only supported when running in the cloud. (In this case you might consider alternative methods for accessing your data from s3.)"
},
{
"code": null,
"e": 15872,
"s": 15622,
"text": "I wish I could tell you that the techniques described here will solve all your problems. But alas, such is not the case. In the next section we will return to the monster bug scenario we illustrated above, and introduce one last debugging technique."
},
{
"code": null,
"e": 16063,
"s": 15872,
"text": "In the scenario we described above, after days of training, a combination of the particular state of the model and a particular training batch sample, suddenly caused the loss to become NaN."
},
{
"code": null,
"e": 16145,
"s": 16063,
"text": "Let's evaluate how we can use the debugging techniques above to debug this issue."
},
{
"code": null,
"e": 16380,
"s": 16145,
"text": "If we kept meticulous track of the seeds that were used for all the random operations, and there were no uncontrolled non-deterministic events, we could in theory reproduce the bug by training from scratch... but that would take days."
},
{
"code": null,
"e": 16467,
"s": 16380,
"text": "Reproducing in a local environment or in eager execution mode would likely take weeks."
},
{
"code": null,
"e": 16697,
"s": 16467,
"text": "We could resume from a recent checkpoint, but we would only be able to reproduce the same model state and batch sample if we can resume from the exact same sample and with the exact same state of all the pseudo-random generators."
},
{
"code": null,
"e": 16760,
"s": 16697,
"text": "Adding tf.prints would help, but introduce tremendous overhead"
},
{
"code": null,
"e": 16988,
"s": 16760,
"text": "Adding tf.debugging.enable_check_numerics would be very helpful in pinpointing the function in which it fails. This might be sufficient if there is an obvious bug in the function. But it does not enable us to reproduce the bug."
},
{
"code": null,
"e": 17203,
"s": 16988,
"text": "Ideally, we would be able to capture the input and model state right before the loss goes bananas. Then we could reproduce the issue in a controlled (local) environment, in eager execution mode and with a debugger."
},
{
"code": null,
"e": 17466,
"s": 17203,
"text": "The problem is that we don't know that problem is about to happen, until it actually happens. By the time the loss is reported as NaN, the model has already been updated with NaN weights, and the batch sample that caused the error has already been iterated over."
},
{
"code": null,
"e": 17955,
"s": 17466,
"text": "The solution I'd like to propose is to customize the training loop such that we record the current sample at every step, and only update the model weights if the gradients are valid. If the gradients are invalid, we will halt training and dump out the last batch sample along with the current model snapshot. This can be carried over to your local environment, where you load the model, and enter the captured data sample in eager execution mode in order to reproduce (and solve) the bug."
},
{
"code": null,
"e": 18071,
"s": 17955,
"text": "We will get to the code in a moment, but first, a few words about the pros and cons of using custom training loops."
},
{
"code": null,
"e": 18226,
"s": 18071,
"text": "There is an age-old dispute amongst TensorFlow users as to whether to write custom training loops or rely on high level APIs such as tf.keras.model.fit()."
},
{
"code": null,
"e": 18678,
"s": 18226,
"text": "Proponents of the custom training loop, herald the ability to have line by line control over how the training is performed, and the freedom to be creative. Supporters of the high level API call out the many conveniences it offers, most notably the built-in callback utilities, and distributed strategy support. Using the high level API is also presumed to ensure that you are using a bug-free, and highly optimized implementation of the training loop."
},
{
"code": null,
"e": 19101,
"s": 18678,
"text": "Starting from version 2.2, TensorFlow introduced the ability to override the train_step and make_train_function routines of the tf.keras.model class. This enables one to introduce some level of customization while continuing to enjoy the conveniences of model.fit(). We will demonstrate how to override these function in such a way that enables us to capture a problematic sample input and model state for local debugging."
},
{
"code": null,
"e": 19573,
"s": 19101,
"text": "In the code block below, we extend the tf.keras.models.Model object with customized implementations of the train_step and make_train_functions routines. To get a full understanding of the implementation, I recommend that you compare it to the default implementations of the routines in github. You'll notice that I have removed all of the logic relating to metrics calculation and to strategy support in order to make the code more readable. The main changes to note are:"
},
{
"code": null,
"e": 19904,
"s": 19573,
"text": "Before applying the gradients to the model weights, we test the gradients for NaN. The gradients will be applied to the weights, only if NaN does not appear. Otherwise, a signal is sent to the training loop that an error was encountered. An example of a signal can be setting the loss to a predetermined value such as zero or NaN."
},
{
"code": null,
"e": 20103,
"s": 19904,
"text": "The train loop stores the data features and labels (x and y) at each step. Note that in order to do that, we have moved the dataset traversal (next(iterator) call) outside of the @tf.function scope."
},
{
"code": null,
"e": 20205,
"s": 20103,
"text": "The class has a boolean \"crash\" flag to signal to the main function whether an error was encountered."
},
{
"code": null,
"e": 23193,
"s": 20205,
"text": "class CustomKerasModel(tf.keras.models.Model): def __init__(self, **kwargs): super(CustomKerasModel, self).__init__(**kwargs) # boolean flag that will signal to main function that # an error was encountered self.crash = False @tf.function def train_step(self, data): x, y = data with tf.GradientTape() as tape: y_pred = self(x, training=True) # Forward pass # Compute the loss value # (the loss function is configured in `compile()`) loss = self.compiled_loss( y, y_pred, regularization_losses=self.losses) res = {'loss':loss} # Compute gradients trainable_vars = self.trainable_variables gradients = tape.gradient(loss, trainable_vars) # concatenate the gradients into a single tensor for testing concat_grads = tf.concat([tf.reshape(g,[-1]) for g in gradients],0) # In this example, we test for NaNs, # but we can include other tests if tf.reduce_any(tf.math.is_nan(concat_grads)): # if any of the gradients are NaN, send a signal to the # outer loop and halt the training. We choose to signal # to the outer loop by setting the loss to 0. return {'loss': 0.} else: # Update weights self.optimizer.apply_gradients( zip(gradients, trainable_vars)) return {'loss': loss} def make_train_function(self): if self.train_function is not None: return self.train_function def train_function(iterator): data = next(iterator) # records the current sample self.x, self.y = data res = self.train_step(data) if res['loss'] == 0.: self.crash = True raise Exception() return res self.train_function = train_function return self.train_functionif __name__ == '__main__': # train_ds = # inputs = # outputs = # optimizer = # loss = # epochs = # steps_per_epoch = model = CustomKerasModel(inputs=inputs, outputs=outputs) opt = tf.keras.optimizers.Adadelta(1.0) model.compile(loss=loss, optimizer=optimizer) try: model.fit(train_ds, epochs=epochs, steps_per_epoch=steps_per_epoch) except Exception as e: # check for signal if model.crash: model.save_weights('model_weights.ckpt') # pickle dump model.x and model.y features_dict = {} for n, v in model.x.items(): features_dict[n] = v.numpy() with open('features.pkl','wb') as f: pickle.dump(features_dict,f) labels_dict = {} for n, v in model.y.items(): labels_dict[n] = v.numpy() with open('labels.pkl', 'wb') as f: pickle.dump(labels_dict, f) raise e"
},
{
"code": null,
"e": 23638,
"s": 23193,
"text": "It is important to note, that there is a small training runtime cost to this technique that comes from reading the data from the dataset in eager execution mode, rather than graph mode. (There are no free lunches.) The precise cost will depend on the size of the model; the larger the model, the less this change will be felt. You should evaluate the overhead of this technique on your own model, and then decide whether, and how, to employ it."
},
{
"code": null,
"e": 23921,
"s": 23638,
"text": "So long as us humans are involved in the development of AI applications, the prevalence of programming bugs is just about guaranteed. Designing your code with debuggability in mind, and acquiring tools and techniques for solving bugs, may prevent some serious torture down the line."
}
] |
Array of Structures vs. Array within a Structure in C/C++ - GeeksforGeeks
|
16 Jul, 2020
A structure is a data type in C/C++ that allows a group of related variables to be treated as a single unit instead of separate entities. A structure may contain elements of different data types – int, char, float, double, etc. It may also contain an array as its member. Such an array is called an array within a structure. An array within a structure is a member of the structure and can be accessed just as we access other elements of the structure.
Below is the demonstration of a program that uses the concept of the array within a structure. The program displays the record of a student comprising the roll number, grade, and marks secured in various subjects. The marks in various subjects have been stored under an array called marks. The whole record is stored under a structure called a candidate.
C
// C program to demonstrate the// use of an array within a structure#include <stdio.h> // Declaration of the structure candidatestruct candidate { int roll_no; char grade; // Array within the structure float marks[4];}; // Function to displays the content of// the structure variablesvoid display(struct candidate a1){ printf("Roll number : %d\n", a1.roll_no); printf("Grade : %c\n", a1.grade); printf("Marks secured:\n"); int i; int len = sizeof(a1.marks) / sizeof(float); // Accessing the contents of the // array within the structure for (i = 0; i < len; i++) { printf("Subject %d : %.2f\n", i + 1, a1.marks[i]); }} // Driver Codeint main(){ // Initialize a structure struct candidate A = { 1, 'A', { 98.5, 77, 89, 78.5 } }; // Function to display structure display(A); return 0;}
Roll number : 1
Grade : A
Marks secured:
Subject 1 : 98.50
Subject 2 : 77.00
Subject 3 : 89.00
Subject 4 : 78.50
An array is a collection of data items of the same type. Each element of the array can be int, char, float, double, or even a structure. We have seen that a structure allows elements of different data types to be grouped together under a single name. This structure can then be thought of as a new data type in itself. So, an array can comprise elements of this new data type. An array of structures finds its applications in grouping the records together and provides for fast accessing.
Below is the demonstration of an array of structures. The array holds the details of the students in a class. The details include the roll number, grade, and marks, which have been grouped under a structure (record). There exists one record for each student. This is how a collection of related variables can be assembled under a single entity for enhancing the clarity of code and increasing its efficiency.
C
// C program to demonstrate the// usage of an array of structures#include <stdio.h> // Declaring a structure classstruct class { int roll_no; char grade; float marks;}; // Function to displays the contents// of the array of structuresvoid display(struct class class_record[3]){ int i, len = 3; // Display the contents of the array // of structures here, each element // of the array is a structure of class for (i = 0; i < len; i++) { printf("Roll number : %d\n", class_record[i].roll_no); printf("Grade : %c\n", class_record[i].grade); printf("Average marks : %.2f\n", class_record[i].marks); printf("\n"); }} // Driver Codeint main(){ // Initialize of an array of structures struct class class_record[3] = { { 1, 'A', 89.5f }, { 2, 'C', 67.5f }, { 3, 'B', 70.5f } }; // Function Call to display // the class_record display(class_record); return 0;}
Roll number : 1
Grade : A
Average marks : 89.50
Roll number : 2
Grade : C
Average marks : 67.50
Roll number : 3
Grade : B
Average marks : 70.50
Below is the tabular difference between the Array within a Structure and Array of Structures:
struct class {
int ar[10];
} a1, a2, a3;
struct class {
int a, b, c;
} students[10];
C-Struct-Union-Enum
C-Structure & Union
cpp-struct
cpp-structure
Arrays
C Language
C++
cpp-struct
Arrays
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Arrays
Multidimensional Arrays in Java
Linked List vs Array
Python | Using 2D arrays/lists the right way
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
std::sort() in C++ STL
Bitwise Operators in C/C++
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
|
[
{
"code": null,
"e": 23889,
"s": 23861,
"text": "\n16 Jul, 2020"
},
{
"code": null,
"e": 24342,
"s": 23889,
"text": "A structure is a data type in C/C++ that allows a group of related variables to be treated as a single unit instead of separate entities. A structure may contain elements of different data types – int, char, float, double, etc. It may also contain an array as its member. Such an array is called an array within a structure. An array within a structure is a member of the structure and can be accessed just as we access other elements of the structure."
},
{
"code": null,
"e": 24697,
"s": 24342,
"text": "Below is the demonstration of a program that uses the concept of the array within a structure. The program displays the record of a student comprising the roll number, grade, and marks secured in various subjects. The marks in various subjects have been stored under an array called marks. The whole record is stored under a structure called a candidate."
},
{
"code": null,
"e": 24699,
"s": 24697,
"text": "C"
},
{
"code": "// C program to demonstrate the// use of an array within a structure#include <stdio.h> // Declaration of the structure candidatestruct candidate { int roll_no; char grade; // Array within the structure float marks[4];}; // Function to displays the content of// the structure variablesvoid display(struct candidate a1){ printf(\"Roll number : %d\\n\", a1.roll_no); printf(\"Grade : %c\\n\", a1.grade); printf(\"Marks secured:\\n\"); int i; int len = sizeof(a1.marks) / sizeof(float); // Accessing the contents of the // array within the structure for (i = 0; i < len; i++) { printf(\"Subject %d : %.2f\\n\", i + 1, a1.marks[i]); }} // Driver Codeint main(){ // Initialize a structure struct candidate A = { 1, 'A', { 98.5, 77, 89, 78.5 } }; // Function to display structure display(A); return 0;}",
"e": 25576,
"s": 24699,
"text": null
},
{
"code": null,
"e": 25690,
"s": 25576,
"text": "Roll number : 1\nGrade : A\nMarks secured:\nSubject 1 : 98.50\nSubject 2 : 77.00\nSubject 3 : 89.00\nSubject 4 : 78.50\n"
},
{
"code": null,
"e": 26179,
"s": 25690,
"text": "An array is a collection of data items of the same type. Each element of the array can be int, char, float, double, or even a structure. We have seen that a structure allows elements of different data types to be grouped together under a single name. This structure can then be thought of as a new data type in itself. So, an array can comprise elements of this new data type. An array of structures finds its applications in grouping the records together and provides for fast accessing."
},
{
"code": null,
"e": 26588,
"s": 26179,
"text": "Below is the demonstration of an array of structures. The array holds the details of the students in a class. The details include the roll number, grade, and marks, which have been grouped under a structure (record). There exists one record for each student. This is how a collection of related variables can be assembled under a single entity for enhancing the clarity of code and increasing its efficiency."
},
{
"code": null,
"e": 26590,
"s": 26588,
"text": "C"
},
{
"code": "// C program to demonstrate the// usage of an array of structures#include <stdio.h> // Declaring a structure classstruct class { int roll_no; char grade; float marks;}; // Function to displays the contents// of the array of structuresvoid display(struct class class_record[3]){ int i, len = 3; // Display the contents of the array // of structures here, each element // of the array is a structure of class for (i = 0; i < len; i++) { printf(\"Roll number : %d\\n\", class_record[i].roll_no); printf(\"Grade : %c\\n\", class_record[i].grade); printf(\"Average marks : %.2f\\n\", class_record[i].marks); printf(\"\\n\"); }} // Driver Codeint main(){ // Initialize of an array of structures struct class class_record[3] = { { 1, 'A', 89.5f }, { 2, 'C', 67.5f }, { 3, 'B', 70.5f } }; // Function Call to display // the class_record display(class_record); return 0;}",
"e": 27592,
"s": 26590,
"text": null
},
{
"code": null,
"e": 27739,
"s": 27592,
"text": "Roll number : 1\nGrade : A\nAverage marks : 89.50\n\nRoll number : 2\nGrade : C\nAverage marks : 67.50\n\nRoll number : 3\nGrade : B\nAverage marks : 70.50\n"
},
{
"code": null,
"e": 27833,
"s": 27739,
"text": "Below is the tabular difference between the Array within a Structure and Array of Structures:"
},
{
"code": null,
"e": 27848,
"s": 27833,
"text": "struct class {"
},
{
"code": null,
"e": 27860,
"s": 27848,
"text": "int ar[10];"
},
{
"code": null,
"e": 27874,
"s": 27860,
"text": "} a1, a2, a3;"
},
{
"code": null,
"e": 27889,
"s": 27874,
"text": "struct class {"
},
{
"code": null,
"e": 27902,
"s": 27889,
"text": "int a, b, c;"
},
{
"code": null,
"e": 27918,
"s": 27902,
"text": "} students[10];"
},
{
"code": null,
"e": 27938,
"s": 27918,
"text": "C-Struct-Union-Enum"
},
{
"code": null,
"e": 27958,
"s": 27938,
"text": "C-Structure & Union"
},
{
"code": null,
"e": 27969,
"s": 27958,
"text": "cpp-struct"
},
{
"code": null,
"e": 27983,
"s": 27969,
"text": "cpp-structure"
},
{
"code": null,
"e": 27990,
"s": 27983,
"text": "Arrays"
},
{
"code": null,
"e": 28001,
"s": 27990,
"text": "C Language"
},
{
"code": null,
"e": 28005,
"s": 28001,
"text": "C++"
},
{
"code": null,
"e": 28016,
"s": 28005,
"text": "cpp-struct"
},
{
"code": null,
"e": 28023,
"s": 28016,
"text": "Arrays"
},
{
"code": null,
"e": 28027,
"s": 28023,
"text": "CPP"
},
{
"code": null,
"e": 28125,
"s": 28027,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28134,
"s": 28125,
"text": "Comments"
},
{
"code": null,
"e": 28147,
"s": 28134,
"text": "Old Comments"
},
{
"code": null,
"e": 28170,
"s": 28147,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 28202,
"s": 28170,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 28223,
"s": 28202,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 28268,
"s": 28223,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 28353,
"s": 28268,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 28431,
"s": 28353,
"text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()"
},
{
"code": null,
"e": 28454,
"s": 28431,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 28481,
"s": 28454,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 28516,
"s": 28481,
"text": "Multidimensional Arrays in C / C++"
}
] |
ML From Scratch: Linear, Polynomial, and Regularized Regression Models | by Luke Newman | Towards Data Science
|
In this new series, I took it upon myself to improve my coding skills and habits by writing clean, reusable, well-documented code with test cases. This is the first part of the series where I implement Linear, Polynomial, Ridge, Lasso, and ElasticNet Regression from scratch in an object-oriented manner.
We’ll start with a simple LinearRegression class and then build upon it creating an entire module of linear models in a simple style similar to Scikit-Learn. My implementations are in no way optimal solutions and are only meant to increase our understanding of machine learning.
In the repository you will find all of the code found in this blog and more including test cases for every class and function.
To view the Github repository please visit here.
To use the classes and functions for testing purposes create a virtual environment and pip install the project.
$ pip install mlscratch==0.0.1
To download all source code in a local repository from Github create a virtual environment and run the following commands in your terminal.
$ git clone https://github.com/lukenew2/mlscratch $ cd mlscratch $ python setup.py install
Often one of the first models anyone learns about in their data science journey is Linear Regression. Simply put, a linear regression model represents the relationship between a dependent scalar variable y and independent variables X by computing parameter weights for each independent variable plus a constant called the bias term (also called the intercept term).
We make predictions by multiplying the vector of feature weights, Θ, by the independent variables X.
And that’s it! That’s all there is to the linear regression model. Let’s look at how we train it.
Training a model means finding the parameters that best fit the training dataset. To do this, we need to be able to measure how well the model fits the data. For linear regression, we find the value of Θ that minimizes the Mean Squared Error (MSE). There are multiple optimization algorithms to do this so we’ll look at a couple.
The first method we’re going to code from scratch is called Ordinary Least Squares (OLS). OLS computes the pseudoinverse of X and multiplies it with the target values y. In python this method is pretty easy to implement using scipy.linalg.lstsq() which is the same function that Scikit-Learn’s LinearRegression() class uses.
We’ll try and make ours similar to Scikit-Learn’s library by having fit() and predict() methods. We’ll also give it the attribute coef_ which is the parameters calculated during training.
To code the fit() method we simply add a bias term to our feature array and perform OLS with the function scipy.linalg.lstsq(). We store the calculated parameter coefficients in our attribute coef_ and then return an instance of self. The predict() method is even simpler. All we do is add a one to each instance for the bias term and then take the dot product of the feature matrix and our calculated parameters.
The ordinary least squares algorithm can get very slow when the number of features grows very large. In these cases it is preferred to use another optimization approach called gradient descent.
Gradient descent is a generic optimization algorithm that searches for the optimal solution by making small tweaks to the parameters. To start, you fill Θ with random values (this approach is called random initialization). Then, tweak the parameters until the algorithm converges to a minimum solution by traveling in a direction that decreases the cost function. In our case that means decreasing the MSE.
To travel in the direction that decreases the cost function, you’re going to need to calculate the gradient vector which contains all the partial derivatives of the cost function.
After you calculate the gradient vector you update your parameters in the opposite direction that the gradient vector is pointing. This is where the learning rate (η) comes in to play. The learning rate determines the size of the steps you take in that direction.
Batch gradient descent is a version of gradient descent where we calculate the gradient vector of the entire dataset at each step. This means that batch gradient descent does not scale well with very large training sets because it has to load the entire dataset to calculate the next step. If you’re dataset is very large you might want to use stochastic gradient descent or mini-batch gradient descent, but we won’t cover those here. Just know they exist.
Let’s edit our current module to include the option to use batch gradient descent for training. Since we’ll also be creating a Ridge, Lasso, and ElasticNet class, we’ll create a base Regression() class that all of our regressors can inherit from.
Now we have a fully functional linear regression model capable of being trained using batch gradient descent and ordinary least squares. But, what if our data isn’t a straight line? If that’s the case we’ll need a more complex model that can fit nonlinear data like polynomial regression.
A simple way to model nonlinear data with a linear model is to add powers of each feature as new features, then train the model on this extended set of features. This technique is called polynomial regression.
When you have multiple features, this technique is capable of finding relationships between features because you’re adding all combinations of features up to the given degree.
Ok, now we know polynomial regression is the same as linear regression except we add polynomial features to our dataset before training. Instead of creating a separate PolynomialRegression() class, we’ll add a preprocessing class that can transform your data before training. This way once we build our regularized linear models, they too will be able to perform polynomial regression.
We’ll code it in a similar style to Scikit-Learn’s preprocessing classes. It will have a fit(), transform(), and fit_transform() method.
If you try to perform polynomial regression at this point you might get an error during training. This is because you’re using gradient descent as the training algorithm. When we transform our features to add polynomial terms, it is very important we normalize our data if we’re using an iterative training algorithm like gradient descent. If we don’t, we risk encountering exploding gradients.
There are many ways to normalize data, but we will stick with one of the simplest. By subtracting out the mean and dividing each instance by the standard deviation for each feature we effectively standardize our data. Meaning all our features are centered with a mean of 0 and unit variance.
Let’s add a class called StandardScaler() to our preprocessing.py module. We’ll include an inverse_transform() method here in case we ever need to return data to its original state after it has been standardized.
With our code, polynomial regression can be implemented in three steps. First, add polynomial features to the dataset. Then, standardize our features using StandardScaler(). Finally, train our LinearRegression model with either OLS or batch gradient descent.
Using polynomial regression we are easily able to overfit datasets by setting the degree parameter too high. One way to reduce overfitting is to regularize the model (i.e., constrain it): the fewer degrees of freedom a model has, the harder it is for it to overfit the data.
For linear models, one way to regularize them is by constraining the parameter weights. Let’s look at three different ways to achieve this through coding Ridge, Lasso, and Elastic Net regression from scratch.
Ridge regression is a regularized form of linear regression where we add a regularization term to the cost function equal to half of the L2 norm of the parameter weights. With ridge regression, our cost function looks like:
where α controls how much regularization you wish to add to the model. To implement this from scratch using gradient descent, we’ll also need the partial derivatives of the regularization term. Easy enough it is simply α multiplied by the parameter weights.
It’s important to note that the regularization term sum starts at i=1 not 0. This is because we don’t regularize the bias term.
Ok, we know everything we need to add Ridge to our regression.py module. First, we’ll create a class that computes the L2 norm and the gradient vector.
When we call this class it will behave as a function and compute the regularization term for us and when we call its grad() method it will compute the gradient vector regularization term. Now we just use our helper class to compute our regularization terms during gradient descent in our base Regression class.
In the fit() method of our base regression class we added the regularization term to our error metric, MSE, and the derivative to the gradient vector.
Next, we updated our LinearRegression Class to include self.regularization and self.regularization.grad attributes which evaluate to 0 through the quick use of lambda functions. Meaning there will be no regularization when using LinearRegression.
Finally, we create our Ridge regression class which inherits from the base Regression class giving it the same attributes and methods. The only thing we need to change is in the __init__() method.
We give it two attributes, alpha and self.regularization. Alpha is used to control the amount of regularization and self.regularization is equal to our l2_regularization class which calculates our penalty terms used in gradient descent.
Least Absolute Shrinkage and Selection Operator (Lasso) regression is implemented in the exact same way as Ridge except it adds a regularization penalty equal to the L1 norm.
Since the L1 norm is not differentiable at 0 we calculate the regularization penalty on the gradients with a subgradient vector equal to the sign function.
All we have to do to complete the implementation of Lasso regression from scratch is to create a regularization class to help compute the penalty terms and then create the Lasso regression class.
First, we’ll add the L1 regularization class to our regularization.py module.
Second, we’ll create a new Lasso class that will also inherit from our base Regression class in our regression.py module.
Lasso regression implements a form of feature selection because it tends to eliminate the least important features (i.e., set them to zero).
Elastic Net implements a simple mix of both Ridge and Lasso’s regularization terms to the cost function and gradient vector. The mix ratio r determines how much of each term is included. When r = 0, Elastic Net is equivalent to Ridge, and when r = 1, it is equivalent to Lasso.
Just as we did when coding Lasso Regression from scratch we create a regularization class to calculate the penalties and make the ElasticNet class inheriting from the base Regression class.
Now let’s code the ElasticNet Regression class.
Let’s mention quickly when you should use each model we coded from scratch. In general, it is almost always preferable to use a regularized linear model with a little bit of regularization.
Ridge is a good default, however if you expect only a few features to be useful you should use Lasso or Elastic Net due to their feature selection properties. Lasso may behave erratically when the number of features is greater than the number of training instances or when several features are strongly correlated. Hence, Elastic Net is generally preferred.
That completes this part of the machine learning from scratch series. We have implemented the most common linear models used for regression.
I can not emphasize enough, coding machine learning models from scratch will increase your knowledge of ML exponentially while also increasing your skills in python and object-oriented programming.
For ideas on extending this project, I would like to include mini-batch and stochastic gradient descent as options for training each model. Also, implementing a form of early stopping would further increase our knowledge of machine learning.
As always, thanks for reading and all feedback is greatly appreciated!
In the next part of the series we’ll build upon our library and code linear models used for classification from scratch including logistic and softmax regression.
Give me a follow if you like the content you see here! :-)
|
[
{
"code": null,
"e": 476,
"s": 171,
"text": "In this new series, I took it upon myself to improve my coding skills and habits by writing clean, reusable, well-documented code with test cases. This is the first part of the series where I implement Linear, Polynomial, Ridge, Lasso, and ElasticNet Regression from scratch in an object-oriented manner."
},
{
"code": null,
"e": 755,
"s": 476,
"text": "We’ll start with a simple LinearRegression class and then build upon it creating an entire module of linear models in a simple style similar to Scikit-Learn. My implementations are in no way optimal solutions and are only meant to increase our understanding of machine learning."
},
{
"code": null,
"e": 882,
"s": 755,
"text": "In the repository you will find all of the code found in this blog and more including test cases for every class and function."
},
{
"code": null,
"e": 931,
"s": 882,
"text": "To view the Github repository please visit here."
},
{
"code": null,
"e": 1043,
"s": 931,
"text": "To use the classes and functions for testing purposes create a virtual environment and pip install the project."
},
{
"code": null,
"e": 1078,
"s": 1043,
"text": " $ pip install mlscratch==0.0.1"
},
{
"code": null,
"e": 1218,
"s": 1078,
"text": "To download all source code in a local repository from Github create a virtual environment and run the following commands in your terminal."
},
{
"code": null,
"e": 1319,
"s": 1218,
"text": " $ git clone https://github.com/lukenew2/mlscratch $ cd mlscratch $ python setup.py install"
},
{
"code": null,
"e": 1685,
"s": 1319,
"text": "Often one of the first models anyone learns about in their data science journey is Linear Regression. Simply put, a linear regression model represents the relationship between a dependent scalar variable y and independent variables X by computing parameter weights for each independent variable plus a constant called the bias term (also called the intercept term)."
},
{
"code": null,
"e": 1786,
"s": 1685,
"text": "We make predictions by multiplying the vector of feature weights, Θ, by the independent variables X."
},
{
"code": null,
"e": 1884,
"s": 1786,
"text": "And that’s it! That’s all there is to the linear regression model. Let’s look at how we train it."
},
{
"code": null,
"e": 2214,
"s": 1884,
"text": "Training a model means finding the parameters that best fit the training dataset. To do this, we need to be able to measure how well the model fits the data. For linear regression, we find the value of Θ that minimizes the Mean Squared Error (MSE). There are multiple optimization algorithms to do this so we’ll look at a couple."
},
{
"code": null,
"e": 2539,
"s": 2214,
"text": "The first method we’re going to code from scratch is called Ordinary Least Squares (OLS). OLS computes the pseudoinverse of X and multiplies it with the target values y. In python this method is pretty easy to implement using scipy.linalg.lstsq() which is the same function that Scikit-Learn’s LinearRegression() class uses."
},
{
"code": null,
"e": 2727,
"s": 2539,
"text": "We’ll try and make ours similar to Scikit-Learn’s library by having fit() and predict() methods. We’ll also give it the attribute coef_ which is the parameters calculated during training."
},
{
"code": null,
"e": 3141,
"s": 2727,
"text": "To code the fit() method we simply add a bias term to our feature array and perform OLS with the function scipy.linalg.lstsq(). We store the calculated parameter coefficients in our attribute coef_ and then return an instance of self. The predict() method is even simpler. All we do is add a one to each instance for the bias term and then take the dot product of the feature matrix and our calculated parameters."
},
{
"code": null,
"e": 3335,
"s": 3141,
"text": "The ordinary least squares algorithm can get very slow when the number of features grows very large. In these cases it is preferred to use another optimization approach called gradient descent."
},
{
"code": null,
"e": 3742,
"s": 3335,
"text": "Gradient descent is a generic optimization algorithm that searches for the optimal solution by making small tweaks to the parameters. To start, you fill Θ with random values (this approach is called random initialization). Then, tweak the parameters until the algorithm converges to a minimum solution by traveling in a direction that decreases the cost function. In our case that means decreasing the MSE."
},
{
"code": null,
"e": 3922,
"s": 3742,
"text": "To travel in the direction that decreases the cost function, you’re going to need to calculate the gradient vector which contains all the partial derivatives of the cost function."
},
{
"code": null,
"e": 4186,
"s": 3922,
"text": "After you calculate the gradient vector you update your parameters in the opposite direction that the gradient vector is pointing. This is where the learning rate (η) comes in to play. The learning rate determines the size of the steps you take in that direction."
},
{
"code": null,
"e": 4643,
"s": 4186,
"text": "Batch gradient descent is a version of gradient descent where we calculate the gradient vector of the entire dataset at each step. This means that batch gradient descent does not scale well with very large training sets because it has to load the entire dataset to calculate the next step. If you’re dataset is very large you might want to use stochastic gradient descent or mini-batch gradient descent, but we won’t cover those here. Just know they exist."
},
{
"code": null,
"e": 4890,
"s": 4643,
"text": "Let’s edit our current module to include the option to use batch gradient descent for training. Since we’ll also be creating a Ridge, Lasso, and ElasticNet class, we’ll create a base Regression() class that all of our regressors can inherit from."
},
{
"code": null,
"e": 5179,
"s": 4890,
"text": "Now we have a fully functional linear regression model capable of being trained using batch gradient descent and ordinary least squares. But, what if our data isn’t a straight line? If that’s the case we’ll need a more complex model that can fit nonlinear data like polynomial regression."
},
{
"code": null,
"e": 5389,
"s": 5179,
"text": "A simple way to model nonlinear data with a linear model is to add powers of each feature as new features, then train the model on this extended set of features. This technique is called polynomial regression."
},
{
"code": null,
"e": 5565,
"s": 5389,
"text": "When you have multiple features, this technique is capable of finding relationships between features because you’re adding all combinations of features up to the given degree."
},
{
"code": null,
"e": 5951,
"s": 5565,
"text": "Ok, now we know polynomial regression is the same as linear regression except we add polynomial features to our dataset before training. Instead of creating a separate PolynomialRegression() class, we’ll add a preprocessing class that can transform your data before training. This way once we build our regularized linear models, they too will be able to perform polynomial regression."
},
{
"code": null,
"e": 6088,
"s": 5951,
"text": "We’ll code it in a similar style to Scikit-Learn’s preprocessing classes. It will have a fit(), transform(), and fit_transform() method."
},
{
"code": null,
"e": 6483,
"s": 6088,
"text": "If you try to perform polynomial regression at this point you might get an error during training. This is because you’re using gradient descent as the training algorithm. When we transform our features to add polynomial terms, it is very important we normalize our data if we’re using an iterative training algorithm like gradient descent. If we don’t, we risk encountering exploding gradients."
},
{
"code": null,
"e": 6775,
"s": 6483,
"text": "There are many ways to normalize data, but we will stick with one of the simplest. By subtracting out the mean and dividing each instance by the standard deviation for each feature we effectively standardize our data. Meaning all our features are centered with a mean of 0 and unit variance."
},
{
"code": null,
"e": 6988,
"s": 6775,
"text": "Let’s add a class called StandardScaler() to our preprocessing.py module. We’ll include an inverse_transform() method here in case we ever need to return data to its original state after it has been standardized."
},
{
"code": null,
"e": 7247,
"s": 6988,
"text": "With our code, polynomial regression can be implemented in three steps. First, add polynomial features to the dataset. Then, standardize our features using StandardScaler(). Finally, train our LinearRegression model with either OLS or batch gradient descent."
},
{
"code": null,
"e": 7522,
"s": 7247,
"text": "Using polynomial regression we are easily able to overfit datasets by setting the degree parameter too high. One way to reduce overfitting is to regularize the model (i.e., constrain it): the fewer degrees of freedom a model has, the harder it is for it to overfit the data."
},
{
"code": null,
"e": 7731,
"s": 7522,
"text": "For linear models, one way to regularize them is by constraining the parameter weights. Let’s look at three different ways to achieve this through coding Ridge, Lasso, and Elastic Net regression from scratch."
},
{
"code": null,
"e": 7955,
"s": 7731,
"text": "Ridge regression is a regularized form of linear regression where we add a regularization term to the cost function equal to half of the L2 norm of the parameter weights. With ridge regression, our cost function looks like:"
},
{
"code": null,
"e": 8213,
"s": 7955,
"text": "where α controls how much regularization you wish to add to the model. To implement this from scratch using gradient descent, we’ll also need the partial derivatives of the regularization term. Easy enough it is simply α multiplied by the parameter weights."
},
{
"code": null,
"e": 8341,
"s": 8213,
"text": "It’s important to note that the regularization term sum starts at i=1 not 0. This is because we don’t regularize the bias term."
},
{
"code": null,
"e": 8493,
"s": 8341,
"text": "Ok, we know everything we need to add Ridge to our regression.py module. First, we’ll create a class that computes the L2 norm and the gradient vector."
},
{
"code": null,
"e": 8804,
"s": 8493,
"text": "When we call this class it will behave as a function and compute the regularization term for us and when we call its grad() method it will compute the gradient vector regularization term. Now we just use our helper class to compute our regularization terms during gradient descent in our base Regression class."
},
{
"code": null,
"e": 8955,
"s": 8804,
"text": "In the fit() method of our base regression class we added the regularization term to our error metric, MSE, and the derivative to the gradient vector."
},
{
"code": null,
"e": 9202,
"s": 8955,
"text": "Next, we updated our LinearRegression Class to include self.regularization and self.regularization.grad attributes which evaluate to 0 through the quick use of lambda functions. Meaning there will be no regularization when using LinearRegression."
},
{
"code": null,
"e": 9399,
"s": 9202,
"text": "Finally, we create our Ridge regression class which inherits from the base Regression class giving it the same attributes and methods. The only thing we need to change is in the __init__() method."
},
{
"code": null,
"e": 9636,
"s": 9399,
"text": "We give it two attributes, alpha and self.regularization. Alpha is used to control the amount of regularization and self.regularization is equal to our l2_regularization class which calculates our penalty terms used in gradient descent."
},
{
"code": null,
"e": 9811,
"s": 9636,
"text": "Least Absolute Shrinkage and Selection Operator (Lasso) regression is implemented in the exact same way as Ridge except it adds a regularization penalty equal to the L1 norm."
},
{
"code": null,
"e": 9967,
"s": 9811,
"text": "Since the L1 norm is not differentiable at 0 we calculate the regularization penalty on the gradients with a subgradient vector equal to the sign function."
},
{
"code": null,
"e": 10163,
"s": 9967,
"text": "All we have to do to complete the implementation of Lasso regression from scratch is to create a regularization class to help compute the penalty terms and then create the Lasso regression class."
},
{
"code": null,
"e": 10241,
"s": 10163,
"text": "First, we’ll add the L1 regularization class to our regularization.py module."
},
{
"code": null,
"e": 10363,
"s": 10241,
"text": "Second, we’ll create a new Lasso class that will also inherit from our base Regression class in our regression.py module."
},
{
"code": null,
"e": 10504,
"s": 10363,
"text": "Lasso regression implements a form of feature selection because it tends to eliminate the least important features (i.e., set them to zero)."
},
{
"code": null,
"e": 10782,
"s": 10504,
"text": "Elastic Net implements a simple mix of both Ridge and Lasso’s regularization terms to the cost function and gradient vector. The mix ratio r determines how much of each term is included. When r = 0, Elastic Net is equivalent to Ridge, and when r = 1, it is equivalent to Lasso."
},
{
"code": null,
"e": 10972,
"s": 10782,
"text": "Just as we did when coding Lasso Regression from scratch we create a regularization class to calculate the penalties and make the ElasticNet class inheriting from the base Regression class."
},
{
"code": null,
"e": 11020,
"s": 10972,
"text": "Now let’s code the ElasticNet Regression class."
},
{
"code": null,
"e": 11210,
"s": 11020,
"text": "Let’s mention quickly when you should use each model we coded from scratch. In general, it is almost always preferable to use a regularized linear model with a little bit of regularization."
},
{
"code": null,
"e": 11568,
"s": 11210,
"text": "Ridge is a good default, however if you expect only a few features to be useful you should use Lasso or Elastic Net due to their feature selection properties. Lasso may behave erratically when the number of features is greater than the number of training instances or when several features are strongly correlated. Hence, Elastic Net is generally preferred."
},
{
"code": null,
"e": 11709,
"s": 11568,
"text": "That completes this part of the machine learning from scratch series. We have implemented the most common linear models used for regression."
},
{
"code": null,
"e": 11907,
"s": 11709,
"text": "I can not emphasize enough, coding machine learning models from scratch will increase your knowledge of ML exponentially while also increasing your skills in python and object-oriented programming."
},
{
"code": null,
"e": 12149,
"s": 11907,
"text": "For ideas on extending this project, I would like to include mini-batch and stochastic gradient descent as options for training each model. Also, implementing a form of early stopping would further increase our knowledge of machine learning."
},
{
"code": null,
"e": 12220,
"s": 12149,
"text": "As always, thanks for reading and all feedback is greatly appreciated!"
},
{
"code": null,
"e": 12383,
"s": 12220,
"text": "In the next part of the series we’ll build upon our library and code linear models used for classification from scratch including logistic and softmax regression."
}
] |
How to Download a Specific Sheet by Name from a Google Spreadsheet as a CSV File | by billydharmawan | Towards Data Science
|
In the past two tutorials on Google Drive API with Python, we have covered how to obtain credentials here and search for a specific file in Google Drive by its name here.
In this tutorial, we are going to learn how to download a specific Sheet by name from a Google Spreadsheet into a csv file. A use case for this: you need to generate a report, which data are stored in a Google Spreadsheet that has many Sheets, but you only need one or two of them. So, instead of downloading the whole Google Spreadsheet, you can handpick the Sheets that you need.
Why by its name? Because I’ve learnt from my work experience that people tend to stick to the naming and usually refer to it by its name. For instance, one might ask his or colleague like this, “Can you extract the data from the Revenue sheet, please?.
Anyways, you know what I’m talking about. 💩Let’s just get into it, alright?
TLDR; download the project repo from Github.
Our current Python script has the capability to search for a specific file by its name. Let’s modify the script so then it is able to reference a specific Sheet in a Google Spreadsheet and download it as a csv file.
At the end of the tutorial, we will end up with a Python script that is executable from command line and takes two input arguments:
Google Spreadsheet’s name
Sheet name to download as csv
To follow along, please check out this commit of the repo.
The first thing we need to do is to enable the Google Sheets API. Now, open your browser and go to https://console.developers.google.com/apis/dashboard. Then, make sure you are on the right project and if not, select the right project from the drop down list.
Next, go to the Library tab and type “Sheets” on the search bar.
Go ahead and click on it. Once you land on the Google Sheets API page, click on the ENABLE button to enable this API.
After that, if you just go to the Credentials tab, you will see that it says our credentials we set up earlier for Google Drive API is compatible with the Sheets API. This means we can use the credentials that we already have and set up for our script. 🙂
To be able to use the Sheets API, we need to initialise a Sheets service instance as follows.
sheets = discovery.build('sheets', 'v4', credentials=credentials)
For now, let’s add the above code to our existing connect_to_google_drive.py file (we’ll refactor this later).
Now that we narrow down the functionality of our script, we can add a filter to our existing retrieve_all_files to only look for Google Spreadsheet type of files. To do this, we just need to add one parameter q as follows.
# define a function to retrieve all filesdef retrieve_all_files(api_service, filename_to_search): results = [] page_token = None while True: try: param = {'q': 'mimeType="application/vnd.google-apps.spreadsheet"'} if page_token: param['pageToken'] = page_token files = api_service.files().list(**param).execute() ... ... ...
By adding mimeType="application/vnd.google-apps.spreadsheet", it tells the Google Drive API’s list() method to only return the result(s) if the file’s mime type is a Google Spreadsheet.
Finally, let’s write the function that will use the Sheets’ API’s values() method to get cell values from a specific sheet snd write them to a csv file.
# define a function to export sheet to csvdef download_sheet_to_csv(spreadsheet_id, sheet_name): result = sheets.spreadsheets().values().get(spreadsheetId=spreadsheet_id, range=sheet_name).execute() output_file = f'{sheet_name}.csv' with open(output_file, 'w') as f: writer = csv.writer(f) writer.writerows(result.get('values')) f.close() print(f'Successfully downloaded {sheet_name}.csv')
Let’s call this new function at the end of our script, like so.
# call the functionfilename_to_search = 'Christmas Plan'all_files, search_file = retrieve_all_files(drive, filename_to_search)download_sheet_to_csv(search_file.get('id'), 'Sheet2')
For this example, the content of the Sheet2 is like this.
Cool. Now go ahead and run this script from the terminal. Remember to activate your virtual environment before running the script. 🙂 This is what you will see in the console when the script is finished.
$ python connect_to_google_drive.py{'kind': 'drive#file', 'id': '1GyIz1NqCg6Bkr0Z_3Craem0BAwG0195usRswduCtKab', 'name': 'Christmas Plan', 'mimeType': 'application/vnd.google-apps.spreadsheet'}Successfully downloaded Sheet2.csv
Let’s validate the downloaded file by looking at its content.
$ cat Sheet2.csvNo,Code,Name1,123,Apple2,234,Watermelon3,345,Banana4,456,Blueberry5,567,Dragonfruit6,678,Cherry7,789,Strawberry8,890,Kiwi9,901,Avocado
Alright. It looks like our script works as expected. Happy days 😃
As promised, we will now refactor the code and transform it so that it will take two input arguments from the command line.
To separate things out, we’re going to extract all the functions in connect_to_google_drive.py into individual Python files. Let’s create a folder and name it google_api_functions.
First, let’s extract the lines of code that initialise our drive and sheets instances into a new file and name it get_api_services.py.
Next, we’ll refactor the retrieve_all_files function. Now, the only information we need from this function is the id of the Google Spreadsheet. So, let’s remove the unnecessary lines and finally, extract it to a new Python file named get_spreadsheet_id.py.
The last function to extract out is the download_sheet_to_csv function. Let’s extract it into a new file named download_sheet_to_csv.py.
Now, we will rename our connect_to_google_drive.py file to main.py. This is the Python file that we will call from the command line.
We are going to add a function in this file that will parse arguments passed through the command line, which will be the spreadsheet name and the sheet name.
def parse_args(): parser = argparse.ArgumentParser(description="Function to download a specific sheet from a Google Spreadsheet") parser.add_argument("--spreadsheet-name", required=True, help="The name of the Google Spreadsheet") parser.add_argument("--sheet-name", required=True, help="The name of the sheet in spreadsheet to download as csv") return parser.parse_args()
Finally, let’s write the lines of code that will get executed when the script main.py is called from the command line.
if __name__ == '__main__': args = parse_args() spreadsheet_name = args.spreadsheet_name sheet_name = args.sheet_name drive, sheets = get_api_services() spreadsheet_id = get_spreadsheet_id(drive, spreadsheet_name) download_sheet_to_csv(sheets, spreadsheet_id, sheet_name)
Nice! Our code becomes so much cleaner and easier to follow now. 🙂
With this new main.py script, the way we can call it from the command line is as follows.
$ python main.py --spreadsheet-name "Christmas Plan" --sheet-name Sheet2Successfully downloaded Sheet2.csv
That’s it. 😺
Over the past three tutorials, we have discussed the following:
Set up credentials to use the Google Drive API — link
Search for a file in Google Drive — link
Download a specific sheet as csv
By now, we should all be familiar with Google Drive and Sheets API. There are still a lot of other things that we can do using the API and so, I encourage all of you to explore it further and build some automation script to help with your work or life in general. 🙏
|
[
{
"code": null,
"e": 342,
"s": 171,
"text": "In the past two tutorials on Google Drive API with Python, we have covered how to obtain credentials here and search for a specific file in Google Drive by its name here."
},
{
"code": null,
"e": 724,
"s": 342,
"text": "In this tutorial, we are going to learn how to download a specific Sheet by name from a Google Spreadsheet into a csv file. A use case for this: you need to generate a report, which data are stored in a Google Spreadsheet that has many Sheets, but you only need one or two of them. So, instead of downloading the whole Google Spreadsheet, you can handpick the Sheets that you need."
},
{
"code": null,
"e": 977,
"s": 724,
"text": "Why by its name? Because I’ve learnt from my work experience that people tend to stick to the naming and usually refer to it by its name. For instance, one might ask his or colleague like this, “Can you extract the data from the Revenue sheet, please?."
},
{
"code": null,
"e": 1053,
"s": 977,
"text": "Anyways, you know what I’m talking about. 💩Let’s just get into it, alright?"
},
{
"code": null,
"e": 1098,
"s": 1053,
"text": "TLDR; download the project repo from Github."
},
{
"code": null,
"e": 1314,
"s": 1098,
"text": "Our current Python script has the capability to search for a specific file by its name. Let’s modify the script so then it is able to reference a specific Sheet in a Google Spreadsheet and download it as a csv file."
},
{
"code": null,
"e": 1446,
"s": 1314,
"text": "At the end of the tutorial, we will end up with a Python script that is executable from command line and takes two input arguments:"
},
{
"code": null,
"e": 1472,
"s": 1446,
"text": "Google Spreadsheet’s name"
},
{
"code": null,
"e": 1502,
"s": 1472,
"text": "Sheet name to download as csv"
},
{
"code": null,
"e": 1561,
"s": 1502,
"text": "To follow along, please check out this commit of the repo."
},
{
"code": null,
"e": 1821,
"s": 1561,
"text": "The first thing we need to do is to enable the Google Sheets API. Now, open your browser and go to https://console.developers.google.com/apis/dashboard. Then, make sure you are on the right project and if not, select the right project from the drop down list."
},
{
"code": null,
"e": 1886,
"s": 1821,
"text": "Next, go to the Library tab and type “Sheets” on the search bar."
},
{
"code": null,
"e": 2004,
"s": 1886,
"text": "Go ahead and click on it. Once you land on the Google Sheets API page, click on the ENABLE button to enable this API."
},
{
"code": null,
"e": 2259,
"s": 2004,
"text": "After that, if you just go to the Credentials tab, you will see that it says our credentials we set up earlier for Google Drive API is compatible with the Sheets API. This means we can use the credentials that we already have and set up for our script. 🙂"
},
{
"code": null,
"e": 2353,
"s": 2259,
"text": "To be able to use the Sheets API, we need to initialise a Sheets service instance as follows."
},
{
"code": null,
"e": 2419,
"s": 2353,
"text": "sheets = discovery.build('sheets', 'v4', credentials=credentials)"
},
{
"code": null,
"e": 2530,
"s": 2419,
"text": "For now, let’s add the above code to our existing connect_to_google_drive.py file (we’ll refactor this later)."
},
{
"code": null,
"e": 2753,
"s": 2530,
"text": "Now that we narrow down the functionality of our script, we can add a filter to our existing retrieve_all_files to only look for Google Spreadsheet type of files. To do this, we just need to add one parameter q as follows."
},
{
"code": null,
"e": 3151,
"s": 2753,
"text": "# define a function to retrieve all filesdef retrieve_all_files(api_service, filename_to_search): results = [] page_token = None while True: try: param = {'q': 'mimeType=\"application/vnd.google-apps.spreadsheet\"'} if page_token: param['pageToken'] = page_token files = api_service.files().list(**param).execute() ... ... ..."
},
{
"code": null,
"e": 3337,
"s": 3151,
"text": "By adding mimeType=\"application/vnd.google-apps.spreadsheet\", it tells the Google Drive API’s list() method to only return the result(s) if the file’s mime type is a Google Spreadsheet."
},
{
"code": null,
"e": 3490,
"s": 3337,
"text": "Finally, let’s write the function that will use the Sheets’ API’s values() method to get cell values from a specific sheet snd write them to a csv file."
},
{
"code": null,
"e": 3909,
"s": 3490,
"text": "# define a function to export sheet to csvdef download_sheet_to_csv(spreadsheet_id, sheet_name): result = sheets.spreadsheets().values().get(spreadsheetId=spreadsheet_id, range=sheet_name).execute() output_file = f'{sheet_name}.csv' with open(output_file, 'w') as f: writer = csv.writer(f) writer.writerows(result.get('values')) f.close() print(f'Successfully downloaded {sheet_name}.csv')"
},
{
"code": null,
"e": 3973,
"s": 3909,
"text": "Let’s call this new function at the end of our script, like so."
},
{
"code": null,
"e": 4154,
"s": 3973,
"text": "# call the functionfilename_to_search = 'Christmas Plan'all_files, search_file = retrieve_all_files(drive, filename_to_search)download_sheet_to_csv(search_file.get('id'), 'Sheet2')"
},
{
"code": null,
"e": 4212,
"s": 4154,
"text": "For this example, the content of the Sheet2 is like this."
},
{
"code": null,
"e": 4415,
"s": 4212,
"text": "Cool. Now go ahead and run this script from the terminal. Remember to activate your virtual environment before running the script. 🙂 This is what you will see in the console when the script is finished."
},
{
"code": null,
"e": 4642,
"s": 4415,
"text": "$ python connect_to_google_drive.py{'kind': 'drive#file', 'id': '1GyIz1NqCg6Bkr0Z_3Craem0BAwG0195usRswduCtKab', 'name': 'Christmas Plan', 'mimeType': 'application/vnd.google-apps.spreadsheet'}Successfully downloaded Sheet2.csv"
},
{
"code": null,
"e": 4704,
"s": 4642,
"text": "Let’s validate the downloaded file by looking at its content."
},
{
"code": null,
"e": 4855,
"s": 4704,
"text": "$ cat Sheet2.csvNo,Code,Name1,123,Apple2,234,Watermelon3,345,Banana4,456,Blueberry5,567,Dragonfruit6,678,Cherry7,789,Strawberry8,890,Kiwi9,901,Avocado"
},
{
"code": null,
"e": 4921,
"s": 4855,
"text": "Alright. It looks like our script works as expected. Happy days 😃"
},
{
"code": null,
"e": 5045,
"s": 4921,
"text": "As promised, we will now refactor the code and transform it so that it will take two input arguments from the command line."
},
{
"code": null,
"e": 5226,
"s": 5045,
"text": "To separate things out, we’re going to extract all the functions in connect_to_google_drive.py into individual Python files. Let’s create a folder and name it google_api_functions."
},
{
"code": null,
"e": 5361,
"s": 5226,
"text": "First, let’s extract the lines of code that initialise our drive and sheets instances into a new file and name it get_api_services.py."
},
{
"code": null,
"e": 5618,
"s": 5361,
"text": "Next, we’ll refactor the retrieve_all_files function. Now, the only information we need from this function is the id of the Google Spreadsheet. So, let’s remove the unnecessary lines and finally, extract it to a new Python file named get_spreadsheet_id.py."
},
{
"code": null,
"e": 5755,
"s": 5618,
"text": "The last function to extract out is the download_sheet_to_csv function. Let’s extract it into a new file named download_sheet_to_csv.py."
},
{
"code": null,
"e": 5888,
"s": 5755,
"text": "Now, we will rename our connect_to_google_drive.py file to main.py. This is the Python file that we will call from the command line."
},
{
"code": null,
"e": 6046,
"s": 5888,
"text": "We are going to add a function in this file that will parse arguments passed through the command line, which will be the spreadsheet name and the sheet name."
},
{
"code": null,
"e": 6430,
"s": 6046,
"text": "def parse_args(): parser = argparse.ArgumentParser(description=\"Function to download a specific sheet from a Google Spreadsheet\") parser.add_argument(\"--spreadsheet-name\", required=True, help=\"The name of the Google Spreadsheet\") parser.add_argument(\"--sheet-name\", required=True, help=\"The name of the sheet in spreadsheet to download as csv\") return parser.parse_args()"
},
{
"code": null,
"e": 6549,
"s": 6430,
"text": "Finally, let’s write the lines of code that will get executed when the script main.py is called from the command line."
},
{
"code": null,
"e": 6838,
"s": 6549,
"text": "if __name__ == '__main__': args = parse_args() spreadsheet_name = args.spreadsheet_name sheet_name = args.sheet_name drive, sheets = get_api_services() spreadsheet_id = get_spreadsheet_id(drive, spreadsheet_name) download_sheet_to_csv(sheets, spreadsheet_id, sheet_name)"
},
{
"code": null,
"e": 6905,
"s": 6838,
"text": "Nice! Our code becomes so much cleaner and easier to follow now. 🙂"
},
{
"code": null,
"e": 6995,
"s": 6905,
"text": "With this new main.py script, the way we can call it from the command line is as follows."
},
{
"code": null,
"e": 7102,
"s": 6995,
"text": "$ python main.py --spreadsheet-name \"Christmas Plan\" --sheet-name Sheet2Successfully downloaded Sheet2.csv"
},
{
"code": null,
"e": 7115,
"s": 7102,
"text": "That’s it. 😺"
},
{
"code": null,
"e": 7179,
"s": 7115,
"text": "Over the past three tutorials, we have discussed the following:"
},
{
"code": null,
"e": 7233,
"s": 7179,
"text": "Set up credentials to use the Google Drive API — link"
},
{
"code": null,
"e": 7274,
"s": 7233,
"text": "Search for a file in Google Drive — link"
},
{
"code": null,
"e": 7307,
"s": 7274,
"text": "Download a specific sheet as csv"
}
] |
getbkcolor() function in C - GeeksforGeeks
|
23 Jan, 2018
The header file graphics.h contains getbkcolor() function which returns the current background color.
Syntax :
int getbkcolor();
As getbkcolor() returns an integer value corresponding to the background color, so below is the table for Color values.Colors Table :
COLOR INT VALUES
-------------------------------
BLACK 0
BLUE 1
GREEN 2
CYAN 3
RED 4
MAGENTA 5
BROWN 6
LIGHTGRAY 7
DARKGRAY 8
LIGHTBLUE 9
LIGHTGREEN 10
LIGHTCYAN 11
LIGHTRED 12
LIGHTMAGENTA 13
YELLOW 14
WHITE 15
When the background color is black:
// C Implementation for getbkcolor function#include <graphics.h>#include <stdio.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // "graphics.h" header file int gd = DETECT, gm; char arr[100]; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, ""); // sprintf stands for “String print”. // Instead of printing on console, it // store output on char buffer which // are specified in sprintf sprintf(arr, "Current background color = %d", getbkcolor()); // outtext function displays text // at current position. outtextxy(10, 10, arr); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0;}
Output :
When the background color is other than black:
// C Implementation for getbkcolor function#include <graphics.h>#include <stdio.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // "graphics.h" header file int gd = DETECT, gm; char arr[100]; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, ""); // set background color as RED setbkcolor(RED); // sprintf stands for “String print”. // Instead of printing on console, it // store output on char buffer which // are specified in sprintf sprintf(arr, "Current background color = %d", getbkcolor()); // outtext function displays text // at current position. outtextxy(10, 10, arr); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0;}
Output :
c-graphics
computer-graphics
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Command line arguments in C/C++
Core Dump (Segmentation fault) in C/C++
Substring in C++
Function Pointer in C
TCP Server-Client implementation in C
Structures in C
|
[
{
"code": null,
"e": 24307,
"s": 24279,
"text": "\n23 Jan, 2018"
},
{
"code": null,
"e": 24409,
"s": 24307,
"text": "The header file graphics.h contains getbkcolor() function which returns the current background color."
},
{
"code": null,
"e": 24418,
"s": 24409,
"text": "Syntax :"
},
{
"code": null,
"e": 24437,
"s": 24418,
"text": "int getbkcolor();\n"
},
{
"code": null,
"e": 24571,
"s": 24437,
"text": "As getbkcolor() returns an integer value corresponding to the background color, so below is the table for Color values.Colors Table :"
},
{
"code": null,
"e": 25056,
"s": 24571,
"text": "COLOR INT VALUES\n-------------------------------\nBLACK 0\nBLUE 1\nGREEN 2\nCYAN 3 \nRED 4\nMAGENTA 5\nBROWN 6 \nLIGHTGRAY 7 \nDARKGRAY 8\nLIGHTBLUE 9\nLIGHTGREEN 10\nLIGHTCYAN 11\nLIGHTRED 12\nLIGHTMAGENTA 13\nYELLOW 14\nWHITE 15\n"
},
{
"code": null,
"e": 25092,
"s": 25056,
"text": "When the background color is black:"
},
{
"code": "// C Implementation for getbkcolor function#include <graphics.h>#include <stdio.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // \"graphics.h\" header file int gd = DETECT, gm; char arr[100]; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, \"\"); // sprintf stands for “String print”. // Instead of printing on console, it // store output on char buffer which // are specified in sprintf sprintf(arr, \"Current background color = %d\", getbkcolor()); // outtext function displays text // at current position. outtextxy(10, 10, arr); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0;}",
"e": 26065,
"s": 25092,
"text": null
},
{
"code": null,
"e": 26074,
"s": 26065,
"text": "Output :"
},
{
"code": null,
"e": 26123,
"s": 26076,
"text": "When the background color is other than black:"
},
{
"code": "// C Implementation for getbkcolor function#include <graphics.h>#include <stdio.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // \"graphics.h\" header file int gd = DETECT, gm; char arr[100]; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, \"\"); // set background color as RED setbkcolor(RED); // sprintf stands for “String print”. // Instead of printing on console, it // store output on char buffer which // are specified in sprintf sprintf(arr, \"Current background color = %d\", getbkcolor()); // outtext function displays text // at current position. outtextxy(10, 10, arr); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0;}",
"e": 27153,
"s": 26123,
"text": null
},
{
"code": null,
"e": 27162,
"s": 27153,
"text": "Output :"
},
{
"code": null,
"e": 27175,
"s": 27164,
"text": "c-graphics"
},
{
"code": null,
"e": 27193,
"s": 27175,
"text": "computer-graphics"
},
{
"code": null,
"e": 27204,
"s": 27193,
"text": "C Language"
},
{
"code": null,
"e": 27302,
"s": 27204,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27311,
"s": 27302,
"text": "Comments"
},
{
"code": null,
"e": 27324,
"s": 27311,
"text": "Old Comments"
},
{
"code": null,
"e": 27359,
"s": 27324,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 27387,
"s": 27359,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 27433,
"s": 27387,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 27445,
"s": 27433,
"text": "fork() in C"
},
{
"code": null,
"e": 27477,
"s": 27445,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 27517,
"s": 27477,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 27534,
"s": 27517,
"text": "Substring in C++"
},
{
"code": null,
"e": 27556,
"s": 27534,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 27594,
"s": 27556,
"text": "TCP Server-Client implementation in C"
}
] |
How to Create WhatsApp Stories View in Android? - GeeksforGeeks
|
21 Apr, 2021
Stories are now becoming one of the most seen features in many different apps such as WhatsApp, LinkedIn, Instagram, and many more. In this article, we will take a look at creating a similar type of view in our Android App.
We will be building a simple application in which we will be creating a stories view which we can get to see on WhatsApp. We will be adding some fixed images to it. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add dependency and JitPack Repository
Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section.
implementation ‘com.github.shts:StoriesProgressView:3.0.0’
Add the JitPack repository to your build file. Add it to your root build.gradle at the end of repositories inside the allprojects{ } section.
allprojects {
repositories {
...
maven { url “https://jitpack.io” }
}
}
After adding this dependency sync your project and now we will move towards its implementation.
Step 3: Updating the theme to NoActionBar in the themes.xml file
Navigate to app > res > values > themes.xml and inside that change the base application theme to NoActionBar. You can get to see the code for the themes.xml file below.
XML
<resources xmlns:tools="http://schemas.android.com/tools"> <!-- Base application theme. --> <style name="Theme.GFGParse" parent="Theme.MaterialComponents.DayNight.NoActionBar"> <!-- Primary brand color. --> <item name="colorPrimary">@color/purple_500</item> <item name="colorPrimaryVariant">@color/purple_700</item> <item name="colorOnPrimary">@color/white</item> <!-- Secondary brand color. --> <item name="colorSecondary">@color/teal_200</item> <item name="colorSecondaryVariant">@color/teal_700</item> <item name="colorOnSecondary">@color/black</item> <!--below is the text color--> <item name="android:textColor">@color/black</item> <!-- Status bar color. --> <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item> <!-- Customize your theme here. --> </style></resources>
Step 4: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/idRLBack" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <!--button for opening our stories activity--> <Button android:id="@+id/idBtnStories" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:onClick="ShowStories" android:text="Show Stories" /> </RelativeLayout>
Step 5: Creating a new activity for displaying stories
Navigate to the app > java > your app’s package name > Right-click on it > New > Activity and select as Empty Activity and name it as StoriesActivity and create a new activity.
Step 6: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.content.Intent;import android.os.Bundle;import android.view.View; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void ShowStories(View view) { // on below line we are opening a new activity using intent. Intent i = new Intent(MainActivity.this, StoriesActivity.class); startActivity(i); }}
Step 7: Working with the activity_stories.xml file
Navigate to the app > res > layout > activity_stories.xml and add the below code to that file. Below is the code for the activity_stories.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><!--we are using merge as a parent layout for merging all our views--><merge 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=".StoriesActivity"> <!--below is the image view where we will be displaying images in our stories--> <ImageView android:id="@+id/image" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/purple_200" android:contentDescription="@null" tools:src="@drawable/logo1" /> <!--on below line we are creating linear layout for our views--> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <!--view to handle move to previous image--> <View android:id="@+id/reverse" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" /> <!--view to move to the next image--> <View android:id="@+id/skip" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" /> </LinearLayout> <!--below widget is use to create indicator for our stories at top--> <jp.shts.android.storiesprogressview.StoriesProgressView android:id="@+id/stories" android:layout_width="match_parent" android:layout_height="3dp" android:layout_gravity="top" android:layout_marginTop="8dp" android:paddingLeft="8dp" android:paddingRight="8dp" /> </merge>
Step 8: Working with the StoriesActivity.java file
Go to the StoriesActivity.java file and refer to the following code. Below is the code for the StoriesActivity.java file. Comments are added inside the code to understand the code in more detail.
Note: Images are added in the drawable folder.
Java
import android.content.Intent;import android.os.Bundle;import android.view.MotionEvent;import android.view.View;import android.view.WindowManager;import android.widget.ImageView; import androidx.appcompat.app.AppCompatActivity; import jp.shts.android.storiesprogressview.StoriesProgressView; public class StoriesActivity extends AppCompatActivity implements StoriesProgressView.StoriesListener { // on below line we are creating a int array // in which we are storing all our image ids. private final int[] resources = new int[]{ R.drawable.logo1, R.drawable.logo2, R.drawable.logo1, R.drawable.logo2, R.drawable.logo1, R.drawable.logo2, }; // on below line we are creating variable for // our press time and time limit to display a story. long pressTime = 0L; long limit = 500L; // on below line we are creating variables for // our progress bar view and image view . private StoriesProgressView storiesProgressView; private ImageView image; // on below line we are creating a counter // for keeping count of our stories. private int counter = 0; // on below line we are creating a new method for adding touch listener private View.OnTouchListener onTouchListener = new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // inside on touch method we are // getting action on below line. switch (event.getAction()) { case MotionEvent.ACTION_DOWN: // on action down when we press our screen // the story will pause for specific time. pressTime = System.currentTimeMillis(); // on below line we are pausing our indicator. storiesProgressView.pause(); return false; case MotionEvent.ACTION_UP: // in action up case when user do not touches // screen this method will skip to next image. long now = System.currentTimeMillis(); // on below line we are resuming our progress bar for status. storiesProgressView.resume(); // on below line we are returning if the limit < now - presstime return limit < now - pressTime; } return false; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // inside in create method below line is use to make a full screen. getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_stories); // on below line we are initializing our variables. storiesProgressView = (StoriesProgressView) findViewById(R.id.stories); // on below line we are setting the total count for our stories. storiesProgressView.setStoriesCount(resources.length); // on below line we are setting story duration for each story. storiesProgressView.setStoryDuration(3000L); // on below line we are calling a method for set // on story listener and passing context to it. storiesProgressView.setStoriesListener(this); // below line is use to start stories progress bar. storiesProgressView.startStories(counter); // initializing our image view. image = (ImageView) findViewById(R.id.image); // on below line we are setting image to our image view. image.setImageResource(resources[counter]); // below is the view for going to the previous story. // initializing our previous view. View reverse = findViewById(R.id.reverse); // adding on click listener for our reverse view. reverse.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // inside on click we are // reversing our progress view. storiesProgressView.reverse(); } }); // on below line we are calling a set on touch // listener method to move towards previous image. reverse.setOnTouchListener(onTouchListener); // on below line we are initializing // view to skip a specific story. View skip = findViewById(R.id.skip); skip.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // inside on click we are // skipping the story progress view. storiesProgressView.skip(); } }); // on below line we are calling a set on touch // listener method to move to next story. skip.setOnTouchListener(onTouchListener); } @Override public void onNext() { // this method is called when we move // to next progress view of story. image.setImageResource(resources[++counter]); } @Override public void onPrev() { // this method id called when we move to previous story. // on below line we are decreasing our counter if ((counter - 1) < 0) return; // on below line we are setting image to image view image.setImageResource(resources[--counter]); } @Override public void onComplete() { // when the stories are completed this method is called. // in this method we are moving back to initial main activity. Intent i = new Intent(StoriesActivity.this, MainActivity.class); startActivity(i); finish(); } @Override protected void onDestroy() { // in on destroy method we are destroying // our stories progress view. storiesProgressView.destroy(); super.onDestroy(); }}
Now run your app and see the output of the app.
Output:
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java
|
[
{
"code": null,
"e": 26407,
"s": 26379,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 26632,
"s": 26407,
"text": "Stories are now becoming one of the most seen features in many different apps such as WhatsApp, LinkedIn, Instagram, and many more. In this article, we will take a look at creating a similar type of view in our Android App. "
},
{
"code": null,
"e": 26964,
"s": 26632,
"text": "We will be building a simple application in which we will be creating a stories view which we can get to see on WhatsApp. We will be adding some fixed images to it. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 26993,
"s": 26964,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 27155,
"s": 26993,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 27201,
"s": 27155,
"text": "Step 2: Add dependency and JitPack Repository"
},
{
"code": null,
"e": 27320,
"s": 27201,
"text": "Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. "
},
{
"code": null,
"e": 27379,
"s": 27320,
"text": "implementation ‘com.github.shts:StoriesProgressView:3.0.0’"
},
{
"code": null,
"e": 27521,
"s": 27379,
"text": "Add the JitPack repository to your build file. Add it to your root build.gradle at the end of repositories inside the allprojects{ } section."
},
{
"code": null,
"e": 27535,
"s": 27521,
"text": "allprojects {"
},
{
"code": null,
"e": 27551,
"s": 27535,
"text": " repositories {"
},
{
"code": null,
"e": 27558,
"s": 27551,
"text": " ..."
},
{
"code": null,
"e": 27596,
"s": 27558,
"text": " maven { url “https://jitpack.io” }"
},
{
"code": null,
"e": 27603,
"s": 27596,
"text": " }"
},
{
"code": null,
"e": 27605,
"s": 27603,
"text": "}"
},
{
"code": null,
"e": 27703,
"s": 27605,
"text": "After adding this dependency sync your project and now we will move towards its implementation. "
},
{
"code": null,
"e": 27768,
"s": 27703,
"text": "Step 3: Updating the theme to NoActionBar in the themes.xml file"
},
{
"code": null,
"e": 27938,
"s": 27768,
"text": "Navigate to app > res > values > themes.xml and inside that change the base application theme to NoActionBar. You can get to see the code for the themes.xml file below. "
},
{
"code": null,
"e": 27942,
"s": 27938,
"text": "XML"
},
{
"code": "<resources xmlns:tools=\"http://schemas.android.com/tools\"> <!-- Base application theme. --> <style name=\"Theme.GFGParse\" parent=\"Theme.MaterialComponents.DayNight.NoActionBar\"> <!-- Primary brand color. --> <item name=\"colorPrimary\">@color/purple_500</item> <item name=\"colorPrimaryVariant\">@color/purple_700</item> <item name=\"colorOnPrimary\">@color/white</item> <!-- Secondary brand color. --> <item name=\"colorSecondary\">@color/teal_200</item> <item name=\"colorSecondaryVariant\">@color/teal_700</item> <item name=\"colorOnSecondary\">@color/black</item> <!--below is the text color--> <item name=\"android:textColor\">@color/black</item> <!-- Status bar color. --> <item name=\"android:statusBarColor\" tools:targetApi=\"l\">?attr/colorPrimaryVariant</item> <!-- Customize your theme here. --> </style></resources>",
"e": 28852,
"s": 27942,
"text": null
},
{
"code": null,
"e": 28900,
"s": 28852,
"text": "Step 4: Working with the activity_main.xml file"
},
{
"code": null,
"e": 29043,
"s": 28900,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 29047,
"s": 29043,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/idRLBack\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <!--button for opening our stories activity--> <Button android:id=\"@+id/idBtnStories\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:onClick=\"ShowStories\" android:text=\"Show Stories\" /> </RelativeLayout>",
"e": 29717,
"s": 29047,
"text": null
},
{
"code": null,
"e": 29773,
"s": 29717,
"text": "Step 5: Creating a new activity for displaying stories "
},
{
"code": null,
"e": 29951,
"s": 29773,
"text": "Navigate to the app > java > your app’s package name > Right-click on it > New > Activity and select as Empty Activity and name it as StoriesActivity and create a new activity. "
},
{
"code": null,
"e": 29999,
"s": 29951,
"text": "Step 6: Working with the MainActivity.java file"
},
{
"code": null,
"e": 30189,
"s": 29999,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 30194,
"s": 30189,
"text": "Java"
},
{
"code": "import android.content.Intent;import android.os.Bundle;import android.view.View; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void ShowStories(View view) { // on below line we are opening a new activity using intent. Intent i = new Intent(MainActivity.this, StoriesActivity.class); startActivity(i); }}",
"e": 30763,
"s": 30194,
"text": null
},
{
"code": null,
"e": 30814,
"s": 30763,
"text": "Step 7: Working with the activity_stories.xml file"
},
{
"code": null,
"e": 30963,
"s": 30814,
"text": "Navigate to the app > res > layout > activity_stories.xml and add the below code to that file. Below is the code for the activity_stories.xml file. "
},
{
"code": null,
"e": 30967,
"s": 30963,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><!--we are using merge as a parent layout for merging all our views--><merge 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=\".StoriesActivity\"> <!--below is the image view where we will be displaying images in our stories--> <ImageView android:id=\"@+id/image\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"@color/purple_200\" android:contentDescription=\"@null\" tools:src=\"@drawable/logo1\" /> <!--on below line we are creating linear layout for our views--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"horizontal\"> <!--view to handle move to previous image--> <View android:id=\"@+id/reverse\" android:layout_width=\"0dp\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" /> <!--view to move to the next image--> <View android:id=\"@+id/skip\" android:layout_width=\"0dp\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" /> </LinearLayout> <!--below widget is use to create indicator for our stories at top--> <jp.shts.android.storiesprogressview.StoriesProgressView android:id=\"@+id/stories\" android:layout_width=\"match_parent\" android:layout_height=\"3dp\" android:layout_gravity=\"top\" android:layout_marginTop=\"8dp\" android:paddingLeft=\"8dp\" android:paddingRight=\"8dp\" /> </merge>",
"e": 32776,
"s": 30967,
"text": null
},
{
"code": null,
"e": 32827,
"s": 32776,
"text": "Step 8: Working with the StoriesActivity.java file"
},
{
"code": null,
"e": 33023,
"s": 32827,
"text": "Go to the StoriesActivity.java file and refer to the following code. Below is the code for the StoriesActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 33071,
"s": 33023,
"text": "Note: Images are added in the drawable folder. "
},
{
"code": null,
"e": 33076,
"s": 33071,
"text": "Java"
},
{
"code": "import android.content.Intent;import android.os.Bundle;import android.view.MotionEvent;import android.view.View;import android.view.WindowManager;import android.widget.ImageView; import androidx.appcompat.app.AppCompatActivity; import jp.shts.android.storiesprogressview.StoriesProgressView; public class StoriesActivity extends AppCompatActivity implements StoriesProgressView.StoriesListener { // on below line we are creating a int array // in which we are storing all our image ids. private final int[] resources = new int[]{ R.drawable.logo1, R.drawable.logo2, R.drawable.logo1, R.drawable.logo2, R.drawable.logo1, R.drawable.logo2, }; // on below line we are creating variable for // our press time and time limit to display a story. long pressTime = 0L; long limit = 500L; // on below line we are creating variables for // our progress bar view and image view . private StoriesProgressView storiesProgressView; private ImageView image; // on below line we are creating a counter // for keeping count of our stories. private int counter = 0; // on below line we are creating a new method for adding touch listener private View.OnTouchListener onTouchListener = new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // inside on touch method we are // getting action on below line. switch (event.getAction()) { case MotionEvent.ACTION_DOWN: // on action down when we press our screen // the story will pause for specific time. pressTime = System.currentTimeMillis(); // on below line we are pausing our indicator. storiesProgressView.pause(); return false; case MotionEvent.ACTION_UP: // in action up case when user do not touches // screen this method will skip to next image. long now = System.currentTimeMillis(); // on below line we are resuming our progress bar for status. storiesProgressView.resume(); // on below line we are returning if the limit < now - presstime return limit < now - pressTime; } return false; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // inside in create method below line is use to make a full screen. getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_stories); // on below line we are initializing our variables. storiesProgressView = (StoriesProgressView) findViewById(R.id.stories); // on below line we are setting the total count for our stories. storiesProgressView.setStoriesCount(resources.length); // on below line we are setting story duration for each story. storiesProgressView.setStoryDuration(3000L); // on below line we are calling a method for set // on story listener and passing context to it. storiesProgressView.setStoriesListener(this); // below line is use to start stories progress bar. storiesProgressView.startStories(counter); // initializing our image view. image = (ImageView) findViewById(R.id.image); // on below line we are setting image to our image view. image.setImageResource(resources[counter]); // below is the view for going to the previous story. // initializing our previous view. View reverse = findViewById(R.id.reverse); // adding on click listener for our reverse view. reverse.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // inside on click we are // reversing our progress view. storiesProgressView.reverse(); } }); // on below line we are calling a set on touch // listener method to move towards previous image. reverse.setOnTouchListener(onTouchListener); // on below line we are initializing // view to skip a specific story. View skip = findViewById(R.id.skip); skip.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // inside on click we are // skipping the story progress view. storiesProgressView.skip(); } }); // on below line we are calling a set on touch // listener method to move to next story. skip.setOnTouchListener(onTouchListener); } @Override public void onNext() { // this method is called when we move // to next progress view of story. image.setImageResource(resources[++counter]); } @Override public void onPrev() { // this method id called when we move to previous story. // on below line we are decreasing our counter if ((counter - 1) < 0) return; // on below line we are setting image to image view image.setImageResource(resources[--counter]); } @Override public void onComplete() { // when the stories are completed this method is called. // in this method we are moving back to initial main activity. Intent i = new Intent(StoriesActivity.this, MainActivity.class); startActivity(i); finish(); } @Override protected void onDestroy() { // in on destroy method we are destroying // our stories progress view. storiesProgressView.destroy(); super.onDestroy(); }}",
"e": 39091,
"s": 33076,
"text": null
},
{
"code": null,
"e": 39140,
"s": 39091,
"text": "Now run your app and see the output of the app. "
},
{
"code": null,
"e": 39149,
"s": 39140,
"text": "Output: "
},
{
"code": null,
"e": 39157,
"s": 39149,
"text": "Android"
},
{
"code": null,
"e": 39162,
"s": 39157,
"text": "Java"
},
{
"code": null,
"e": 39167,
"s": 39162,
"text": "Java"
},
{
"code": null,
"e": 39175,
"s": 39167,
"text": "Android"
},
{
"code": null,
"e": 39273,
"s": 39175,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39311,
"s": 39273,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 39350,
"s": 39311,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 39400,
"s": 39350,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 39442,
"s": 39400,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 39493,
"s": 39442,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 39508,
"s": 39493,
"text": "Arrays in Java"
},
{
"code": null,
"e": 39552,
"s": 39508,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 39574,
"s": 39552,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 39625,
"s": 39574,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
Compare two floating-point numbers given in Scientific Notations - GeeksforGeeks
|
21 Feb, 2022
Given two strings N and M in the form of a * 10 b. The task is to compare given two floating-point numbers and print the smaller number and if both the numbers are equal then print Equal.
0<|a|<10^9 and -10^9<b<10^9.
Example:
N and M are two numbers with two parts:
a1 is mantissa of N and a2 is mantissa of M.b1 is exponent of N and b2 is exponent of M.
a1 is mantissa of N and a2 is mantissa of M.
b1 is exponent of N and b2 is exponent of M.
Input: N = 3*10^2, M = 299*10^0Output: MExplanation: a1 = 3, b1 = 2a2 = 299, b2 = 0N = 3*10^2 = 300 M = 299*10^0 = 299. We know that 299 is smaller than 300.
Input: N = -5*10^3, M = -50*10^2Output : Equal Explanation: a1 = -5, b1 = 3a2 = -50, b2 = 2N = -5*10^3 = -5000M = -50*10^2 = -5000Hence, N and M are equal.
Input: N = -2*10^1, M = -3*10^1Output: MExplanation:a1 = -2 , b1 = 1a2 = -3 , b2 = 1N = -20M = -30-30 is less than -20, hence M is smaller number.
Naive Approach: We will calculate the values of numbers extracted from strings N and M and then compare which one is better. The bigInteger class will be used for storing and calculating the value of N and M in Java. This approach can give Time Limit Exceeded error for larger test cases.
Optimal Approach:
Extract mantissa and exponents from both the strings N and M.
Find the index of ‘*’ ( let say mulInd), then substring before mulInd will be mantissa(a1).
Find the index of ‘^’, let say powInd, then substring after powInd will be exponent(b1).
Similarly, find out a2 and b2.
if(a1 > 0 && a2 < 0), print M ( M will always be smaller).
Similarly, if (a2 > 0 && a1 < 0), print N.
else there will be need to use log to compare.
The following formula will be used to calculate the log and arrive at a result that will be compared to determine which number is larger.
N = a1 * 10 ^ b1
Taking log base 10 both side
log N = log(a1) + b1 ———-(1)
Similarly, log(M) = log(a2) + b2 ———(2)
Subtract equation (1) from equation (2) ans = (2) – (1) ans = log(a1/a2) + b1 – b2
Therefore: int ans = log(a1/a2) + b1 – b2
if a1 < 0, then ans = -ans. This is because both a1 and a2 are both negative.if ans < 0, print N.else if ans > 0, print M.
if ans < 0, print N.
else if ans > 0, print M.
else print Equal.
Below is the Jave program to implement the above approach:
Java
Python3
C#
// Java program to implement// the above approachimport java.io.*;import java.util.*;import java.math.*;import java.lang.*; class GFG{ // Function to extract mantissa static int[] extract_mantissa(String N, String M) { int mantissa[] = new int [2]; int mulInd1 = N.indexOf('*'); int a1 = Integer.parseInt( N.substring(0, mulInd1)); mantissa[0] = a1; int mulInd2 = M.indexOf('*'); int a2 = Integer.parseInt( M.substring(0, mulInd2)); mantissa[1] = a2; return mantissa; } // Function to extract exponent static int[] extract_exponent(String N, String M) { int exponent[] = new int [2]; int powInd1 = N.indexOf('^'); int b1 = Integer.parseInt( N.substring(powInd1 + 1)); exponent[0] = b1; int powInd2 = M.indexOf('^'); int b2 = Integer.parseInt( M.substring(powInd2 + 1)); exponent[1] = b2; return exponent; } // Function to find smaller number static void solution(int a1, int b1, int a2, int b2) { double x = ((double)(a1) / (double)(a2)); double ans = (b1 - b2 + Math.log10(x)); // If both are negative if(a1 < 0) ans = -ans; if(ans < 0) System.out.println("N"); else if(ans > 0) System.out.println("M"); else System.out.println("Equal"); } static void solve(String N, String M) { // Extract mantissa(a1) and mantissa(a2) // from num1 and num2 int mantissa[] = extract_mantissa(N, M); // Extract exponent(b1) and exponent(b2) // from num1 and num2 int exponent[] = extract_exponent(N, M); if(mantissa[0] > 0 && mantissa[1] < 0) System.out.println("M"); else if(mantissa[0] < 0 && mantissa[1] > 0) System.out.println("N"); else { // if mantissa of both num1 and num2 // are positive or both are negative solution(mantissa[0], exponent[0], mantissa[1], exponent[1]); } } // Driver code public static void main (String[] args) { // Mantissa is negative and // exponent is positive String N = "-5*10^3"; String M = "-50*10^2"; solve(N, M); // Mantissa is negative and // exponent is negative N = "-5*10^-3"; M = "-50*10^-2"; solve(N, M); // Mantissa is positive and // exponent is negative N = "5*10^-3"; M = "50*10^-2"; solve(N, M); // Mantissa is positive and // exponent is positive N = "5*10^3"; M = "50*10^2"; solve(N, M); }}
# Python 3 program to implement# the above approachimport math # Function to extract mantissadef extract_mantissa(N, M): mantissa = [0]*2 mulInd1 = list(N).index('*') a1 = N[0: mulInd1] mantissa[0] = a1 mulInd2 = list(M).index('*') a2 = M[0: mulInd2] mantissa[1] = a2 return mantissa # Function to extract exponentdef extract_exponent(N, M): exponent = [0]*2 powInd1 = list(N).index('^') b1 = N[powInd1 + 1:] exponent[0] = b1 powInd2 = list(M).index('^') b2 = M[powInd2 + 1:] exponent[1] = b2 return exponent # Function to find smaller numberdef solution(a1, b1, a2, b2): x = int(a1) / int(a2) ans = (int(b1) - int(b2) + math.log10(x)) # If both are negative if(int(a1) < 0): ans = -ans if(ans < 0): print("N") elif(ans > 0): print("M") else: print("Equal") def solve(N, M): # Extract mantissa(a1) and mantissa(a2) # from num1 and num2 mantissa = extract_mantissa(N, M) # Extract exponent(b1) and exponent(b2) # from num1 and num2 exponent = extract_exponent(N, M) if(int(mantissa[0]) > 0 and int(mantissa[1]) < 0): print("M") elif(int(mantissa[0]) < 0 and int(mantissa[1]) > 0): print("N") else: # if mantissa of both num1 and num2 # are positive or both are negative solution(mantissa[0], exponent[0], mantissa[1], exponent[1]) # Driver codeif __name__ == "__main__": # Mantissa is negative and # exponent is positive N = "-5*10^3" M = "-50*10^2" solve(N, M) # Mantissa is negative and # exponent is negative N = "-5*10^-3" M = "-50*10^-2" solve(N, M) # Mantissa is positive and # exponent is negative N = "5*10^-3" M = "50*10^-2" solve(N, M) # Mantissa is positive and # exponent is positive N = "5*10^3" M = "50*10^2" solve(N, M) # This code is contributed by ukasp.
// C# program to implement// the above approachusing System; class GFG{ // Function to extract mantissa public static int[] extract_mantissa(String N, String M) { int[] mantissa = new int [2]; int mulInd1 = N.IndexOf('*'); int a1 = int.Parse(N.Substring(0, mulInd1)); mantissa[0] = a1; int mulInd2 = M.IndexOf('*'); int a2 = int.Parse(M.Substring(0, mulInd2)); mantissa[1] = a2; return mantissa; } // Function to extract exponent public static int[] extract_exponent(String N, String M) { int[] exponent = new int [2]; int powInd1 = N.IndexOf('^'); int b1 = int.Parse(N.Substring(powInd1 + 1)); exponent[0] = b1; int powInd2 = M.IndexOf('^'); int b2 = int.Parse( M.Substring(powInd2 + 1)); exponent[1] = b2; return exponent; } // Function to find smaller number static void solution(int a1, int b1, int a2, int b2) { double x = ((double)(a1) / (double)(a2)); double ans = (b1 - b2 + Math.Log10(x)); // If both are negative if(a1 < 0) ans = -ans; if(ans < 0) Console.WriteLine("N"); else if(ans > 0) Console.WriteLine("M"); else Console.WriteLine("Equal"); } static void solve(String N, String M) { // Extract mantissa(a1) and mantissa(a2) // from num1 and num2 int[] mantissa = extract_mantissa(N, M); // Extract exponent(b1) and exponent(b2) // from num1 and num2 int[] exponent = extract_exponent(N, M); if(mantissa[0] > 0 && mantissa[1] < 0) Console.WriteLine("M"); else if(mantissa[0] < 0 && mantissa[1] > 0) Console.WriteLine("N"); else { // if mantissa of both num1 and num2 // are positive or both are negative solution(mantissa[0], exponent[0], mantissa[1], exponent[1]); } } // Driver code public static void Main () { // Mantissa is negative and // exponent is positive String N = "-5*10^3"; String M = "-50*10^2"; solve(N, M); // Mantissa is negative and // exponent is negative N = "-5*10^-3"; M = "-50*10^-2"; solve(N, M); // Mantissa is positive and // exponent is negative N = "5*10^-3"; M = "50*10^-2"; solve(N, M); // Mantissa is positive and // exponent is positive N = "5*10^3"; M = "50*10^2"; solve(N, M); }} // This code is contributed by saurabh_jaiswal.
Output:
EqualMNEqual
Time Complexity: O ( 1 ) According to the given constraints |a| can be of a maximum of 10 lengths of string and if it is negative, then it could be of 11 lengths, similarly b can also be of 11 digits. The maximum length of string could be 25 (11 +3+11), so we can consider extracting a and b of constant time operation.
Auxiliary Space: O ( 1 )
_saurabh_jaiswal
ukasp
kk9826225
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Modular multiplicative inverse
Fizz Buzz Implementation
Check if a number is Palindrome
Segment Tree | Set 1 (Sum of given range)
Generate all permutation of a set in Python
How to check if a given point lies inside or outside a polygon?
Merge two sorted arrays with O(1) extra space
Singular Value Decomposition (SVD)
Program to multiply two matrices
|
[
{
"code": null,
"e": 26071,
"s": 26043,
"text": "\n21 Feb, 2022"
},
{
"code": null,
"e": 26260,
"s": 26071,
"text": "Given two strings N and M in the form of a * 10 b. The task is to compare given two floating-point numbers and print the smaller number and if both the numbers are equal then print Equal. "
},
{
"code": null,
"e": 26292,
"s": 26260,
"text": " 0<|a|<10^9 and -10^9<b<10^9."
},
{
"code": null,
"e": 26301,
"s": 26292,
"text": "Example:"
},
{
"code": null,
"e": 26341,
"s": 26301,
"text": "N and M are two numbers with two parts:"
},
{
"code": null,
"e": 26430,
"s": 26341,
"text": "a1 is mantissa of N and a2 is mantissa of M.b1 is exponent of N and b2 is exponent of M."
},
{
"code": null,
"e": 26475,
"s": 26430,
"text": "a1 is mantissa of N and a2 is mantissa of M."
},
{
"code": null,
"e": 26520,
"s": 26475,
"text": "b1 is exponent of N and b2 is exponent of M."
},
{
"code": null,
"e": 26678,
"s": 26520,
"text": "Input: N = 3*10^2, M = 299*10^0Output: MExplanation: a1 = 3, b1 = 2a2 = 299, b2 = 0N = 3*10^2 = 300 M = 299*10^0 = 299. We know that 299 is smaller than 300."
},
{
"code": null,
"e": 26836,
"s": 26678,
"text": "Input: N = -5*10^3, M = -50*10^2Output : Equal Explanation: a1 = -5, b1 = 3a2 = -50, b2 = 2N = -5*10^3 = -5000M = -50*10^2 = -5000Hence, N and M are equal."
},
{
"code": null,
"e": 26984,
"s": 26836,
"text": "Input: N = -2*10^1, M = -3*10^1Output: MExplanation:a1 = -2 , b1 = 1a2 = -3 , b2 = 1N = -20M = -30-30 is less than -20, hence M is smaller number."
},
{
"code": null,
"e": 27273,
"s": 26984,
"text": "Naive Approach: We will calculate the values of numbers extracted from strings N and M and then compare which one is better. The bigInteger class will be used for storing and calculating the value of N and M in Java. This approach can give Time Limit Exceeded error for larger test cases."
},
{
"code": null,
"e": 27293,
"s": 27273,
"text": "Optimal Approach: "
},
{
"code": null,
"e": 27355,
"s": 27293,
"text": "Extract mantissa and exponents from both the strings N and M."
},
{
"code": null,
"e": 27447,
"s": 27355,
"text": "Find the index of ‘*’ ( let say mulInd), then substring before mulInd will be mantissa(a1)."
},
{
"code": null,
"e": 27536,
"s": 27447,
"text": "Find the index of ‘^’, let say powInd, then substring after powInd will be exponent(b1)."
},
{
"code": null,
"e": 27567,
"s": 27536,
"text": "Similarly, find out a2 and b2."
},
{
"code": null,
"e": 27626,
"s": 27567,
"text": "if(a1 > 0 && a2 < 0), print M ( M will always be smaller)."
},
{
"code": null,
"e": 27669,
"s": 27626,
"text": "Similarly, if (a2 > 0 && a1 < 0), print N."
},
{
"code": null,
"e": 27716,
"s": 27669,
"text": "else there will be need to use log to compare."
},
{
"code": null,
"e": 27856,
"s": 27716,
"text": "The following formula will be used to calculate the log and arrive at a result that will be compared to determine which number is larger. "
},
{
"code": null,
"e": 27873,
"s": 27856,
"text": "N = a1 * 10 ^ b1"
},
{
"code": null,
"e": 27902,
"s": 27873,
"text": "Taking log base 10 both side"
},
{
"code": null,
"e": 27946,
"s": 27902,
"text": "log N = log(a1) + b1 ———-(1)"
},
{
"code": null,
"e": 27986,
"s": 27946,
"text": "Similarly, log(M) = log(a2) + b2 ———(2)"
},
{
"code": null,
"e": 28077,
"s": 27986,
"text": "Subtract equation (1) from equation (2) ans = (2) – (1) ans = log(a1/a2) + b1 – b2"
},
{
"code": null,
"e": 28119,
"s": 28077,
"text": "Therefore: int ans = log(a1/a2) + b1 – b2"
},
{
"code": null,
"e": 28243,
"s": 28119,
"text": "if a1 < 0, then ans = -ans. This is because both a1 and a2 are both negative.if ans < 0, print N.else if ans > 0, print M."
},
{
"code": null,
"e": 28264,
"s": 28243,
"text": "if ans < 0, print N."
},
{
"code": null,
"e": 28290,
"s": 28264,
"text": "else if ans > 0, print M."
},
{
"code": null,
"e": 28308,
"s": 28290,
"text": "else print Equal."
},
{
"code": null,
"e": 28367,
"s": 28308,
"text": "Below is the Jave program to implement the above approach:"
},
{
"code": null,
"e": 28372,
"s": 28367,
"text": "Java"
},
{
"code": null,
"e": 28380,
"s": 28372,
"text": "Python3"
},
{
"code": null,
"e": 28383,
"s": 28380,
"text": "C#"
},
{
"code": "// Java program to implement// the above approachimport java.io.*;import java.util.*;import java.math.*;import java.lang.*; class GFG{ // Function to extract mantissa static int[] extract_mantissa(String N, String M) { int mantissa[] = new int [2]; int mulInd1 = N.indexOf('*'); int a1 = Integer.parseInt( N.substring(0, mulInd1)); mantissa[0] = a1; int mulInd2 = M.indexOf('*'); int a2 = Integer.parseInt( M.substring(0, mulInd2)); mantissa[1] = a2; return mantissa; } // Function to extract exponent static int[] extract_exponent(String N, String M) { int exponent[] = new int [2]; int powInd1 = N.indexOf('^'); int b1 = Integer.parseInt( N.substring(powInd1 + 1)); exponent[0] = b1; int powInd2 = M.indexOf('^'); int b2 = Integer.parseInt( M.substring(powInd2 + 1)); exponent[1] = b2; return exponent; } // Function to find smaller number static void solution(int a1, int b1, int a2, int b2) { double x = ((double)(a1) / (double)(a2)); double ans = (b1 - b2 + Math.log10(x)); // If both are negative if(a1 < 0) ans = -ans; if(ans < 0) System.out.println(\"N\"); else if(ans > 0) System.out.println(\"M\"); else System.out.println(\"Equal\"); } static void solve(String N, String M) { // Extract mantissa(a1) and mantissa(a2) // from num1 and num2 int mantissa[] = extract_mantissa(N, M); // Extract exponent(b1) and exponent(b2) // from num1 and num2 int exponent[] = extract_exponent(N, M); if(mantissa[0] > 0 && mantissa[1] < 0) System.out.println(\"M\"); else if(mantissa[0] < 0 && mantissa[1] > 0) System.out.println(\"N\"); else { // if mantissa of both num1 and num2 // are positive or both are negative solution(mantissa[0], exponent[0], mantissa[1], exponent[1]); } } // Driver code public static void main (String[] args) { // Mantissa is negative and // exponent is positive String N = \"-5*10^3\"; String M = \"-50*10^2\"; solve(N, M); // Mantissa is negative and // exponent is negative N = \"-5*10^-3\"; M = \"-50*10^-2\"; solve(N, M); // Mantissa is positive and // exponent is negative N = \"5*10^-3\"; M = \"50*10^-2\"; solve(N, M); // Mantissa is positive and // exponent is positive N = \"5*10^3\"; M = \"50*10^2\"; solve(N, M); }}",
"e": 30981,
"s": 28383,
"text": null
},
{
"code": "# Python 3 program to implement# the above approachimport math # Function to extract mantissadef extract_mantissa(N, M): mantissa = [0]*2 mulInd1 = list(N).index('*') a1 = N[0: mulInd1] mantissa[0] = a1 mulInd2 = list(M).index('*') a2 = M[0: mulInd2] mantissa[1] = a2 return mantissa # Function to extract exponentdef extract_exponent(N, M): exponent = [0]*2 powInd1 = list(N).index('^') b1 = N[powInd1 + 1:] exponent[0] = b1 powInd2 = list(M).index('^') b2 = M[powInd2 + 1:] exponent[1] = b2 return exponent # Function to find smaller numberdef solution(a1, b1, a2, b2): x = int(a1) / int(a2) ans = (int(b1) - int(b2) + math.log10(x)) # If both are negative if(int(a1) < 0): ans = -ans if(ans < 0): print(\"N\") elif(ans > 0): print(\"M\") else: print(\"Equal\") def solve(N, M): # Extract mantissa(a1) and mantissa(a2) # from num1 and num2 mantissa = extract_mantissa(N, M) # Extract exponent(b1) and exponent(b2) # from num1 and num2 exponent = extract_exponent(N, M) if(int(mantissa[0]) > 0 and int(mantissa[1]) < 0): print(\"M\") elif(int(mantissa[0]) < 0 and int(mantissa[1]) > 0): print(\"N\") else: # if mantissa of both num1 and num2 # are positive or both are negative solution(mantissa[0], exponent[0], mantissa[1], exponent[1]) # Driver codeif __name__ == \"__main__\": # Mantissa is negative and # exponent is positive N = \"-5*10^3\" M = \"-50*10^2\" solve(N, M) # Mantissa is negative and # exponent is negative N = \"-5*10^-3\" M = \"-50*10^-2\" solve(N, M) # Mantissa is positive and # exponent is negative N = \"5*10^-3\" M = \"50*10^-2\" solve(N, M) # Mantissa is positive and # exponent is positive N = \"5*10^3\" M = \"50*10^2\" solve(N, M) # This code is contributed by ukasp.",
"e": 32922,
"s": 30981,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System; class GFG{ // Function to extract mantissa public static int[] extract_mantissa(String N, String M) { int[] mantissa = new int [2]; int mulInd1 = N.IndexOf('*'); int a1 = int.Parse(N.Substring(0, mulInd1)); mantissa[0] = a1; int mulInd2 = M.IndexOf('*'); int a2 = int.Parse(M.Substring(0, mulInd2)); mantissa[1] = a2; return mantissa; } // Function to extract exponent public static int[] extract_exponent(String N, String M) { int[] exponent = new int [2]; int powInd1 = N.IndexOf('^'); int b1 = int.Parse(N.Substring(powInd1 + 1)); exponent[0] = b1; int powInd2 = M.IndexOf('^'); int b2 = int.Parse( M.Substring(powInd2 + 1)); exponent[1] = b2; return exponent; } // Function to find smaller number static void solution(int a1, int b1, int a2, int b2) { double x = ((double)(a1) / (double)(a2)); double ans = (b1 - b2 + Math.Log10(x)); // If both are negative if(a1 < 0) ans = -ans; if(ans < 0) Console.WriteLine(\"N\"); else if(ans > 0) Console.WriteLine(\"M\"); else Console.WriteLine(\"Equal\"); } static void solve(String N, String M) { // Extract mantissa(a1) and mantissa(a2) // from num1 and num2 int[] mantissa = extract_mantissa(N, M); // Extract exponent(b1) and exponent(b2) // from num1 and num2 int[] exponent = extract_exponent(N, M); if(mantissa[0] > 0 && mantissa[1] < 0) Console.WriteLine(\"M\"); else if(mantissa[0] < 0 && mantissa[1] > 0) Console.WriteLine(\"N\"); else { // if mantissa of both num1 and num2 // are positive or both are negative solution(mantissa[0], exponent[0], mantissa[1], exponent[1]); } } // Driver code public static void Main () { // Mantissa is negative and // exponent is positive String N = \"-5*10^3\"; String M = \"-50*10^2\"; solve(N, M); // Mantissa is negative and // exponent is negative N = \"-5*10^-3\"; M = \"-50*10^-2\"; solve(N, M); // Mantissa is positive and // exponent is negative N = \"5*10^-3\"; M = \"50*10^-2\"; solve(N, M); // Mantissa is positive and // exponent is positive N = \"5*10^3\"; M = \"50*10^2\"; solve(N, M); }} // This code is contributed by saurabh_jaiswal.",
"e": 35373,
"s": 32922,
"text": null
},
{
"code": null,
"e": 35381,
"s": 35373,
"text": "Output:"
},
{
"code": null,
"e": 35394,
"s": 35381,
"text": "EqualMNEqual"
},
{
"code": null,
"e": 35887,
"s": 35394,
"text": "Time Complexity: O ( 1 ) According to the given constraints |a| can be of a maximum of 10 lengths of string and if it is negative, then it could be of 11 lengths, similarly b can also be of 11 digits. The maximum length of string could be 25 (11 +3+11), so we can consider extracting a and b of constant time operation."
},
{
"code": null,
"e": 35912,
"s": 35887,
"text": "Auxiliary Space: O ( 1 )"
},
{
"code": null,
"e": 35929,
"s": 35912,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 35935,
"s": 35929,
"text": "ukasp"
},
{
"code": null,
"e": 35945,
"s": 35935,
"text": "kk9826225"
},
{
"code": null,
"e": 35958,
"s": 35945,
"text": "Mathematical"
},
{
"code": null,
"e": 35971,
"s": 35958,
"text": "Mathematical"
},
{
"code": null,
"e": 36069,
"s": 35971,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36113,
"s": 36069,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 36144,
"s": 36113,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 36169,
"s": 36144,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 36201,
"s": 36169,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 36243,
"s": 36201,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 36287,
"s": 36243,
"text": "Generate all permutation of a set in Python"
},
{
"code": null,
"e": 36351,
"s": 36287,
"text": "How to check if a given point lies inside or outside a polygon?"
},
{
"code": null,
"e": 36397,
"s": 36351,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 36432,
"s": 36397,
"text": "Singular Value Decomposition (SVD)"
}
] |
Check if three consecutive elements in an array is identical in JavaScript
|
We are required to write a JavaScript function, say checkThree() that takes in an array and
returns true if anywhere in the array there exists three consecutive elements that are identical
(i.e., have the same value) otherwise it returns false.
Therefore, let’s write the code for this function −
const arr = ["g", "z", "z", "v" ,"b", "b", "b"];
const checkThree = arr => {
const prev = {
element: null,
count: 0
};
for(let i = 0; i < arr.length; i++){
const { count, element } = prev;
if(count === 2 && element === arr[i]){
return true;
};
prev.count = element === arr[i] ? count + 1 : count;
prev.element = arr[i];
};
return false;
};
console.log(checkThree(arr));
console.log(checkThree(["z", "g", "z", "z"]));
The output in the console will be −
true
false
|
[
{
"code": null,
"e": 1307,
"s": 1062,
"text": "We are required to write a JavaScript function, say checkThree() that takes in an array and\nreturns true if anywhere in the array there exists three consecutive elements that are identical\n(i.e., have the same value) otherwise it returns false."
},
{
"code": null,
"e": 1359,
"s": 1307,
"text": "Therefore, let’s write the code for this function −"
},
{
"code": null,
"e": 1842,
"s": 1359,
"text": "const arr = [\"g\", \"z\", \"z\", \"v\" ,\"b\", \"b\", \"b\"];\nconst checkThree = arr => {\n const prev = {\n element: null,\n count: 0\n };\n for(let i = 0; i < arr.length; i++){\n const { count, element } = prev;\n if(count === 2 && element === arr[i]){\n return true;\n };\n prev.count = element === arr[i] ? count + 1 : count;\n prev.element = arr[i];\n };\n return false;\n};\nconsole.log(checkThree(arr));\nconsole.log(checkThree([\"z\", \"g\", \"z\", \"z\"]));"
},
{
"code": null,
"e": 1878,
"s": 1842,
"text": "The output in the console will be −"
},
{
"code": null,
"e": 1889,
"s": 1878,
"text": "true\nfalse"
}
] |
CSS | stroke-miterlimit Property - GeeksforGeeks
|
23 Jan, 2020
The stroke-miterlimit property is used to represent the limit on the ratio of the miter length to the stroke-width, that is used to draw a miter join. This property is used in situations when the miter extends beyond the thickness of the line. If this limit specified is exceeded, the ‘miter’ type of the join is converted to ‘bevel’.
This will crop the connecting point perpendicular to the join, instead of a sharp join.
Syntax:
stroke-miterlimit: number|initial|inherit
Property Values:
number: It is used to define the ratio limit. It can be any value greater than or equal to 1. The default value is 4.Example 1:<!DOCTYPE html><html> <head> <title> CSS | stroke-miterlimit property </title> <style> rect { stroke-linejoin: miter; stroke-width: 20px; stroke: green; fill: none; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | stroke-miterlimit </b> <p> Each angle of the square is of 90 degrees. Increasing the miterlimit progressively converts the miter joints to bevel ones. </p> <div class="container"> <svg width="500px" height="200px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <rect x="50" y="20" width="100" height="100" stroke-miterlimit=1 /> <text x="40" y="150"> stroke-miterlimit: 1 </text> <rect x="250" y="20" width="100" height="100" stroke-miterlimit=2 /> <text x="240" y="150"> stroke-miterlimit: 2 </text> </svg> </div></body> </html>Output:Example 2:<!DOCTYPE html><html> <head> <title> CSS | stroke-miterlimit property </title> <style> polygon { stroke-linejoin: miter; stroke-width: 8px; stroke: green; fill: none; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | stroke-miterlimit </b> <p> Each of the triangles have two angles equal to 24 degrees and one angle equal to 130 degrees. Increasing the miterlimit progressively converts the miter joints to bevel ones. </p> <div class="container"> <svg width="500px" height="200px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <polygon points="20, 20 150, 20 85, 80" stroke-miterlimit=1 /> <text x="30" y="100"> stroke-miterlimit: 1 </text> <polygon points="170, 20 300, 20 235, 80" stroke-miterlimit=2 /> <text x="180" y="100"> stroke-miterlimit: 2 </text> <polygon points="320, 20 450, 20 385, 80" stroke-miterlimit=3 /> <text x="330" y="100"> stroke-miterlimit: 3 </text> </svg> </div></body> </html>Output:
Example 1:
<!DOCTYPE html><html> <head> <title> CSS | stroke-miterlimit property </title> <style> rect { stroke-linejoin: miter; stroke-width: 20px; stroke: green; fill: none; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | stroke-miterlimit </b> <p> Each angle of the square is of 90 degrees. Increasing the miterlimit progressively converts the miter joints to bevel ones. </p> <div class="container"> <svg width="500px" height="200px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <rect x="50" y="20" width="100" height="100" stroke-miterlimit=1 /> <text x="40" y="150"> stroke-miterlimit: 1 </text> <rect x="250" y="20" width="100" height="100" stroke-miterlimit=2 /> <text x="240" y="150"> stroke-miterlimit: 2 </text> </svg> </div></body> </html>
Output:
Example 2:
<!DOCTYPE html><html> <head> <title> CSS | stroke-miterlimit property </title> <style> polygon { stroke-linejoin: miter; stroke-width: 8px; stroke: green; fill: none; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | stroke-miterlimit </b> <p> Each of the triangles have two angles equal to 24 degrees and one angle equal to 130 degrees. Increasing the miterlimit progressively converts the miter joints to bevel ones. </p> <div class="container"> <svg width="500px" height="200px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <polygon points="20, 20 150, 20 85, 80" stroke-miterlimit=1 /> <text x="30" y="100"> stroke-miterlimit: 1 </text> <polygon points="170, 20 300, 20 235, 80" stroke-miterlimit=2 /> <text x="180" y="100"> stroke-miterlimit: 2 </text> <polygon points="320, 20 450, 20 385, 80" stroke-miterlimit=3 /> <text x="330" y="100"> stroke-miterlimit: 3 </text> </svg> </div></body> </html>
Output:
initial: It is used to set the property to its default value.
inherit: It is used to set the property to inherit from its parent element.
Supported Browsers: The browsers supported by stroke-miterlimit property are listed below:
Google Chrome
Firefox
Opera
Internet Explorer 9
CSS-Properties
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
How to set space between the flexbox ?
Design a web page using HTML and 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 ?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26541,
"s": 26513,
"text": "\n23 Jan, 2020"
},
{
"code": null,
"e": 26876,
"s": 26541,
"text": "The stroke-miterlimit property is used to represent the limit on the ratio of the miter length to the stroke-width, that is used to draw a miter join. This property is used in situations when the miter extends beyond the thickness of the line. If this limit specified is exceeded, the ‘miter’ type of the join is converted to ‘bevel’."
},
{
"code": null,
"e": 26964,
"s": 26876,
"text": "This will crop the connecting point perpendicular to the join, instead of a sharp join."
},
{
"code": null,
"e": 26972,
"s": 26964,
"text": "Syntax:"
},
{
"code": null,
"e": 27014,
"s": 26972,
"text": "stroke-miterlimit: number|initial|inherit"
},
{
"code": null,
"e": 27031,
"s": 27014,
"text": "Property Values:"
},
{
"code": null,
"e": 29753,
"s": 27031,
"text": "number: It is used to define the ratio limit. It can be any value greater than or equal to 1. The default value is 4.Example 1:<!DOCTYPE html><html> <head> <title> CSS | stroke-miterlimit property </title> <style> rect { stroke-linejoin: miter; stroke-width: 20px; stroke: green; fill: none; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | stroke-miterlimit </b> <p> Each angle of the square is of 90 degrees. Increasing the miterlimit progressively converts the miter joints to bevel ones. </p> <div class=\"container\"> <svg width=\"500px\" height=\"200px\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"> <rect x=\"50\" y=\"20\" width=\"100\" height=\"100\" stroke-miterlimit=1 /> <text x=\"40\" y=\"150\"> stroke-miterlimit: 1 </text> <rect x=\"250\" y=\"20\" width=\"100\" height=\"100\" stroke-miterlimit=2 /> <text x=\"240\" y=\"150\"> stroke-miterlimit: 2 </text> </svg> </div></body> </html>Output:Example 2:<!DOCTYPE html><html> <head> <title> CSS | stroke-miterlimit property </title> <style> polygon { stroke-linejoin: miter; stroke-width: 8px; stroke: green; fill: none; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | stroke-miterlimit </b> <p> Each of the triangles have two angles equal to 24 degrees and one angle equal to 130 degrees. Increasing the miterlimit progressively converts the miter joints to bevel ones. </p> <div class=\"container\"> <svg width=\"500px\" height=\"200px\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"> <polygon points=\"20, 20 150, 20 85, 80\" stroke-miterlimit=1 /> <text x=\"30\" y=\"100\"> stroke-miterlimit: 1 </text> <polygon points=\"170, 20 300, 20 235, 80\" stroke-miterlimit=2 /> <text x=\"180\" y=\"100\"> stroke-miterlimit: 2 </text> <polygon points=\"320, 20 450, 20 385, 80\" stroke-miterlimit=3 /> <text x=\"330\" y=\"100\"> stroke-miterlimit: 3 </text> </svg> </div></body> </html>Output:"
},
{
"code": null,
"e": 29764,
"s": 29753,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> CSS | stroke-miterlimit property </title> <style> rect { stroke-linejoin: miter; stroke-width: 20px; stroke: green; fill: none; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | stroke-miterlimit </b> <p> Each angle of the square is of 90 degrees. Increasing the miterlimit progressively converts the miter joints to bevel ones. </p> <div class=\"container\"> <svg width=\"500px\" height=\"200px\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"> <rect x=\"50\" y=\"20\" width=\"100\" height=\"100\" stroke-miterlimit=1 /> <text x=\"40\" y=\"150\"> stroke-miterlimit: 1 </text> <rect x=\"250\" y=\"20\" width=\"100\" height=\"100\" stroke-miterlimit=2 /> <text x=\"240\" y=\"150\"> stroke-miterlimit: 2 </text> </svg> </div></body> </html>",
"e": 30937,
"s": 29764,
"text": null
},
{
"code": null,
"e": 30945,
"s": 30937,
"text": "Output:"
},
{
"code": null,
"e": 30956,
"s": 30945,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> CSS | stroke-miterlimit property </title> <style> polygon { stroke-linejoin: miter; stroke-width: 8px; stroke: green; fill: none; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | stroke-miterlimit </b> <p> Each of the triangles have two angles equal to 24 degrees and one angle equal to 130 degrees. Increasing the miterlimit progressively converts the miter joints to bevel ones. </p> <div class=\"container\"> <svg width=\"500px\" height=\"200px\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"> <polygon points=\"20, 20 150, 20 85, 80\" stroke-miterlimit=1 /> <text x=\"30\" y=\"100\"> stroke-miterlimit: 1 </text> <polygon points=\"170, 20 300, 20 235, 80\" stroke-miterlimit=2 /> <text x=\"180\" y=\"100\"> stroke-miterlimit: 2 </text> <polygon points=\"320, 20 450, 20 385, 80\" stroke-miterlimit=3 /> <text x=\"330\" y=\"100\"> stroke-miterlimit: 3 </text> </svg> </div></body> </html>",
"e": 32355,
"s": 30956,
"text": null
},
{
"code": null,
"e": 32363,
"s": 32355,
"text": "Output:"
},
{
"code": null,
"e": 32425,
"s": 32363,
"text": "initial: It is used to set the property to its default value."
},
{
"code": null,
"e": 32501,
"s": 32425,
"text": "inherit: It is used to set the property to inherit from its parent element."
},
{
"code": null,
"e": 32592,
"s": 32501,
"text": "Supported Browsers: The browsers supported by stroke-miterlimit property are listed below:"
},
{
"code": null,
"e": 32606,
"s": 32592,
"text": "Google Chrome"
},
{
"code": null,
"e": 32614,
"s": 32606,
"text": "Firefox"
},
{
"code": null,
"e": 32620,
"s": 32614,
"text": "Opera"
},
{
"code": null,
"e": 32640,
"s": 32620,
"text": "Internet Explorer 9"
},
{
"code": null,
"e": 32655,
"s": 32640,
"text": "CSS-Properties"
},
{
"code": null,
"e": 32659,
"s": 32655,
"text": "CSS"
},
{
"code": null,
"e": 32676,
"s": 32659,
"text": "Web Technologies"
},
{
"code": null,
"e": 32774,
"s": 32676,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32822,
"s": 32774,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 32859,
"s": 32822,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 32923,
"s": 32859,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 32962,
"s": 32923,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 32999,
"s": 32962,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 33039,
"s": 32999,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 33072,
"s": 33039,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 33117,
"s": 33072,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 33160,
"s": 33117,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
A Better Approach to Text Summarization | by Vinicius Monteiro | Towards Data Science
|
There are several approaches to perform automatic text summarization. It can be done with supervised or unsupervised learning, with deep or only machine learning. And inside these categories, there are a wide variety of methods.
In terms of types of summaries, there are two — extractive and abstractive. The program presented here uses unsupervised learning and generates an extractive summarization.
Extractive summarization is when the summary is a subset of the original text because all words in the summary are included in the original text. For an overview of the automatic text summarization field, I recommend this survey.
In general, in a simplistic explanation, a summarizer’s goal is to find the most relevant words and then select the sentences that contain those words to be part of the summary.
What about words that are different but have the same meaning?
For instance,
Harry moved to the US.
The prince relocated to North America.
They have no words in common, but the two sentences are strongly related. “The” and “to” doesn’t count. These words would’ve have been removed in the preprocessing step. More about it below.
In a naive approach, “Harry” or “US” could be selected as relevant words, but the sentence “The prince relocated to North America” would have no chance to be part of the summary.
The technique presented in this research paper resolves this problem.
The code shown in this post is only a slightly modified version (structure, method name, etc.) of the source available on Github.
The text I use in this tutorial is the same one used in this excellent article by Praveen Dubey. Make sure to read it as well (I changed one of the sentences for proof of concept).
The summarizer relies on the word embeddings, so it also selects sentences that contain words with the same meaning as the most relevant words (centroid) — even if the words are different.
For more details on word embeddings, check out this article by Zhi Li
So, before even preprocessing the text, the program must define the embedding model. I used the text being summarized as the data to get the embedding model.
But it could be the Wikipedia dump or some other text. There are already available models as well that can be used. To obtain the word embedding, I split the text into words and passed it to Word2vec.
for sent in clean_sentences: words.append(nlkt_word_tokenize(sent))model = Word2Vec(words, min_count=1, sg = 1)
You must preprocess the text. It includes splitting the text into sentences, lowering the case of all words, removing stopwords (is, an, the, etc.) and punctuation and other tasks.
I covered this step alone in another article. The goal is not to waste resources (compute power, time) processing things that don’t add much value to extracting the semantics and understanding the text.
Especifically to identifying and splitting the text into sentences, it’s crucial as later the algorithm will score and select them to be part of the summary.
def sent_tokenize(text): sents = nlkt_sent_tokenize(text) sents_filtered = [] for s in sents: sents_filtered.append(s) return sents_filtereddef cleanup_sentences(text): stop_words = set(stopwords.words('english')) sentences = sent_tokenize(text) sentences_cleaned = [] for sent in sentences: words = nlkt_word_tokenize(sent) words = [w for w in words if w not in string.punctuation] words = [w for w in words if not w.lower() in stop_words] words = [w.lower() for w in words] sentences_cleaned.append(" ".join(words)) return sentences_cleaned
The algorithm uses TF-IDF to find the most relevant words of the text. These words are the centroid of the text.
After finding the words centroid, the program sums up the vectors of the words that are part of the centroid, and that sum is the embedding representation of the centroid.
Let’s say the most relevant words are: Microsoft, program, AI
The embedding representation of the centroid (most relevant terms) = Microsoft vector + program vector + AI vector.
To remind, the embedding model represents each word as a vector. That’s how you have a vector for each word.
def build_embedding_representation(words, word_vectors, embedding_model): embedding_representation = np.zeros(embedding_model.vector_size, dtype="float32") word_vectors_keys = set(word_vectors.keys()) count = 0 for w in words: if w in word_vectors_keys: embedding_representation = embedding_representation + word_vectors[w] count += 1 if count != 0: embedding_representation = np.divide(embedding_representation, count) return embedding_representationdef get_tf_idf(sentences): vectorizer = CountVectorizer() sent_word_matrix = vectorizer.fit_transform(sentences)transformer = TfidfTransformer(norm=None, sublinear_tf=False, smooth_idf=False) tfidf = transformer.fit_transform(sent_word_matrix) tfidf = tfidf.toarray()centroid_vector = tfidf.sum(0) centroid_vector = np.divide(centroid_vector, centroid_vector.max())feature_names = vectorizer.get_feature_names()relevant_vector_indices = np.where(centroid_vector > 0.3)[0]word_list = list(np.array(feature_names)[relevant_vector_indices]) return word_listcentroid_words = get_tf_idf(clean_sentences)centroid_vector = build_embedding_representation(centroid_words, word_vectors, emdedding_model)
The sentences are scored based on how similar they are to the centroid embedding.
In order to compare to the centroid embedding, the algorithm calculates the embedding representation of each sentence.
Sentence embedding = sum of words vectors that are part of the sentence.
For instance,
Sentence1 = word1, word2, word3Sentence1 embedding = word1 vector + word2 vector + word3 vector
Lastly, after the sentence embedding is defined, the algorithm uses cosine similarity to calculate the similarity between the centroid and the sentence embedding.
Each sentence gets a score based on how similar they are to the centroid.
def build_embedding_representation(words, word_vectors, embedding_model): embedding_representation = np.zeros(embedding_model.vector_size, dtype="float32") word_vectors_keys = set(word_vectors.keys()) count = 0 for w in words: if w in word_vectors_keys: embedding_representation = embedding_representation + word_vectors[w] count += 1 if count != 0: embedding_representation = np.divide(embedding_representation, count) return embedding_representationsentences_scores = []for i in range(len(clean_sentences)): scores = [] words = clean_sentences[i].split() #Sentence embedding representation sentence_vector = build_embedding_representation(words, word_vectors, emdedding_model) #Cosine similarity between sentence embedding and centroid embedding score = similarity(sentence_vector, centroid_vector) sentences_scores.append((i, raw_sentences[i], score, sentence_vector))sentence_scores_sort = sorted(sentences_scores, key=lambda el: el[2], reverse=True)sentence_scores_sort = sorted(sentences_scores, key=lambda el: el[2], reverse=True)
Sentences score
The sentence in red has no words part of the centroid. Still, it had a good score. Higher than another one that includes centroid words.
The sentences are selected based on their score. The number of sentences selected is limited by how many words the summary should contain (50 words, 100 words, or?).
A common problem when dealing with automatic summarization is handling redundancy — too similar sentences being part of the summary.
To overcome that, when selecting the sentences, you compare them with the sentences already in summary. If a chosen sentence is too similar to one in summary, you don’t add it to the final text.
The algorithm uses cosine similarity with some predefined threshold when making the comparison.
count = 0sentences_summary = []#Handle redundancyfor s in sentence_scores_sort: if count > 100: break include_flag = True for ps in sentences_summary: sim = similarity(s[3], ps[3]) if sim > 0.95: include_flag = False if include_flag: sentences_summary.append(s) count += len(s[1].split())sentences_summary = sorted(sentences_summary, key=lambda el: el[0], reverse=False)summary = "\n".join([s[1] for s in sentences_summary])
Original Text
Generated summary
The code was slightly modified/simplified for me to understand better and explain in this article. But you can view the research paper author’s Github for the complete and more accurate implementation.
I find this project really interesting. It’s more efficient than other algorithms that relies on bag of words (BOW) or TF-IDF only. The research paper I used as my main reference is much more detailed. It evaluates the generated summary against other algorithms and covers multi-language documents summarization.
Evaluation comes next. I plan to write another post covering ROUGE, a tool commonly used to score how good the summary is. I’ll also dive into summarizers based on supervised machine learning. And deep learning as well.
Thanks for reading.
[1] Text Summarization Techniques: A Brief Survey. By Mehdi Allahyari, Seyedamin Pouriyeh, Mehdi Assefi, Saeid Safaei, Elizabeth D. Trippe, Juan B. Gutierrez, Krys Kochut
[2] Centroid-based Text Summarization through Compositionality of Word Embeddings. By Gaetano Rossiello, Pierpaolo Basile and Giovanni Semeraro | Github page: https://github.com/gaetangate/text-summarizer
|
[
{
"code": null,
"e": 400,
"s": 171,
"text": "There are several approaches to perform automatic text summarization. It can be done with supervised or unsupervised learning, with deep or only machine learning. And inside these categories, there are a wide variety of methods."
},
{
"code": null,
"e": 573,
"s": 400,
"text": "In terms of types of summaries, there are two — extractive and abstractive. The program presented here uses unsupervised learning and generates an extractive summarization."
},
{
"code": null,
"e": 803,
"s": 573,
"text": "Extractive summarization is when the summary is a subset of the original text because all words in the summary are included in the original text. For an overview of the automatic text summarization field, I recommend this survey."
},
{
"code": null,
"e": 981,
"s": 803,
"text": "In general, in a simplistic explanation, a summarizer’s goal is to find the most relevant words and then select the sentences that contain those words to be part of the summary."
},
{
"code": null,
"e": 1044,
"s": 981,
"text": "What about words that are different but have the same meaning?"
},
{
"code": null,
"e": 1058,
"s": 1044,
"text": "For instance,"
},
{
"code": null,
"e": 1081,
"s": 1058,
"text": "Harry moved to the US."
},
{
"code": null,
"e": 1120,
"s": 1081,
"text": "The prince relocated to North America."
},
{
"code": null,
"e": 1311,
"s": 1120,
"text": "They have no words in common, but the two sentences are strongly related. “The” and “to” doesn’t count. These words would’ve have been removed in the preprocessing step. More about it below."
},
{
"code": null,
"e": 1490,
"s": 1311,
"text": "In a naive approach, “Harry” or “US” could be selected as relevant words, but the sentence “The prince relocated to North America” would have no chance to be part of the summary."
},
{
"code": null,
"e": 1560,
"s": 1490,
"text": "The technique presented in this research paper resolves this problem."
},
{
"code": null,
"e": 1690,
"s": 1560,
"text": "The code shown in this post is only a slightly modified version (structure, method name, etc.) of the source available on Github."
},
{
"code": null,
"e": 1871,
"s": 1690,
"text": "The text I use in this tutorial is the same one used in this excellent article by Praveen Dubey. Make sure to read it as well (I changed one of the sentences for proof of concept)."
},
{
"code": null,
"e": 2060,
"s": 1871,
"text": "The summarizer relies on the word embeddings, so it also selects sentences that contain words with the same meaning as the most relevant words (centroid) — even if the words are different."
},
{
"code": null,
"e": 2130,
"s": 2060,
"text": "For more details on word embeddings, check out this article by Zhi Li"
},
{
"code": null,
"e": 2288,
"s": 2130,
"text": "So, before even preprocessing the text, the program must define the embedding model. I used the text being summarized as the data to get the embedding model."
},
{
"code": null,
"e": 2489,
"s": 2288,
"text": "But it could be the Wikipedia dump or some other text. There are already available models as well that can be used. To obtain the word embedding, I split the text into words and passed it to Word2vec."
},
{
"code": null,
"e": 2604,
"s": 2489,
"text": "for sent in clean_sentences: words.append(nlkt_word_tokenize(sent))model = Word2Vec(words, min_count=1, sg = 1)"
},
{
"code": null,
"e": 2785,
"s": 2604,
"text": "You must preprocess the text. It includes splitting the text into sentences, lowering the case of all words, removing stopwords (is, an, the, etc.) and punctuation and other tasks."
},
{
"code": null,
"e": 2988,
"s": 2785,
"text": "I covered this step alone in another article. The goal is not to waste resources (compute power, time) processing things that don’t add much value to extracting the semantics and understanding the text."
},
{
"code": null,
"e": 3146,
"s": 2988,
"text": "Especifically to identifying and splitting the text into sentences, it’s crucial as later the algorithm will score and select them to be part of the summary."
},
{
"code": null,
"e": 3758,
"s": 3146,
"text": "def sent_tokenize(text): sents = nlkt_sent_tokenize(text) sents_filtered = [] for s in sents: sents_filtered.append(s) return sents_filtereddef cleanup_sentences(text): stop_words = set(stopwords.words('english')) sentences = sent_tokenize(text) sentences_cleaned = [] for sent in sentences: words = nlkt_word_tokenize(sent) words = [w for w in words if w not in string.punctuation] words = [w for w in words if not w.lower() in stop_words] words = [w.lower() for w in words] sentences_cleaned.append(\" \".join(words)) return sentences_cleaned"
},
{
"code": null,
"e": 3871,
"s": 3758,
"text": "The algorithm uses TF-IDF to find the most relevant words of the text. These words are the centroid of the text."
},
{
"code": null,
"e": 4043,
"s": 3871,
"text": "After finding the words centroid, the program sums up the vectors of the words that are part of the centroid, and that sum is the embedding representation of the centroid."
},
{
"code": null,
"e": 4105,
"s": 4043,
"text": "Let’s say the most relevant words are: Microsoft, program, AI"
},
{
"code": null,
"e": 4221,
"s": 4105,
"text": "The embedding representation of the centroid (most relevant terms) = Microsoft vector + program vector + AI vector."
},
{
"code": null,
"e": 4330,
"s": 4221,
"text": "To remind, the embedding model represents each word as a vector. That’s how you have a vector for each word."
},
{
"code": null,
"e": 5546,
"s": 4330,
"text": "def build_embedding_representation(words, word_vectors, embedding_model): embedding_representation = np.zeros(embedding_model.vector_size, dtype=\"float32\") word_vectors_keys = set(word_vectors.keys()) count = 0 for w in words: if w in word_vectors_keys: embedding_representation = embedding_representation + word_vectors[w] count += 1 if count != 0: embedding_representation = np.divide(embedding_representation, count) return embedding_representationdef get_tf_idf(sentences): vectorizer = CountVectorizer() sent_word_matrix = vectorizer.fit_transform(sentences)transformer = TfidfTransformer(norm=None, sublinear_tf=False, smooth_idf=False) tfidf = transformer.fit_transform(sent_word_matrix) tfidf = tfidf.toarray()centroid_vector = tfidf.sum(0) centroid_vector = np.divide(centroid_vector, centroid_vector.max())feature_names = vectorizer.get_feature_names()relevant_vector_indices = np.where(centroid_vector > 0.3)[0]word_list = list(np.array(feature_names)[relevant_vector_indices]) return word_listcentroid_words = get_tf_idf(clean_sentences)centroid_vector = build_embedding_representation(centroid_words, word_vectors, emdedding_model)"
},
{
"code": null,
"e": 5628,
"s": 5546,
"text": "The sentences are scored based on how similar they are to the centroid embedding."
},
{
"code": null,
"e": 5747,
"s": 5628,
"text": "In order to compare to the centroid embedding, the algorithm calculates the embedding representation of each sentence."
},
{
"code": null,
"e": 5820,
"s": 5747,
"text": "Sentence embedding = sum of words vectors that are part of the sentence."
},
{
"code": null,
"e": 5834,
"s": 5820,
"text": "For instance,"
},
{
"code": null,
"e": 5930,
"s": 5834,
"text": "Sentence1 = word1, word2, word3Sentence1 embedding = word1 vector + word2 vector + word3 vector"
},
{
"code": null,
"e": 6093,
"s": 5930,
"text": "Lastly, after the sentence embedding is defined, the algorithm uses cosine similarity to calculate the similarity between the centroid and the sentence embedding."
},
{
"code": null,
"e": 6167,
"s": 6093,
"text": "Each sentence gets a score based on how similar they are to the centroid."
},
{
"code": null,
"e": 7310,
"s": 6167,
"text": "def build_embedding_representation(words, word_vectors, embedding_model): embedding_representation = np.zeros(embedding_model.vector_size, dtype=\"float32\") word_vectors_keys = set(word_vectors.keys()) count = 0 for w in words: if w in word_vectors_keys: embedding_representation = embedding_representation + word_vectors[w] count += 1 if count != 0: embedding_representation = np.divide(embedding_representation, count) return embedding_representationsentences_scores = []for i in range(len(clean_sentences)): scores = [] words = clean_sentences[i].split() #Sentence embedding representation sentence_vector = build_embedding_representation(words, word_vectors, emdedding_model) #Cosine similarity between sentence embedding and centroid embedding score = similarity(sentence_vector, centroid_vector) sentences_scores.append((i, raw_sentences[i], score, sentence_vector))sentence_scores_sort = sorted(sentences_scores, key=lambda el: el[2], reverse=True)sentence_scores_sort = sorted(sentences_scores, key=lambda el: el[2], reverse=True)"
},
{
"code": null,
"e": 7326,
"s": 7310,
"text": "Sentences score"
},
{
"code": null,
"e": 7463,
"s": 7326,
"text": "The sentence in red has no words part of the centroid. Still, it had a good score. Higher than another one that includes centroid words."
},
{
"code": null,
"e": 7629,
"s": 7463,
"text": "The sentences are selected based on their score. The number of sentences selected is limited by how many words the summary should contain (50 words, 100 words, or?)."
},
{
"code": null,
"e": 7762,
"s": 7629,
"text": "A common problem when dealing with automatic summarization is handling redundancy — too similar sentences being part of the summary."
},
{
"code": null,
"e": 7957,
"s": 7762,
"text": "To overcome that, when selecting the sentences, you compare them with the sentences already in summary. If a chosen sentence is too similar to one in summary, you don’t add it to the final text."
},
{
"code": null,
"e": 8053,
"s": 7957,
"text": "The algorithm uses cosine similarity with some predefined threshold when making the comparison."
},
{
"code": null,
"e": 8576,
"s": 8053,
"text": "count = 0sentences_summary = []#Handle redundancyfor s in sentence_scores_sort: if count > 100: break include_flag = True for ps in sentences_summary: sim = similarity(s[3], ps[3]) if sim > 0.95: include_flag = False if include_flag: sentences_summary.append(s) count += len(s[1].split())sentences_summary = sorted(sentences_summary, key=lambda el: el[0], reverse=False)summary = \"\\n\".join([s[1] for s in sentences_summary])"
},
{
"code": null,
"e": 8590,
"s": 8576,
"text": "Original Text"
},
{
"code": null,
"e": 8608,
"s": 8590,
"text": "Generated summary"
},
{
"code": null,
"e": 8810,
"s": 8608,
"text": "The code was slightly modified/simplified for me to understand better and explain in this article. But you can view the research paper author’s Github for the complete and more accurate implementation."
},
{
"code": null,
"e": 9123,
"s": 8810,
"text": "I find this project really interesting. It’s more efficient than other algorithms that relies on bag of words (BOW) or TF-IDF only. The research paper I used as my main reference is much more detailed. It evaluates the generated summary against other algorithms and covers multi-language documents summarization."
},
{
"code": null,
"e": 9343,
"s": 9123,
"text": "Evaluation comes next. I plan to write another post covering ROUGE, a tool commonly used to score how good the summary is. I’ll also dive into summarizers based on supervised machine learning. And deep learning as well."
},
{
"code": null,
"e": 9363,
"s": 9343,
"text": "Thanks for reading."
},
{
"code": null,
"e": 9534,
"s": 9363,
"text": "[1] Text Summarization Techniques: A Brief Survey. By Mehdi Allahyari, Seyedamin Pouriyeh, Mehdi Assefi, Saeid Safaei, Elizabeth D. Trippe, Juan B. Gutierrez, Krys Kochut"
}
] |
Sign Magnitude notation
|
The sign-magnitude binary format is the simplest conceptual format. In this method of representing signed numbers, the most significant digit (MSD) takes on extra meaning.
If the MSD is a 0, we can evaluate the number just as we would any normal unsigned integer. And also we shall treat the number as a positive one.
If the MSD is a 0, we can evaluate the number just as we would any normal unsigned integer. And also we shall treat the number as a positive one.
If the MSD is a 1, this indicates that the number is negative.
The other bits indicate the magnitude (absolute value) of the number. Some of the signed decimal numbers and their equivalent in SM notation follows assuming a word size of 4 bits.
From the above table, it is obvious that if the word size is n bits, the range of numbers that can be represented is from -(2n-1 -1) to +(2n-1 -1). A table of word size and the range of SM numbers that can be represented as shown in the following.
Notice that the bit sequence 1101corresponds to the unsigned number 13, as well as the number –5 in SM notation. Its value depends only on the way the user or the programmer interprets the bit sequence.
A number is represented inside a computer with the purpose of performing some calculations using that number. The most basic arithmetic operation in a computer is the addition operation. That’s why a computer can also be called as an adder.
When adding two numbers with the same signs, add the values and keep the common sign.
Add the numbers (+5) and (+3) using a computer. The numbers are assumed to be represented using 4-bit SM notation.
111 <- carry generated during addition
0101 <- (+5) First Number
+ 0011 <- (+3) Second Number
1000 <- (+8) Sum
111 <- carry generated during addition
0101 <- (+5) First Number
+ 0011 <- (+3) Second Number
1000 <- (+8) Sum
Let’s take another example of two numbers with unlike signs.
Add the numbers (-4) and (+2) using a computer. The numbers are assumed to be represented using 4-bit SM notation.
000 <- carry generated during addition 1100 <- (-4) First number + 0010 <-(+2) Second Number 1110 <- (-2) Sum
000 <- carry generated during addition
1100 <- (-4) First number
+ 0010 <-(+2) Second Number
1110 <- (-2) Sum
Here, the computer has given the wrong answer of -6 = 1110, instead of giving the correct answer of -2 = 1010.
There are two notations for 0(0000 and 1000), which is very inconvenient when the computer wants to test for a 0 result.
There are two notations for 0(0000 and 1000), which is very inconvenient when the computer wants to test for a 0 result.
It is not convenient for the computer to perform arithmetic.
It is not convenient for the computer to perform arithmetic.
Hence, due to the above mention ambiguities, SM notation is generally not used to represent signed numbers inside a computer.
|
[
{
"code": null,
"e": 1234,
"s": 1062,
"text": "The sign-magnitude binary format is the simplest conceptual format. In this method of representing signed numbers, the most significant digit (MSD) takes on extra meaning."
},
{
"code": null,
"e": 1380,
"s": 1234,
"text": "If the MSD is a 0, we can evaluate the number just as we would any normal unsigned integer. And also we shall treat the number as a positive one."
},
{
"code": null,
"e": 1526,
"s": 1380,
"text": "If the MSD is a 0, we can evaluate the number just as we would any normal unsigned integer. And also we shall treat the number as a positive one."
},
{
"code": null,
"e": 1589,
"s": 1526,
"text": "If the MSD is a 1, this indicates that the number is negative."
},
{
"code": null,
"e": 1770,
"s": 1589,
"text": "The other bits indicate the magnitude (absolute value) of the number. Some of the signed decimal numbers and their equivalent in SM notation follows assuming a word size of 4 bits."
},
{
"code": null,
"e": 2018,
"s": 1770,
"text": "From the above table, it is obvious that if the word size is n bits, the range of numbers that can be represented is from -(2n-1 -1) to +(2n-1 -1). A table of word size and the range of SM numbers that can be represented as shown in the following."
},
{
"code": null,
"e": 2221,
"s": 2018,
"text": "Notice that the bit sequence 1101corresponds to the unsigned number 13, as well as the number –5 in SM notation. Its value depends only on the way the user or the programmer interprets the bit sequence."
},
{
"code": null,
"e": 2462,
"s": 2221,
"text": "A number is represented inside a computer with the purpose of performing some calculations using that number. The most basic arithmetic operation in a computer is the addition operation. That’s why a computer can also be called as an adder."
},
{
"code": null,
"e": 2549,
"s": 2462,
"text": "When adding two numbers with the same signs, add the values and keep the common sign. "
},
{
"code": null,
"e": 2664,
"s": 2549,
"text": "Add the numbers (+5) and (+3) using a computer. The numbers are assumed to be represented using 4-bit SM notation."
},
{
"code": null,
"e": 2843,
"s": 2664,
"text": " 111 <- carry generated during addition\n 0101 <- (+5) First Number\n + 0011 <- (+3) Second Number\n 1000 <- (+8) Sum "
},
{
"code": null,
"e": 3022,
"s": 2843,
"text": " 111 <- carry generated during addition\n 0101 <- (+5) First Number\n + 0011 <- (+3) Second Number\n 1000 <- (+8) Sum "
},
{
"code": null,
"e": 3083,
"s": 3022,
"text": "Let’s take another example of two numbers with unlike signs."
},
{
"code": null,
"e": 3198,
"s": 3083,
"text": "Add the numbers (-4) and (+2) using a computer. The numbers are assumed to be represented using 4-bit SM notation."
},
{
"code": null,
"e": 3359,
"s": 3198,
"text": " 000 <- carry generated during addition 1100 <- (-4) First number + 0010 <-(+2) Second Number 1110 <- (-2) Sum"
},
{
"code": null,
"e": 3412,
"s": 3359,
"text": " 000 <- carry generated during addition"
},
{
"code": null,
"e": 3452,
"s": 3412,
"text": " 1100 <- (-4) First number"
},
{
"code": null,
"e": 3492,
"s": 3452,
"text": " + 0010 <-(+2) Second Number"
},
{
"code": null,
"e": 3523,
"s": 3492,
"text": " 1110 <- (-2) Sum"
},
{
"code": null,
"e": 3634,
"s": 3523,
"text": "Here, the computer has given the wrong answer of -6 = 1110, instead of giving the correct answer of -2 = 1010."
},
{
"code": null,
"e": 3755,
"s": 3634,
"text": "There are two notations for 0(0000 and 1000), which is very inconvenient when the computer wants to test for a 0 result."
},
{
"code": null,
"e": 3876,
"s": 3755,
"text": "There are two notations for 0(0000 and 1000), which is very inconvenient when the computer wants to test for a 0 result."
},
{
"code": null,
"e": 3937,
"s": 3876,
"text": "It is not convenient for the computer to perform arithmetic."
},
{
"code": null,
"e": 3998,
"s": 3937,
"text": "It is not convenient for the computer to perform arithmetic."
},
{
"code": null,
"e": 4124,
"s": 3998,
"text": "Hence, due to the above mention ambiguities, SM notation is generally not used to represent signed numbers inside a computer."
}
] |
React.js constructor() Method - GeeksforGeeks
|
08 Mar, 2021
A constructor is a method that is called automatically when we created an object from that class. It can manage initial initialization tasks such as defaulting certain object properties or sanity testing the arguments passed in. Simply placed, the constructor is a method that helps in the creation of objects.
The constructor is no different in React. This can connect event handlers to the component and/or initialize the component’s local state. Before the component is mounted, the constructor() function is shot, and, like most things in React, it has a few rules that you can follow when using them.
Step 1: Call super(props) before using this.propsDue to the nature of the constructor, this.props object is not accessible straight out of the gate, which can lead to errors. An error will be thrown by this constructor:constructor() {
console.log(this.props);
}Instead, we transfer the value of a prop to the super() function from the constructor():constructor(props) {
super(props);
console.log(this.props);
}When you call the super() function, the parent class constructor is called, which is in the case of a React is React.Component.
Step 1: Call super(props) before using this.props
Due to the nature of the constructor, this.props object is not accessible straight out of the gate, which can lead to errors. An error will be thrown by this constructor:
constructor() {
console.log(this.props);
}
Instead, we transfer the value of a prop to the super() function from the constructor():
constructor(props) {
super(props);
console.log(this.props);
}
When you call the super() function, the parent class constructor is called, which is in the case of a React is React.Component.
Step 2: Never call setState() inside constructor()The constructor of your component is the ideal place to set the component’s initial state. You must set the initial state directly, rather than using setState() as you can in other methods in your class:constructor(props) {
super(props);
this.state = {
name 'kapil',
age: 22,
};
}The only place you can assign the local state directly like that is the constructor. You should depend on setState() somewhere else inside our component instead.
Step 2: Never call setState() inside constructor()
The constructor of your component is the ideal place to set the component’s initial state. You must set the initial state directly, rather than using setState() as you can in other methods in your class:
constructor(props) {
super(props);
this.state = {
name 'kapil',
age: 22,
};
}
The only place you can assign the local state directly like that is the constructor. You should depend on setState() somewhere else inside our component instead.
Step 3: Avoid assigning values from this.props to this.stateYou should try to avoid setting values from the properties when setting the initial component state in the constructor. We can do the following:constructor(props) {
super(props);
this.state = {
name: props.name,
};
}You wouldn’t be allowed to use setState() to change the property later. You may easily reference the property directly in your code by naming this.props.name, instead of assigning the property directly to the state.
Step 3: Avoid assigning values from this.props to this.state
You should try to avoid setting values from the properties when setting the initial component state in the constructor. We can do the following:
constructor(props) {
super(props);
this.state = {
name: props.name,
};
}
You wouldn’t be allowed to use setState() to change the property later. You may easily reference the property directly in your code by naming this.props.name, instead of assigning the property directly to the state.
Step 4: Bind events all in one placeWe can easily bind your event handlers in the constructor:constructor(props) {
super(props);
this.state = {
// Sets that initial state
};
// Our event handlers
this.onClick = this.onClick.bind(this);
this.onKeyUp = this.onKeyUp.bind(this);
// Rest Code
}
Step 4: Bind events all in one place
We can easily bind your event handlers in the constructor:
constructor(props) {
super(props);
this.state = {
// Sets that initial state
};
// Our event handlers
this.onClick = this.onClick.bind(this);
this.onKeyUp = this.onKeyUp.bind(this);
// Rest Code
}
Creating React Application:
Step 1: Create a React application using the following command.npx create-react-app foldername
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Project Structure: It will look like the following.
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. The following example covers constructor demonstration.
App.js
import React, { Component } from 'react'; class App extends Component { constructor(props) { // Calling super class constructor super(props); // Creating state this.state = { data: 'My name is User' } // Binding event handler this.handleEvent = this.handleEvent.bind(this); } handleEvent() { console.log(this.props); } render() { return ( <div > <input type="text" value={this.state.data} /> <br></br> <br></br> <button onClick={this.handleEvent}>Please Click</button> </div> ); }} export default App;
Step to Run Application: Run the application from the root directory of the project, using the following command
npm start
Output:
Picked
React.js-Methods
ReactJS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
Axios in React: A Guide for Beginners
How to set background images in ReactJS ?
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
How to create a multi-page website using React.js ?
How to build a basic CRUD app with Node.js and ReactJS ?
How to Use Bootstrap with React?
How to check the version of ReactJS ?
Destructuring of Props in ReactJS
|
[
{
"code": null,
"e": 26622,
"s": 26594,
"text": "\n08 Mar, 2021"
},
{
"code": null,
"e": 26934,
"s": 26622,
"text": "A constructor is a method that is called automatically when we created an object from that class. It can manage initial initialization tasks such as defaulting certain object properties or sanity testing the arguments passed in. Simply placed, the constructor is a method that helps in the creation of objects. "
},
{
"code": null,
"e": 27229,
"s": 26934,
"text": "The constructor is no different in React. This can connect event handlers to the component and/or initialize the component’s local state. Before the component is mounted, the constructor() function is shot, and, like most things in React, it has a few rules that you can follow when using them."
},
{
"code": null,
"e": 27771,
"s": 27229,
"text": "Step 1: Call super(props) before using this.propsDue to the nature of the constructor, this.props object is not accessible straight out of the gate, which can lead to errors. An error will be thrown by this constructor:constructor() {\n console.log(this.props);\n}Instead, we transfer the value of a prop to the super() function from the constructor():constructor(props) {\n super(props);\n console.log(this.props);\n}When you call the super() function, the parent class constructor is called, which is in the case of a React is React.Component. "
},
{
"code": null,
"e": 27821,
"s": 27771,
"text": "Step 1: Call super(props) before using this.props"
},
{
"code": null,
"e": 27992,
"s": 27821,
"text": "Due to the nature of the constructor, this.props object is not accessible straight out of the gate, which can lead to errors. An error will be thrown by this constructor:"
},
{
"code": null,
"e": 28036,
"s": 27992,
"text": "constructor() {\n console.log(this.props);\n}"
},
{
"code": null,
"e": 28125,
"s": 28036,
"text": "Instead, we transfer the value of a prop to the super() function from the constructor():"
},
{
"code": null,
"e": 28189,
"s": 28125,
"text": "constructor(props) {\n super(props);\n console.log(this.props);\n}"
},
{
"code": null,
"e": 28318,
"s": 28189,
"text": "When you call the super() function, the parent class constructor is called, which is in the case of a React is React.Component. "
},
{
"code": null,
"e": 28820,
"s": 28318,
"text": "Step 2: Never call setState() inside constructor()The constructor of your component is the ideal place to set the component’s initial state. You must set the initial state directly, rather than using setState() as you can in other methods in your class:constructor(props) {\n super(props);\n\n this.state = {\n name 'kapil',\n age: 22,\n };\n}The only place you can assign the local state directly like that is the constructor. You should depend on setState() somewhere else inside our component instead."
},
{
"code": null,
"e": 28871,
"s": 28820,
"text": "Step 2: Never call setState() inside constructor()"
},
{
"code": null,
"e": 29075,
"s": 28871,
"text": "The constructor of your component is the ideal place to set the component’s initial state. You must set the initial state directly, rather than using setState() as you can in other methods in your class:"
},
{
"code": null,
"e": 29163,
"s": 29075,
"text": "constructor(props) {\n super(props);\n\n this.state = {\n name 'kapil',\n age: 22,\n };\n}"
},
{
"code": null,
"e": 29325,
"s": 29163,
"text": "The only place you can assign the local state directly like that is the constructor. You should depend on setState() somewhere else inside our component instead."
},
{
"code": null,
"e": 29824,
"s": 29325,
"text": "Step 3: Avoid assigning values from this.props to this.stateYou should try to avoid setting values from the properties when setting the initial component state in the constructor. We can do the following:constructor(props) {\n super(props);\n\n this.state = {\n name: props.name,\n };\n}You wouldn’t be allowed to use setState() to change the property later. You may easily reference the property directly in your code by naming this.props.name, instead of assigning the property directly to the state."
},
{
"code": null,
"e": 29885,
"s": 29824,
"text": "Step 3: Avoid assigning values from this.props to this.state"
},
{
"code": null,
"e": 30030,
"s": 29885,
"text": "You should try to avoid setting values from the properties when setting the initial component state in the constructor. We can do the following:"
},
{
"code": null,
"e": 30110,
"s": 30030,
"text": "constructor(props) {\n super(props);\n\n this.state = {\n name: props.name,\n };\n}"
},
{
"code": null,
"e": 30326,
"s": 30110,
"text": "You wouldn’t be allowed to use setState() to change the property later. You may easily reference the property directly in your code by naming this.props.name, instead of assigning the property directly to the state."
},
{
"code": null,
"e": 30629,
"s": 30326,
"text": "Step 4: Bind events all in one placeWe can easily bind your event handlers in the constructor:constructor(props) {\n super(props);\n\n this.state = {\n // Sets that initial state\n };\n\n // Our event handlers\n this.onClick = this.onClick.bind(this);\n this.onKeyUp = this.onKeyUp.bind(this);\n // Rest Code\n}"
},
{
"code": null,
"e": 30666,
"s": 30629,
"text": "Step 4: Bind events all in one place"
},
{
"code": null,
"e": 30725,
"s": 30666,
"text": "We can easily bind your event handlers in the constructor:"
},
{
"code": null,
"e": 30934,
"s": 30725,
"text": "constructor(props) {\n super(props);\n\n this.state = {\n // Sets that initial state\n };\n\n // Our event handlers\n this.onClick = this.onClick.bind(this);\n this.onKeyUp = this.onKeyUp.bind(this);\n // Rest Code\n}"
},
{
"code": null,
"e": 30962,
"s": 30934,
"text": "Creating React Application:"
},
{
"code": null,
"e": 31057,
"s": 30962,
"text": "Step 1: Create a React application using the following command.npx create-react-app foldername"
},
{
"code": null,
"e": 31121,
"s": 31057,
"text": "Step 1: Create a React application using the following command."
},
{
"code": null,
"e": 31153,
"s": 31121,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 31266,
"s": 31153,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername"
},
{
"code": null,
"e": 31366,
"s": 31266,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command."
},
{
"code": null,
"e": 31380,
"s": 31366,
"text": "cd foldername"
},
{
"code": null,
"e": 31432,
"s": 31380,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 31618,
"s": 31432,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. The following example covers constructor demonstration."
},
{
"code": null,
"e": 31625,
"s": 31618,
"text": "App.js"
},
{
"code": "import React, { Component } from 'react'; class App extends Component { constructor(props) { // Calling super class constructor super(props); // Creating state this.state = { data: 'My name is User' } // Binding event handler this.handleEvent = this.handleEvent.bind(this); } handleEvent() { console.log(this.props); } render() { return ( <div > <input type=\"text\" value={this.state.data} /> <br></br> <br></br> <button onClick={this.handleEvent}>Please Click</button> </div> ); }} export default App;",
"e": 32221,
"s": 31625,
"text": null
},
{
"code": null,
"e": 32335,
"s": 32221,
"text": "Step to Run Application: Run the application from the root directory of the project, using the following command"
},
{
"code": null,
"e": 32345,
"s": 32335,
"text": "npm start"
},
{
"code": null,
"e": 32353,
"s": 32345,
"text": "Output:"
},
{
"code": null,
"e": 32360,
"s": 32353,
"text": "Picked"
},
{
"code": null,
"e": 32377,
"s": 32360,
"text": "React.js-Methods"
},
{
"code": null,
"e": 32385,
"s": 32377,
"text": "ReactJS"
},
{
"code": null,
"e": 32483,
"s": 32385,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32510,
"s": 32483,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 32548,
"s": 32510,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 32590,
"s": 32548,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 32625,
"s": 32590,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 32683,
"s": 32625,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 32735,
"s": 32683,
"text": "How to create a multi-page website using React.js ?"
},
{
"code": null,
"e": 32792,
"s": 32735,
"text": "How to build a basic CRUD app with Node.js and ReactJS ?"
},
{
"code": null,
"e": 32825,
"s": 32792,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 32863,
"s": 32825,
"text": "How to check the version of ReactJS ?"
}
] |
AUC-ROC Curve - GeeksforGeeks
|
07 Jan, 2022
One important aspect of Machine Learning is model evaluation. You need to have some mechanism to evaluate your model. This is where these performance metrics come into the picture they give us a sense of how good a model is. If you are familiar with some basics of Machine Learning then you must have across some of these metrics like accuracy, precision, recall, auc-roc, etc.
Let’s say you are working on a binary classification problem and come up with a model with 95% accuracy, now someone asks you what does that mean you would be quick enough to say out of 100 predictions your model makes, 95 of them are correct. Well lets notch it up a bit, now the underlying metric is recall and you are asked the same question, you might take a moment here but eventually, you would come up with an explanation like out of 100 relevant data points(positive class in general) your model is able to identify 80 of them. So far so good, now let us assume you evaluated your model using AUC-ROC as a metric and got a value of 0.75 and again I shoot the same question at you what does 0.75 or 75% signify, now you might need to give it a thought, some of you might say there is a 75% chance that model identifies a data point correctly but by now you would have already realized that’s not it. Let us try to get a basic understanding of one the most used performance metrics out there for classification problems.
History:
If you have participated in any online machine learning competition/hackathon then you must have come across Area Under Curve Receiver Operator Characteristic a.k.a AUC-ROC, many of them have it as their evaluation criteria for their classification problems. Let’s admit when you had first heard about it, this thought once must have crossed your mind, what’s with the long name? Well, the origin of ROC curve goes way back in World War II, it was originally used for the analysis of radar signals. The United States Army tried to measure the ability of their radar receiver to correctly identify the Japanese Aircraft. Now that we have a bit of origin story lets get down to business
Geometric Interpretation:
This is the most common definition that you would have encountered when you would Google AUC-ROC. Basically, ROC curve is a graph that shows the performance of a classification model at all possible thresholds( threshold is a particular value beyond which you say a point belongs to a particular class). The curve is plotted between two parameters
TRUE POSITIVE RATE
FALSE POSITIVE RATE
Before understanding, TPR and FPR let us quickly look at the confusion matrix.
Source: Creative Commons
True Positive: Actual Positive and Predicted as Positive
True Negative: Actual Negative and Predicted as Negative
False Positive(Type I Error): Actual Negative but predicted as Positive
False Negative(Type II Error): Actual Positive but predicted as Negative
In simple terms, you can call False Positive as false alarm and False Negative as a miss. Now let us look at what TPR and FPR.
Basically TPR/Recall/Sensitivity is ratio of positive examples that are correctly identified and FPR is the ratio of negative examples that are incorrectly classified.
and as said earlier ROC is nothing but the plot between TPR and FPR across all possible thresholds and AUC is the entire area beneath this ROC curve.
Source: Creative Commons
PROBABILISITC INTERPRETION:
We looked at the geometric interpretation, but I guess it is still not enough in developing the intuition behind what does 0.75 AUC actually means, now let us look at AUC-ROC with a probabilistic point of view.
Let me first talk about what AUC does and later we will build our understanding on top of this
AUC measures how well a model is able to distinguish between classes
An AUC of 0.75 would actually mean that let’s say we take two data points belonging to separate classes then there is 75% chance model would be able to segregate them or rank order them correctly i.e positive point has a higher prediction probability than the negative class. (assuming a higher prediction probability means the point would ideally belong to the positive class)
Here is a small example to make things more clear.
Here we have 6 points where P1, P2, P5 belong to class 1 and P3, P4, P6 belong to class 0 and we’re corresponding predicted probabilities in the Probability column, as we said if we take two points belonging to separate classes then what is the probability that model rank orders them correctly
We will take all possible pairs such that one point belongs to class 1 and other belongs to class 0, we will have total 9 such pairs below are all of these 9 possible pairs
Here column isCorrect tells if the mentioned pair is correct rank-ordered based on the predicted probability i.e class 1 point has a higher probability than class 0 point, in 7 out of these 9 possible pairs the class 1 is ranked higher than class 0, or we can say that there is a 77% chance that if you pick a pair of points belonging to separate classes the model would be able to distinguish them correctly. Now, I think you might have a bit intuition behind this AUC number, just to clear up any further doubts lets validate it using scikit learn’s AUC-ROC implementation
Python implementation code:
python3
import numpy as np from sklearn .metrics import roc_auc_score y_true = [1, 1, 0, 0, 1, 0] y_pred = [0.95, 0.90, 0.85, 0.81, 0.78, 0.70] auc = np.round(roc_auc_score(y_true, y_pred), 3) print("Auc for our sample data is {}". format(auc))
When to use:
Having said that there certain places where ROC-AUC might not be ideal.
ROC-AUC does not work well under severe imbalance in the dataset, to give some intuition for this lets us look back at the geometric interpretation here. Basically, ROC is the plot between TPR and FPR( assuming the minority class is a positive class), now let us have a close look at the FPR formula again
Denominator of FPR has a True Negatives as one factor since Negative Class is in majority the denominator of FPR is dominated by True Negatives which makes FPR less sensitive to any changes in minority class predictions. To overcome this, Precision-Recall Curves are used instead of ROC and then the AUC is calculated, try to answer this yourself how does Precision-Recall curve handle this problem (Hint: Recall and TPR are same technically only FPR is replaced with Precision, just compare the denominators for both and try to assess how imbalance problem is solved here)
ROC-AUC tries to measure if the rank ordering of classifications is correct it does not take into account actually predicted probabilities, let me try to make this point clear with a small code snippet
python3
import pandas as pd y_pred_1 = [0.99, 0.98, 0.97, 0.96, 0.91, 0.90, 0.89, 0.88]y_pred_2 = [0.99, 0.95, 0.90, 0.85, 0.20, 0.15, 0.10, 0.05]y_act = [1, 1, 1, 1, 0, 0, 0, 0]test_df = pd.DataFrame(zip(y_act, y_pred_1, y_pred_2), columns=['Class', 'Model_1', 'Model_2'])
Class Probabilities for two sample models
We have two models Model_1 and Model_2 as mentioned above, both do a perfect job in segregating the two classes, but if I ask you to choose one among them which one would it be, hold on to your answer let me first plot these model probabilities.
python3
import matplotlib.pyplot as plt cols = ['Model_1', 'Model_2']fig, axs = plt.subplots(1, 2, figsize=(15, 5))for index, col in enumerate(cols): sns.kdeplot(d2[d2['Status'] == 1][col], label="Class 1", shade=True, ax=axs[index]) sns.kdeplot(d2[d2['Status'] == 0][col], label="Class 0", shade=True, ax=axs[index]) axs[index].set_xlabel(col)plt.show()
Class Probability Distribution for sample models
If there were any slightest of doubts earlier, I guess now your choice would quite clear, Model_2 is a clear winner. But the AUC-ROC values would be same for both, this is the drawback it just measures if the model is able to rank order the classes correctly it does not look at how well the model separates the two classes, hence if you have a requirement where you want to use the actually predicted probabilities then roc might not be the right choice, for those who are curious log loss is one such metric that solves this problem
So ideally one should use AUC when there dataset does not have a severe imbalance and when your use case does not require you to use actual predicted probabilities.
AUC FOR MULTI-CLASS:
For a multi-class setting, we can simply use one vs all methodology and you will have one ROC curve for each class. Let’s say you have four classes A, B, C, D then there would ROC curves and corresponding AUC values for all the four classes, i.e. once A would be one class and B, C and D combined would be the others class, similarly B is one class and A, C and D combined as others class, etc.
apoorvjoshi23
Technical Scripter 2020
Machine Learning
Technical Scripter
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
Intuition of Adam Optimizer
CNN | Introduction to Pooling Layer
Convolutional Neural Network (CNN) in Machine Learning
Markov Decision Process
k-nearest neighbor algorithm in Python
Singular Value Decomposition (SVD)
Q-Learning in Python
SARSA Reinforcement Learning
|
[
{
"code": null,
"e": 25615,
"s": 25587,
"text": "\n07 Jan, 2022"
},
{
"code": null,
"e": 25993,
"s": 25615,
"text": "One important aspect of Machine Learning is model evaluation. You need to have some mechanism to evaluate your model. This is where these performance metrics come into the picture they give us a sense of how good a model is. If you are familiar with some basics of Machine Learning then you must have across some of these metrics like accuracy, precision, recall, auc-roc, etc."
},
{
"code": null,
"e": 27020,
"s": 25993,
"text": "Let’s say you are working on a binary classification problem and come up with a model with 95% accuracy, now someone asks you what does that mean you would be quick enough to say out of 100 predictions your model makes, 95 of them are correct. Well lets notch it up a bit, now the underlying metric is recall and you are asked the same question, you might take a moment here but eventually, you would come up with an explanation like out of 100 relevant data points(positive class in general) your model is able to identify 80 of them. So far so good, now let us assume you evaluated your model using AUC-ROC as a metric and got a value of 0.75 and again I shoot the same question at you what does 0.75 or 75% signify, now you might need to give it a thought, some of you might say there is a 75% chance that model identifies a data point correctly but by now you would have already realized that’s not it. Let us try to get a basic understanding of one the most used performance metrics out there for classification problems."
},
{
"code": null,
"e": 27029,
"s": 27020,
"text": "History:"
},
{
"code": null,
"e": 27714,
"s": 27029,
"text": "If you have participated in any online machine learning competition/hackathon then you must have come across Area Under Curve Receiver Operator Characteristic a.k.a AUC-ROC, many of them have it as their evaluation criteria for their classification problems. Let’s admit when you had first heard about it, this thought once must have crossed your mind, what’s with the long name? Well, the origin of ROC curve goes way back in World War II, it was originally used for the analysis of radar signals. The United States Army tried to measure the ability of their radar receiver to correctly identify the Japanese Aircraft. Now that we have a bit of origin story lets get down to business"
},
{
"code": null,
"e": 27740,
"s": 27714,
"text": "Geometric Interpretation:"
},
{
"code": null,
"e": 28088,
"s": 27740,
"text": "This is the most common definition that you would have encountered when you would Google AUC-ROC. Basically, ROC curve is a graph that shows the performance of a classification model at all possible thresholds( threshold is a particular value beyond which you say a point belongs to a particular class). The curve is plotted between two parameters"
},
{
"code": null,
"e": 28107,
"s": 28088,
"text": "TRUE POSITIVE RATE"
},
{
"code": null,
"e": 28127,
"s": 28107,
"text": "FALSE POSITIVE RATE"
},
{
"code": null,
"e": 28206,
"s": 28127,
"text": "Before understanding, TPR and FPR let us quickly look at the confusion matrix."
},
{
"code": null,
"e": 28231,
"s": 28206,
"text": "Source: Creative Commons"
},
{
"code": null,
"e": 28288,
"s": 28231,
"text": "True Positive: Actual Positive and Predicted as Positive"
},
{
"code": null,
"e": 28345,
"s": 28288,
"text": "True Negative: Actual Negative and Predicted as Negative"
},
{
"code": null,
"e": 28417,
"s": 28345,
"text": "False Positive(Type I Error): Actual Negative but predicted as Positive"
},
{
"code": null,
"e": 28490,
"s": 28417,
"text": "False Negative(Type II Error): Actual Positive but predicted as Negative"
},
{
"code": null,
"e": 28617,
"s": 28490,
"text": "In simple terms, you can call False Positive as false alarm and False Negative as a miss. Now let us look at what TPR and FPR."
},
{
"code": null,
"e": 28785,
"s": 28617,
"text": "Basically TPR/Recall/Sensitivity is ratio of positive examples that are correctly identified and FPR is the ratio of negative examples that are incorrectly classified."
},
{
"code": null,
"e": 28935,
"s": 28785,
"text": "and as said earlier ROC is nothing but the plot between TPR and FPR across all possible thresholds and AUC is the entire area beneath this ROC curve."
},
{
"code": null,
"e": 28960,
"s": 28935,
"text": "Source: Creative Commons"
},
{
"code": null,
"e": 28988,
"s": 28960,
"text": "PROBABILISITC INTERPRETION:"
},
{
"code": null,
"e": 29199,
"s": 28988,
"text": "We looked at the geometric interpretation, but I guess it is still not enough in developing the intuition behind what does 0.75 AUC actually means, now let us look at AUC-ROC with a probabilistic point of view."
},
{
"code": null,
"e": 29294,
"s": 29199,
"text": "Let me first talk about what AUC does and later we will build our understanding on top of this"
},
{
"code": null,
"e": 29363,
"s": 29294,
"text": "AUC measures how well a model is able to distinguish between classes"
},
{
"code": null,
"e": 29741,
"s": 29363,
"text": "An AUC of 0.75 would actually mean that let’s say we take two data points belonging to separate classes then there is 75% chance model would be able to segregate them or rank order them correctly i.e positive point has a higher prediction probability than the negative class. (assuming a higher prediction probability means the point would ideally belong to the positive class)"
},
{
"code": null,
"e": 29792,
"s": 29741,
"text": "Here is a small example to make things more clear."
},
{
"code": null,
"e": 30087,
"s": 29792,
"text": "Here we have 6 points where P1, P2, P5 belong to class 1 and P3, P4, P6 belong to class 0 and we’re corresponding predicted probabilities in the Probability column, as we said if we take two points belonging to separate classes then what is the probability that model rank orders them correctly"
},
{
"code": null,
"e": 30260,
"s": 30087,
"text": "We will take all possible pairs such that one point belongs to class 1 and other belongs to class 0, we will have total 9 such pairs below are all of these 9 possible pairs"
},
{
"code": null,
"e": 30835,
"s": 30260,
"text": "Here column isCorrect tells if the mentioned pair is correct rank-ordered based on the predicted probability i.e class 1 point has a higher probability than class 0 point, in 7 out of these 9 possible pairs the class 1 is ranked higher than class 0, or we can say that there is a 77% chance that if you pick a pair of points belonging to separate classes the model would be able to distinguish them correctly. Now, I think you might have a bit intuition behind this AUC number, just to clear up any further doubts lets validate it using scikit learn’s AUC-ROC implementation"
},
{
"code": null,
"e": 30865,
"s": 30835,
"text": "Python implementation code: "
},
{
"code": null,
"e": 30873,
"s": 30865,
"text": "python3"
},
{
"code": "import numpy as np from sklearn .metrics import roc_auc_score y_true = [1, 1, 0, 0, 1, 0] y_pred = [0.95, 0.90, 0.85, 0.81, 0.78, 0.70] auc = np.round(roc_auc_score(y_true, y_pred), 3) print(\"Auc for our sample data is {}\". format(auc))",
"e": 31110,
"s": 30873,
"text": null
},
{
"code": null,
"e": 31123,
"s": 31110,
"text": "When to use:"
},
{
"code": null,
"e": 31195,
"s": 31123,
"text": "Having said that there certain places where ROC-AUC might not be ideal."
},
{
"code": null,
"e": 31501,
"s": 31195,
"text": "ROC-AUC does not work well under severe imbalance in the dataset, to give some intuition for this lets us look back at the geometric interpretation here. Basically, ROC is the plot between TPR and FPR( assuming the minority class is a positive class), now let us have a close look at the FPR formula again"
},
{
"code": null,
"e": 32075,
"s": 31501,
"text": "Denominator of FPR has a True Negatives as one factor since Negative Class is in majority the denominator of FPR is dominated by True Negatives which makes FPR less sensitive to any changes in minority class predictions. To overcome this, Precision-Recall Curves are used instead of ROC and then the AUC is calculated, try to answer this yourself how does Precision-Recall curve handle this problem (Hint: Recall and TPR are same technically only FPR is replaced with Precision, just compare the denominators for both and try to assess how imbalance problem is solved here)"
},
{
"code": null,
"e": 32277,
"s": 32075,
"text": "ROC-AUC tries to measure if the rank ordering of classifications is correct it does not take into account actually predicted probabilities, let me try to make this point clear with a small code snippet"
},
{
"code": null,
"e": 32285,
"s": 32277,
"text": "python3"
},
{
"code": "import pandas as pd y_pred_1 = [0.99, 0.98, 0.97, 0.96, 0.91, 0.90, 0.89, 0.88]y_pred_2 = [0.99, 0.95, 0.90, 0.85, 0.20, 0.15, 0.10, 0.05]y_act = [1, 1, 1, 1, 0, 0, 0, 0]test_df = pd.DataFrame(zip(y_act, y_pred_1, y_pred_2), columns=['Class', 'Model_1', 'Model_2'])",
"e": 32573,
"s": 32285,
"text": null
},
{
"code": null,
"e": 32615,
"s": 32573,
"text": "Class Probabilities for two sample models"
},
{
"code": null,
"e": 32861,
"s": 32615,
"text": "We have two models Model_1 and Model_2 as mentioned above, both do a perfect job in segregating the two classes, but if I ask you to choose one among them which one would it be, hold on to your answer let me first plot these model probabilities."
},
{
"code": null,
"e": 32869,
"s": 32861,
"text": "python3"
},
{
"code": "import matplotlib.pyplot as plt cols = ['Model_1', 'Model_2']fig, axs = plt.subplots(1, 2, figsize=(15, 5))for index, col in enumerate(cols): sns.kdeplot(d2[d2['Status'] == 1][col], label=\"Class 1\", shade=True, ax=axs[index]) sns.kdeplot(d2[d2['Status'] == 0][col], label=\"Class 0\", shade=True, ax=axs[index]) axs[index].set_xlabel(col)plt.show()",
"e": 33255,
"s": 32869,
"text": null
},
{
"code": null,
"e": 33304,
"s": 33255,
"text": "Class Probability Distribution for sample models"
},
{
"code": null,
"e": 33839,
"s": 33304,
"text": "If there were any slightest of doubts earlier, I guess now your choice would quite clear, Model_2 is a clear winner. But the AUC-ROC values would be same for both, this is the drawback it just measures if the model is able to rank order the classes correctly it does not look at how well the model separates the two classes, hence if you have a requirement where you want to use the actually predicted probabilities then roc might not be the right choice, for those who are curious log loss is one such metric that solves this problem"
},
{
"code": null,
"e": 34004,
"s": 33839,
"text": "So ideally one should use AUC when there dataset does not have a severe imbalance and when your use case does not require you to use actual predicted probabilities."
},
{
"code": null,
"e": 34025,
"s": 34004,
"text": "AUC FOR MULTI-CLASS:"
},
{
"code": null,
"e": 34420,
"s": 34025,
"text": "For a multi-class setting, we can simply use one vs all methodology and you will have one ROC curve for each class. Let’s say you have four classes A, B, C, D then there would ROC curves and corresponding AUC values for all the four classes, i.e. once A would be one class and B, C and D combined would be the others class, similarly B is one class and A, C and D combined as others class, etc."
},
{
"code": null,
"e": 34434,
"s": 34420,
"text": "apoorvjoshi23"
},
{
"code": null,
"e": 34458,
"s": 34434,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 34475,
"s": 34458,
"text": "Machine Learning"
},
{
"code": null,
"e": 34494,
"s": 34475,
"text": "Technical Scripter"
},
{
"code": null,
"e": 34511,
"s": 34494,
"text": "Machine Learning"
},
{
"code": null,
"e": 34609,
"s": 34511,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34650,
"s": 34609,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 34683,
"s": 34650,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 34711,
"s": 34683,
"text": "Intuition of Adam Optimizer"
},
{
"code": null,
"e": 34747,
"s": 34711,
"text": "CNN | Introduction to Pooling Layer"
},
{
"code": null,
"e": 34802,
"s": 34747,
"text": "Convolutional Neural Network (CNN) in Machine Learning"
},
{
"code": null,
"e": 34826,
"s": 34802,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 34865,
"s": 34826,
"text": "k-nearest neighbor algorithm in Python"
},
{
"code": null,
"e": 34900,
"s": 34865,
"text": "Singular Value Decomposition (SVD)"
},
{
"code": null,
"e": 34921,
"s": 34900,
"text": "Q-Learning in Python"
}
] |
Least Square Regression Line - GeeksforGeeks
|
07 Jul, 2021
Given a set of coordinates in the form of (X, Y), the task is to find the least regression line that can be formed.
In statistics, Linear Regression is a linear approach to model the relationship between a scalar response (or dependent variable), say Y, and one or more explanatory variables (or independent variables), say X. Regression Line: If our data shows a linear relationship between X and Y, then the straight line which best describes the relationship is the regression line. It is the straight line that covers the maximum points in the graph.
Examples:
Input: X = [95, 85, 80, 70, 60] Y = [90, 80, 70, 65, 60] Output: Y = 5.685 + 0.863*X Explanation: The graph of the data given below is: X = [95, 85, 80, 70, 60] Y = [90, 80, 70, 65, 60] The regression line obtained is Y = 5.685 + 0.863*X
The graph shows that the regression line is the line that covers the maximum of the points.Input: X = [100, 95, 85, 80, 70, 60] Y = [90, 95, 80, 70, 65, 60] Output: Y = 4.007 + 0.89*X
Approach:
A regression line is given as Y = a + b*X where the formula of b and a are given as: b = (nΣ(xiyi) – Σ(xi)Σ(yi)) ÷ (nΣ(xi2)-Σ(xi)2) a = ȳ – b.x̄ where x̄ and ȳ are mean of x and y respectively.
To find regression line, we need to find a and b.Calculate a, which is given by Calculate b, which is given by Put value of a and b in the equation of regression line.
To find regression line, we need to find a and b.
Calculate a, which is given by
Calculate b, which is given by
Put value of a and b in the equation of regression line.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program to find the// regression line#include<bits/stdc++.h>using namespace std; // Function to calculate bdouble calculateB(int x[], int y[], int n){ // sum of array x int sx = accumulate(x, x + n, 0); // sum of array y int sy = accumulate(y, y + n, 0); // for sum of product of x and y int sxsy = 0; // sum of square of x int sx2 = 0; for(int i = 0; i < n; i++) { sxsy += x[i] * y[i]; sx2 += x[i] * x[i]; } double b = (double)(n * sxsy - sx * sy) / (n * sx2 - sx * sx); return b;} // Function to find the// least regression linevoid leastRegLine( int X[], int Y[], int n){ // Finding b double b = calculateB(X, Y, n); int meanX = accumulate(X, X + n, 0) / n; int meanY = accumulate(Y, Y + n, 0) / n; // Calculating a double a = meanY - b * meanX; // Printing regression line cout << ("Regression line:") << endl; cout << ("Y = "); printf("%.3f + ", a); printf("%.3f *X", b);} // Driver codeint main(){ // Statistical data int X[] = { 95, 85, 80, 70, 60 }; int Y[] = { 90, 80, 70, 65, 60 }; int n = sizeof(X) / sizeof(X[0]); leastRegLine(X, Y, n);} // This code is contributed by PrinciRaj1992
// Java program to find the// regression line import java.util.Arrays; public class GFG { // Function to calculate b private static double calculateB( int[] x, int[] y) { int n = x.length; // sum of array x int sx = Arrays.stream(x).sum(); // sum of array y int sy = Arrays.stream(y).sum(); // for sum of product of x and y int sxsy = 0; // sum of square of x int sx2 = 0; for (int i = 0; i < n; i++) { sxsy += x[i] * y[i]; sx2 += x[i] * x[i]; } double b = (double)(n * sxsy - sx * sy) / (n * sx2 - sx * sx); return b; } // Function to find the // least regression line public static void leastRegLine( int X[], int Y[]) { // Finding b double b = calculateB(X, Y); int n = X.length; int meanX = Arrays.stream(X).sum() / n; int meanY = Arrays.stream(Y).sum() / n; // calculating a double a = meanY - b * meanX; // Printing regression line System.out.println("Regression line:"); System.out.print("Y = "); System.out.printf("%.3f", a); System.out.print(" + "); System.out.printf("%.3f", b); System.out.print("*X"); } // Driver code public static void main(String[] args) { // statistical data int X[] = { 95, 85, 80, 70, 60 }; int Y[] = { 90, 80, 70, 65, 60 }; leastRegLine(X, Y); }}
# Python program to find the# regression line # Function to calculate bdef calculateB(x, y, n): # sum of array x sx = sum(x) # sum of array y sy = sum(y) # for sum of product of x and y sxsy = 0 # sum of square of x sx2 = 0 for i in range(n): sxsy += x[i] * y[i] sx2 += x[i] * x[i] b = (n * sxsy - sx * sy)/(n * sx2 - sx * sx) return b # Function to find the# least regression linedef leastRegLine(X,Y,n): # Finding b b = calculateB(X, Y, n) meanX = int(sum(X)/n) meanY = int(sum(Y)/n) # Calculating a a = meanY - b * meanX # Printing regression line print("Regression line:") print("Y = ", '%.3f'%a, " + ", '%.3f'%b, "*X", sep="") # Driver code # Statistical dataX = [95, 85, 80, 70, 60 ]Y = [90, 80, 70, 65, 60 ]n = len(X)leastRegLine(X, Y, n) # This code is contributed by avanitrachhadiya2155
// C# program to find the// regression lineusing System;using System.Linq; class GFG{ // Function to calculate bprivate static double calculateB(int[] x, int[] y){ int n = x.Length; // Sum of array x int sx = x.Sum(); // Sum of array y int sy = y.Sum(); // For sum of product of x and y int sxsy = 0; // Sum of square of x int sx2 = 0; for(int i = 0; i < n; i++) { sxsy += x[i] * y[i]; sx2 += x[i] * x[i]; } double b = (double)(n * sxsy - sx * sy) / (n * sx2 - sx * sx); return b;} // Function to find the// least regression linepublic static void leastRegLine(int []X, int []Y){ // Finding b double b = calculateB(X, Y); int n = X.Length; int meanX = X.Sum() / n; int meanY = Y.Sum() / n; // Calculating a double a = meanY - b * meanX; // Printing regression line Console.WriteLine("Regression line:"); Console.Write("Y = "); Console.Write("{0:F3}",a ); Console.Write(" + "); Console.Write("{0:F3}", b); Console.Write("*X");} // Driver codepublic static void Main(String[] args){ // Statistical data int []X = { 95, 85, 80, 70, 60 }; int []Y = { 90, 80, 70, 65, 60 }; leastRegLine(X, Y);}} // This code is contributed by gauravrajput1
<script>// Javascript program to find the// regression line // Function to calculate bfunction calculateB(x,y){ let n = x.length; // sum of array x let sx = x.reduce((a, b) => a + b, 0); // sum of array y let sy =y.reduce((a, b) => a + b, 0) // for sum of product of x and y let sxsy = 0; // sum of square of x let sx2 = 0; for (let i = 0; i < n; i++) { sxsy += x[i] * y[i]; sx2 += x[i] * x[i]; } let b = (n * sxsy - sx * sy) / (n * sx2 - sx * sx); return b;} // Function to find the // least regression linefunction leastRegLine(X,Y){ // Finding b let b = calculateB(X, Y); let n = X.length; let meanX = X.reduce((a, b) => a + b, 0) / n; let meanY = Y.reduce((a, b) => a + b, 0) / n; // calculating a let a = meanY - b * meanX; // Printing regression line document.write("Regression line:<br>"); document.write("Y = "); document.write( a.toFixed(3)); document.write(" + "); document.write( b.toFixed(3)); document.write("*X");} // Driver code// statistical datalet X = [95, 85, 80, 70, 60 ];let Y = [90, 80, 70, 65, 60];leastRegLine(X, Y); // This code is contributed by ab2127</script>
Regression line:
Y = 5.685 + 0.863*X
GauravRajput1
princiraj1992
avanitrachhadiya2155
ab2127
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Modular multiplicative inverse
Count all possible paths from top left to bottom right of a mXn matrix
Fizz Buzz Implementation
Check if a number is Palindrome
Program to multiply two matrices
Merge two sorted arrays with O(1) extra space
Generate all permutation of a set in Python
Count ways to reach the n'th stair
|
[
{
"code": null,
"e": 25963,
"s": 25935,
"text": "\n07 Jul, 2021"
},
{
"code": null,
"e": 26080,
"s": 25963,
"text": "Given a set of coordinates in the form of (X, Y), the task is to find the least regression line that can be formed. "
},
{
"code": null,
"e": 26519,
"s": 26080,
"text": "In statistics, Linear Regression is a linear approach to model the relationship between a scalar response (or dependent variable), say Y, and one or more explanatory variables (or independent variables), say X. Regression Line: If our data shows a linear relationship between X and Y, then the straight line which best describes the relationship is the regression line. It is the straight line that covers the maximum points in the graph."
},
{
"code": null,
"e": 26531,
"s": 26519,
"text": "Examples: "
},
{
"code": null,
"e": 26771,
"s": 26531,
"text": "Input: X = [95, 85, 80, 70, 60] Y = [90, 80, 70, 65, 60] Output: Y = 5.685 + 0.863*X Explanation: The graph of the data given below is: X = [95, 85, 80, 70, 60] Y = [90, 80, 70, 65, 60] The regression line obtained is Y = 5.685 + 0.863*X "
},
{
"code": null,
"e": 26957,
"s": 26771,
"text": "The graph shows that the regression line is the line that covers the maximum of the points.Input: X = [100, 95, 85, 80, 70, 60] Y = [90, 95, 80, 70, 65, 60] Output: Y = 4.007 + 0.89*X "
},
{
"code": null,
"e": 26969,
"s": 26957,
"text": "Approach: "
},
{
"code": null,
"e": 27167,
"s": 26969,
"text": "A regression line is given as Y = a + b*X where the formula of b and a are given as: b = (nΣ(xiyi) – Σ(xi)Σ(yi)) ÷ (nΣ(xi2)-Σ(xi)2) a = ȳ – b.x̄ where x̄ and ȳ are mean of x and y respectively. "
},
{
"code": null,
"e": 27336,
"s": 27167,
"text": "To find regression line, we need to find a and b.Calculate a, which is given by Calculate b, which is given by Put value of a and b in the equation of regression line."
},
{
"code": null,
"e": 27386,
"s": 27336,
"text": "To find regression line, we need to find a and b."
},
{
"code": null,
"e": 27418,
"s": 27386,
"text": "Calculate a, which is given by "
},
{
"code": null,
"e": 27451,
"s": 27418,
"text": "Calculate b, which is given by "
},
{
"code": null,
"e": 27508,
"s": 27451,
"text": "Put value of a and b in the equation of regression line."
},
{
"code": null,
"e": 27560,
"s": 27508,
"text": "Below is the implementation of the above approach. "
},
{
"code": null,
"e": 27564,
"s": 27560,
"text": "C++"
},
{
"code": null,
"e": 27569,
"s": 27564,
"text": "Java"
},
{
"code": null,
"e": 27577,
"s": 27569,
"text": "Python3"
},
{
"code": null,
"e": 27580,
"s": 27577,
"text": "C#"
},
{
"code": null,
"e": 27591,
"s": 27580,
"text": "Javascript"
},
{
"code": "// C++ program to find the// regression line#include<bits/stdc++.h>using namespace std; // Function to calculate bdouble calculateB(int x[], int y[], int n){ // sum of array x int sx = accumulate(x, x + n, 0); // sum of array y int sy = accumulate(y, y + n, 0); // for sum of product of x and y int sxsy = 0; // sum of square of x int sx2 = 0; for(int i = 0; i < n; i++) { sxsy += x[i] * y[i]; sx2 += x[i] * x[i]; } double b = (double)(n * sxsy - sx * sy) / (n * sx2 - sx * sx); return b;} // Function to find the// least regression linevoid leastRegLine( int X[], int Y[], int n){ // Finding b double b = calculateB(X, Y, n); int meanX = accumulate(X, X + n, 0) / n; int meanY = accumulate(Y, Y + n, 0) / n; // Calculating a double a = meanY - b * meanX; // Printing regression line cout << (\"Regression line:\") << endl; cout << (\"Y = \"); printf(\"%.3f + \", a); printf(\"%.3f *X\", b);} // Driver codeint main(){ // Statistical data int X[] = { 95, 85, 80, 70, 60 }; int Y[] = { 90, 80, 70, 65, 60 }; int n = sizeof(X) / sizeof(X[0]); leastRegLine(X, Y, n);} // This code is contributed by PrinciRaj1992",
"e": 28845,
"s": 27591,
"text": null
},
{
"code": "// Java program to find the// regression line import java.util.Arrays; public class GFG { // Function to calculate b private static double calculateB( int[] x, int[] y) { int n = x.length; // sum of array x int sx = Arrays.stream(x).sum(); // sum of array y int sy = Arrays.stream(y).sum(); // for sum of product of x and y int sxsy = 0; // sum of square of x int sx2 = 0; for (int i = 0; i < n; i++) { sxsy += x[i] * y[i]; sx2 += x[i] * x[i]; } double b = (double)(n * sxsy - sx * sy) / (n * sx2 - sx * sx); return b; } // Function to find the // least regression line public static void leastRegLine( int X[], int Y[]) { // Finding b double b = calculateB(X, Y); int n = X.length; int meanX = Arrays.stream(X).sum() / n; int meanY = Arrays.stream(Y).sum() / n; // calculating a double a = meanY - b * meanX; // Printing regression line System.out.println(\"Regression line:\"); System.out.print(\"Y = \"); System.out.printf(\"%.3f\", a); System.out.print(\" + \"); System.out.printf(\"%.3f\", b); System.out.print(\"*X\"); } // Driver code public static void main(String[] args) { // statistical data int X[] = { 95, 85, 80, 70, 60 }; int Y[] = { 90, 80, 70, 65, 60 }; leastRegLine(X, Y); }}",
"e": 30350,
"s": 28845,
"text": null
},
{
"code": "# Python program to find the# regression line # Function to calculate bdef calculateB(x, y, n): # sum of array x sx = sum(x) # sum of array y sy = sum(y) # for sum of product of x and y sxsy = 0 # sum of square of x sx2 = 0 for i in range(n): sxsy += x[i] * y[i] sx2 += x[i] * x[i] b = (n * sxsy - sx * sy)/(n * sx2 - sx * sx) return b # Function to find the# least regression linedef leastRegLine(X,Y,n): # Finding b b = calculateB(X, Y, n) meanX = int(sum(X)/n) meanY = int(sum(Y)/n) # Calculating a a = meanY - b * meanX # Printing regression line print(\"Regression line:\") print(\"Y = \", '%.3f'%a, \" + \", '%.3f'%b, \"*X\", sep=\"\") # Driver code # Statistical dataX = [95, 85, 80, 70, 60 ]Y = [90, 80, 70, 65, 60 ]n = len(X)leastRegLine(X, Y, n) # This code is contributed by avanitrachhadiya2155",
"e": 31239,
"s": 30350,
"text": null
},
{
"code": "// C# program to find the// regression lineusing System;using System.Linq; class GFG{ // Function to calculate bprivate static double calculateB(int[] x, int[] y){ int n = x.Length; // Sum of array x int sx = x.Sum(); // Sum of array y int sy = y.Sum(); // For sum of product of x and y int sxsy = 0; // Sum of square of x int sx2 = 0; for(int i = 0; i < n; i++) { sxsy += x[i] * y[i]; sx2 += x[i] * x[i]; } double b = (double)(n * sxsy - sx * sy) / (n * sx2 - sx * sx); return b;} // Function to find the// least regression linepublic static void leastRegLine(int []X, int []Y){ // Finding b double b = calculateB(X, Y); int n = X.Length; int meanX = X.Sum() / n; int meanY = Y.Sum() / n; // Calculating a double a = meanY - b * meanX; // Printing regression line Console.WriteLine(\"Regression line:\"); Console.Write(\"Y = \"); Console.Write(\"{0:F3}\",a ); Console.Write(\" + \"); Console.Write(\"{0:F3}\", b); Console.Write(\"*X\");} // Driver codepublic static void Main(String[] args){ // Statistical data int []X = { 95, 85, 80, 70, 60 }; int []Y = { 90, 80, 70, 65, 60 }; leastRegLine(X, Y);}} // This code is contributed by gauravrajput1",
"e": 32559,
"s": 31239,
"text": null
},
{
"code": "<script>// Javascript program to find the// regression line // Function to calculate bfunction calculateB(x,y){ let n = x.length; // sum of array x let sx = x.reduce((a, b) => a + b, 0); // sum of array y let sy =y.reduce((a, b) => a + b, 0) // for sum of product of x and y let sxsy = 0; // sum of square of x let sx2 = 0; for (let i = 0; i < n; i++) { sxsy += x[i] * y[i]; sx2 += x[i] * x[i]; } let b = (n * sxsy - sx * sy) / (n * sx2 - sx * sx); return b;} // Function to find the // least regression linefunction leastRegLine(X,Y){ // Finding b let b = calculateB(X, Y); let n = X.length; let meanX = X.reduce((a, b) => a + b, 0) / n; let meanY = Y.reduce((a, b) => a + b, 0) / n; // calculating a let a = meanY - b * meanX; // Printing regression line document.write(\"Regression line:<br>\"); document.write(\"Y = \"); document.write( a.toFixed(3)); document.write(\" + \"); document.write( b.toFixed(3)); document.write(\"*X\");} // Driver code// statistical datalet X = [95, 85, 80, 70, 60 ];let Y = [90, 80, 70, 65, 60];leastRegLine(X, Y); // This code is contributed by ab2127</script>",
"e": 33887,
"s": 32559,
"text": null
},
{
"code": null,
"e": 33924,
"s": 33887,
"text": "Regression line:\nY = 5.685 + 0.863*X"
},
{
"code": null,
"e": 33940,
"s": 33926,
"text": "GauravRajput1"
},
{
"code": null,
"e": 33954,
"s": 33940,
"text": "princiraj1992"
},
{
"code": null,
"e": 33975,
"s": 33954,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 33982,
"s": 33975,
"text": "ab2127"
},
{
"code": null,
"e": 33995,
"s": 33982,
"text": "Mathematical"
},
{
"code": null,
"e": 34008,
"s": 33995,
"text": "Mathematical"
},
{
"code": null,
"e": 34106,
"s": 34008,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34150,
"s": 34106,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 34192,
"s": 34150,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 34223,
"s": 34192,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 34294,
"s": 34223,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 34319,
"s": 34294,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 34351,
"s": 34319,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 34384,
"s": 34351,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 34430,
"s": 34384,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 34474,
"s": 34430,
"text": "Generate all permutation of a set in Python"
}
] |
Streamlined Data Ingestion with Pandas - GeeksforGeeks
|
09 Jul, 2021
Data Ingestion is the process of, transferring data, from varied sources to an approach, where it can be analyzed, archived, or utilized by an establishment. The usual steps, involved in this process, are drawing out data, from its current place, converting the data, and, finally loading it, in a location, for efficient research. Python provides many such tools, and, frameworks for data ingestion. These include Bonobo, Beautiful Soup4, Airflow, Pandas, etc. In this article, we will learn about Data Ingestion with Pandas library.
Data Ingestion with Pandas, is the process, of shifting data, from a variety of sources, into the Pandas DataFrame structure. The source of data can be varying file formats such as Comma Separated Data, JSON, HTML webpage table, Excel. In this article, we will learn about, transferring data, from such formats, into the destination, which is a Pandas dataframe object.
Approach:
The basic approach, for transferring any such data, into a dataframe object, is as follows –
Prepare your source data.Data can be present, on any remote server, or, on a local machine. We need to know, the URL of the file if it’s on a remote server. The path of the file, on local machine, is required, if data is present locally.
Data can be present, on any remote server, or, on a local machine. We need to know, the URL of the file if it’s on a remote server. The path of the file, on local machine, is required, if data is present locally.
Use Pandas ‘read_x’ methodPandas provide ‘read_x’ methods, for loading and converting the data, into a Dataframe object.Depending on the data format, use the ‘read’ method.
Pandas provide ‘read_x’ methods, for loading and converting the data, into a Dataframe object.
Depending on the data format, use the ‘read’ method.
Print data from DataFrame object.Print the dataframe object, to verify, that the conversion was smooth.
Print the dataframe object, to verify, that the conversion was smooth.
In this article, we will be converting, data present in the following files, to dataframe structures –
Read data from CSV fileRead data from Excel fileRead data from JSON fileRead data from ClipboardRead data from HTML table from web pageRead data from SQLite table
Read data from CSV file
Read data from Excel file
Read data from JSON file
Read data from Clipboard
Read data from HTML table from web page
Read data from SQLite table
To load, data present in Comma-separated file(CSV), we will follow steps as below:
Prepare your sample dataset. Here, we have a CSV file, containing information, about Indian Metro cities. It describes if the city is a Tier1 or Tier2 city, their geographical location, state they belong to, and if it is a coastal city.
Use Pandas method ‘read_csv’Method used – read_csv(file_path)Parameter – String format, containing the path of the file and its name, or, URL when present on the remote server. It reads, the file data, and, converts it, into a valid two-dimensional dataframe object. This method can be used to read data, present in “.csv” as well as “.txt” file formats.
Method used – read_csv(file_path)
Parameter – String format, containing the path of the file and its name, or, URL when present on the remote server. It reads, the file data, and, converts it, into a valid two-dimensional dataframe object. This method can be used to read data, present in “.csv” as well as “.txt” file formats.
The file contents are as follows:
The contents of “gfg_indianmetros.csv” file
The code to get the data in a Pandas Data Frame is:
Python
# Import the Pandas libraryimport pandas # Load data from Comma separated file# Use method - read_csv(filepath)# Parameter - the path/URL of the CSV/TXT filedfIndianMetros = pandas.read_csv("gfg_indianmetros.csv") # print the dataframe objectprint(dfIndianMetros)
Output:
The CSV data, in dataframe object
To load data present in an Excel file(.xlsx, .xls) we will follow steps as below-
Prepare your sample dataset. Here, we have an Excel file, containing information about Bakery and its branches. It describes the number of employees, address of branches of the bakery.
Use Pandas method ‘read_excel’ .Method used – read_excel(file_path)Parameter – The method accepts, the path of the file and its name, in string format as a parameter. The file can be on a remote server, or, on a machine locally. It reads the file data, and, converts it, into a valid two-dimensional data frame object. This method, can be used, to read data present in “.xlsx” as well as “.xls” file formats.
Method used – read_excel(file_path)
Parameter – The method accepts, the path of the file and its name, in string format as a parameter. The file can be on a remote server, or, on a machine locally. It reads the file data, and, converts it, into a valid two-dimensional data frame object. This method, can be used, to read data present in “.xlsx” as well as “.xls” file formats.
The file contents are as follows:
The contents of “gfg_bakery.xlsx” file
The code to get the data in a Pandas DataFrame is:
Python
# Import the Pandas libraryimport pandas # Load data from an Excel file# Use method - read_excel(filepath)# Method parameter - The file location(URL/path) and namedfBakery = pandas.read_excel("gfg_bakery.xlsx") # print the dataframe objectprint(dfBakery)
Output:
The Excel data, in dataframe object
To load data present in a JavaScript Object Notation file(.json) we will follow steps as below:
Prepare your sample dataset. Here, we have a JSON file, containing information about Countries and their dial code.
Use Pandas method ‘read_json’ .Method used – read_json(file_path)Parameter – This method, accepts the path of the file and its name, in string format, as a parameter. It reads the file data, and, converts it, into a valid two-dimensional data frame object.
Method used – read_json(file_path)
Parameter – This method, accepts the path of the file and its name, in string format, as a parameter. It reads the file data, and, converts it, into a valid two-dimensional data frame object.
The file contents are as follows:
The contents of “gfg_codecountry.json” file
The code to get the data in a Pandas DataFrame is:
Python
# Import the Pandas libraryimport pandas # Load data from a JSON file# Use method - read_json(filepath)# Method parameter - The file location(URL/path) and namedfCodeCountry = pandas.read_json("gfg_codecountry.json") # print the dataframe objectprint(dfCodeCountry)
Output:
The JSON data, in dataframe objects
We can also transfer data present in Clipboard to a dataframe object. A clipboard is a part of Random Access Memory(RAM), where copied data is present. Whenever we copy any file, text, image, or any type of data, using the ‘Copy’ command, it gets stored in the Clipboard. To convert, data present here, follow the steps as mentioned below –
Select all the contents of the file. The file should be a CSV file. It can be a ‘.txt’ file as well, containing comma-separated values, as shown in the example. Please note, if the file contents are not in a favorable format, then, one can get a Parser Error at runtime.
Right, Click and say Copy. Now, this data is transferred, to the computer Clipboard.
Use Pandas method ‘read_clipboard’ .Method used – read_clipboardParameter – The method, does not accept any parameter. It reads the latest copied data as present in the clipboard, and, converts it, into a valid two-dimensional dataframe object.
Method used – read_clipboard
Parameter – The method, does not accept any parameter. It reads the latest copied data as present in the clipboard, and, converts it, into a valid two-dimensional dataframe object.
The file contents selected are as follows:
The contents of “gfg_clothing.txt” file
The code to get the data in a Pandas DataFrame is:
Python
# Import the required libraryimport pandas # Copy file contents which are in proper format# Whatever data you have copied will# get transferred to dataframe object# Method does not accept any parameterpdCopiedData = pd.read_clipboard() # Print the data frame objectprint(pdCopiedData)
Output:
The clipboard data, in dataframe object
A webpage is usually made of HTML elements. There are different HTML tags such as <head>, <title> , <table>, <div> based on the purpose of data display, on browser. We can transfer, the content between <table> element, present in an HTML webpage, to a Pandas data frame object. Follow the steps as mentioned below –
Select all the elements present in the <table>, between start and end tags. Assign it, to a Python variable.
Use Pandas method ‘read_html’ .Method used – read_html(string within <table> tag)Parameter – The method, accepts string variable, containing the elements present between <table> tag. It reads the elements, traversing through the table, <tr> and <td> tags, and, converts it, into a list object. The first element of the list object is the desired dataframe object.
Method used – read_html(string within <table> tag)
Parameter – The method, accepts string variable, containing the elements present between <table> tag. It reads the elements, traversing through the table, <tr> and <td> tags, and, converts it, into a list object. The first element of the list object is the desired dataframe object.
The HTML webpage used is as follows:
HTML
<!DOCTYPE html><html><head><title>Data Ingestion with Pandas Example</title></head><body><h2>Welcome To GFG</h2><table> <thead> <tr> <th>Date</th> <th>Empname</th> <th>Year</th> <th>Rating</th> <th>Region</th> </tr> </thead> <tbody> <tr> <td>2020-01-01</td> <td>Savio</td> <td>2004</td> <td>0.5</td> <td>South</td> </tr> <tr> <td>2020-01-02</td> <td>Rahul</td> <td>1998</td> <td>1.34</td> <td>East</td> </tr> <tr> <td>2020-01-03</td> <td>Tina</td> <td>1988</td> <td>1.00023</td> <td>West</td> </tr> <tr> <td>2021-01-03</td> <td>Sonia</td> <td>2001</td> <td>2.23</td> <td>North</td> </tr> </tbody></table></body></html>
Write the following code to convert the HTML table content in the Pandas Dataframe object:
Python
# Import the Pandas libraryimport pandas # Variable containing the elements# between <table> tag from webpagehtml_string = """<table> <thead> <tr> <th>Date</th> <th>Empname</th> <th>Year</th> <th>Rating</th> <th>Region</th> </tr> </thead> <tbody> <tr> <td>2020-01-01</td> <td>Savio</td> <td>2004</td> <td>0.5</td> <td>South</td> </tr> <tr> <td>2020-01-02</td> <td>Rahul</td> <td>1998</td> <td>1.34</td> <td>East</td> </tr> <tr> <td>2020-01-03</td> <td>Tina</td> <td>1988</td> <td>1.00023</td> <td>West</td> </tr> <tr> <td>2021-01-03</td> <td>Sonia</td> <td>2001</td> <td>2.23</td> <td>North</td> </tr> <tr> <td>2008-01-03</td> <td>Milo</td> <td>2008</td> <td>3.23</td> <td>East</td> </tr> <tr> <td>2006-01-03</td> <td>Edward</td> <td>2005</td> <td>0.43</td> <td>West</td> </tr> </tbody></table>""" # Pass the string containing html table elementdf = pandas.read_html(html_string) # Since read_html, returns a list object,# extract first element of the listdfHtml = df[0] # Print the data frame objectprint(dfHtml)
Output:
The HTML <table> data, in dataframe object,
We can convert, data present in database tables, to valid dataframe objects as well. Python allows easy interface, with a variety of databases, such as SQLite, MySQL, MongoDB, etc. SQLite is a lightweight database, which can be embedded in any program. The SQLite database holds all the related SQL tables. We can load, SQLite table data, to a Pandas dataframe object. Follow the steps, as mentioned below –
Prepare a sample SQLite table using ‘DB Browser for SQLite tool’ or any such tool. These tools allow the effortless creation, edition of database files compatible with SQLite. The database file, has a ‘.db’ file extension. In this example, we have ‘Novels.db’ file, containing a table called “novels”. This table has information about Novels, such as Novel Name, Price, Genre, etc.
Here, to connect to the database, we will import the ‘sqlite3’ module, in our code. The sqlite3 module, is an interface, to connect to the SQLite databases. The sqlite3 library is included in Python, since Python version 2.5. Hence, no separate installation is required. To connect to the database, we will use the SQLite method ‘connect’, which returns a connection object. The connect method accepts the following parameters:database_name – The name of the database in which the table is present. This is a .db extension file. If the file is present, an open connection object is returned. If the file is not present, it is created first and then a connection object is returned.
database_name – The name of the database in which the table is present. This is a .db extension file. If the file is present, an open connection object is returned. If the file is not present, it is created first and then a connection object is returned.
Use Pandas method ‘read_sql_query’.Method used – read_sql_queryParameter – This method accepts the following parametersSQL query – Select query, to fetch the required rows from the table.Connection object – The connection object returned by the ‘connect’ method. The read_sql_query method, converts, the resultant rows of the query, to a dataframe object.
Method used – read_sql_query
Parameter – This method accepts the following parametersSQL query – Select query, to fetch the required rows from the table.Connection object – The connection object returned by the ‘connect’ method. The read_sql_query method, converts, the resultant rows of the query, to a dataframe object.
SQL query – Select query, to fetch the required rows from the table.
Connection object – The connection object returned by the ‘connect’ method. The read_sql_query method, converts, the resultant rows of the query, to a dataframe object.
Print the dataframe object using the print method.
The Novels.db database file looks as follows –
The novels table, as seen, using DB Browser for SQLite tool
Write the following code to convert the Novels table, in Pandas Data frame object:
Python
# Import the required librariesimport sqlite3import pandas # Prepare a connection object# Pass the Database name as a parameterconn = sqlite3.connect("Novels.db") # Use read_sql_query method# Pass SELECT query and connection object as parameterpdSql = pd.read_sql_query("SELECT * FROM novels", conn) # Print the dataframe objectprint(pdSql) # Close the connection objectconn.close()
Output:
The Novels table data in dataframe object
Picked
Python pandas-io
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25555,
"s": 25527,
"text": "\n09 Jul, 2021"
},
{
"code": null,
"e": 26090,
"s": 25555,
"text": "Data Ingestion is the process of, transferring data, from varied sources to an approach, where it can be analyzed, archived, or utilized by an establishment. The usual steps, involved in this process, are drawing out data, from its current place, converting the data, and, finally loading it, in a location, for efficient research. Python provides many such tools, and, frameworks for data ingestion. These include Bonobo, Beautiful Soup4, Airflow, Pandas, etc. In this article, we will learn about Data Ingestion with Pandas library."
},
{
"code": null,
"e": 26460,
"s": 26090,
"text": "Data Ingestion with Pandas, is the process, of shifting data, from a variety of sources, into the Pandas DataFrame structure. The source of data can be varying file formats such as Comma Separated Data, JSON, HTML webpage table, Excel. In this article, we will learn about, transferring data, from such formats, into the destination, which is a Pandas dataframe object."
},
{
"code": null,
"e": 26470,
"s": 26460,
"text": "Approach:"
},
{
"code": null,
"e": 26563,
"s": 26470,
"text": "The basic approach, for transferring any such data, into a dataframe object, is as follows –"
},
{
"code": null,
"e": 26801,
"s": 26563,
"text": "Prepare your source data.Data can be present, on any remote server, or, on a local machine. We need to know, the URL of the file if it’s on a remote server. The path of the file, on local machine, is required, if data is present locally."
},
{
"code": null,
"e": 27014,
"s": 26801,
"text": "Data can be present, on any remote server, or, on a local machine. We need to know, the URL of the file if it’s on a remote server. The path of the file, on local machine, is required, if data is present locally."
},
{
"code": null,
"e": 27187,
"s": 27014,
"text": "Use Pandas ‘read_x’ methodPandas provide ‘read_x’ methods, for loading and converting the data, into a Dataframe object.Depending on the data format, use the ‘read’ method."
},
{
"code": null,
"e": 27282,
"s": 27187,
"text": "Pandas provide ‘read_x’ methods, for loading and converting the data, into a Dataframe object."
},
{
"code": null,
"e": 27335,
"s": 27282,
"text": "Depending on the data format, use the ‘read’ method."
},
{
"code": null,
"e": 27439,
"s": 27335,
"text": "Print data from DataFrame object.Print the dataframe object, to verify, that the conversion was smooth."
},
{
"code": null,
"e": 27510,
"s": 27439,
"text": "Print the dataframe object, to verify, that the conversion was smooth."
},
{
"code": null,
"e": 27613,
"s": 27510,
"text": "In this article, we will be converting, data present in the following files, to dataframe structures –"
},
{
"code": null,
"e": 27776,
"s": 27613,
"text": "Read data from CSV fileRead data from Excel fileRead data from JSON fileRead data from ClipboardRead data from HTML table from web pageRead data from SQLite table"
},
{
"code": null,
"e": 27800,
"s": 27776,
"text": "Read data from CSV file"
},
{
"code": null,
"e": 27826,
"s": 27800,
"text": "Read data from Excel file"
},
{
"code": null,
"e": 27851,
"s": 27826,
"text": "Read data from JSON file"
},
{
"code": null,
"e": 27876,
"s": 27851,
"text": "Read data from Clipboard"
},
{
"code": null,
"e": 27916,
"s": 27876,
"text": "Read data from HTML table from web page"
},
{
"code": null,
"e": 27944,
"s": 27916,
"text": "Read data from SQLite table"
},
{
"code": null,
"e": 28027,
"s": 27944,
"text": "To load, data present in Comma-separated file(CSV), we will follow steps as below:"
},
{
"code": null,
"e": 28264,
"s": 28027,
"text": "Prepare your sample dataset. Here, we have a CSV file, containing information, about Indian Metro cities. It describes if the city is a Tier1 or Tier2 city, their geographical location, state they belong to, and if it is a coastal city."
},
{
"code": null,
"e": 28619,
"s": 28264,
"text": "Use Pandas method ‘read_csv’Method used – read_csv(file_path)Parameter – String format, containing the path of the file and its name, or, URL when present on the remote server. It reads, the file data, and, converts it, into a valid two-dimensional dataframe object. This method can be used to read data, present in “.csv” as well as “.txt” file formats."
},
{
"code": null,
"e": 28653,
"s": 28619,
"text": "Method used – read_csv(file_path)"
},
{
"code": null,
"e": 28947,
"s": 28653,
"text": "Parameter – String format, containing the path of the file and its name, or, URL when present on the remote server. It reads, the file data, and, converts it, into a valid two-dimensional dataframe object. This method can be used to read data, present in “.csv” as well as “.txt” file formats."
},
{
"code": null,
"e": 28981,
"s": 28947,
"text": "The file contents are as follows:"
},
{
"code": null,
"e": 29025,
"s": 28981,
"text": "The contents of “gfg_indianmetros.csv” file"
},
{
"code": null,
"e": 29077,
"s": 29025,
"text": "The code to get the data in a Pandas Data Frame is:"
},
{
"code": null,
"e": 29084,
"s": 29077,
"text": "Python"
},
{
"code": "# Import the Pandas libraryimport pandas # Load data from Comma separated file# Use method - read_csv(filepath)# Parameter - the path/URL of the CSV/TXT filedfIndianMetros = pandas.read_csv(\"gfg_indianmetros.csv\") # print the dataframe objectprint(dfIndianMetros)",
"e": 29350,
"s": 29084,
"text": null
},
{
"code": null,
"e": 29358,
"s": 29350,
"text": "Output:"
},
{
"code": null,
"e": 29393,
"s": 29358,
"text": "The CSV data, in dataframe object"
},
{
"code": null,
"e": 29475,
"s": 29393,
"text": "To load data present in an Excel file(.xlsx, .xls) we will follow steps as below-"
},
{
"code": null,
"e": 29660,
"s": 29475,
"text": "Prepare your sample dataset. Here, we have an Excel file, containing information about Bakery and its branches. It describes the number of employees, address of branches of the bakery."
},
{
"code": null,
"e": 30070,
"s": 29660,
"text": "Use Pandas method ‘read_excel’ .Method used – read_excel(file_path)Parameter – The method accepts, the path of the file and its name, in string format as a parameter. The file can be on a remote server, or, on a machine locally. It reads the file data, and, converts it, into a valid two-dimensional data frame object. This method, can be used, to read data present in “.xlsx” as well as “.xls” file formats."
},
{
"code": null,
"e": 30106,
"s": 30070,
"text": "Method used – read_excel(file_path)"
},
{
"code": null,
"e": 30448,
"s": 30106,
"text": "Parameter – The method accepts, the path of the file and its name, in string format as a parameter. The file can be on a remote server, or, on a machine locally. It reads the file data, and, converts it, into a valid two-dimensional data frame object. This method, can be used, to read data present in “.xlsx” as well as “.xls” file formats."
},
{
"code": null,
"e": 30482,
"s": 30448,
"text": "The file contents are as follows:"
},
{
"code": null,
"e": 30522,
"s": 30482,
"text": "The contents of “gfg_bakery.xlsx” file"
},
{
"code": null,
"e": 30573,
"s": 30522,
"text": "The code to get the data in a Pandas DataFrame is:"
},
{
"code": null,
"e": 30580,
"s": 30573,
"text": "Python"
},
{
"code": "# Import the Pandas libraryimport pandas # Load data from an Excel file# Use method - read_excel(filepath)# Method parameter - The file location(URL/path) and namedfBakery = pandas.read_excel(\"gfg_bakery.xlsx\") # print the dataframe objectprint(dfBakery)",
"e": 30837,
"s": 30580,
"text": null
},
{
"code": null,
"e": 30845,
"s": 30837,
"text": "Output:"
},
{
"code": null,
"e": 30883,
"s": 30845,
"text": "The Excel data, in dataframe object "
},
{
"code": null,
"e": 30979,
"s": 30883,
"text": "To load data present in a JavaScript Object Notation file(.json) we will follow steps as below:"
},
{
"code": null,
"e": 31095,
"s": 30979,
"text": "Prepare your sample dataset. Here, we have a JSON file, containing information about Countries and their dial code."
},
{
"code": null,
"e": 31353,
"s": 31095,
"text": "Use Pandas method ‘read_json’ .Method used – read_json(file_path)Parameter – This method, accepts the path of the file and its name, in string format, as a parameter. It reads the file data, and, converts it, into a valid two-dimensional data frame object."
},
{
"code": null,
"e": 31388,
"s": 31353,
"text": "Method used – read_json(file_path)"
},
{
"code": null,
"e": 31580,
"s": 31388,
"text": "Parameter – This method, accepts the path of the file and its name, in string format, as a parameter. It reads the file data, and, converts it, into a valid two-dimensional data frame object."
},
{
"code": null,
"e": 31614,
"s": 31580,
"text": "The file contents are as follows:"
},
{
"code": null,
"e": 31659,
"s": 31614,
"text": "The contents of “gfg_codecountry.json” file"
},
{
"code": null,
"e": 31710,
"s": 31659,
"text": "The code to get the data in a Pandas DataFrame is:"
},
{
"code": null,
"e": 31717,
"s": 31710,
"text": "Python"
},
{
"code": "# Import the Pandas libraryimport pandas # Load data from a JSON file# Use method - read_json(filepath)# Method parameter - The file location(URL/path) and namedfCodeCountry = pandas.read_json(\"gfg_codecountry.json\") # print the dataframe objectprint(dfCodeCountry)",
"e": 31985,
"s": 31717,
"text": null
},
{
"code": null,
"e": 31993,
"s": 31985,
"text": "Output:"
},
{
"code": null,
"e": 32030,
"s": 31993,
"text": "The JSON data, in dataframe objects"
},
{
"code": null,
"e": 32371,
"s": 32030,
"text": "We can also transfer data present in Clipboard to a dataframe object. A clipboard is a part of Random Access Memory(RAM), where copied data is present. Whenever we copy any file, text, image, or any type of data, using the ‘Copy’ command, it gets stored in the Clipboard. To convert, data present here, follow the steps as mentioned below –"
},
{
"code": null,
"e": 32642,
"s": 32371,
"text": "Select all the contents of the file. The file should be a CSV file. It can be a ‘.txt’ file as well, containing comma-separated values, as shown in the example. Please note, if the file contents are not in a favorable format, then, one can get a Parser Error at runtime."
},
{
"code": null,
"e": 32727,
"s": 32642,
"text": "Right, Click and say Copy. Now, this data is transferred, to the computer Clipboard."
},
{
"code": null,
"e": 32973,
"s": 32727,
"text": "Use Pandas method ‘read_clipboard’ .Method used – read_clipboardParameter – The method, does not accept any parameter. It reads the latest copied data as present in the clipboard, and, converts it, into a valid two-dimensional dataframe object."
},
{
"code": null,
"e": 33002,
"s": 32973,
"text": "Method used – read_clipboard"
},
{
"code": null,
"e": 33183,
"s": 33002,
"text": "Parameter – The method, does not accept any parameter. It reads the latest copied data as present in the clipboard, and, converts it, into a valid two-dimensional dataframe object."
},
{
"code": null,
"e": 33226,
"s": 33183,
"text": "The file contents selected are as follows:"
},
{
"code": null,
"e": 33267,
"s": 33226,
"text": "The contents of “gfg_clothing.txt” file"
},
{
"code": null,
"e": 33318,
"s": 33267,
"text": "The code to get the data in a Pandas DataFrame is:"
},
{
"code": null,
"e": 33325,
"s": 33318,
"text": "Python"
},
{
"code": "# Import the required libraryimport pandas # Copy file contents which are in proper format# Whatever data you have copied will# get transferred to dataframe object# Method does not accept any parameterpdCopiedData = pd.read_clipboard() # Print the data frame objectprint(pdCopiedData)",
"e": 33612,
"s": 33325,
"text": null
},
{
"code": null,
"e": 33620,
"s": 33612,
"text": "Output:"
},
{
"code": null,
"e": 33661,
"s": 33620,
"text": "The clipboard data, in dataframe object"
},
{
"code": null,
"e": 33977,
"s": 33661,
"text": "A webpage is usually made of HTML elements. There are different HTML tags such as <head>, <title> , <table>, <div> based on the purpose of data display, on browser. We can transfer, the content between <table> element, present in an HTML webpage, to a Pandas data frame object. Follow the steps as mentioned below –"
},
{
"code": null,
"e": 34086,
"s": 33977,
"text": "Select all the elements present in the <table>, between start and end tags. Assign it, to a Python variable."
},
{
"code": null,
"e": 34451,
"s": 34086,
"text": "Use Pandas method ‘read_html’ .Method used – read_html(string within <table> tag)Parameter – The method, accepts string variable, containing the elements present between <table> tag. It reads the elements, traversing through the table, <tr> and <td> tags, and, converts it, into a list object. The first element of the list object is the desired dataframe object."
},
{
"code": null,
"e": 34502,
"s": 34451,
"text": "Method used – read_html(string within <table> tag)"
},
{
"code": null,
"e": 34785,
"s": 34502,
"text": "Parameter – The method, accepts string variable, containing the elements present between <table> tag. It reads the elements, traversing through the table, <tr> and <td> tags, and, converts it, into a list object. The first element of the list object is the desired dataframe object."
},
{
"code": null,
"e": 34822,
"s": 34785,
"text": "The HTML webpage used is as follows:"
},
{
"code": null,
"e": 34827,
"s": 34822,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head><title>Data Ingestion with Pandas Example</title></head><body><h2>Welcome To GFG</h2><table> <thead> <tr> <th>Date</th> <th>Empname</th> <th>Year</th> <th>Rating</th> <th>Region</th> </tr> </thead> <tbody> <tr> <td>2020-01-01</td> <td>Savio</td> <td>2004</td> <td>0.5</td> <td>South</td> </tr> <tr> <td>2020-01-02</td> <td>Rahul</td> <td>1998</td> <td>1.34</td> <td>East</td> </tr> <tr> <td>2020-01-03</td> <td>Tina</td> <td>1988</td> <td>1.00023</td> <td>West</td> </tr> <tr> <td>2021-01-03</td> <td>Sonia</td> <td>2001</td> <td>2.23</td> <td>North</td> </tr> </tbody></table></body></html>",
"e": 35610,
"s": 34827,
"text": null
},
{
"code": null,
"e": 35701,
"s": 35610,
"text": "Write the following code to convert the HTML table content in the Pandas Dataframe object:"
},
{
"code": null,
"e": 35708,
"s": 35701,
"text": "Python"
},
{
"code": "# Import the Pandas libraryimport pandas # Variable containing the elements# between <table> tag from webpagehtml_string = \"\"\"<table> <thead> <tr> <th>Date</th> <th>Empname</th> <th>Year</th> <th>Rating</th> <th>Region</th> </tr> </thead> <tbody> <tr> <td>2020-01-01</td> <td>Savio</td> <td>2004</td> <td>0.5</td> <td>South</td> </tr> <tr> <td>2020-01-02</td> <td>Rahul</td> <td>1998</td> <td>1.34</td> <td>East</td> </tr> <tr> <td>2020-01-03</td> <td>Tina</td> <td>1988</td> <td>1.00023</td> <td>West</td> </tr> <tr> <td>2021-01-03</td> <td>Sonia</td> <td>2001</td> <td>2.23</td> <td>North</td> </tr> <tr> <td>2008-01-03</td> <td>Milo</td> <td>2008</td> <td>3.23</td> <td>East</td> </tr> <tr> <td>2006-01-03</td> <td>Edward</td> <td>2005</td> <td>0.43</td> <td>West</td> </tr> </tbody></table>\"\"\" # Pass the string containing html table elementdf = pandas.read_html(html_string) # Since read_html, returns a list object,# extract first element of the listdfHtml = df[0] # Print the data frame objectprint(dfHtml)",
"e": 36950,
"s": 35708,
"text": null
},
{
"code": null,
"e": 36958,
"s": 36950,
"text": "Output:"
},
{
"code": null,
"e": 37003,
"s": 36958,
"text": "The HTML <table> data, in dataframe object,"
},
{
"code": null,
"e": 37411,
"s": 37003,
"text": "We can convert, data present in database tables, to valid dataframe objects as well. Python allows easy interface, with a variety of databases, such as SQLite, MySQL, MongoDB, etc. SQLite is a lightweight database, which can be embedded in any program. The SQLite database holds all the related SQL tables. We can load, SQLite table data, to a Pandas dataframe object. Follow the steps, as mentioned below –"
},
{
"code": null,
"e": 37793,
"s": 37411,
"text": "Prepare a sample SQLite table using ‘DB Browser for SQLite tool’ or any such tool. These tools allow the effortless creation, edition of database files compatible with SQLite. The database file, has a ‘.db’ file extension. In this example, we have ‘Novels.db’ file, containing a table called “novels”. This table has information about Novels, such as Novel Name, Price, Genre, etc."
},
{
"code": null,
"e": 38476,
"s": 37793,
"text": "Here, to connect to the database, we will import the ‘sqlite3’ module, in our code. The sqlite3 module, is an interface, to connect to the SQLite databases. The sqlite3 library is included in Python, since Python version 2.5. Hence, no separate installation is required. To connect to the database, we will use the SQLite method ‘connect’, which returns a connection object. The connect method accepts the following parameters:database_name – The name of the database in which the table is present. This is a .db extension file. If the file is present, an open connection object is returned. If the file is not present, it is created first and then a connection object is returned."
},
{
"code": null,
"e": 38731,
"s": 38476,
"text": "database_name – The name of the database in which the table is present. This is a .db extension file. If the file is present, an open connection object is returned. If the file is not present, it is created first and then a connection object is returned."
},
{
"code": null,
"e": 39089,
"s": 38731,
"text": "Use Pandas method ‘read_sql_query’.Method used – read_sql_queryParameter – This method accepts the following parametersSQL query – Select query, to fetch the required rows from the table.Connection object – The connection object returned by the ‘connect’ method. The read_sql_query method, converts, the resultant rows of the query, to a dataframe object."
},
{
"code": null,
"e": 39118,
"s": 39089,
"text": "Method used – read_sql_query"
},
{
"code": null,
"e": 39412,
"s": 39118,
"text": "Parameter – This method accepts the following parametersSQL query – Select query, to fetch the required rows from the table.Connection object – The connection object returned by the ‘connect’ method. The read_sql_query method, converts, the resultant rows of the query, to a dataframe object."
},
{
"code": null,
"e": 39481,
"s": 39412,
"text": "SQL query – Select query, to fetch the required rows from the table."
},
{
"code": null,
"e": 39650,
"s": 39481,
"text": "Connection object – The connection object returned by the ‘connect’ method. The read_sql_query method, converts, the resultant rows of the query, to a dataframe object."
},
{
"code": null,
"e": 39701,
"s": 39650,
"text": "Print the dataframe object using the print method."
},
{
"code": null,
"e": 39748,
"s": 39701,
"text": "The Novels.db database file looks as follows –"
},
{
"code": null,
"e": 39808,
"s": 39748,
"text": "The novels table, as seen, using DB Browser for SQLite tool"
},
{
"code": null,
"e": 39891,
"s": 39808,
"text": "Write the following code to convert the Novels table, in Pandas Data frame object:"
},
{
"code": null,
"e": 39898,
"s": 39891,
"text": "Python"
},
{
"code": "# Import the required librariesimport sqlite3import pandas # Prepare a connection object# Pass the Database name as a parameterconn = sqlite3.connect(\"Novels.db\") # Use read_sql_query method# Pass SELECT query and connection object as parameterpdSql = pd.read_sql_query(\"SELECT * FROM novels\", conn) # Print the dataframe objectprint(pdSql) # Close the connection objectconn.close()",
"e": 40285,
"s": 39898,
"text": null
},
{
"code": null,
"e": 40293,
"s": 40285,
"text": "Output:"
},
{
"code": null,
"e": 40336,
"s": 40293,
"text": "The Novels table data in dataframe object"
},
{
"code": null,
"e": 40343,
"s": 40336,
"text": "Picked"
},
{
"code": null,
"e": 40360,
"s": 40343,
"text": "Python pandas-io"
},
{
"code": null,
"e": 40374,
"s": 40360,
"text": "Python-pandas"
},
{
"code": null,
"e": 40381,
"s": 40374,
"text": "Python"
},
{
"code": null,
"e": 40479,
"s": 40381,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40511,
"s": 40479,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 40553,
"s": 40511,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 40595,
"s": 40553,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 40651,
"s": 40595,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 40678,
"s": 40651,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 40709,
"s": 40678,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 40748,
"s": 40709,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 40777,
"s": 40748,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 40799,
"s": 40777,
"text": "Defaultdict in Python"
}
] |
Number of squares of side length required to cover an N*M rectangle - GeeksforGeeks
|
20 May, 2021
Given three numbers , , . Find Number of squares of dimension required to cover rectangle. Note:
It’s allowed to cover the surface larger than the rectangle, but the rectangle has to be covered.
It’s not allowed to break a square.
The sides of squares should be parallel to the sides of the rectangle.
Examples:
Input: N = 6, M = 6, a = 4
Output: 4
Input: N = 2, M = 3, a = 1
Output: 6
Approach: An efficient approach is to make an observation and find a formula. The constraint that edges of each square must be parallel to the edges of the rectangle allows to analyze X and Y axes separately, that is, how many squares of length ‘a’ are needed to cover squares of length ‘m’ and ‘n’ and take the product of these two quantities. The number of small squares of side length ‘a’ required to cover ‘m’ sized square are ceil(m/a). Similarly, number of ‘a’ sized squares required to cover ‘n’ sized square are ceil(n/a). So, the answer will be ceil(m/a)*ceil(n/a).Below is the implementation of the above approach:
C++
Java
Python 3
C#
PHP
Javascript
// CPP program to find number of squares// of a*a required to cover n*m rectangle#include <bits/stdc++.h>using namespace std; // function to find number of squares// of a*a required to cover n*m rectangleint Squares(int n, int m, int a){ return ((m + a - 1) / a) * ((n + a - 1) / a);} // Driver codeint main(){ int n = 6, m = 6, a = 4; // function call cout << Squares(n, m, a); return 0;}
// Java program to find number of squares// of a*a required to cover n*m rectangleimport java.util.*; class solution{ // function to find a number of squares// of a*a required to cover n*m rectanglestatic int Squares(int n, int m, int a){ return ((m + a - 1) / a) * ((n + a - 1) / a); } // Driver codepublic static void main(String arr[]){ int n = 6, m = 6, a = 4; // function call System.out.println(Squares(n, m, a)); } }//This code is contributed by Surendra_Gangwar
# Python 3 program to find number# of squares of a*a required to# cover n*m rectangle # function to find number of# squares of a*a required to# cover n*m rectangledef Squares(n, m, a): return (((m + a - 1) // a) * ((n + a - 1) // a)) # Driver codeif __name__ == "__main__": n = 6 m = 6 a = 4 # function call print(Squares(n, m, a)) # This code is contributed# by ChitraNayal
// CSHARP program to find number of squares// of a*a required to cover n*m rectangle using System; class GFG{ // function to find a number of squares // of a*a required to cover n*m rectangle static int Squares(int n, int m, int a) { return ((m + a - 1) / a) * ((n + a - 1) / a); } static void Main() { int n = 6, m = 6, a = 4; // function call Console.WriteLine(Squares(n, m, a)); } // This code is contributed by ANKITRAI1}
<?php// PHP program to find number of squares// of a*a required to cover n*m rectangle // function to find number of squares// of a*a required to cover n*m rectanglefunction Squares($n, $m, $a){ return ((int)(($m + $a - 1) / $a)) * ((int)(($n + $a - 1) / $a));} // Driver code$n = 6; $m = 6; $a = 4; // function callecho Squares($n, $m, $a); // This code is contributed// by Akanksha Rai?>
<script> // JavaScript program to find number of squares// of a*a required to cover n*m rectangle // function to find a number of squares// of a*a required to cover n*m rectanglefunction Squares(n, m, a){ return parseInt(((m + a - 1) / a)) * parseInt(((n + a - 1) / a));} // Driver codevar n = 6, m = 6, a = 4; // Function calldocument.write(Squares(n, m, a)); // This code is contributed by Ankita saini </script>
4
SURENDRA_GANGWAR
ankthon
ukasp
Akanksha_Rai
ankita_saini
square-rectangle
Competitive Programming
Geometric
Mathematical
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Prefix Sum Array - Implementation and Applications in Competitive Programming
Ordered Set and GNU C++ PBDS
Modulo 10^9+7 (1000000007)
Bits manipulation (Important tactics)
What is Competitive Programming and How to Prepare for It?
Closest Pair of Points using Divide and Conquer algorithm
How to check if a given point lies inside or outside a polygon?
Program for distance between two points on earth
How to check if two given line segments intersect?
Find if two rectangles overlap
|
[
{
"code": null,
"e": 26367,
"s": 26339,
"text": "\n20 May, 2021"
},
{
"code": null,
"e": 26466,
"s": 26367,
"text": "Given three numbers , , . Find Number of squares of dimension required to cover rectangle. Note: "
},
{
"code": null,
"e": 26564,
"s": 26466,
"text": "It’s allowed to cover the surface larger than the rectangle, but the rectangle has to be covered."
},
{
"code": null,
"e": 26600,
"s": 26564,
"text": "It’s not allowed to break a square."
},
{
"code": null,
"e": 26671,
"s": 26600,
"text": "The sides of squares should be parallel to the sides of the rectangle."
},
{
"code": null,
"e": 26683,
"s": 26671,
"text": "Examples: "
},
{
"code": null,
"e": 26758,
"s": 26683,
"text": "Input: N = 6, M = 6, a = 4\nOutput: 4\n\nInput: N = 2, M = 3, a = 1\nOutput: 6"
},
{
"code": null,
"e": 27387,
"s": 26760,
"text": "Approach: An efficient approach is to make an observation and find a formula. The constraint that edges of each square must be parallel to the edges of the rectangle allows to analyze X and Y axes separately, that is, how many squares of length ‘a’ are needed to cover squares of length ‘m’ and ‘n’ and take the product of these two quantities. The number of small squares of side length ‘a’ required to cover ‘m’ sized square are ceil(m/a). Similarly, number of ‘a’ sized squares required to cover ‘n’ sized square are ceil(n/a). So, the answer will be ceil(m/a)*ceil(n/a).Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27391,
"s": 27387,
"text": "C++"
},
{
"code": null,
"e": 27396,
"s": 27391,
"text": "Java"
},
{
"code": null,
"e": 27405,
"s": 27396,
"text": "Python 3"
},
{
"code": null,
"e": 27408,
"s": 27405,
"text": "C#"
},
{
"code": null,
"e": 27412,
"s": 27408,
"text": "PHP"
},
{
"code": null,
"e": 27423,
"s": 27412,
"text": "Javascript"
},
{
"code": "// CPP program to find number of squares// of a*a required to cover n*m rectangle#include <bits/stdc++.h>using namespace std; // function to find number of squares// of a*a required to cover n*m rectangleint Squares(int n, int m, int a){ return ((m + a - 1) / a) * ((n + a - 1) / a);} // Driver codeint main(){ int n = 6, m = 6, a = 4; // function call cout << Squares(n, m, a); return 0;}",
"e": 27830,
"s": 27423,
"text": null
},
{
"code": "// Java program to find number of squares// of a*a required to cover n*m rectangleimport java.util.*; class solution{ // function to find a number of squares// of a*a required to cover n*m rectanglestatic int Squares(int n, int m, int a){ return ((m + a - 1) / a) * ((n + a - 1) / a); } // Driver codepublic static void main(String arr[]){ int n = 6, m = 6, a = 4; // function call System.out.println(Squares(n, m, a)); } }//This code is contributed by Surendra_Gangwar",
"e": 28314,
"s": 27830,
"text": null
},
{
"code": "# Python 3 program to find number# of squares of a*a required to# cover n*m rectangle # function to find number of# squares of a*a required to# cover n*m rectangledef Squares(n, m, a): return (((m + a - 1) // a) * ((n + a - 1) // a)) # Driver codeif __name__ == \"__main__\": n = 6 m = 6 a = 4 # function call print(Squares(n, m, a)) # This code is contributed# by ChitraNayal",
"e": 28719,
"s": 28314,
"text": null
},
{
"code": "// CSHARP program to find number of squares// of a*a required to cover n*m rectangle using System; class GFG{ // function to find a number of squares // of a*a required to cover n*m rectangle static int Squares(int n, int m, int a) { return ((m + a - 1) / a) * ((n + a - 1) / a); } static void Main() { int n = 6, m = 6, a = 4; // function call Console.WriteLine(Squares(n, m, a)); } // This code is contributed by ANKITRAI1}",
"e": 29216,
"s": 28719,
"text": null
},
{
"code": "<?php// PHP program to find number of squares// of a*a required to cover n*m rectangle // function to find number of squares// of a*a required to cover n*m rectanglefunction Squares($n, $m, $a){ return ((int)(($m + $a - 1) / $a)) * ((int)(($n + $a - 1) / $a));} // Driver code$n = 6; $m = 6; $a = 4; // function callecho Squares($n, $m, $a); // This code is contributed// by Akanksha Rai?>",
"e": 29619,
"s": 29216,
"text": null
},
{
"code": "<script> // JavaScript program to find number of squares// of a*a required to cover n*m rectangle // function to find a number of squares// of a*a required to cover n*m rectanglefunction Squares(n, m, a){ return parseInt(((m + a - 1) / a)) * parseInt(((n + a - 1) / a));} // Driver codevar n = 6, m = 6, a = 4; // Function calldocument.write(Squares(n, m, a)); // This code is contributed by Ankita saini </script>",
"e": 30053,
"s": 29619,
"text": null
},
{
"code": null,
"e": 30055,
"s": 30053,
"text": "4"
},
{
"code": null,
"e": 30074,
"s": 30057,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 30082,
"s": 30074,
"text": "ankthon"
},
{
"code": null,
"e": 30088,
"s": 30082,
"text": "ukasp"
},
{
"code": null,
"e": 30101,
"s": 30088,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 30114,
"s": 30101,
"text": "ankita_saini"
},
{
"code": null,
"e": 30131,
"s": 30114,
"text": "square-rectangle"
},
{
"code": null,
"e": 30155,
"s": 30131,
"text": "Competitive Programming"
},
{
"code": null,
"e": 30165,
"s": 30155,
"text": "Geometric"
},
{
"code": null,
"e": 30178,
"s": 30165,
"text": "Mathematical"
},
{
"code": null,
"e": 30191,
"s": 30178,
"text": "Mathematical"
},
{
"code": null,
"e": 30201,
"s": 30191,
"text": "Geometric"
},
{
"code": null,
"e": 30299,
"s": 30201,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30377,
"s": 30299,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
},
{
"code": null,
"e": 30406,
"s": 30377,
"text": "Ordered Set and GNU C++ PBDS"
},
{
"code": null,
"e": 30433,
"s": 30406,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 30471,
"s": 30433,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 30530,
"s": 30471,
"text": "What is Competitive Programming and How to Prepare for It?"
},
{
"code": null,
"e": 30588,
"s": 30530,
"text": "Closest Pair of Points using Divide and Conquer algorithm"
},
{
"code": null,
"e": 30652,
"s": 30588,
"text": "How to check if a given point lies inside or outside a polygon?"
},
{
"code": null,
"e": 30701,
"s": 30652,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 30752,
"s": 30701,
"text": "How to check if two given line segments intersect?"
}
] |
HTML script Tag - GeeksforGeeks
|
17 Mar, 2022
The <script> tag in HTML is used to define the client-side script. The <script> tag contains the scripting statements, or it points to an external script file. The JavaScript is mainly used in form validation, dynamic changes of content, image manipulation, etc.Syntax:
<script> Script Contents... </script>
Attributes: Many attribute associated with script tag.
async: It is used to specify the script is executed asynchronously.
charset: It is used to specify the character encoding used in an external script file.
defer: It is used to specify that the script is executed when the page has finished parsing.
src: It is used to specify the URL of an external script file.
type: It is used to specify the media type of the script.
Example 1:
HTML
<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2><script> Tag</h2> <p id="Geeks"></p> <!-- html script tag starts here --> <script> document.getElementById("Geeks").innerHTML = "Hello GeeksforGeeks!"; </script> <!-- html script tag ends here --> </body> </html>
Output:
Example 2(script outside body tag):
HTML
<!DOCTYPE html><html> <head> <title>script tag</title> <style> body { text-align:center; } h1 { color:green; } </style> <script> function Geeks() { alert('Welcome to GeeksforGeeks!'); } </script> </head> <body> <h1>GeeksforGeeks</h1> <h2><script> Tag</h2> <button type="button" onclick="Geeks()"> Hello GeeksforGeeks</button> </body></html>
Output:
Supported Browsers:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
shubham_singh
shubhamyadav4
HTML-Tags
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
|
[
{
"code": null,
"e": 24303,
"s": 24275,
"text": "\n17 Mar, 2022"
},
{
"code": null,
"e": 24575,
"s": 24303,
"text": "The <script> tag in HTML is used to define the client-side script. The <script> tag contains the scripting statements, or it points to an external script file. The JavaScript is mainly used in form validation, dynamic changes of content, image manipulation, etc.Syntax: "
},
{
"code": null,
"e": 24613,
"s": 24575,
"text": "<script> Script Contents... </script>"
},
{
"code": null,
"e": 24670,
"s": 24613,
"text": "Attributes: Many attribute associated with script tag. "
},
{
"code": null,
"e": 24738,
"s": 24670,
"text": "async: It is used to specify the script is executed asynchronously."
},
{
"code": null,
"e": 24825,
"s": 24738,
"text": "charset: It is used to specify the character encoding used in an external script file."
},
{
"code": null,
"e": 24918,
"s": 24825,
"text": "defer: It is used to specify that the script is executed when the page has finished parsing."
},
{
"code": null,
"e": 24981,
"s": 24918,
"text": "src: It is used to specify the URL of an external script file."
},
{
"code": null,
"e": 25039,
"s": 24981,
"text": "type: It is used to specify the media type of the script."
},
{
"code": null,
"e": 25052,
"s": 25039,
"text": "Example 1: "
},
{
"code": null,
"e": 25057,
"s": 25052,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2><script> Tag</h2> <p id=\"Geeks\"></p> <!-- html script tag starts here --> <script> document.getElementById(\"Geeks\").innerHTML = \"Hello GeeksforGeeks!\"; </script> <!-- html script tag ends here --> </body> </html> ",
"e": 25494,
"s": 25057,
"text": null
},
{
"code": null,
"e": 25504,
"s": 25494,
"text": "Output: "
},
{
"code": null,
"e": 25541,
"s": 25504,
"text": "Example 2(script outside body tag): "
},
{
"code": null,
"e": 25546,
"s": 25541,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>script tag</title> <style> body { text-align:center; } h1 { color:green; } </style> <script> function Geeks() { alert('Welcome to GeeksforGeeks!'); } </script> </head> <body> <h1>GeeksforGeeks</h1> <h2><script> Tag</h2> <button type=\"button\" onclick=\"Geeks()\"> Hello GeeksforGeeks</button> </body></html> ",
"e": 26096,
"s": 25546,
"text": null
},
{
"code": null,
"e": 26106,
"s": 26096,
"text": "Output: "
},
{
"code": null,
"e": 26128,
"s": 26106,
"text": "Supported Browsers: "
},
{
"code": null,
"e": 26142,
"s": 26128,
"text": "Google Chrome"
},
{
"code": null,
"e": 26160,
"s": 26142,
"text": "Internet Explorer"
},
{
"code": null,
"e": 26168,
"s": 26160,
"text": "Firefox"
},
{
"code": null,
"e": 26174,
"s": 26168,
"text": "Opera"
},
{
"code": null,
"e": 26181,
"s": 26174,
"text": "Safari"
},
{
"code": null,
"e": 26320,
"s": 26183,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 26334,
"s": 26320,
"text": "shubham_singh"
},
{
"code": null,
"e": 26348,
"s": 26334,
"text": "shubhamyadav4"
},
{
"code": null,
"e": 26358,
"s": 26348,
"text": "HTML-Tags"
},
{
"code": null,
"e": 26363,
"s": 26358,
"text": "HTML"
},
{
"code": null,
"e": 26368,
"s": 26363,
"text": "HTML"
},
{
"code": null,
"e": 26466,
"s": 26368,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26516,
"s": 26466,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 26578,
"s": 26516,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26626,
"s": 26578,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 26686,
"s": 26626,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 26739,
"s": 26686,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 26800,
"s": 26739,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 26824,
"s": 26800,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 26874,
"s": 26824,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 26924,
"s": 26874,
"text": "CSS to put icon inside an input element in a form"
}
] |
HTML Attributes - GeeksforGeeks
|
10 Dec, 2021
In this article, we will know HTML Attributes, their implementation through the examples. All HTML elements have attributes that will provide additional information about that particular element. It takes 2 parameters, ie, a name & a value which define the properties of the element and are placed inside the element tag.
The name parameter takes the name of the property we would like to assign to the element and the value takes the properties value or extent of the property names that can be aligned over the element. Every name has some value that must be written within quotes.
Syntax:
<element attribute_name="attribute_value">
Supported Attributes: It is a global attribute that is supported by all the tags.
Please refer to the HTML Attributes Complete Reference article for all the attributes in detail.
The below are some of the most commonly used Attributes in HTML.
HTML src Attribute: If we want to insert an image into a webpage, then we need to use the <img> tag and the src attribute. We will need to specify the address of the image as the attribute’s value inside the double quote.
Example: This example explains the HTML src Attributes to specify the source address of the file.
HTML
<html><head> <title>src Attribute</title></head><body> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/Geek_logi_-low_res.png"></body></html>
Output:
src Attribute
HTML alt Attribute: This is an alternate tag that is used to show or display something if the primary attribute i.e., the <img> tag, fails to display the value assigned to it. This can also be used to describe the image to a developer who is actually sitting at the coding end.
Example: This example explains the HTML alt Attributes to specify the name of the file when the image is not loaded properly.
HTML
<html><head> <title>alt Attribute</title></head><body> <!--If the image is not found or the img field is left blank the alt value gets displayed--> <img src= "https://media.geeksforgeeks.org/wp-content/cdn-uploads/Geek_logi_-low_res.png" alt="The Logo"><br> <img src="" alt="Since the src value is blank,the alt value is displayed"></body></html>
Output:
alt Attribute
HTML width and height Attribute: This attribute is used to adjust the width and height of an image.
Example: This example explains the HTML width & height Attributes to specify the different sizes of the images.
HTML
<html><head> <title>Width and Height</title></head><body> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/Geek_logi_-low_res.png" width="300px" height="100px" ></body></html>
Output:
width& height attribute
HTML id Attribute: This attribute is used to provide a unique identification to an element. Situations may arise when we will need to access a particular element that may have a similar name as the others. In that case, we provide different id’s to various elements so that they can be uniquely accessed. The properties extending the use of id are generally used in CSS, which we will be learning later.
Example: This example explains the HTML id Attributes to specify the unique value for the specific element.
HTML
<!DOCTYPE html><html> <head> <style> #geeks { color: green; } </style></head> <body> <h1 id="geeks">Welcome to GeeksforGeeks</h1> </body> </html>
Output:
id attribute
HTML title Attribute: The title attribute is used to explain an element on hovering the mouse over it. The behavior differs with various elements but generally, the value is displayed while loading or hovering the mouse pointer over it.
Example: This example explains the HTML title Attributes to specify the metadata for the element on hovering the mouse over it.
HTML
<html><head> <title>title Attribute</title></head><body> <h3 title="Hello GeeksforGeeks">Hover to see the effect</h3></body></html>
Output:
title attribute
HTML href Attribute: This attribute is used to specify a link to any address. This attribute is used along with the <a> tag. The link put inside the href attribute gets linked to the text displayed inside the<a> tag. On clicking on the text we will be redirected to the link. By default, the link gets opened in the same tag but by using the target attribute and setting its value to “_blank”, we will be redirected to another tab or another window based on the browser’s configuration.
Example: This example explains the HTML href Attributes specify the link address of the file.
HTML
<html><head> <title>link Attribute</title></head><body> <a href="https://www.geeksforgeeks.org/"> Click to open in the same tab </a><br> <a href="https://www.geeksforgeeks.org/" target="_blank"> Click to open in a different tab </a></body></html>
Output:
href attribute
HTML style Attribute: This attribute is used to provide various CSS effects to the HTML elements such as increasing font-size, changing font-family, coloring, etc.
Example: This example explains the HTML style Attributes to specify the style properties for the HTML element.
HTML
<html><head> <title>style Attribute</title></head><body> <h2 style="font-family:Chaparral Pro Light;">Hello GeeksforGeeks.</h2> <h3 style="font-size:20px;">Hello GeeksforGeeks.</h3> <h2 style="color:#8CCEF9;">Hello GeeksforGeeks.</h2> <h2 style="text-align:center;">Hello GeeksforGeeks.</h2></body></html>
Output:
style Attribute
HTML lang attribute: The language is declared with the lang attribute. Declaring a language is can be important for accessibility applications and search engines.
Example: This example explains the HTML lang Attributes that specify the language of the HTML page.
HTML
<!DOCTYPE html><html lang="en-US"><body> ... </body></html>
This article is contributed by Chinmoy Lenka. 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.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
AKSAHARAN
ysachin2314
bhaskargeeksforgeeks
HTML and XML
HTML-Basics
Web technologies-HTML and XML
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 31645,
"s": 31617,
"text": "\n10 Dec, 2021"
},
{
"code": null,
"e": 31967,
"s": 31645,
"text": "In this article, we will know HTML Attributes, their implementation through the examples. All HTML elements have attributes that will provide additional information about that particular element. It takes 2 parameters, ie, a name & a value which define the properties of the element and are placed inside the element tag."
},
{
"code": null,
"e": 32229,
"s": 31967,
"text": "The name parameter takes the name of the property we would like to assign to the element and the value takes the properties value or extent of the property names that can be aligned over the element. Every name has some value that must be written within quotes."
},
{
"code": null,
"e": 32237,
"s": 32229,
"text": "Syntax:"
},
{
"code": null,
"e": 32280,
"s": 32237,
"text": "<element attribute_name=\"attribute_value\">"
},
{
"code": null,
"e": 32362,
"s": 32280,
"text": "Supported Attributes: It is a global attribute that is supported by all the tags."
},
{
"code": null,
"e": 32459,
"s": 32362,
"text": "Please refer to the HTML Attributes Complete Reference article for all the attributes in detail."
},
{
"code": null,
"e": 32524,
"s": 32459,
"text": "The below are some of the most commonly used Attributes in HTML."
},
{
"code": null,
"e": 32746,
"s": 32524,
"text": "HTML src Attribute: If we want to insert an image into a webpage, then we need to use the <img> tag and the src attribute. We will need to specify the address of the image as the attribute’s value inside the double quote."
},
{
"code": null,
"e": 32844,
"s": 32746,
"text": "Example: This example explains the HTML src Attributes to specify the source address of the file."
},
{
"code": null,
"e": 32849,
"s": 32844,
"text": "HTML"
},
{
"code": "<html><head> <title>src Attribute</title></head><body> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/Geek_logi_-low_res.png\"></body></html>",
"e": 33014,
"s": 32849,
"text": null
},
{
"code": null,
"e": 33022,
"s": 33014,
"text": "Output:"
},
{
"code": null,
"e": 33036,
"s": 33022,
"text": "src Attribute"
},
{
"code": null,
"e": 33314,
"s": 33036,
"text": "HTML alt Attribute: This is an alternate tag that is used to show or display something if the primary attribute i.e., the <img> tag, fails to display the value assigned to it. This can also be used to describe the image to a developer who is actually sitting at the coding end."
},
{
"code": null,
"e": 33440,
"s": 33314,
"text": "Example: This example explains the HTML alt Attributes to specify the name of the file when the image is not loaded properly."
},
{
"code": null,
"e": 33445,
"s": 33440,
"text": "HTML"
},
{
"code": "<html><head> <title>alt Attribute</title></head><body> <!--If the image is not found or the img field is left blank the alt value gets displayed--> <img src= \"https://media.geeksforgeeks.org/wp-content/cdn-uploads/Geek_logi_-low_res.png\" alt=\"The Logo\"><br> <img src=\"\" alt=\"Since the src value is blank,the alt value is displayed\"></body></html>",
"e": 33819,
"s": 33445,
"text": null
},
{
"code": null,
"e": 33827,
"s": 33819,
"text": "Output:"
},
{
"code": null,
"e": 33841,
"s": 33827,
"text": "alt Attribute"
},
{
"code": null,
"e": 33941,
"s": 33841,
"text": "HTML width and height Attribute: This attribute is used to adjust the width and height of an image."
},
{
"code": null,
"e": 34053,
"s": 33941,
"text": "Example: This example explains the HTML width & height Attributes to specify the different sizes of the images."
},
{
"code": null,
"e": 34058,
"s": 34053,
"text": "HTML"
},
{
"code": "<html><head> <title>Width and Height</title></head><body> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/Geek_logi_-low_res.png\" width=\"300px\" height=\"100px\" ></body></html>",
"e": 34264,
"s": 34058,
"text": null
},
{
"code": null,
"e": 34272,
"s": 34264,
"text": "Output:"
},
{
"code": null,
"e": 34296,
"s": 34272,
"text": "width& height attribute"
},
{
"code": null,
"e": 34700,
"s": 34296,
"text": "HTML id Attribute: This attribute is used to provide a unique identification to an element. Situations may arise when we will need to access a particular element that may have a similar name as the others. In that case, we provide different id’s to various elements so that they can be uniquely accessed. The properties extending the use of id are generally used in CSS, which we will be learning later."
},
{
"code": null,
"e": 34808,
"s": 34700,
"text": "Example: This example explains the HTML id Attributes to specify the unique value for the specific element."
},
{
"code": null,
"e": 34813,
"s": 34808,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> #geeks { color: green; } </style></head> <body> <h1 id=\"geeks\">Welcome to GeeksforGeeks</h1> </body> </html>",
"e": 34981,
"s": 34813,
"text": null
},
{
"code": null,
"e": 34989,
"s": 34981,
"text": "Output:"
},
{
"code": null,
"e": 35002,
"s": 34989,
"text": "id attribute"
},
{
"code": null,
"e": 35239,
"s": 35002,
"text": "HTML title Attribute: The title attribute is used to explain an element on hovering the mouse over it. The behavior differs with various elements but generally, the value is displayed while loading or hovering the mouse pointer over it."
},
{
"code": null,
"e": 35367,
"s": 35239,
"text": "Example: This example explains the HTML title Attributes to specify the metadata for the element on hovering the mouse over it."
},
{
"code": null,
"e": 35372,
"s": 35367,
"text": "HTML"
},
{
"code": "<html><head> <title>title Attribute</title></head><body> <h3 title=\"Hello GeeksforGeeks\">Hover to see the effect</h3></body></html>",
"e": 35510,
"s": 35372,
"text": null
},
{
"code": null,
"e": 35518,
"s": 35510,
"text": "Output:"
},
{
"code": null,
"e": 35534,
"s": 35518,
"text": "title attribute"
},
{
"code": null,
"e": 36021,
"s": 35534,
"text": "HTML href Attribute: This attribute is used to specify a link to any address. This attribute is used along with the <a> tag. The link put inside the href attribute gets linked to the text displayed inside the<a> tag. On clicking on the text we will be redirected to the link. By default, the link gets opened in the same tag but by using the target attribute and setting its value to “_blank”, we will be redirected to another tab or another window based on the browser’s configuration."
},
{
"code": null,
"e": 36115,
"s": 36021,
"text": "Example: This example explains the HTML href Attributes specify the link address of the file."
},
{
"code": null,
"e": 36120,
"s": 36115,
"text": "HTML"
},
{
"code": "<html><head> <title>link Attribute</title></head><body> <a href=\"https://www.geeksforgeeks.org/\"> Click to open in the same tab </a><br> <a href=\"https://www.geeksforgeeks.org/\" target=\"_blank\"> Click to open in a different tab </a></body></html>",
"e": 36396,
"s": 36120,
"text": null
},
{
"code": null,
"e": 36404,
"s": 36396,
"text": "Output:"
},
{
"code": null,
"e": 36419,
"s": 36404,
"text": "href attribute"
},
{
"code": null,
"e": 36583,
"s": 36419,
"text": "HTML style Attribute: This attribute is used to provide various CSS effects to the HTML elements such as increasing font-size, changing font-family, coloring, etc."
},
{
"code": null,
"e": 36694,
"s": 36583,
"text": "Example: This example explains the HTML style Attributes to specify the style properties for the HTML element."
},
{
"code": null,
"e": 36699,
"s": 36694,
"text": "HTML"
},
{
"code": "<html><head> <title>style Attribute</title></head><body> <h2 style=\"font-family:Chaparral Pro Light;\">Hello GeeksforGeeks.</h2> <h3 style=\"font-size:20px;\">Hello GeeksforGeeks.</h3> <h2 style=\"color:#8CCEF9;\">Hello GeeksforGeeks.</h2> <h2 style=\"text-align:center;\">Hello GeeksforGeeks.</h2></body></html>",
"e": 37020,
"s": 36699,
"text": null
},
{
"code": null,
"e": 37028,
"s": 37020,
"text": "Output:"
},
{
"code": null,
"e": 37044,
"s": 37028,
"text": "style Attribute"
},
{
"code": null,
"e": 37207,
"s": 37044,
"text": "HTML lang attribute: The language is declared with the lang attribute. Declaring a language is can be important for accessibility applications and search engines."
},
{
"code": null,
"e": 37307,
"s": 37207,
"text": "Example: This example explains the HTML lang Attributes that specify the language of the HTML page."
},
{
"code": null,
"e": 37312,
"s": 37307,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en-US\"><body> ... </body></html>",
"e": 37372,
"s": 37312,
"text": null
},
{
"code": null,
"e": 37793,
"s": 37372,
"text": "This article is contributed by Chinmoy Lenka. 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": 37930,
"s": 37793,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 37940,
"s": 37930,
"text": "AKSAHARAN"
},
{
"code": null,
"e": 37952,
"s": 37940,
"text": "ysachin2314"
},
{
"code": null,
"e": 37973,
"s": 37952,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 37986,
"s": 37973,
"text": "HTML and XML"
},
{
"code": null,
"e": 37998,
"s": 37986,
"text": "HTML-Basics"
},
{
"code": null,
"e": 38028,
"s": 37998,
"text": "Web technologies-HTML and XML"
},
{
"code": null,
"e": 38033,
"s": 38028,
"text": "HTML"
},
{
"code": null,
"e": 38050,
"s": 38033,
"text": "Web Technologies"
},
{
"code": null,
"e": 38055,
"s": 38050,
"text": "HTML"
},
{
"code": null,
"e": 38153,
"s": 38055,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38203,
"s": 38153,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 38265,
"s": 38203,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 38313,
"s": 38265,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 38373,
"s": 38313,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 38426,
"s": 38373,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 38466,
"s": 38426,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 38499,
"s": 38466,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 38544,
"s": 38499,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 38587,
"s": 38544,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
UNIX_TIMESTAMP() function in MySQL - GeeksforGeeks
|
22 Dec, 2020
UNIX_TIMESTAMP() :This function in MySQL helps to return a Unix timestamp. We can define a Unix timestamp as the number of seconds that have passed since ‘1970-01-01 00:00:00’UTC. Even if you pass the current date/time or another specified date/time, the function will return a Unix timestamp based on that.
Syntax :
UNIX_TIMESTAMP()
UNIX_TIMESTAMP(date)
Parameters :It will accept only one argument.
date –A date value which can be DATE, DATETIME, TIMESTAMP, or a number in ‘YYYYMMDD’ or ‘YYMMDD’ format.
Return :
If no parameter is passed, the function will return a Unix timestamp in seconds since ‘1970-01-01 00:00:00’ UTC in form of an unsigned integer.
But if the date parameter is passed, the function will return the value of parameter in form of an unsigned integer in seconds since ‘1970-01-01 00:00:00’ UTC.
Example-1 :Working of UNIX_TIMESTAMP() using Current date/time.
SELECT UNIX_TIMESTAMP()
As TimeStamp;
Output :
Example-2 :Working of UNIX_TIMESTAMP() using date value ‘1999-01-22’.
SELECT UNIX_TIMESTAMP('1999-01-22')
As TimeStamp;
Output :
Example-3 :Working of UNIX_TIMESTAMP() using DateTime value ‘2020-10-17 02:35:43’.
SELECT UNIX_TIMESTAMP('2020-10-17 02:35:43')
As TimeStamp;
Output :
Example-4 :Working of UNIX_TIMESTAMP() using DateTime value along with fractional seconds ‘2020-10-17 02:35:43.12345’.
SELECT UNIX_TIMESTAMP('2020-10-17 02:35:43.12345')
As TimeStamp;
Output :
DBMS-SQL
mysql
Technical Scripter 2020
SQL
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?
SQL | Subquery
What is Temporary Table in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
|
[
{
"code": null,
"e": 25513,
"s": 25485,
"text": "\n22 Dec, 2020"
},
{
"code": null,
"e": 25821,
"s": 25513,
"text": "UNIX_TIMESTAMP() :This function in MySQL helps to return a Unix timestamp. We can define a Unix timestamp as the number of seconds that have passed since ‘1970-01-01 00:00:00’UTC. Even if you pass the current date/time or another specified date/time, the function will return a Unix timestamp based on that."
},
{
"code": null,
"e": 25830,
"s": 25821,
"text": "Syntax :"
},
{
"code": null,
"e": 25868,
"s": 25830,
"text": "UNIX_TIMESTAMP()\nUNIX_TIMESTAMP(date)"
},
{
"code": null,
"e": 25914,
"s": 25868,
"text": "Parameters :It will accept only one argument."
},
{
"code": null,
"e": 26019,
"s": 25914,
"text": "date –A date value which can be DATE, DATETIME, TIMESTAMP, or a number in ‘YYYYMMDD’ or ‘YYMMDD’ format."
},
{
"code": null,
"e": 26028,
"s": 26019,
"text": "Return :"
},
{
"code": null,
"e": 26172,
"s": 26028,
"text": "If no parameter is passed, the function will return a Unix timestamp in seconds since ‘1970-01-01 00:00:00’ UTC in form of an unsigned integer."
},
{
"code": null,
"e": 26332,
"s": 26172,
"text": "But if the date parameter is passed, the function will return the value of parameter in form of an unsigned integer in seconds since ‘1970-01-01 00:00:00’ UTC."
},
{
"code": null,
"e": 26396,
"s": 26332,
"text": "Example-1 :Working of UNIX_TIMESTAMP() using Current date/time."
},
{
"code": null,
"e": 26436,
"s": 26396,
"text": "SELECT UNIX_TIMESTAMP() \nAs TimeStamp; "
},
{
"code": null,
"e": 26445,
"s": 26436,
"text": "Output :"
},
{
"code": null,
"e": 26515,
"s": 26445,
"text": "Example-2 :Working of UNIX_TIMESTAMP() using date value ‘1999-01-22’."
},
{
"code": null,
"e": 26567,
"s": 26515,
"text": "SELECT UNIX_TIMESTAMP('1999-01-22') \nAs TimeStamp; "
},
{
"code": null,
"e": 26576,
"s": 26567,
"text": "Output :"
},
{
"code": null,
"e": 26659,
"s": 26576,
"text": "Example-3 :Working of UNIX_TIMESTAMP() using DateTime value ‘2020-10-17 02:35:43’."
},
{
"code": null,
"e": 26720,
"s": 26659,
"text": "SELECT UNIX_TIMESTAMP('2020-10-17 02:35:43') \nAs TimeStamp; "
},
{
"code": null,
"e": 26729,
"s": 26720,
"text": "Output :"
},
{
"code": null,
"e": 26848,
"s": 26729,
"text": "Example-4 :Working of UNIX_TIMESTAMP() using DateTime value along with fractional seconds ‘2020-10-17 02:35:43.12345’."
},
{
"code": null,
"e": 26915,
"s": 26848,
"text": "SELECT UNIX_TIMESTAMP('2020-10-17 02:35:43.12345') \nAs TimeStamp; "
},
{
"code": null,
"e": 26924,
"s": 26915,
"text": "Output :"
},
{
"code": null,
"e": 26933,
"s": 26924,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 26939,
"s": 26933,
"text": "mysql"
},
{
"code": null,
"e": 26963,
"s": 26939,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 26967,
"s": 26963,
"text": "SQL"
},
{
"code": null,
"e": 26971,
"s": 26967,
"text": "SQL"
},
{
"code": null,
"e": 27069,
"s": 26971,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27135,
"s": 27069,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 27150,
"s": 27135,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 27182,
"s": 27150,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 27239,
"s": 27182,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 27317,
"s": 27239,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 27334,
"s": 27317,
"text": "SQL using Python"
},
{
"code": null,
"e": 27370,
"s": 27334,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 27401,
"s": 27370,
"text": "SQL Query to Compare Two Dates"
},
{
"code": null,
"e": 27467,
"s": 27401,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
}
] |
Python - Remove records if Key not present - GeeksforGeeks
|
21 Feb, 2022
Sometimes, while working with Python dictionaries, we can have a problem in which we need to remove all the dictionaries in which a particular key is not present. This kind of problem can have applications in many domains such as day-day programming and data domain. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [{‘Gfg’ : 1, ‘Best’ : 3}, {‘Gfg’ : 3, ‘Best’ : 5}, {‘Best’ : 3}] , K = ‘Best’ Output : [{‘Gfg’ : 1, ‘Best’ : 3}, {‘Gfg’ : 3, ‘Best’ : 5}, {‘Best’ : 3}]Input : test_list = [{‘Gfg’ : 1, ‘Best’ : 3}, {‘Gfg’ : 3, ‘Best’ : 5}, {‘Best’ : 3}], K = ‘good’ Output : []
Method #1: Using list comprehension This is one of the ways in which this task can be performed. In this, we iterate and test for key presence using list comprehension and conditional statements.
Python3
# Python3 code to demonstrate working of# Remove records if Key not present# Using list comprehension # initializing listtest_list = [{'Gfg' : 1, 'Best' : 3}, {'Gfg' : 3, 'Best' : 5}, {'Best' : 3}] # printing original listprint("The original list : " + str(test_list)) # initializing K KeyK = 'Gfg' # Remove records if Key not present# Using list comprehensionres = [ele for ele in test_list if K in ele] # printing resultprint("List after filtration : " + str(res))
The original list : [{'Gfg': 1, 'Best': 3}, {'Gfg': 3, 'Best': 5}, {'Best': 3}]
List after filteration : [{'Gfg': 1, 'Best': 3}, {'Gfg': 3, 'Best': 5}]
Method #2 : Using list comprehension + keys() The combination of the above functions can be used to solve this problem. In this, we perform the task of extraction of all the keys using keys(), reduces the overhead of checking in items.
Python3
# Python3 code to demonstrate working of# Remove records if Key not present# Using list comprehension + keys() # initializing listtest_list = [{'Gfg' : 1, 'Best' : 3}, {'Gfg' : 3, 'Best' : 5}, {'Best' : 3}] # printing original listprint("The original list : " + str(test_list)) # initializing K KeyK = 'Gfg' # Remove records if Key not present# Using list comprehension + keys()res = [ele for ele in test_list if K in ele.keys()] # printing resultprint("List after filtration : " + str(res))
The original list : [{'Gfg': 1, 'Best': 3}, {'Gfg': 3, 'Best': 5}, {'Best': 3}]
List after filteration : [{'Gfg': 1, 'Best': 3}, {'Gfg': 3, 'Best': 5}]
adnanirshad158
reenadevi98412200
Python List-of-Dict
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n21 Feb, 2022"
},
{
"code": null,
"e": 25869,
"s": 25537,
"text": "Sometimes, while working with Python dictionaries, we can have a problem in which we need to remove all the dictionaries in which a particular key is not present. This kind of problem can have applications in many domains such as day-day programming and data domain. Let’s discuss certain ways in which this task can be performed. "
},
{
"code": null,
"e": 26151,
"s": 25869,
"text": "Input : test_list = [{‘Gfg’ : 1, ‘Best’ : 3}, {‘Gfg’ : 3, ‘Best’ : 5}, {‘Best’ : 3}] , K = ‘Best’ Output : [{‘Gfg’ : 1, ‘Best’ : 3}, {‘Gfg’ : 3, ‘Best’ : 5}, {‘Best’ : 3}]Input : test_list = [{‘Gfg’ : 1, ‘Best’ : 3}, {‘Gfg’ : 3, ‘Best’ : 5}, {‘Best’ : 3}], K = ‘good’ Output : [] "
},
{
"code": null,
"e": 26348,
"s": 26151,
"text": "Method #1: Using list comprehension This is one of the ways in which this task can be performed. In this, we iterate and test for key presence using list comprehension and conditional statements. "
},
{
"code": null,
"e": 26356,
"s": 26348,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Remove records if Key not present# Using list comprehension # initializing listtest_list = [{'Gfg' : 1, 'Best' : 3}, {'Gfg' : 3, 'Best' : 5}, {'Best' : 3}] # printing original listprint(\"The original list : \" + str(test_list)) # initializing K KeyK = 'Gfg' # Remove records if Key not present# Using list comprehensionres = [ele for ele in test_list if K in ele] # printing resultprint(\"List after filtration : \" + str(res))",
"e": 26855,
"s": 26356,
"text": null
},
{
"code": null,
"e": 27007,
"s": 26855,
"text": "The original list : [{'Gfg': 1, 'Best': 3}, {'Gfg': 3, 'Best': 5}, {'Best': 3}]\nList after filteration : [{'Gfg': 1, 'Best': 3}, {'Gfg': 3, 'Best': 5}]"
},
{
"code": null,
"e": 27247,
"s": 27009,
"text": " Method #2 : Using list comprehension + keys() The combination of the above functions can be used to solve this problem. In this, we perform the task of extraction of all the keys using keys(), reduces the overhead of checking in items. "
},
{
"code": null,
"e": 27255,
"s": 27247,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Remove records if Key not present# Using list comprehension + keys() # initializing listtest_list = [{'Gfg' : 1, 'Best' : 3}, {'Gfg' : 3, 'Best' : 5}, {'Best' : 3}] # printing original listprint(\"The original list : \" + str(test_list)) # initializing K KeyK = 'Gfg' # Remove records if Key not present# Using list comprehension + keys()res = [ele for ele in test_list if K in ele.keys()] # printing resultprint(\"List after filtration : \" + str(res))",
"e": 27779,
"s": 27255,
"text": null
},
{
"code": null,
"e": 27931,
"s": 27779,
"text": "The original list : [{'Gfg': 1, 'Best': 3}, {'Gfg': 3, 'Best': 5}, {'Best': 3}]\nList after filteration : [{'Gfg': 1, 'Best': 3}, {'Gfg': 3, 'Best': 5}]"
},
{
"code": null,
"e": 27948,
"s": 27933,
"text": "adnanirshad158"
},
{
"code": null,
"e": 27966,
"s": 27948,
"text": "reenadevi98412200"
},
{
"code": null,
"e": 27986,
"s": 27966,
"text": "Python List-of-Dict"
},
{
"code": null,
"e": 28007,
"s": 27986,
"text": "Python list-programs"
},
{
"code": null,
"e": 28014,
"s": 28007,
"text": "Python"
},
{
"code": null,
"e": 28030,
"s": 28014,
"text": "Python Programs"
},
{
"code": null,
"e": 28128,
"s": 28030,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28160,
"s": 28128,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28202,
"s": 28160,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28244,
"s": 28202,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28271,
"s": 28244,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28327,
"s": 28271,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28349,
"s": 28327,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28388,
"s": 28349,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28434,
"s": 28388,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 28472,
"s": 28434,
"text": "Python | Convert a list to dictionary"
}
] |
Split a text column into two columns in Pandas DataFrame - GeeksforGeeks
|
26 Dec, 2018
Let’s see how to split a text column into two columns in Pandas DataFrame.
Method #1 : Using Series.str.split() functions.
Split Name column into two different columns. By default splitting is done on the basis of single space by str.split() function.
# import Pandas as pdimport pandas as pd # create a new data framedf = pd.DataFrame({'Name': ['John Larter', 'Robert Junior', 'Jonny Depp'], 'Age':[32, 34, 36]}) print("Given Dataframe is :\n",df) # bydefault splitting is done on the basis of single space.print("\nSplitting 'Name' column into two different columns :\n", df.Name.str.split(expand=True))
Output : Split Name column into “First” and “Last” column respectively and add it to the existing Dataframe .
# import Pandas as pdimport pandas as pd # create a new data framedf = pd.DataFrame({'Name': ['John Larter', 'Robert Junior', 'Jonny Depp'], 'Age':[32, 34, 36]}) print("Given Dataframe is :\n",df) # Adding two new columns to the existing dataframe.# bydefault splitting is done on the basis of single space.df[['First','Last']] = df.Name.str.split(expand=True) print("\n After adding two new columns : \n", df)
Output:
Use underscore as delimiter to split the column into two columns.
# import Pandas as pdimport pandas as pd # create a new data framedf = pd.DataFrame({'Name': ['John_Larter', 'Robert_Junior', 'Jonny_Depp'], 'Age':[32, 34, 36]}) print("Given Dataframe is :\n",df) # Adding two new columns to the existing dataframe.# splitting is done on the basis of underscore.df[['First','Last']] = df.Name.str.split("_",expand=True) print("\n After adding two new columns : \n",df)
Output : Use str.split(), tolist() function together.
# import Pandas as pdimport pandas as pd # create a new data framedf = pd.DataFrame({'Name': ['John_Larter', 'Robert_Junior', 'Jonny_Depp'], 'Age':[32, 34, 36]}) print("Given Dataframe is :\n",df) print("\nSplitting Name column into two different columns :") print(pd.DataFrame(df.Name.str.split('_',1).tolist(), columns = ['first','Last']))
Output : Method #2 : Using apply() function.
Split Name column into two different columns.
# import Pandas as pdimport pandas as pd # create a new data framedf = pd.DataFrame({'Name': ['John_Larter', 'Robert_Junior', 'Jonny_Depp'], 'Age':[32, 34, 36]}) print("Given Dataframe is :\n",df) print("\nSplitting Name column into two different columns :") print(df.Name.apply(lambda x: pd.Series(str(x).split("_"))))
Output :
Split Name column into two different columns named as “First” and “Last” respectively and then add it to the existing Dataframe.
# import Pandas as pdimport pandas as pd # create a new data framedf = pd.DataFrame({'Name': ['John_Larter', 'Robert_Junior', 'Jonny_Depp'], 'Age':[32, 34, 36]}) print("Given Dataframe is :\n",df) print("\nSplitting Name column into two different columns :") # splitting 'Name' column into Two columns # i.e. 'First' and 'Last'respectively and # Adding these columns to the existing dataframe.df[['First','Last']] = df.Name.apply( lambda x: pd.Series(str(x).split("_"))) print(df)
Output :
pandas-dataframe-program
Picked
Python pandas-dataFrame
Python-pandas
Technical Scripter 2018
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Convert integer to string in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
|
[
{
"code": null,
"e": 25821,
"s": 25793,
"text": "\n26 Dec, 2018"
},
{
"code": null,
"e": 25896,
"s": 25821,
"text": "Let’s see how to split a text column into two columns in Pandas DataFrame."
},
{
"code": null,
"e": 25944,
"s": 25896,
"text": "Method #1 : Using Series.str.split() functions."
},
{
"code": null,
"e": 26073,
"s": 25944,
"text": "Split Name column into two different columns. By default splitting is done on the basis of single space by str.split() function."
},
{
"code": "# import Pandas as pdimport pandas as pd # create a new data framedf = pd.DataFrame({'Name': ['John Larter', 'Robert Junior', 'Jonny Depp'], 'Age':[32, 34, 36]}) print(\"Given Dataframe is :\\n\",df) # bydefault splitting is done on the basis of single space.print(\"\\nSplitting 'Name' column into two different columns :\\n\", df.Name.str.split(expand=True))",
"e": 26484,
"s": 26073,
"text": null
},
{
"code": null,
"e": 26594,
"s": 26484,
"text": "Output : Split Name column into “First” and “Last” column respectively and add it to the existing Dataframe ."
},
{
"code": "# import Pandas as pdimport pandas as pd # create a new data framedf = pd.DataFrame({'Name': ['John Larter', 'Robert Junior', 'Jonny Depp'], 'Age':[32, 34, 36]}) print(\"Given Dataframe is :\\n\",df) # Adding two new columns to the existing dataframe.# bydefault splitting is done on the basis of single space.df[['First','Last']] = df.Name.str.split(expand=True) print(\"\\n After adding two new columns : \\n\", df)",
"e": 27032,
"s": 26594,
"text": null
},
{
"code": null,
"e": 27040,
"s": 27032,
"text": "Output:"
},
{
"code": null,
"e": 27107,
"s": 27040,
"text": " Use underscore as delimiter to split the column into two columns."
},
{
"code": "# import Pandas as pdimport pandas as pd # create a new data framedf = pd.DataFrame({'Name': ['John_Larter', 'Robert_Junior', 'Jonny_Depp'], 'Age':[32, 34, 36]}) print(\"Given Dataframe is :\\n\",df) # Adding two new columns to the existing dataframe.# splitting is done on the basis of underscore.df[['First','Last']] = df.Name.str.split(\"_\",expand=True) print(\"\\n After adding two new columns : \\n\",df)",
"e": 27536,
"s": 27107,
"text": null
},
{
"code": null,
"e": 27590,
"s": 27536,
"text": "Output : Use str.split(), tolist() function together."
},
{
"code": "# import Pandas as pdimport pandas as pd # create a new data framedf = pd.DataFrame({'Name': ['John_Larter', 'Robert_Junior', 'Jonny_Depp'], 'Age':[32, 34, 36]}) print(\"Given Dataframe is :\\n\",df) print(\"\\nSplitting Name column into two different columns :\") print(pd.DataFrame(df.Name.str.split('_',1).tolist(), columns = ['first','Last']))",
"e": 27980,
"s": 27590,
"text": null
},
{
"code": null,
"e": 28025,
"s": 27980,
"text": "Output : Method #2 : Using apply() function."
},
{
"code": null,
"e": 28071,
"s": 28025,
"text": "Split Name column into two different columns."
},
{
"code": "# import Pandas as pdimport pandas as pd # create a new data framedf = pd.DataFrame({'Name': ['John_Larter', 'Robert_Junior', 'Jonny_Depp'], 'Age':[32, 34, 36]}) print(\"Given Dataframe is :\\n\",df) print(\"\\nSplitting Name column into two different columns :\") print(df.Name.apply(lambda x: pd.Series(str(x).split(\"_\"))))",
"e": 28415,
"s": 28071,
"text": null
},
{
"code": null,
"e": 28424,
"s": 28415,
"text": "Output :"
},
{
"code": null,
"e": 28553,
"s": 28424,
"text": "Split Name column into two different columns named as “First” and “Last” respectively and then add it to the existing Dataframe."
},
{
"code": "# import Pandas as pdimport pandas as pd # create a new data framedf = pd.DataFrame({'Name': ['John_Larter', 'Robert_Junior', 'Jonny_Depp'], 'Age':[32, 34, 36]}) print(\"Given Dataframe is :\\n\",df) print(\"\\nSplitting Name column into two different columns :\") # splitting 'Name' column into Two columns # i.e. 'First' and 'Last'respectively and # Adding these columns to the existing dataframe.df[['First','Last']] = df.Name.apply( lambda x: pd.Series(str(x).split(\"_\"))) print(df)",
"e": 29064,
"s": 28553,
"text": null
},
{
"code": null,
"e": 29073,
"s": 29064,
"text": "Output :"
},
{
"code": null,
"e": 29098,
"s": 29073,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 29105,
"s": 29098,
"text": "Picked"
},
{
"code": null,
"e": 29129,
"s": 29105,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 29143,
"s": 29129,
"text": "Python-pandas"
},
{
"code": null,
"e": 29167,
"s": 29143,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 29174,
"s": 29167,
"text": "Python"
},
{
"code": null,
"e": 29272,
"s": 29174,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29290,
"s": 29272,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29322,
"s": 29290,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29344,
"s": 29322,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29386,
"s": 29344,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29412,
"s": 29386,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29441,
"s": 29412,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 29485,
"s": 29441,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 29521,
"s": 29485,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 29558,
"s": 29521,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Python | Pandas Dataframe.sample() - GeeksforGeeks
|
24 Apr, 2020
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas sample() is used to generate a sample random row or column from the function caller data frame.
Syntax:
DataFrame.sample(n=None, frac=None, replace=False, weights=None, random_state=None, axis=None)
Parameters:
n: int value, Number of random rows to generate.frac: Float value, Returns (float value * length of data frame values ). frac cannot be used with n.replace: Boolean value, return sample with replacement if True.random_state: int value or numpy.random.RandomState, optional. if set to a particular integer, will return same rows as sample in every iteration.axis: 0 or ‘row’ for Rows and 1 or ‘column’ for Columns.
Return type: New object of same type as caller.
To download the CSV file used, Click Here.
Example #1: Random row from Data frame
In this example, two random rows are generated by the .sample() method and compared later.
# importing pandas packageimport pandas as pd # making data frame from csv file data = pd.read_csv("employees.csv") # generating one row row1 = data.sample(n = 1) # displayrow1 # generating another rowrow2 = data.sample(n = 1) # displayrow2
Output:As shown in the output image, the two random sample rows generated are different from each other.
Example #2: Generating 25% sample of data frameIn this example, 25% random sample data is generated out of the Data frame.
# importing pandas packageimport pandas as pd # making data frame from csv file data = pd.read_csv("employees.csv") # generating one row rows = data.sample(frac =.25) # checking if sample is 0.25 times data or not if (0.25*(len(data))== len(rows)): print( "Cool") print(len(data), len(rows)) # displayrows
Output:As shown in the output image, the length of sample generated is 25% of data frame. Also the sample is generated randomly.
pacificlion
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.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
*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": 26153,
"s": 26125,
"text": "\n24 Apr, 2020"
},
{
"code": null,
"e": 26367,
"s": 26153,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 26470,
"s": 26367,
"text": "Pandas sample() is used to generate a sample random row or column from the function caller data frame."
},
{
"code": null,
"e": 26478,
"s": 26470,
"text": "Syntax:"
},
{
"code": null,
"e": 26573,
"s": 26478,
"text": "DataFrame.sample(n=None, frac=None, replace=False, weights=None, random_state=None, axis=None)"
},
{
"code": null,
"e": 26585,
"s": 26573,
"text": "Parameters:"
},
{
"code": null,
"e": 26999,
"s": 26585,
"text": "n: int value, Number of random rows to generate.frac: Float value, Returns (float value * length of data frame values ). frac cannot be used with n.replace: Boolean value, return sample with replacement if True.random_state: int value or numpy.random.RandomState, optional. if set to a particular integer, will return same rows as sample in every iteration.axis: 0 or ‘row’ for Rows and 1 or ‘column’ for Columns."
},
{
"code": null,
"e": 27047,
"s": 26999,
"text": "Return type: New object of same type as caller."
},
{
"code": null,
"e": 27090,
"s": 27047,
"text": "To download the CSV file used, Click Here."
},
{
"code": null,
"e": 27129,
"s": 27090,
"text": "Example #1: Random row from Data frame"
},
{
"code": null,
"e": 27220,
"s": 27129,
"text": "In this example, two random rows are generated by the .sample() method and compared later."
},
{
"code": "# importing pandas packageimport pandas as pd # making data frame from csv file data = pd.read_csv(\"employees.csv\") # generating one row row1 = data.sample(n = 1) # displayrow1 # generating another rowrow2 = data.sample(n = 1) # displayrow2",
"e": 27466,
"s": 27220,
"text": null
},
{
"code": null,
"e": 27571,
"s": 27466,
"text": "Output:As shown in the output image, the two random sample rows generated are different from each other."
},
{
"code": null,
"e": 27695,
"s": 27571,
"text": " Example #2: Generating 25% sample of data frameIn this example, 25% random sample data is generated out of the Data frame."
},
{
"code": "# importing pandas packageimport pandas as pd # making data frame from csv file data = pd.read_csv(\"employees.csv\") # generating one row rows = data.sample(frac =.25) # checking if sample is 0.25 times data or not if (0.25*(len(data))== len(rows)): print( \"Cool\") print(len(data), len(rows)) # displayrows",
"e": 28012,
"s": 27695,
"text": null
},
{
"code": null,
"e": 28141,
"s": 28012,
"text": "Output:As shown in the output image, the length of sample generated is 25% of data frame. Also the sample is generated randomly."
},
{
"code": null,
"e": 28153,
"s": 28141,
"text": "pacificlion"
},
{
"code": null,
"e": 28177,
"s": 28153,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 28209,
"s": 28177,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 28223,
"s": 28209,
"text": "Python-pandas"
},
{
"code": null,
"e": 28230,
"s": 28223,
"text": "Python"
},
{
"code": null,
"e": 28328,
"s": 28230,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28346,
"s": 28328,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28381,
"s": 28346,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28413,
"s": 28381,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28435,
"s": 28413,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28477,
"s": 28435,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28507,
"s": 28477,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28536,
"s": 28507,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28580,
"s": 28536,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28617,
"s": 28580,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Java String charAt() method with example - GeeksforGeeks
|
04 Dec, 2018
The Java String charAt() method returns the character at the specified index. The index value should lie between 0 and length()-1.Signature:
public char charAt(int index)
Parameter:
index- Index of the character to be returned.
Return:
returns character at the specified position.
Exception:
StringIndexOutOfBoundsException- If index is
negative or greater then the length of the
String.
Example:To show working of charAt() method
// Java program to demonstrate// working of charAt() method class Gfg { public static void main(String args[]) { String s = "Welcome! to Geeksforgeeks Planet"; char ch = s.charAt(3); System.out.println(ch); ch = s.charAt(0); System.out.println(ch); }}
c
W
// Java program to demonstrate// working of charAt() method class Gfg { public static void main(String args[]) { String s = "abc"; char ch = s.charAt(4); System.out.println(ch); }}
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(String.java:658)
at Gfg.main(File.java:9)
String Class in Java
Java-Functions
Java-lang package
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Multithreading in Java
Collections in Java
|
[
{
"code": null,
"e": 26048,
"s": 26020,
"text": "\n04 Dec, 2018"
},
{
"code": null,
"e": 26189,
"s": 26048,
"text": "The Java String charAt() method returns the character at the specified index. The index value should lie between 0 and length()-1.Signature:"
},
{
"code": null,
"e": 26223,
"s": 26189,
"text": " public char charAt(int index) \n"
},
{
"code": null,
"e": 26234,
"s": 26223,
"text": "Parameter:"
},
{
"code": null,
"e": 26282,
"s": 26234,
"text": " index- Index of the character to be returned.\n"
},
{
"code": null,
"e": 26290,
"s": 26282,
"text": "Return:"
},
{
"code": null,
"e": 26337,
"s": 26290,
"text": " returns character at the specified position.\n"
},
{
"code": null,
"e": 26348,
"s": 26337,
"text": "Exception:"
},
{
"code": null,
"e": 26450,
"s": 26348,
"text": " StringIndexOutOfBoundsException- If index is \n negative or greater then the length of the \n String.\n"
},
{
"code": null,
"e": 26493,
"s": 26450,
"text": "Example:To show working of charAt() method"
},
{
"code": "// Java program to demonstrate// working of charAt() method class Gfg { public static void main(String args[]) { String s = \"Welcome! to Geeksforgeeks Planet\"; char ch = s.charAt(3); System.out.println(ch); ch = s.charAt(0); System.out.println(ch); }}",
"e": 26794,
"s": 26493,
"text": null
},
{
"code": null,
"e": 26799,
"s": 26794,
"text": "c\nW\n"
},
{
"code": "// Java program to demonstrate// working of charAt() method class Gfg { public static void main(String args[]) { String s = \"abc\"; char ch = s.charAt(4); System.out.println(ch); }}",
"e": 27013,
"s": 26799,
"text": null
},
{
"code": null,
"e": 27191,
"s": 27013,
"text": "Exception in thread \"main\" java.lang.StringIndexOutOfBoundsException: String index out of range: 4\n at java.lang.String.charAt(String.java:658)\n at Gfg.main(File.java:9)\n\n"
},
{
"code": null,
"e": 27212,
"s": 27191,
"text": "String Class in Java"
},
{
"code": null,
"e": 27227,
"s": 27212,
"text": "Java-Functions"
},
{
"code": null,
"e": 27245,
"s": 27227,
"text": "Java-lang package"
},
{
"code": null,
"e": 27258,
"s": 27245,
"text": "Java-Strings"
},
{
"code": null,
"e": 27263,
"s": 27258,
"text": "Java"
},
{
"code": null,
"e": 27276,
"s": 27263,
"text": "Java-Strings"
},
{
"code": null,
"e": 27281,
"s": 27276,
"text": "Java"
},
{
"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": 27394,
"s": 27379,
"text": "Stream In Java"
},
{
"code": null,
"e": 27413,
"s": 27394,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27431,
"s": 27413,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27463,
"s": 27431,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27483,
"s": 27463,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 27507,
"s": 27483,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 27539,
"s": 27507,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 27551,
"s": 27539,
"text": "Set in Java"
},
{
"code": null,
"e": 27574,
"s": 27551,
"text": "Multithreading in Java"
}
] |
Maximum value of expression (arr[i] + arr[j] * arr[k]) formed from a valid Triplet - GeeksforGeeks
|
18 Aug, 2021
Given an array arr[] of N integers. The task is to find the maximum value of (arr[i] + arr[j] * arr[k]) among every triplet (i, j, k) such that arr[i] < arr[j] < arr[k] and i < j < k. If there doesn’t exist any such triplets then print “-1′′.
Examples:
Input: arr[]={7, 9, 3, 8, 11, 10}Output: 106Explanation:The valid triplets are:1) (7, 9, 11), and value of (arr[i] + arr[j] * arr[k]) is 106.2) (7, 9, 10), and value of (arr[i] + arr[j] * arr[k]) is 97.3) (7, 8, 10), and value of (arr[i] + arr[j] * arr[k]) is 87.4) (7, 8, 11), and value of (arr[i] + arr[j] * arr[k]) is 105.5) (3, 8, 10), and value of (arr[i] + arr[j] * arr[k]) is 83.6) (3, 8, 11), and value of (arr[i] + arr[j] * arr[k]) is 91.Therefore, the maximum among the values is 106
Input: arr[]={1, 2, 3}Output: 7
Naive Approach: The idea is to generate all possible valid triplets (i, j, k) and print the maximum value of arr[i] + arr[j]*arr[k] among all the triplets. Below are the steps:
Iterate over the array using three nested loops.For each valid triplets check if arr[i] < arr[j] < arr[k]. If so then the triplet is valid.Find the value of arr[i] + arr[j]*arr[k] for all such triplets if the above condition is true and store it in the variable called value.Keep updating the value of above expression to maximum value among all possible triplets.If no valid triplet found print -1 Otherwise print the maximum value.
Iterate over the array using three nested loops.
For each valid triplets check if arr[i] < arr[j] < arr[k]. If so then the triplet is valid.
Find the value of arr[i] + arr[j]*arr[k] for all such triplets if the above condition is true and store it in the variable called value.
Keep updating the value of above expression to maximum value among all possible triplets.
If no valid triplet found print -1 Otherwise print the maximum value.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function that generate all valid// triplets and calculate the value// of the valid tripletsvoid max_valid_triplet(int A[], int n){ int ans = -1; // Generate all triplets for(int i = 0; i < n - 2; i++) { for(int j = i + 1; j < n - 1; j++) { for(int k = j + 1; k < n; k++) { // Check whether the triplet // is valid or not if (A[i] < A[j] && A[j] < A[k]) { int value = A[i] + A[j] * A[k]; // Update the value if (value > ans) { ans = value; } } } } } // Print the maximum value cout << (ans);} // Driver Codeint main(){ // Given array arr[] int arr[] = { 7, 9, 3, 8, 11, 10 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call max_valid_triplet(arr, n); return 0;} // This code is contributed by chitranayal
// Java program for the above approachimport java.util.Scanner; class GFG { // Function that generate all valid // triplets and calculate the value // of the valid triplets static void max_valid_triplet(int A[], int n) { int ans = -1; // Generate all triplets for (int i = 0; i < n - 2; i++) { for (int j = i + 1; j < n - 1; j++) { for (int k = j + 1; k < n; k++) { // Check whether the triplet // is valid or not if (A[i] < A[j] && A[j] < A[k]) { int value = A[i] + A[j] * A[k]; // Update the value if (value > ans) { ans = value; } } } } } // Print the maximum value System.out.println(ans); } // Driver Code public static void main(String args[]) { // Given array arr[] int[] arr = new int[] { 7, 9, 3, 8, 11, 10 }; int n = arr.length; // Function Call max_valid_triplet(arr, n); }}
# Python3 program for the above approach # Function that generate all valid# triplets and calculate the value# of the valid tripletsdef max_valid_triplet(A, n): ans = -1; # Generate all triplets for i in range(0, n - 2): for j in range(i + 1, n - 1): for k in range(j + 1, n): # Check whether the triplet # is valid or not if (A[i] < A[j] and A[j] < A[k]): value = A[i] + A[j] * A[k]; # Update the value if (value > ans): ans = value; # Print the maximum value print(ans); # Driver Codeif __name__ == '__main__': # Given array arr arr = [ 7, 9, 3, 8, 11, 10 ]; n = len(arr); # Function call max_valid_triplet(arr, n); # This code is contributed by Amit Katiyar
// C# program for the above approachusing System;class GFG{ // Function that generate all valid // triplets and calculate the value // of the valid triplets static void max_valid_triplet(int[] A, int n) { int ans = -1; // Generate all triplets for (int i = 0; i < n - 2; i++) { for (int j = i + 1; j < n - 1; j++) { for (int k = j + 1; k < n; k++) { // Check whether the triplet // is valid or not if (A[i] < A[j] && A[j] < A[k]) { int value = A[i] + A[j] * A[k]; // Update the value if (value > ans) { ans = value; } } } } } // Print the maximum value Console.WriteLine(ans); } // Driver Code public static void Main(String[] args) { // Given array []arr int[] arr = new int[] { 7, 9, 3, 8, 11, 10 }; int n = arr.Length; // Function Call max_valid_triplet(arr, n); }} // This code is contributed by gauravrajput1
<script>// JavaScript program for the above approach // Function that generate all valid// triplets and calculate the value// of the valid tripletsfunction max_valid_triplet(A, n){ let ans = -1; // Generate all triplets for(let i = 0; i < n - 2; i++) { for(let j = i + 1; j < n - 1; j++) { for(let k = j + 1; k < n; k++) { // Check whether the triplet // is valid or not if (A[i] < A[j] && A[j] < A[k]) { let value = A[i] + A[j] * A[k]; // Update the value if (value > ans) { ans = value; } } } } } // Print the maximum value document.write(ans);} // Driver Code // Given array arr[] let arr = [ 7, 9, 3, 8, 11, 10 ]; let n = arr.length; // Function call max_valid_triplet(arr, n); // This code is contributed by Surbhi Tyagi.</script>
106
Time Complexity: O(N3)Auxiliary Space: O(1)
Efficient approach: The above method can be optimized by using TreeSet in Java. Below are the steps:
Create two arrays. One array (left) to store the maximum element on the left side which strictly less than the present element in the original array and another array (right) to store the right side maximum of the present element in the original array as shown in the below image for array arr[] = {7, 9, 3, 8, 11, 10}:
For the construction of the left array, we use TreeSet in Java, insert the elements into the TreeSet, use the lower() method in TreeSet which will return the greatest element in this set which is strictly less than the given element. If no such element exists in this TreeSet collection then this method returns a NULL.
The elements in the left array will be arr[i] of the valid triplets and the elements in the right array will be arr[k] of the valid triplet.
Now, traverse the original array from 1 to N – 1, to select arr[j] for the valid triplet.
If left[i]!=-1 && right[i]!=-1 then there is a chance for forming triplet.
Find the value arr[i] + arr[j]*arr[k] for all such valid triplets and update the ans according to the maximum value.
Print the maximum value if it exists otherwise print “-1”.
Below is the implementation of the above approach:
Java
C#
Javascript
// Java program for the above approachimport java.util.*; class GFG { // Function that finds the maximum // valid triplets static int max_valid_triplet(int A[], int n) { int ans = -1; // Declare the left[] and // right[] array int left[] = new int[n]; int right[] = new int[n]; // Consider last element as maximum int max = A[n - 1]; // Iterate array from the last for (int i = n - 2; i >= 0; i--) { // If present is less the maximum // update the right[i] with // previous maximum if (max > A[i]) right[i] = max; // Else store -1 else right[i] = -1; // Find the maximum for // the next iteration if (max < A[i]) max = A[i]; } TreeSet<Integer> set = new TreeSet<Integer>(); for (int i = 1; i < n; i++) { // Insert previous element // to the set set.add(A[i - 1]); Integer result = set.lower(A[i]); // Search for maximum element // which is < present element // If result is null there is // no such element exists // so store -1 at left[i] if (result == null) left[i] = -1; // Else store the result else left[i] = result; } // Traverse the original array for (int i = 1; i < n - 1; i++) { // Condition for valid triplet if (left[i] != -1 && right[i] != -1) // Find the value and update // the maximum value ans = Math.max(ans, left[i] + A[i] * right[i]); } // Return the ans return ans; } // Driver Code public static void main(String args[]) { // Given array arr[] int[] A = new int[] { 7, 9, 3, 8, 11, 10 }; int n = A.length; // Function Call System.out.println(max_valid_triplet(A, n)); }}
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function that finds the maximum// valid tripletsstatic int max_valid_triplet(int []A, int n){ int ans = -1; // Declare the []left and // []right array int []left = new int[n]; int []right = new int[n]; // Consider last element as maximum int max = A[n - 1]; // Iterate array from the last for(int i = n - 2; i >= 0; i--) { // If present is less the maximum // update the right[i] with // previous maximum if (max > A[i]) right[i] = max; // Else store -1 else right[i] = -1; // Find the maximum for // the next iteration if (max < A[i]) max = A[i]; } SortedSet<int> set = new SortedSet<int>(); for(int i = 1; i < n; i++) { // Insert previous element // to the set set.Add(A[i - 1]); int result = set.Min; // Search for maximum element // which is < present element // If result is null there is // no such element exists // so store -1 at left[i] if (result == 0) left[i] = -1; // Else store the result else left[i] = result; } // Traverse the original array for(int i = 1; i < n - 1; i++) { // Condition for valid triplet if (left[i] != -1 && right[i] != -1) // Find the value and update // the maximum value ans = Math.Max(ans, left[i] + A[i] * right[i]); } // Return the ans return ans;} // Driver Codepublic static void Main(String []args){ // Given array []arr int[] A = new int[]{ 7, 9, 3, 8, 11, 10 }; int n = A.Length; // Function call Console.WriteLine(max_valid_triplet(A, n));}} // This code is contributed by Amit Katiyar
<script> // Javascript program for the above approach // Function that finds the maximum// valid tripletsfunction max_valid_triplet(A, n){ let ans = -1; // Declare the []left and // []right array let left = new Array(n); let right = new Array(n); for(let i = 0; i < n; i++) { left[i] = 0; right[i] = 0; } // Consider last element as maximum let max = A[n - 1]; // Iterate array from the last for(let i = n - 2; i >= 0; i--) { // If present is less the maximum // update the right[i] with // previous maximum if (max > A[i]) right[i] = max; // Else store -1 else right[i] = -1; // Find the maximum for // the next iteration if (max < A[i]) max = A[i]; } let set = new Set(); for(let i = 1; i < n; i++) { // Insert previous element // to the set set.add(A[i - 1]); let result = Math.min(...Array.from(set)); // Search for maximum element // which is < present element // If result is null there is // no such element exists // so store -1 at left[i] if (result == 0) left[i] = -1; // Else store the result else left[i] = result; } // Traverse the original array for(let i = 1; i < n - 1; i++) { // Condition for valid triplet if (left[i] != -1 && right[i] != -1) // Find the value and update // the maximum value ans = Math.max(ans, left[i] + A[i] * right[i]); } // Return the ans return ans;} // Driver Codelet A = [ 7, 9, 3, 8, 11, 10 ];let n = A.length; document.write(max_valid_triplet(A, n)); // This code is contributed by avanitrachhadiya2155 </script>
106
Time Complexity: O(N)Auxiliary Space: O(N)
ukasp
GauravRajput1
amit143katiyar
surbhityagi15
avanitrachhadiya2155
singghakshay
java-treeset
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Find duplicates in O(n) time and O(1) extra space | Set 1
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 26067,
"s": 26039,
"text": "\n18 Aug, 2021"
},
{
"code": null,
"e": 26311,
"s": 26067,
"text": "Given an array arr[] of N integers. The task is to find the maximum value of (arr[i] + arr[j] * arr[k]) among every triplet (i, j, k) such that arr[i] < arr[j] < arr[k] and i < j < k. If there doesn’t exist any such triplets then print “-1′′."
},
{
"code": null,
"e": 26321,
"s": 26311,
"text": "Examples:"
},
{
"code": null,
"e": 26815,
"s": 26321,
"text": "Input: arr[]={7, 9, 3, 8, 11, 10}Output: 106Explanation:The valid triplets are:1) (7, 9, 11), and value of (arr[i] + arr[j] * arr[k]) is 106.2) (7, 9, 10), and value of (arr[i] + arr[j] * arr[k]) is 97.3) (7, 8, 10), and value of (arr[i] + arr[j] * arr[k]) is 87.4) (7, 8, 11), and value of (arr[i] + arr[j] * arr[k]) is 105.5) (3, 8, 10), and value of (arr[i] + arr[j] * arr[k]) is 83.6) (3, 8, 11), and value of (arr[i] + arr[j] * arr[k]) is 91.Therefore, the maximum among the values is 106"
},
{
"code": null,
"e": 26847,
"s": 26815,
"text": "Input: arr[]={1, 2, 3}Output: 7"
},
{
"code": null,
"e": 27024,
"s": 26847,
"text": "Naive Approach: The idea is to generate all possible valid triplets (i, j, k) and print the maximum value of arr[i] + arr[j]*arr[k] among all the triplets. Below are the steps:"
},
{
"code": null,
"e": 27458,
"s": 27024,
"text": "Iterate over the array using three nested loops.For each valid triplets check if arr[i] < arr[j] < arr[k]. If so then the triplet is valid.Find the value of arr[i] + arr[j]*arr[k] for all such triplets if the above condition is true and store it in the variable called value.Keep updating the value of above expression to maximum value among all possible triplets.If no valid triplet found print -1 Otherwise print the maximum value."
},
{
"code": null,
"e": 27507,
"s": 27458,
"text": "Iterate over the array using three nested loops."
},
{
"code": null,
"e": 27599,
"s": 27507,
"text": "For each valid triplets check if arr[i] < arr[j] < arr[k]. If so then the triplet is valid."
},
{
"code": null,
"e": 27736,
"s": 27599,
"text": "Find the value of arr[i] + arr[j]*arr[k] for all such triplets if the above condition is true and store it in the variable called value."
},
{
"code": null,
"e": 27826,
"s": 27736,
"text": "Keep updating the value of above expression to maximum value among all possible triplets."
},
{
"code": null,
"e": 27896,
"s": 27826,
"text": "If no valid triplet found print -1 Otherwise print the maximum value."
},
{
"code": null,
"e": 27947,
"s": 27896,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27951,
"s": 27947,
"text": "C++"
},
{
"code": null,
"e": 27956,
"s": 27951,
"text": "Java"
},
{
"code": null,
"e": 27964,
"s": 27956,
"text": "Python3"
},
{
"code": null,
"e": 27967,
"s": 27964,
"text": "C#"
},
{
"code": null,
"e": 27978,
"s": 27967,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function that generate all valid// triplets and calculate the value// of the valid tripletsvoid max_valid_triplet(int A[], int n){ int ans = -1; // Generate all triplets for(int i = 0; i < n - 2; i++) { for(int j = i + 1; j < n - 1; j++) { for(int k = j + 1; k < n; k++) { // Check whether the triplet // is valid or not if (A[i] < A[j] && A[j] < A[k]) { int value = A[i] + A[j] * A[k]; // Update the value if (value > ans) { ans = value; } } } } } // Print the maximum value cout << (ans);} // Driver Codeint main(){ // Given array arr[] int arr[] = { 7, 9, 3, 8, 11, 10 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call max_valid_triplet(arr, n); return 0;} // This code is contributed by chitranayal",
"e": 29091,
"s": 27978,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.Scanner; class GFG { // Function that generate all valid // triplets and calculate the value // of the valid triplets static void max_valid_triplet(int A[], int n) { int ans = -1; // Generate all triplets for (int i = 0; i < n - 2; i++) { for (int j = i + 1; j < n - 1; j++) { for (int k = j + 1; k < n; k++) { // Check whether the triplet // is valid or not if (A[i] < A[j] && A[j] < A[k]) { int value = A[i] + A[j] * A[k]; // Update the value if (value > ans) { ans = value; } } } } } // Print the maximum value System.out.println(ans); } // Driver Code public static void main(String args[]) { // Given array arr[] int[] arr = new int[] { 7, 9, 3, 8, 11, 10 }; int n = arr.length; // Function Call max_valid_triplet(arr, n); }}",
"e": 30246,
"s": 29091,
"text": null
},
{
"code": "# Python3 program for the above approach # Function that generate all valid# triplets and calculate the value# of the valid tripletsdef max_valid_triplet(A, n): ans = -1; # Generate all triplets for i in range(0, n - 2): for j in range(i + 1, n - 1): for k in range(j + 1, n): # Check whether the triplet # is valid or not if (A[i] < A[j] and A[j] < A[k]): value = A[i] + A[j] * A[k]; # Update the value if (value > ans): ans = value; # Print the maximum value print(ans); # Driver Codeif __name__ == '__main__': # Given array arr arr = [ 7, 9, 3, 8, 11, 10 ]; n = len(arr); # Function call max_valid_triplet(arr, n); # This code is contributed by Amit Katiyar ",
"e": 31113,
"s": 30246,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG{ // Function that generate all valid // triplets and calculate the value // of the valid triplets static void max_valid_triplet(int[] A, int n) { int ans = -1; // Generate all triplets for (int i = 0; i < n - 2; i++) { for (int j = i + 1; j < n - 1; j++) { for (int k = j + 1; k < n; k++) { // Check whether the triplet // is valid or not if (A[i] < A[j] && A[j] < A[k]) { int value = A[i] + A[j] * A[k]; // Update the value if (value > ans) { ans = value; } } } } } // Print the maximum value Console.WriteLine(ans); } // Driver Code public static void Main(String[] args) { // Given array []arr int[] arr = new int[] { 7, 9, 3, 8, 11, 10 }; int n = arr.Length; // Function Call max_valid_triplet(arr, n); }} // This code is contributed by gauravrajput1",
"e": 32130,
"s": 31113,
"text": null
},
{
"code": "<script>// JavaScript program for the above approach // Function that generate all valid// triplets and calculate the value// of the valid tripletsfunction max_valid_triplet(A, n){ let ans = -1; // Generate all triplets for(let i = 0; i < n - 2; i++) { for(let j = i + 1; j < n - 1; j++) { for(let k = j + 1; k < n; k++) { // Check whether the triplet // is valid or not if (A[i] < A[j] && A[j] < A[k]) { let value = A[i] + A[j] * A[k]; // Update the value if (value > ans) { ans = value; } } } } } // Print the maximum value document.write(ans);} // Driver Code // Given array arr[] let arr = [ 7, 9, 3, 8, 11, 10 ]; let n = arr.length; // Function call max_valid_triplet(arr, n); // This code is contributed by Surbhi Tyagi.</script>",
"e": 33175,
"s": 32130,
"text": null
},
{
"code": null,
"e": 33179,
"s": 33175,
"text": "106"
},
{
"code": null,
"e": 33225,
"s": 33181,
"text": "Time Complexity: O(N3)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 33326,
"s": 33225,
"text": "Efficient approach: The above method can be optimized by using TreeSet in Java. Below are the steps:"
},
{
"code": null,
"e": 33648,
"s": 33326,
"text": "Create two arrays. One array (left) to store the maximum element on the left side which strictly less than the present element in the original array and another array (right) to store the right side maximum of the present element in the original array as shown in the below image for array arr[] = {7, 9, 3, 8, 11, 10}: "
},
{
"code": null,
"e": 33968,
"s": 33648,
"text": "For the construction of the left array, we use TreeSet in Java, insert the elements into the TreeSet, use the lower() method in TreeSet which will return the greatest element in this set which is strictly less than the given element. If no such element exists in this TreeSet collection then this method returns a NULL."
},
{
"code": null,
"e": 34109,
"s": 33968,
"text": "The elements in the left array will be arr[i] of the valid triplets and the elements in the right array will be arr[k] of the valid triplet."
},
{
"code": null,
"e": 34199,
"s": 34109,
"text": "Now, traverse the original array from 1 to N – 1, to select arr[j] for the valid triplet."
},
{
"code": null,
"e": 34274,
"s": 34199,
"text": "If left[i]!=-1 && right[i]!=-1 then there is a chance for forming triplet."
},
{
"code": null,
"e": 34391,
"s": 34274,
"text": "Find the value arr[i] + arr[j]*arr[k] for all such valid triplets and update the ans according to the maximum value."
},
{
"code": null,
"e": 34450,
"s": 34391,
"text": "Print the maximum value if it exists otherwise print “-1”."
},
{
"code": null,
"e": 34501,
"s": 34450,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 34506,
"s": 34501,
"text": "Java"
},
{
"code": null,
"e": 34509,
"s": 34506,
"text": "C#"
},
{
"code": null,
"e": 34520,
"s": 34509,
"text": "Javascript"
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG { // Function that finds the maximum // valid triplets static int max_valid_triplet(int A[], int n) { int ans = -1; // Declare the left[] and // right[] array int left[] = new int[n]; int right[] = new int[n]; // Consider last element as maximum int max = A[n - 1]; // Iterate array from the last for (int i = n - 2; i >= 0; i--) { // If present is less the maximum // update the right[i] with // previous maximum if (max > A[i]) right[i] = max; // Else store -1 else right[i] = -1; // Find the maximum for // the next iteration if (max < A[i]) max = A[i]; } TreeSet<Integer> set = new TreeSet<Integer>(); for (int i = 1; i < n; i++) { // Insert previous element // to the set set.add(A[i - 1]); Integer result = set.lower(A[i]); // Search for maximum element // which is < present element // If result is null there is // no such element exists // so store -1 at left[i] if (result == null) left[i] = -1; // Else store the result else left[i] = result; } // Traverse the original array for (int i = 1; i < n - 1; i++) { // Condition for valid triplet if (left[i] != -1 && right[i] != -1) // Find the value and update // the maximum value ans = Math.max(ans, left[i] + A[i] * right[i]); } // Return the ans return ans; } // Driver Code public static void main(String args[]) { // Given array arr[] int[] A = new int[] { 7, 9, 3, 8, 11, 10 }; int n = A.length; // Function Call System.out.println(max_valid_triplet(A, n)); }}",
"e": 36638,
"s": 34520,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function that finds the maximum// valid tripletsstatic int max_valid_triplet(int []A, int n){ int ans = -1; // Declare the []left and // []right array int []left = new int[n]; int []right = new int[n]; // Consider last element as maximum int max = A[n - 1]; // Iterate array from the last for(int i = n - 2; i >= 0; i--) { // If present is less the maximum // update the right[i] with // previous maximum if (max > A[i]) right[i] = max; // Else store -1 else right[i] = -1; // Find the maximum for // the next iteration if (max < A[i]) max = A[i]; } SortedSet<int> set = new SortedSet<int>(); for(int i = 1; i < n; i++) { // Insert previous element // to the set set.Add(A[i - 1]); int result = set.Min; // Search for maximum element // which is < present element // If result is null there is // no such element exists // so store -1 at left[i] if (result == 0) left[i] = -1; // Else store the result else left[i] = result; } // Traverse the original array for(int i = 1; i < n - 1; i++) { // Condition for valid triplet if (left[i] != -1 && right[i] != -1) // Find the value and update // the maximum value ans = Math.Max(ans, left[i] + A[i] * right[i]); } // Return the ans return ans;} // Driver Codepublic static void Main(String []args){ // Given array []arr int[] A = new int[]{ 7, 9, 3, 8, 11, 10 }; int n = A.Length; // Function call Console.WriteLine(max_valid_triplet(A, n));}} // This code is contributed by Amit Katiyar",
"e": 38631,
"s": 36638,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function that finds the maximum// valid tripletsfunction max_valid_triplet(A, n){ let ans = -1; // Declare the []left and // []right array let left = new Array(n); let right = new Array(n); for(let i = 0; i < n; i++) { left[i] = 0; right[i] = 0; } // Consider last element as maximum let max = A[n - 1]; // Iterate array from the last for(let i = n - 2; i >= 0; i--) { // If present is less the maximum // update the right[i] with // previous maximum if (max > A[i]) right[i] = max; // Else store -1 else right[i] = -1; // Find the maximum for // the next iteration if (max < A[i]) max = A[i]; } let set = new Set(); for(let i = 1; i < n; i++) { // Insert previous element // to the set set.add(A[i - 1]); let result = Math.min(...Array.from(set)); // Search for maximum element // which is < present element // If result is null there is // no such element exists // so store -1 at left[i] if (result == 0) left[i] = -1; // Else store the result else left[i] = result; } // Traverse the original array for(let i = 1; i < n - 1; i++) { // Condition for valid triplet if (left[i] != -1 && right[i] != -1) // Find the value and update // the maximum value ans = Math.max(ans, left[i] + A[i] * right[i]); } // Return the ans return ans;} // Driver Codelet A = [ 7, 9, 3, 8, 11, 10 ];let n = A.length; document.write(max_valid_triplet(A, n)); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 40529,
"s": 38631,
"text": null
},
{
"code": null,
"e": 40533,
"s": 40529,
"text": "106"
},
{
"code": null,
"e": 40579,
"s": 40535,
"text": "Time Complexity: O(N)Auxiliary Space: O(N) "
},
{
"code": null,
"e": 40585,
"s": 40579,
"text": "ukasp"
},
{
"code": null,
"e": 40599,
"s": 40585,
"text": "GauravRajput1"
},
{
"code": null,
"e": 40614,
"s": 40599,
"text": "amit143katiyar"
},
{
"code": null,
"e": 40628,
"s": 40614,
"text": "surbhityagi15"
},
{
"code": null,
"e": 40649,
"s": 40628,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 40662,
"s": 40649,
"text": "singghakshay"
},
{
"code": null,
"e": 40675,
"s": 40662,
"text": "java-treeset"
},
{
"code": null,
"e": 40682,
"s": 40675,
"text": "Arrays"
},
{
"code": null,
"e": 40695,
"s": 40682,
"text": "Mathematical"
},
{
"code": null,
"e": 40702,
"s": 40695,
"text": "Arrays"
},
{
"code": null,
"e": 40715,
"s": 40702,
"text": "Mathematical"
},
{
"code": null,
"e": 40813,
"s": 40715,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40844,
"s": 40813,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 40869,
"s": 40844,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 40907,
"s": 40869,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 40928,
"s": 40907,
"text": "Next Greater Element"
},
{
"code": null,
"e": 40986,
"s": 40928,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 41016,
"s": 40986,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 41076,
"s": 41016,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 41091,
"s": 41076,
"text": "C++ Data Types"
},
{
"code": null,
"e": 41134,
"s": 41091,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
JavaFX - Layout BorderPane
|
If we use the BorderPane, the nodes are arranged in the Top, Left, Right, Bottom and Center positions.
The class named BorderPane of the package javafx.scene.layout represents the BorderPane.
This class contains five properties, which include −
bottom − This property is of Node type and it represents the node placed at the bottom of the BorderPane. You can set value to this property using the setter method setBottom().
bottom − This property is of Node type and it represents the node placed at the bottom of the BorderPane. You can set value to this property using the setter method setBottom().
center − This property is of Node type and it represents the node placed at the center of the BorderPane. You can set value to this property using the setter method setCenter().
center − This property is of Node type and it represents the node placed at the center of the BorderPane. You can set value to this property using the setter method setCenter().
left − This property is of Node type and it represents the node placed at the left of the BorderPane. You can set value to this property using the setter method setLeft().
left − This property is of Node type and it represents the node placed at the left of the BorderPane. You can set value to this property using the setter method setLeft().
right − This property is of Node type and it represents the node placed at the right of the BorderPane. You can set value to this property using the setter method setRight().
right − This property is of Node type and it represents the node placed at the right of the BorderPane. You can set value to this property using the setter method setRight().
top − This property is of Node type and it represents the node placed at the top of the BorderPane. You can set value to this property using the setter method setTop().
top − This property is of Node type and it represents the node placed at the top of the BorderPane. You can set value to this property using the setter method setTop().
In addition to these, this class also provides the following method −
setAlignment() − This method is used to set the alignment of the nodes belonging to this pane. This method accepts a node and a priority value.
setAlignment() − This method is used to set the alignment of the nodes belonging to this pane. This method accepts a node and a priority value.
The following program is an example of the BorderPane layout. In this, we are inserting a five text fields in the Top, Bottom, Right, Left and Center positions.
Save this code in a file with the name BorderPaneExample.java.
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class BorderPaneExample extends Application {
@Override
public void start(Stage stage) {
//Instantiating the BorderPane class
BorderPane bPane = new BorderPane();
//Setting the top, bottom, center, right and left nodes to the pane
bPane.setTop(new TextField("Top"));
bPane.setBottom(new TextField("Bottom"));
bPane.setLeft(new TextField("Left"));
bPane.setRight(new TextField("Right"));
bPane.setCenter(new TextField("Center"));
//Creating a scene object
Scene scene = new Scene(bPane);
//Setting title to the Stage
stage.setTitle("BorderPane Example");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Compile and execute the saved java file from the command prompt using the following commands.
javac BorderPaneExample.java
java BorderPaneExample
On executing, the above program generates a JavaFX window as shown below.
33 Lectures
7.5 hours
Syed Raza
64 Lectures
12.5 hours
Emenwa Global, Ejike IfeanyiChukwu
20 Lectures
4 hours
Emenwa Global, Ejike IfeanyiChukwu
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2003,
"s": 1900,
"text": "If we use the BorderPane, the nodes are arranged in the Top, Left, Right, Bottom and Center positions."
},
{
"code": null,
"e": 2092,
"s": 2003,
"text": "The class named BorderPane of the package javafx.scene.layout represents the BorderPane."
},
{
"code": null,
"e": 2145,
"s": 2092,
"text": "This class contains five properties, which include −"
},
{
"code": null,
"e": 2323,
"s": 2145,
"text": "bottom − This property is of Node type and it represents the node placed at the bottom of the BorderPane. You can set value to this property using the setter method setBottom()."
},
{
"code": null,
"e": 2501,
"s": 2323,
"text": "bottom − This property is of Node type and it represents the node placed at the bottom of the BorderPane. You can set value to this property using the setter method setBottom()."
},
{
"code": null,
"e": 2679,
"s": 2501,
"text": "center − This property is of Node type and it represents the node placed at the center of the BorderPane. You can set value to this property using the setter method setCenter()."
},
{
"code": null,
"e": 2857,
"s": 2679,
"text": "center − This property is of Node type and it represents the node placed at the center of the BorderPane. You can set value to this property using the setter method setCenter()."
},
{
"code": null,
"e": 3029,
"s": 2857,
"text": "left − This property is of Node type and it represents the node placed at the left of the BorderPane. You can set value to this property using the setter method setLeft()."
},
{
"code": null,
"e": 3201,
"s": 3029,
"text": "left − This property is of Node type and it represents the node placed at the left of the BorderPane. You can set value to this property using the setter method setLeft()."
},
{
"code": null,
"e": 3376,
"s": 3201,
"text": "right − This property is of Node type and it represents the node placed at the right of the BorderPane. You can set value to this property using the setter method setRight()."
},
{
"code": null,
"e": 3551,
"s": 3376,
"text": "right − This property is of Node type and it represents the node placed at the right of the BorderPane. You can set value to this property using the setter method setRight()."
},
{
"code": null,
"e": 3720,
"s": 3551,
"text": "top − This property is of Node type and it represents the node placed at the top of the BorderPane. You can set value to this property using the setter method setTop()."
},
{
"code": null,
"e": 3889,
"s": 3720,
"text": "top − This property is of Node type and it represents the node placed at the top of the BorderPane. You can set value to this property using the setter method setTop()."
},
{
"code": null,
"e": 3959,
"s": 3889,
"text": "In addition to these, this class also provides the following method −"
},
{
"code": null,
"e": 4103,
"s": 3959,
"text": "setAlignment() − This method is used to set the alignment of the nodes belonging to this pane. This method accepts a node and a priority value."
},
{
"code": null,
"e": 4247,
"s": 4103,
"text": "setAlignment() − This method is used to set the alignment of the nodes belonging to this pane. This method accepts a node and a priority value."
},
{
"code": null,
"e": 4408,
"s": 4247,
"text": "The following program is an example of the BorderPane layout. In this, we are inserting a five text fields in the Top, Bottom, Right, Left and Center positions."
},
{
"code": null,
"e": 4471,
"s": 4408,
"text": "Save this code in a file with the name BorderPaneExample.java."
},
{
"code": null,
"e": 5621,
"s": 4471,
"text": "import javafx.application.Application; \nimport javafx.collections.ObservableList; \nimport javafx.scene.Scene; \nimport javafx.scene.control.TextField; \nimport javafx.scene.layout.BorderPane; \nimport javafx.stage.Stage; \n \npublic class BorderPaneExample extends Application { \n @Override \n public void start(Stage stage) { \n //Instantiating the BorderPane class \n BorderPane bPane = new BorderPane(); \n \n //Setting the top, bottom, center, right and left nodes to the pane \n bPane.setTop(new TextField(\"Top\")); \n bPane.setBottom(new TextField(\"Bottom\")); \n bPane.setLeft(new TextField(\"Left\")); \n bPane.setRight(new TextField(\"Right\")); \n bPane.setCenter(new TextField(\"Center\")); \n \n //Creating a scene object \n Scene scene = new Scene(bPane); \n \n //Setting title to the Stage\n stage.setTitle(\"BorderPane Example\"); \n \n //Adding scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of the stage \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n}"
},
{
"code": null,
"e": 5715,
"s": 5621,
"text": "Compile and execute the saved java file from the command prompt using the following commands."
},
{
"code": null,
"e": 5769,
"s": 5715,
"text": "javac BorderPaneExample.java \njava BorderPaneExample\n"
},
{
"code": null,
"e": 5843,
"s": 5769,
"text": "On executing, the above program generates a JavaFX window as shown below."
},
{
"code": null,
"e": 5878,
"s": 5843,
"text": "\n 33 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 5889,
"s": 5878,
"text": " Syed Raza"
},
{
"code": null,
"e": 5925,
"s": 5889,
"text": "\n 64 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 5961,
"s": 5925,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 5994,
"s": 5961,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6030,
"s": 5994,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 6037,
"s": 6030,
"text": " Print"
},
{
"code": null,
"e": 6048,
"s": 6037,
"text": " Add Notes"
}
] |
Prime or not in Python
|
Prime numbers play a central role in many e it applications like cryptography. So it is a necessity to check for prime numbers using Python programs in various applications. A prime number is a number which doesn't have any factors other than one and itself. Below will see programs that can find out if a given number is prime or not.
We take the following approach to decide whether a number is prime or not.
Check at the beginning is positive or not. As only positive numbers can be prime numbers.
Check at the beginning is positive or not. As only positive numbers can be prime numbers.
We divide the number with all the numbers in the range of 2 to one number less than given number.
We divide the number with all the numbers in the range of 2 to one number less than given number.
If the remainder becomes zero for any number in this range then it is not a prime number.
If the remainder becomes zero for any number in this range then it is not a prime number.
Live Demo
x = 23
if x > 1:
for n in range(2, x):
if (x % n) == 0:
print(x, "is not prime")
print(n, "times", x // n, "is", x)
break
else:
print(x, "is a prime number")
else:
print(x, "is not prime number")
Running the above code gives us the following result −
23 is a prime number
All prime numbers which are greater than 6 can be represented in the form of 6i+1. Here I starts from 1 and goes on as integer. In the below example we will check if the number can be presented in the form of 6i+1 by dividing its 6 and checking for a reminder as one. Accordingly, will decide if the number is prime or not. Also we need to check for a i value which is equal to square root of the given number.
Live Demo
def CheckPrime(n):
# Check for cases of 2 and 3
if (n <= 1):
return False
if (n <= 3):
return True
# skip checking middle five numbers in the loop
if (n % 2 == 0 or n % 3 == 0):
return False
i = 5
while (i * i <= n):
if (n % i == 0 or n % (i + 2) == 0):
return False
i = i + 6
return True
# Check for inputs
if (CheckPrime(31)):
print(" true")
else:
print(" false")
if (CheckPrime(25)):
print(" true")
else:
print(" false")
Running the above code gives us the following result −
true
false
|
[
{
"code": null,
"e": 1398,
"s": 1062,
"text": "Prime numbers play a central role in many e it applications like cryptography. So it is a necessity to check for prime numbers using Python programs in various applications. A prime number is a number which doesn't have any factors other than one and itself. Below will see programs that can find out if a given number is prime or not."
},
{
"code": null,
"e": 1473,
"s": 1398,
"text": "We take the following approach to decide whether a number is prime or not."
},
{
"code": null,
"e": 1563,
"s": 1473,
"text": "Check at the beginning is positive or not. As only positive numbers can be prime numbers."
},
{
"code": null,
"e": 1653,
"s": 1563,
"text": "Check at the beginning is positive or not. As only positive numbers can be prime numbers."
},
{
"code": null,
"e": 1751,
"s": 1653,
"text": "We divide the number with all the numbers in the range of 2 to one number less than given number."
},
{
"code": null,
"e": 1849,
"s": 1751,
"text": "We divide the number with all the numbers in the range of 2 to one number less than given number."
},
{
"code": null,
"e": 1939,
"s": 1849,
"text": "If the remainder becomes zero for any number in this range then it is not a prime number."
},
{
"code": null,
"e": 2029,
"s": 1939,
"text": "If the remainder becomes zero for any number in this range then it is not a prime number."
},
{
"code": null,
"e": 2040,
"s": 2029,
"text": " Live Demo"
},
{
"code": null,
"e": 2290,
"s": 2040,
"text": "x = 23\nif x > 1:\n for n in range(2, x):\n if (x % n) == 0:\n print(x, \"is not prime\")\n print(n, \"times\", x // n, \"is\", x)\n break\n else:\n print(x, \"is a prime number\")\n else:\n print(x, \"is not prime number\")"
},
{
"code": null,
"e": 2345,
"s": 2290,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2366,
"s": 2345,
"text": "23 is a prime number"
},
{
"code": null,
"e": 2777,
"s": 2366,
"text": "All prime numbers which are greater than 6 can be represented in the form of 6i+1. Here I starts from 1 and goes on as integer. In the below example we will check if the number can be presented in the form of 6i+1 by dividing its 6 and checking for a reminder as one. Accordingly, will decide if the number is prime or not. Also we need to check for a i value which is equal to square root of the given number."
},
{
"code": null,
"e": 2788,
"s": 2777,
"text": " Live Demo"
},
{
"code": null,
"e": 3287,
"s": 2788,
"text": "def CheckPrime(n):\n # Check for cases of 2 and 3\n if (n <= 1):\n return False\n if (n <= 3):\n return True\n # skip checking middle five numbers in the loop\n if (n % 2 == 0 or n % 3 == 0):\n return False\n i = 5\n while (i * i <= n):\n if (n % i == 0 or n % (i + 2) == 0):\n return False\n i = i + 6\n return True\n# Check for inputs\nif (CheckPrime(31)):\n print(\" true\")\nelse:\n print(\" false\")\nif (CheckPrime(25)):\n print(\" true\")\nelse:\n print(\" false\")"
},
{
"code": null,
"e": 3342,
"s": 3287,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 3353,
"s": 3342,
"text": "true\nfalse"
}
] |
KnockoutJS - Text Binding
|
Text binding causes the associated DOM element to display the text value of the parameter. This is used in text-level DOM elements such as <span> or <em>. The text binding accepts any data type and parses it into String before rendering it.
Syntax
text: <binding-value>
Parameters
KO sets the element's content to a text node with your parameter value. Any previous content will be overwritten.
KO sets the element's content to a text node with your parameter value. Any previous content will be overwritten.
If the parameter is an observable, then the element value is updated whenever the underlying property changes, else it is assigned only for the first time.
If the parameter is an observable, then the element value is updated whenever the underlying property changes, else it is assigned only for the first time.
If anything other than a Number or a String is passed, then KO parses it into a String format equivalent to yourParameter.toString().
If anything other than a Number or a String is passed, then KO parses it into a String format equivalent to yourParameter.toString().
The parameter value can also be JavaScript function or arbitrary JavaScript expression that returns a text value.
The parameter value can also be JavaScript function or arbitrary JavaScript expression that returns a text value.
Example
Let us take a look at the following example which demonstrates the use of text binding.
<!DOCTYPE html>
<head>
<title>KnockoutJS text binding</title>
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type = "text/javascript"></script>
</head>
<body>
<p data-bind = "text: hiThere"></p>
<script>
function AppViewModel() {
this.hiThere = ko.observable("Hi TutorialsPoint !!!");
}
var vm = new AppViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works −
Save the above code in text-bind.htm file.
Save the above code in text-bind.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
Hi TutorialsPoint !!!
Example
Let us take a look at another example in which the text is derived using Computed Observable.
<!DOCTYPE html>
<head>
<title>KnockoutJS text binding</title>
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type = "text/javascript"></script>
</head>
<body>
<p>Your full Name is <span data-bind="text: fullName"></span></p>
<script>
function AppViewModel() {
this.firstName= ko.observable("John");
this.lastName= ko.observable("Smith");
this.fullName = ko.computed( function() {
return this.firstName()+" "+this.lastName();
},this);
}
var vm = new AppViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works −
Save the above code in text-bind-fun.htm file.
Save the above code in text-bind-fun.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
Your full Name is John Smith
The text binding escapes HTML entities, meaning that it is possible to set any String value without getting it injected. For example −
viewModel.message("<strong>Hi TutorialsPoint !!!</strong>");
The above code will just print <strong>Hi TutorialsPoint !!!</strong> on the screen. It will not make the text bold.
Sometimes it is not possible to use HTML element to set the text inside another element. In such cases, container-less syntax can be used which consists of comment tags shown as follows −
The <!--ko--> and <!--/ko--> comment works as start and end markers making it a virtual syntax and binds the data as if it is a real container.
Let us take a look at the following example.
<!DOCTYPE html>
<head>
<title>KnockoutJS container less text binding</title>
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type = "text/javascript"></script>
</head>
<body>
<p data-bind="text: hiThere"></p>
<select data-bind="foreach: items">
<option> <!--ko text: $data --><!--/ko--></option>
</select>
<script>
function AppViewModel() {
this.hiThere = ko.observable("Days of week !!!");
this.items = (['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday',
'Sunday']);
}
var vm = new AppViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works −
Save the above code in text-bind-containerless.htm file.
Save the above code in text-bind-containerless.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
Note, that $data binding context is used here to display the current item from the array.
Note, that $data binding context is used here to display the current item from the array.
Days of week !!!
38 Lectures
2 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2093,
"s": 1852,
"text": "Text binding causes the associated DOM element to display the text value of the parameter. This is used in text-level DOM elements such as <span> or <em>. The text binding accepts any data type and parses it into String before rendering it."
},
{
"code": null,
"e": 2100,
"s": 2093,
"text": "Syntax"
},
{
"code": null,
"e": 2123,
"s": 2100,
"text": "text: <binding-value>\n"
},
{
"code": null,
"e": 2134,
"s": 2123,
"text": "Parameters"
},
{
"code": null,
"e": 2248,
"s": 2134,
"text": "KO sets the element's content to a text node with your parameter value. Any previous content will be overwritten."
},
{
"code": null,
"e": 2362,
"s": 2248,
"text": "KO sets the element's content to a text node with your parameter value. Any previous content will be overwritten."
},
{
"code": null,
"e": 2518,
"s": 2362,
"text": "If the parameter is an observable, then the element value is updated whenever the underlying property changes, else it is assigned only for the first time."
},
{
"code": null,
"e": 2674,
"s": 2518,
"text": "If the parameter is an observable, then the element value is updated whenever the underlying property changes, else it is assigned only for the first time."
},
{
"code": null,
"e": 2809,
"s": 2674,
"text": "If anything other than a Number or a String is passed, then KO parses it into a String format equivalent to yourParameter.toString().\n"
},
{
"code": null,
"e": 2944,
"s": 2809,
"text": "If anything other than a Number or a String is passed, then KO parses it into a String format equivalent to yourParameter.toString().\n"
},
{
"code": null,
"e": 3058,
"s": 2944,
"text": "The parameter value can also be JavaScript function or arbitrary JavaScript expression that returns a text value."
},
{
"code": null,
"e": 3172,
"s": 3058,
"text": "The parameter value can also be JavaScript function or arbitrary JavaScript expression that returns a text value."
},
{
"code": null,
"e": 3180,
"s": 3172,
"text": "Example"
},
{
"code": null,
"e": 3268,
"s": 3180,
"text": "Let us take a look at the following example which demonstrates the use of text binding."
},
{
"code": null,
"e": 3781,
"s": 3268,
"text": "<!DOCTYPE html>\n <head>\n <title>KnockoutJS text binding</title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js\"\n type = \"text/javascript\"></script>\n </head>\n \n <body>\n <p data-bind = \"text: hiThere\"></p>\n\n <script>\n function AppViewModel() {\n this.hiThere = ko.observable(\"Hi TutorialsPoint !!!\");\n }\n \n var vm = new AppViewModel();\n ko.applyBindings(vm);\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 3788,
"s": 3781,
"text": "Output"
},
{
"code": null,
"e": 3858,
"s": 3788,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 3901,
"s": 3858,
"text": "Save the above code in text-bind.htm file."
},
{
"code": null,
"e": 3944,
"s": 3901,
"text": "Save the above code in text-bind.htm file."
},
{
"code": null,
"e": 3978,
"s": 3944,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 4012,
"s": 3978,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 4034,
"s": 4012,
"text": "Hi TutorialsPoint !!!"
},
{
"code": null,
"e": 4042,
"s": 4034,
"text": "Example"
},
{
"code": null,
"e": 4136,
"s": 4042,
"text": "Let us take a look at another example in which the text is derived using Computed Observable."
},
{
"code": null,
"e": 4848,
"s": 4136,
"text": "<!DOCTYPE html>\n <head>\n <title>KnockoutJS text binding</title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js\" \n type = \"text/javascript\"></script>\n </head>\n \n <body>\n <p>Your full Name is <span data-bind=\"text: fullName\"></span></p>\n\n <script>\n function AppViewModel() {\n this.firstName= ko.observable(\"John\");\n this.lastName= ko.observable(\"Smith\");\n\n this.fullName = ko.computed( function() {\n return this.firstName()+\" \"+this.lastName();\n },this);\n }\n \n var vm = new AppViewModel();\n ko.applyBindings(vm);\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 4855,
"s": 4848,
"text": "Output"
},
{
"code": null,
"e": 4925,
"s": 4855,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 4972,
"s": 4925,
"text": "Save the above code in text-bind-fun.htm file."
},
{
"code": null,
"e": 5019,
"s": 4972,
"text": "Save the above code in text-bind-fun.htm file."
},
{
"code": null,
"e": 5053,
"s": 5019,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 5087,
"s": 5053,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 5116,
"s": 5087,
"text": "Your full Name is John Smith"
},
{
"code": null,
"e": 5251,
"s": 5116,
"text": "The text binding escapes HTML entities, meaning that it is possible to set any String value without getting it injected. For example −"
},
{
"code": null,
"e": 5312,
"s": 5251,
"text": "viewModel.message(\"<strong>Hi TutorialsPoint !!!</strong>\");"
},
{
"code": null,
"e": 5429,
"s": 5312,
"text": "The above code will just print <strong>Hi TutorialsPoint !!!</strong> on the screen. It will not make the text bold."
},
{
"code": null,
"e": 5617,
"s": 5429,
"text": "Sometimes it is not possible to use HTML element to set the text inside another element. In such cases, container-less syntax can be used which consists of comment tags shown as follows −"
},
{
"code": null,
"e": 5761,
"s": 5617,
"text": "The <!--ko--> and <!--/ko--> comment works as start and end markers making it a virtual syntax and binds the data as if it is a real container."
},
{
"code": null,
"e": 5806,
"s": 5761,
"text": "Let us take a look at the following example."
},
{
"code": null,
"e": 6562,
"s": 5806,
"text": "<!DOCTYPE html>\n <head>\n <title>KnockoutJS container less text binding</title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js\"\n type = \"text/javascript\"></script>\n </head>\n \n <body>\n <p data-bind=\"text: hiThere\"></p>\n <select data-bind=\"foreach: items\">\n <option> <!--ko text: $data --><!--/ko--></option>\n </select>\n\n <script>\n function AppViewModel() {\n this.hiThere = ko.observable(\"Days of week !!!\");\n this.items = (['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday',\n 'Sunday']);\n }\n \n var vm = new AppViewModel();\n ko.applyBindings(vm);\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 6569,
"s": 6562,
"text": "Output"
},
{
"code": null,
"e": 6639,
"s": 6569,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 6696,
"s": 6639,
"text": "Save the above code in text-bind-containerless.htm file."
},
{
"code": null,
"e": 6753,
"s": 6696,
"text": "Save the above code in text-bind-containerless.htm file."
},
{
"code": null,
"e": 6787,
"s": 6753,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 6821,
"s": 6787,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 6911,
"s": 6821,
"text": "Note, that $data binding context is used here to display the current item from the array."
},
{
"code": null,
"e": 7001,
"s": 6911,
"text": "Note, that $data binding context is used here to display the current item from the array."
},
{
"code": null,
"e": 7018,
"s": 7001,
"text": "Days of week !!!"
},
{
"code": null,
"e": 7051,
"s": 7018,
"text": "\n 38 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7071,
"s": 7051,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 7078,
"s": 7071,
"text": " Print"
},
{
"code": null,
"e": 7089,
"s": 7078,
"text": " Add Notes"
}
] |
Find maximum average subarray of k length - GeeksforGeeks
|
12 Apr, 2022
Given an array with positive and negative numbers, find the maximum average subarray of given length.
Example:
Input: arr[] = {1, 12, -5, -6, 50, 3}, k = 4
Output: Maximum average subarray of length 4 begins
at index 1.
Maximum average is (12 - 5 - 6 + 50)/4 = 51/4
A Simple Solution is to run two loops. The outer loop picks starting point, the inner loop goes till length ‘k’ from the starting point and computes average of elements. Time complexity of this solution is O(n*k).
A Better Solution is to create an auxiliary array of size n. Store cumulative sum of elements in this array. Let the array be csum[]. csum[i] stores sum of elements from arr[0] to arr[i]. Once we have csum[] array with us, we can compute sum between two indexes in O(1) time. Below is the implementation of this idea. One observation is, a subarray of given length has maximum average if it has maximum sum. So we can avoid floating point arithmetic by just comparing sum.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find maximum average subarray// of given length.#include<bits/stdc++.h>using namespace std; // Returns beginning index of maximum average// subarray of length 'k'int findMaxAverage(int arr[], int n, int k){ // Check if 'k' is valid if (k > n) return -1; // Create and fill array to store cumulative // sum. csum[i] stores sum of arr[0] to arr[i] int *csum = new int[n]; csum[0] = arr[0]; for (int i=1; i<n; i++) csum[i] = csum[i-1] + arr[i]; // Initialize max_sm as sum of first subarray int max_sum = csum[k-1], max_end = k-1; // Find sum of other subarrays and update // max_sum if required. for (int i=k; i<n; i++) { int curr_sum = csum[i] - csum[i-k]; if (curr_sum > max_sum) { max_sum = curr_sum; max_end = i; } } delete [] csum; // To avoid memory leak // Return starting index return max_end - k + 1;} // Driver programint main(){ int arr[] = {1, 12, -5, -6, 50, 3}; int k = 4; int n = sizeof(arr)/sizeof(arr[0]); cout << "The maximum average subarray of " "length "<< k << " begins at index " << findMaxAverage(arr, n, k); return 0;}
// Java program to find maximum average// subarray of given length.import java .io.*; class GFG { // Returns beginning index // of maximum average // subarray of length 'k' static int findMaxAverage(int []arr, int n, int k) { // Check if 'k' is valid if (k > n) return -1; // Create and fill array // to store cumulative // sum. csum[i] stores // sum of arr[0] to arr[i] int []csum = new int[n]; csum[0] = arr[0]; for (int i = 1; i < n; i++) csum[i] = csum[i - 1] + arr[i]; // Initialize max_sm as // sum of first subarray int max_sum = csum[k - 1], max_end = k - 1; // Find sum of other // subarrays and update // max_sum if required. for (int i = k; i < n; i++) { int curr_sum = csum[i] - csum[i - k]; if (curr_sum > max_sum) { max_sum = curr_sum; max_end = i; } } // To avoid memory leak //delete [] csum; // Return starting index return max_end - k + 1; } // Driver Code static public void main (String[] args) { int []arr = {1, 12, -5, -6, 50, 3}; int k = 4; int n = arr.length; System.out.println("The maximum " + "average subarray of length " + k + " begins at index " + findMaxAverage(arr, n, k)); }} // This code is contributed by anuj_67.
# Python program to find maximum average subarray# of given length. # Returns beginning index of maximum average# subarray of length 'k'def findMaxAverage(arr, n, k): # Check if 'k' is valid if k > n: return -1 # Create and fill array to store cumulative # sum. csum[i] stores sum of arr[0] to arr[i] csum = [0]*n csum[0] = arr[0] for i in range(1, n): csum[i] = csum[i-1] + arr[i]; # Initialize max_sm as sum of first subarray max_sum = csum[k-1] max_end = k-1 # Find sum of other subarrays and update # max_sum if required. for i in range(k, n): curr_sum = csum[i] - csum[i-k] if curr_sum > max_sum: max_sum = curr_sum max_end = i # Return starting index return max_end - k + 1 # Driver programarr = [1, 12, -5, -6, 50, 3]k = 4n = len(arr)print("The maximum average subarray of length",k,"begins at index",findMaxAverage(arr, n, k)) #This code is contributed by#Smitha Dinesh Semwal
// C# program to find maximum average// subarray of given length.using System;class GFG{ // Returns beginning index// of maximum average// subarray of length 'k'static int findMaxAverage(int []arr, int n, int k){ // Check if 'k' is valid if (k > n) return -1; // Create and fill array // to store cumulative // sum. csum[i] stores // sum of arr[0] to arr[i] int []csum = new int[n]; csum[0] = arr[0]; for (int i = 1; i < n; i++) csum[i] = csum[i - 1] + arr[i]; // Initialize max_sm as // sum of first subarray int max_sum = csum[k - 1], max_end = k - 1; // Find sum of other // subarrays and update // max_sum if required. for (int i = k; i < n; i++) { int curr_sum = csum[i] - csum[i - k]; if (curr_sum > max_sum) { max_sum = curr_sum; max_end = i; } } // To avoid memory leak //delete [] csum; // Return starting index return max_end - k + 1;} // Driver Code static public void Main () { int []arr = {1, 12, -5, -6, 50, 3}; int k = 4; int n = arr.Length; Console.WriteLine("The maximum average subarray of "+ "length "+ k + " begins at index " + findMaxAverage(arr, n, k)); }} // This code is contributed by anuj_67.
<?php// PHP program to find maximum// average subarray of given length. // Returns beginning index of// maximum average subarray of// length 'k'function findMaxAverage($arr, $n, $k){ // Check if 'k' is valid if ($k > $n) return -1; // Create and fill array to // store cumulative sum. // csum[i] stores sum of // arr[0] to arr[i] $csum = array(); $csum[0] = $arr[0]; for($i = 1; $i < $n; $i++) $csum[$i] = $csum[$i - 1] + $arr[$i]; // Initialize max_sm as sum // of first subarray $max_sum = $csum[$k - 1]; $max_end = $k - 1; // Find sum of other subarrays // and update max_sum if required. for($i = $k; $i < $n; $i++) { $curr_sum = $csum[$i] - $csum[$i - $k]; if ($curr_sum > $max_sum) { $max_sum = $curr_sum; $max_end = $i; } } // Return starting index return $max_end - $k + 1;} // Driver Code $arr = array(1, 12, -5, -6, 50, 3); $k = 4; $n = count($arr); echo "The maximum average subarray of " ,"length ", $k , " begins at index " , findMaxAverage($arr, $n, $k); // This code is contributed by anuj_67.?>
<script> // Javascript program to find maximum average// subarray of given length. // Returns beginning index// of maximum average// subarray of length 'k'function findMaxAverage(arr, n, k){ // Check if 'k' is valid if (k > n) return -1; // Create and fill array // to store cumulative // sum. csum[i] stores // sum of arr[0] to arr[i] let csum = new Array(n); csum[0] = arr[0]; for(let i = 1; i < n; i++) csum[i] = csum[i - 1] + arr[i]; // Initialize max_sm as // sum of first subarray let max_sum = csum[k - 1], max_end = k - 1; // Find sum of other // subarrays and update // max_sum if required. for(let i = k; i < n; i++) { let curr_sum = csum[i] - csum[i - k]; if (curr_sum > max_sum) { max_sum = curr_sum; max_end = i; } } // To avoid memory leak //delete [] csum; // Return starting index return max_end - k + 1;} // Driver codelet arr = [ 1, 12, -5, -6, 50, 3 ];let k = 4;let n = arr.length;document.write("The maximum average subarray of "+ "length "+ k + " begins at index " + findMaxAverage(arr, n, k)); // This code is contributed by divyeshrabadiya07 </script>
Output:
The maximum average subarray of length 4 begins at index 1
Time Complexity of above solution is O(n), but it requires O(n) auxiliary space. We can avoid need of extra space by using below Efficient Method. 1) Compute sum of first ‘k’ elements, i.e., elements arr[0..k-1]. Let this sum be ‘sum’. Initialize ‘max_sum’ as ‘sum’ 2) Do following for every element arr[i] where i varies from ‘k’ to ‘n-1’ .......a) Remove arr[i-k] from sum and add arr[i], i.e., do sum += arr[i] – arr[i-k] .......b) If new sum becomes more than max_sum so far, update max_sum. 3) Return ‘max_sum’
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find maximum average subarray// of given length.#include<bits/stdc++.h>using namespace std; // Returns beginning index of maximum average// subarray of length 'k'int findMaxAverage(int arr[], int n, int k){ // Check if 'k' is valid if (k > n) return -1; // Compute sum of first 'k' elements int sum = arr[0]; for (int i=1; i<k; i++) sum += arr[i]; int max_sum = sum, max_end = k-1; // Compute sum of remaining subarrays for (int i=k; i<n; i++) { sum = sum + arr[i] - arr[i-k]; if (sum > max_sum) { max_sum = sum; max_end = i; } } // Return starting index return max_end - k + 1;} // Driver programint main(){ int arr[] = {1, 12, -5, -6, 50, 3}; int k = 4; int n = sizeof(arr)/sizeof(arr[0]); cout << "The maximum average subarray of " "length "<< k << " begins at index " << findMaxAverage(arr, n, k); return 0;}
// Java program to find maximum average subarray// of given length. import java.io.*; class GFG { // Returns beginning index of maximum average // subarray of length 'k' static int findMaxAverage(int arr[], int n, int k) { // Check if 'k' is valid if (k > n) return -1; // Compute sum of first 'k' elements int sum = arr[0]; for (int i = 1; i < k; i++) sum += arr[i]; int max_sum = sum, max_end = k-1; // Compute sum of remaining subarrays for (int i = k; i < n; i++) { sum = sum + arr[i] - arr[i-k]; if (sum > max_sum) { max_sum = sum; max_end = i; } } // Return starting index return max_end - k + 1; } // Driver program public static void main (String[] args) { int arr[] = {1, 12, -5, -6, 50, 3}; int k = 4; int n = arr.length; System.out.println( "The maximum average" + " subarray of length " + k + " begins at index " + findMaxAverage(arr, n, k)); }} // This code is contributed by anuj_67.
# Python 3 program to find maximum# average subarray of given length. # Returns beginning index of maximum# average subarray of length 'k'def findMaxAverage(arr, n, k): # Check if 'k' is valid if (k > n): return -1 # Compute sum of first 'k' elements sum = arr[0] for i in range(1, k): sum += arr[i] max_sum = sum max_end = k - 1 # Compute sum of remaining subarrays for i in range(k, n): sum = sum + arr[i] - arr[i - k] if (sum > max_sum): max_sum = sum max_end = i # Return starting index return max_end - k + 1 # Driver programarr = [1, 12, -5, -6, 50, 3]k = 4n = len(arr) print("The maximum average subarray of length", k, "begins at index", findMaxAverage(arr, n, k)) # This code is contributed by# Smitha Dinesh Semwal
// C# program to find maximum average// subarray of given length.using System; class GFG { // Returns beginning index of // maximum average subarray of // length 'k' static int findMaxAverage(int []arr, int n, int k) { // Check if 'k' is valid if (k > n) return -1; // Compute sum of first 'k' // elements int sum = arr[0]; for (int i = 1; i < k; i++) sum += arr[i]; int max_sum = sum; int max_end = k-1; // Compute sum of remaining // subarrays for (int i = k; i < n; i++) { sum = sum + arr[i] - arr[i-k]; if (sum > max_sum) { max_sum = sum; max_end = i; } } // Return starting index return max_end - k + 1; } // Driver program public static void Main () { int []arr = {1, 12, -5, -6, 50, 3}; int k = 4; int n = arr.Length; Console.WriteLine( "The maximum " + "average subarray of length " + k + " begins at index " + findMaxAverage(arr, n, k)); }} // This code is contributed by anuj_67.
<?php// PHP program to find maximum// average subarray of given length. // Returns beginning index// of maximum average// subarray of length 'k'function findMaxAverage($arr, $n, $k){ // Check if 'k' is valid if ($k > $n) return -1; // Compute sum of first // 'k' elements $sum = $arr[0]; for($i = 1; $i < $k; $i++) $sum += $arr[$i]; $max_sum = $sum; $max_end = $k-1; // Compute sum of // remaining subarrays for($i = $k; $i < $n; $i++) { $sum = $sum + $arr[$i] - $arr[$i - $k]; if ($sum > $max_sum) { $max_sum = $sum; $max_end = $i; } } // Return starting index return $max_end - $k + 1;} // Driver Code $arr = array(1, 12, -5, -6, 50, 3); $k = 4; $n = count($arr); echo "The maximum average subarray of ", "length ", $k , " begins at index " , findMaxAverage($arr, $n, $k); // This code is contributed by anuj_67.?>
<script> // Javascript program to find maximum average // subarray of given length. // Returns beginning index of // maximum average subarray of // length 'k' function findMaxAverage(arr, n, k) { // Check if 'k' is valid if (k > n) return -1; // Compute sum of first 'k' // elements let sum = arr[0]; for (let i = 1; i < k; i++) sum += arr[i]; let max_sum = sum; let max_end = k-1; // Compute sum of remaining // subarrays for (let i = k; i < n; i++) { sum = sum + arr[i] - arr[i-k]; if (sum > max_sum) { max_sum = sum; max_end = i; } } // Return starting index return max_end - k + 1; } let arr = [1, 12, -5, -6, 50, 3]; let k = 4; let n = arr.length; document.write( "The maximum " + "average subarray of length " + k + " begins at index " + findMaxAverage(arr, n, k)); // This code is contributed by suresh07. </script>
Output:
The maximum average subarray of length 4 begins at index 1
Time complexity of this method is also O(n), but it requires constant extra space.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
vt_m
divyeshrabadiya07
suresh07
subhammahanty235
Amazon
Arrays
Amazon
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Arrays in Java
Arrays in C/C++
Program for array rotation
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Largest Sum Contiguous Subarray
Write a program to reverse an array or string
Introduction to Arrays
Multidimensional Arrays in Java
|
[
{
"code": null,
"e": 40883,
"s": 40855,
"text": "\n12 Apr, 2022"
},
{
"code": null,
"e": 40985,
"s": 40883,
"text": "Given an array with positive and negative numbers, find the maximum average subarray of given length."
},
{
"code": null,
"e": 40995,
"s": 40985,
"text": "Example: "
},
{
"code": null,
"e": 41159,
"s": 40995,
"text": "Input: arr[] = {1, 12, -5, -6, 50, 3}, k = 4\nOutput: Maximum average subarray of length 4 begins\n at index 1.\nMaximum average is (12 - 5 - 6 + 50)/4 = 51/4"
},
{
"code": null,
"e": 41373,
"s": 41159,
"text": "A Simple Solution is to run two loops. The outer loop picks starting point, the inner loop goes till length ‘k’ from the starting point and computes average of elements. Time complexity of this solution is O(n*k)."
},
{
"code": null,
"e": 41846,
"s": 41373,
"text": "A Better Solution is to create an auxiliary array of size n. Store cumulative sum of elements in this array. Let the array be csum[]. csum[i] stores sum of elements from arr[0] to arr[i]. Once we have csum[] array with us, we can compute sum between two indexes in O(1) time. Below is the implementation of this idea. One observation is, a subarray of given length has maximum average if it has maximum sum. So we can avoid floating point arithmetic by just comparing sum."
},
{
"code": null,
"e": 41850,
"s": 41846,
"text": "C++"
},
{
"code": null,
"e": 41855,
"s": 41850,
"text": "Java"
},
{
"code": null,
"e": 41863,
"s": 41855,
"text": "Python3"
},
{
"code": null,
"e": 41866,
"s": 41863,
"text": "C#"
},
{
"code": null,
"e": 41870,
"s": 41866,
"text": "PHP"
},
{
"code": null,
"e": 41881,
"s": 41870,
"text": "Javascript"
},
{
"code": "// C++ program to find maximum average subarray// of given length.#include<bits/stdc++.h>using namespace std; // Returns beginning index of maximum average// subarray of length 'k'int findMaxAverage(int arr[], int n, int k){ // Check if 'k' is valid if (k > n) return -1; // Create and fill array to store cumulative // sum. csum[i] stores sum of arr[0] to arr[i] int *csum = new int[n]; csum[0] = arr[0]; for (int i=1; i<n; i++) csum[i] = csum[i-1] + arr[i]; // Initialize max_sm as sum of first subarray int max_sum = csum[k-1], max_end = k-1; // Find sum of other subarrays and update // max_sum if required. for (int i=k; i<n; i++) { int curr_sum = csum[i] - csum[i-k]; if (curr_sum > max_sum) { max_sum = curr_sum; max_end = i; } } delete [] csum; // To avoid memory leak // Return starting index return max_end - k + 1;} // Driver programint main(){ int arr[] = {1, 12, -5, -6, 50, 3}; int k = 4; int n = sizeof(arr)/sizeof(arr[0]); cout << \"The maximum average subarray of \" \"length \"<< k << \" begins at index \" << findMaxAverage(arr, n, k); return 0;}",
"e": 43091,
"s": 41881,
"text": null
},
{
"code": "// Java program to find maximum average// subarray of given length.import java .io.*; class GFG { // Returns beginning index // of maximum average // subarray of length 'k' static int findMaxAverage(int []arr, int n, int k) { // Check if 'k' is valid if (k > n) return -1; // Create and fill array // to store cumulative // sum. csum[i] stores // sum of arr[0] to arr[i] int []csum = new int[n]; csum[0] = arr[0]; for (int i = 1; i < n; i++) csum[i] = csum[i - 1] + arr[i]; // Initialize max_sm as // sum of first subarray int max_sum = csum[k - 1], max_end = k - 1; // Find sum of other // subarrays and update // max_sum if required. for (int i = k; i < n; i++) { int curr_sum = csum[i] - csum[i - k]; if (curr_sum > max_sum) { max_sum = curr_sum; max_end = i; } } // To avoid memory leak //delete [] csum; // Return starting index return max_end - k + 1; } // Driver Code static public void main (String[] args) { int []arr = {1, 12, -5, -6, 50, 3}; int k = 4; int n = arr.length; System.out.println(\"The maximum \" + \"average subarray of length \" + k + \" begins at index \" + findMaxAverage(arr, n, k)); }} // This code is contributed by anuj_67.",
"e": 44701,
"s": 43091,
"text": null
},
{
"code": "# Python program to find maximum average subarray# of given length. # Returns beginning index of maximum average# subarray of length 'k'def findMaxAverage(arr, n, k): # Check if 'k' is valid if k > n: return -1 # Create and fill array to store cumulative # sum. csum[i] stores sum of arr[0] to arr[i] csum = [0]*n csum[0] = arr[0] for i in range(1, n): csum[i] = csum[i-1] + arr[i]; # Initialize max_sm as sum of first subarray max_sum = csum[k-1] max_end = k-1 # Find sum of other subarrays and update # max_sum if required. for i in range(k, n): curr_sum = csum[i] - csum[i-k] if curr_sum > max_sum: max_sum = curr_sum max_end = i # Return starting index return max_end - k + 1 # Driver programarr = [1, 12, -5, -6, 50, 3]k = 4n = len(arr)print(\"The maximum average subarray of length\",k,\"begins at index\",findMaxAverage(arr, n, k)) #This code is contributed by#Smitha Dinesh Semwal",
"e": 45707,
"s": 44701,
"text": null
},
{
"code": "// C# program to find maximum average// subarray of given length.using System;class GFG{ // Returns beginning index// of maximum average// subarray of length 'k'static int findMaxAverage(int []arr, int n, int k){ // Check if 'k' is valid if (k > n) return -1; // Create and fill array // to store cumulative // sum. csum[i] stores // sum of arr[0] to arr[i] int []csum = new int[n]; csum[0] = arr[0]; for (int i = 1; i < n; i++) csum[i] = csum[i - 1] + arr[i]; // Initialize max_sm as // sum of first subarray int max_sum = csum[k - 1], max_end = k - 1; // Find sum of other // subarrays and update // max_sum if required. for (int i = k; i < n; i++) { int curr_sum = csum[i] - csum[i - k]; if (curr_sum > max_sum) { max_sum = curr_sum; max_end = i; } } // To avoid memory leak //delete [] csum; // Return starting index return max_end - k + 1;} // Driver Code static public void Main () { int []arr = {1, 12, -5, -6, 50, 3}; int k = 4; int n = arr.Length; Console.WriteLine(\"The maximum average subarray of \"+ \"length \"+ k + \" begins at index \" + findMaxAverage(arr, n, k)); }} // This code is contributed by anuj_67.",
"e": 47127,
"s": 45707,
"text": null
},
{
"code": "<?php// PHP program to find maximum// average subarray of given length. // Returns beginning index of// maximum average subarray of// length 'k'function findMaxAverage($arr, $n, $k){ // Check if 'k' is valid if ($k > $n) return -1; // Create and fill array to // store cumulative sum. // csum[i] stores sum of // arr[0] to arr[i] $csum = array(); $csum[0] = $arr[0]; for($i = 1; $i < $n; $i++) $csum[$i] = $csum[$i - 1] + $arr[$i]; // Initialize max_sm as sum // of first subarray $max_sum = $csum[$k - 1]; $max_end = $k - 1; // Find sum of other subarrays // and update max_sum if required. for($i = $k; $i < $n; $i++) { $curr_sum = $csum[$i] - $csum[$i - $k]; if ($curr_sum > $max_sum) { $max_sum = $curr_sum; $max_end = $i; } } // Return starting index return $max_end - $k + 1;} // Driver Code $arr = array(1, 12, -5, -6, 50, 3); $k = 4; $n = count($arr); echo \"The maximum average subarray of \" ,\"length \", $k , \" begins at index \" , findMaxAverage($arr, $n, $k); // This code is contributed by anuj_67.?>",
"e": 48339,
"s": 47127,
"text": null
},
{
"code": "<script> // Javascript program to find maximum average// subarray of given length. // Returns beginning index// of maximum average// subarray of length 'k'function findMaxAverage(arr, n, k){ // Check if 'k' is valid if (k > n) return -1; // Create and fill array // to store cumulative // sum. csum[i] stores // sum of arr[0] to arr[i] let csum = new Array(n); csum[0] = arr[0]; for(let i = 1; i < n; i++) csum[i] = csum[i - 1] + arr[i]; // Initialize max_sm as // sum of first subarray let max_sum = csum[k - 1], max_end = k - 1; // Find sum of other // subarrays and update // max_sum if required. for(let i = k; i < n; i++) { let curr_sum = csum[i] - csum[i - k]; if (curr_sum > max_sum) { max_sum = curr_sum; max_end = i; } } // To avoid memory leak //delete [] csum; // Return starting index return max_end - k + 1;} // Driver codelet arr = [ 1, 12, -5, -6, 50, 3 ];let k = 4;let n = arr.length;document.write(\"The maximum average subarray of \"+ \"length \"+ k + \" begins at index \" + findMaxAverage(arr, n, k)); // This code is contributed by divyeshrabadiya07 </script>",
"e": 49605,
"s": 48339,
"text": null
},
{
"code": null,
"e": 49614,
"s": 49605,
"text": "Output: "
},
{
"code": null,
"e": 49673,
"s": 49614,
"text": "The maximum average subarray of length 4 begins at index 1"
},
{
"code": null,
"e": 50189,
"s": 49673,
"text": "Time Complexity of above solution is O(n), but it requires O(n) auxiliary space. We can avoid need of extra space by using below Efficient Method. 1) Compute sum of first ‘k’ elements, i.e., elements arr[0..k-1]. Let this sum be ‘sum’. Initialize ‘max_sum’ as ‘sum’ 2) Do following for every element arr[i] where i varies from ‘k’ to ‘n-1’ .......a) Remove arr[i-k] from sum and add arr[i], i.e., do sum += arr[i] – arr[i-k] .......b) If new sum becomes more than max_sum so far, update max_sum. 3) Return ‘max_sum’"
},
{
"code": null,
"e": 50193,
"s": 50189,
"text": "C++"
},
{
"code": null,
"e": 50198,
"s": 50193,
"text": "Java"
},
{
"code": null,
"e": 50206,
"s": 50198,
"text": "Python3"
},
{
"code": null,
"e": 50209,
"s": 50206,
"text": "C#"
},
{
"code": null,
"e": 50213,
"s": 50209,
"text": "PHP"
},
{
"code": null,
"e": 50224,
"s": 50213,
"text": "Javascript"
},
{
"code": "// C++ program to find maximum average subarray// of given length.#include<bits/stdc++.h>using namespace std; // Returns beginning index of maximum average// subarray of length 'k'int findMaxAverage(int arr[], int n, int k){ // Check if 'k' is valid if (k > n) return -1; // Compute sum of first 'k' elements int sum = arr[0]; for (int i=1; i<k; i++) sum += arr[i]; int max_sum = sum, max_end = k-1; // Compute sum of remaining subarrays for (int i=k; i<n; i++) { sum = sum + arr[i] - arr[i-k]; if (sum > max_sum) { max_sum = sum; max_end = i; } } // Return starting index return max_end - k + 1;} // Driver programint main(){ int arr[] = {1, 12, -5, -6, 50, 3}; int k = 4; int n = sizeof(arr)/sizeof(arr[0]); cout << \"The maximum average subarray of \" \"length \"<< k << \" begins at index \" << findMaxAverage(arr, n, k); return 0;}",
"e": 51190,
"s": 50224,
"text": null
},
{
"code": "// Java program to find maximum average subarray// of given length. import java.io.*; class GFG { // Returns beginning index of maximum average // subarray of length 'k' static int findMaxAverage(int arr[], int n, int k) { // Check if 'k' is valid if (k > n) return -1; // Compute sum of first 'k' elements int sum = arr[0]; for (int i = 1; i < k; i++) sum += arr[i]; int max_sum = sum, max_end = k-1; // Compute sum of remaining subarrays for (int i = k; i < n; i++) { sum = sum + arr[i] - arr[i-k]; if (sum > max_sum) { max_sum = sum; max_end = i; } } // Return starting index return max_end - k + 1; } // Driver program public static void main (String[] args) { int arr[] = {1, 12, -5, -6, 50, 3}; int k = 4; int n = arr.length; System.out.println( \"The maximum average\" + \" subarray of length \" + k + \" begins at index \" + findMaxAverage(arr, n, k)); }} // This code is contributed by anuj_67.",
"e": 52413,
"s": 51190,
"text": null
},
{
"code": "# Python 3 program to find maximum# average subarray of given length. # Returns beginning index of maximum# average subarray of length 'k'def findMaxAverage(arr, n, k): # Check if 'k' is valid if (k > n): return -1 # Compute sum of first 'k' elements sum = arr[0] for i in range(1, k): sum += arr[i] max_sum = sum max_end = k - 1 # Compute sum of remaining subarrays for i in range(k, n): sum = sum + arr[i] - arr[i - k] if (sum > max_sum): max_sum = sum max_end = i # Return starting index return max_end - k + 1 # Driver programarr = [1, 12, -5, -6, 50, 3]k = 4n = len(arr) print(\"The maximum average subarray of length\", k, \"begins at index\", findMaxAverage(arr, n, k)) # This code is contributed by# Smitha Dinesh Semwal",
"e": 53316,
"s": 52413,
"text": null
},
{
"code": "// C# program to find maximum average// subarray of given length.using System; class GFG { // Returns beginning index of // maximum average subarray of // length 'k' static int findMaxAverage(int []arr, int n, int k) { // Check if 'k' is valid if (k > n) return -1; // Compute sum of first 'k' // elements int sum = arr[0]; for (int i = 1; i < k; i++) sum += arr[i]; int max_sum = sum; int max_end = k-1; // Compute sum of remaining // subarrays for (int i = k; i < n; i++) { sum = sum + arr[i] - arr[i-k]; if (sum > max_sum) { max_sum = sum; max_end = i; } } // Return starting index return max_end - k + 1; } // Driver program public static void Main () { int []arr = {1, 12, -5, -6, 50, 3}; int k = 4; int n = arr.Length; Console.WriteLine( \"The maximum \" + \"average subarray of length \" + k + \" begins at index \" + findMaxAverage(arr, n, k)); }} // This code is contributed by anuj_67.",
"e": 54557,
"s": 53316,
"text": null
},
{
"code": "<?php// PHP program to find maximum// average subarray of given length. // Returns beginning index// of maximum average// subarray of length 'k'function findMaxAverage($arr, $n, $k){ // Check if 'k' is valid if ($k > $n) return -1; // Compute sum of first // 'k' elements $sum = $arr[0]; for($i = 1; $i < $k; $i++) $sum += $arr[$i]; $max_sum = $sum; $max_end = $k-1; // Compute sum of // remaining subarrays for($i = $k; $i < $n; $i++) { $sum = $sum + $arr[$i] - $arr[$i - $k]; if ($sum > $max_sum) { $max_sum = $sum; $max_end = $i; } } // Return starting index return $max_end - $k + 1;} // Driver Code $arr = array(1, 12, -5, -6, 50, 3); $k = 4; $n = count($arr); echo \"The maximum average subarray of \", \"length \", $k , \" begins at index \" , findMaxAverage($arr, $n, $k); // This code is contributed by anuj_67.?>",
"e": 55547,
"s": 54557,
"text": null
},
{
"code": "<script> // Javascript program to find maximum average // subarray of given length. // Returns beginning index of // maximum average subarray of // length 'k' function findMaxAverage(arr, n, k) { // Check if 'k' is valid if (k > n) return -1; // Compute sum of first 'k' // elements let sum = arr[0]; for (let i = 1; i < k; i++) sum += arr[i]; let max_sum = sum; let max_end = k-1; // Compute sum of remaining // subarrays for (let i = k; i < n; i++) { sum = sum + arr[i] - arr[i-k]; if (sum > max_sum) { max_sum = sum; max_end = i; } } // Return starting index return max_end - k + 1; } let arr = [1, 12, -5, -6, 50, 3]; let k = 4; let n = arr.length; document.write( \"The maximum \" + \"average subarray of length \" + k + \" begins at index \" + findMaxAverage(arr, n, k)); // This code is contributed by suresh07. </script>",
"e": 56756,
"s": 55547,
"text": null
},
{
"code": null,
"e": 56765,
"s": 56756,
"text": "Output: "
},
{
"code": null,
"e": 56824,
"s": 56765,
"text": "The maximum average subarray of length 4 begins at index 1"
},
{
"code": null,
"e": 57031,
"s": 56824,
"text": "Time complexity of this method is also O(n), but it requires constant extra space.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 57036,
"s": 57031,
"text": "vt_m"
},
{
"code": null,
"e": 57054,
"s": 57036,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 57063,
"s": 57054,
"text": "suresh07"
},
{
"code": null,
"e": 57080,
"s": 57063,
"text": "subhammahanty235"
},
{
"code": null,
"e": 57087,
"s": 57080,
"text": "Amazon"
},
{
"code": null,
"e": 57094,
"s": 57087,
"text": "Arrays"
},
{
"code": null,
"e": 57101,
"s": 57094,
"text": "Amazon"
},
{
"code": null,
"e": 57108,
"s": 57101,
"text": "Arrays"
},
{
"code": null,
"e": 57206,
"s": 57108,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 57215,
"s": 57206,
"text": "Comments"
},
{
"code": null,
"e": 57228,
"s": 57215,
"text": "Old Comments"
},
{
"code": null,
"e": 57243,
"s": 57228,
"text": "Arrays in Java"
},
{
"code": null,
"e": 57259,
"s": 57243,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 57286,
"s": 57259,
"text": "Program for array rotation"
},
{
"code": null,
"e": 57334,
"s": 57286,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 57378,
"s": 57334,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 57410,
"s": 57378,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 57456,
"s": 57410,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 57479,
"s": 57456,
"text": "Introduction to Arrays"
}
] |
BFS using STL for competitive coding - GeeksforGeeks
|
15 Nov, 2021
A STL based simple implementation of BFS using queue and vector in STL. The adjacency list is represented using vectors of vector.
In BFS, we start with a node.
1) Create a queue and enqueue source into it.
Mark source as visited.
2) While queue is not empty, do following
a) Dequeue a vertex from queue. Let this
be f.
b) Print f
c) Enqueue all not yet visited adjacent
of f and mark them visited.
Below is an example BFS starting from source vertex 1. Note that there can be multiple BFSs possible for a graph (even from a particular vertex).
For more details of BFS, refer this post . The code here is simplified such that it could be used in competitive coding.
CPP
// A Quick implementation of BFS using// vectors and queue#include <bits/stdc++.h>#define pb push_back using namespace std; vector<bool> v;vector<vector<int> > g; void edge(int a, int b){ g[a].pb(b); // for undirected graph add this line // g[b].pb(a);} void bfs(int u){ queue<int> q; q.push(u); v[u] = true; while (!q.empty()) { int f = q.front(); q.pop(); cout << f << " "; // Enqueue all adjacent of f and mark them visited for (auto i = g[f].begin(); i != g[f].end(); i++) { if (!v[*i]) { q.push(*i); v[*i] = true; } } }} // Driver codeint main(){ int n, e; cin >> n >> e; v.assign(n, false); g.assign(n, vector<int>()); int a, b; for (int i = 0; i < e; i++) { cin >> a >> b; edge(a, b); } for (int i = 0; i < n; i++) { if (!v[i]) bfs(i); } return 0;}
Input:
8 10
0 1
0 2
0 3
0 4
1 5
2 5
3 6
4 6
5 7
6 7
Output:
0 1 2 3 4 5 6 7
This article is contributed by Nikhil Mahendran. 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.
chhabradhanvi
BFS
cpp-queue
cpp-vector
Competitive Programming
Graph
Graph
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Bits manipulation (Important tactics)
Formatted output in Java
Algorithm Library | C++ Magicians STL Algorithm
Use of FLAG in programming
Setting up Sublime Text for C++ Competitive Programming Environment
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Graph and its representations
|
[
{
"code": null,
"e": 24923,
"s": 24895,
"text": "\n15 Nov, 2021"
},
{
"code": null,
"e": 25056,
"s": 24923,
"text": "A STL based simple implementation of BFS using queue and vector in STL. The adjacency list is represented using vectors of vector. "
},
{
"code": null,
"e": 25355,
"s": 25056,
"text": "In BFS, we start with a node.\n1) Create a queue and enqueue source into it. \n Mark source as visited.\n2) While queue is not empty, do following\n a) Dequeue a vertex from queue. Let this \n be f.\n b) Print f\n c) Enqueue all not yet visited adjacent\n of f and mark them visited."
},
{
"code": null,
"e": 25503,
"s": 25355,
"text": "Below is an example BFS starting from source vertex 1. Note that there can be multiple BFSs possible for a graph (even from a particular vertex). "
},
{
"code": null,
"e": 25626,
"s": 25503,
"text": "For more details of BFS, refer this post . The code here is simplified such that it could be used in competitive coding. "
},
{
"code": null,
"e": 25630,
"s": 25626,
"text": "CPP"
},
{
"code": "// A Quick implementation of BFS using// vectors and queue#include <bits/stdc++.h>#define pb push_back using namespace std; vector<bool> v;vector<vector<int> > g; void edge(int a, int b){ g[a].pb(b); // for undirected graph add this line // g[b].pb(a);} void bfs(int u){ queue<int> q; q.push(u); v[u] = true; while (!q.empty()) { int f = q.front(); q.pop(); cout << f << \" \"; // Enqueue all adjacent of f and mark them visited for (auto i = g[f].begin(); i != g[f].end(); i++) { if (!v[*i]) { q.push(*i); v[*i] = true; } } }} // Driver codeint main(){ int n, e; cin >> n >> e; v.assign(n, false); g.assign(n, vector<int>()); int a, b; for (int i = 0; i < e; i++) { cin >> a >> b; edge(a, b); } for (int i = 0; i < n; i++) { if (!v[i]) bfs(i); } return 0;}",
"e": 26592,
"s": 25630,
"text": null
},
{
"code": null,
"e": 26669,
"s": 26592,
"text": "Input:\n8 10\n0 1\n0 2\n0 3\n0 4\n1 5\n2 5\n3 6\n4 6\n5 7\n6 7\n\nOutput:\n0 1 2 3 4 5 6 7"
},
{
"code": null,
"e": 27094,
"s": 26669,
"text": "This article is contributed by Nikhil Mahendran. 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": 27108,
"s": 27094,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 27112,
"s": 27108,
"text": "BFS"
},
{
"code": null,
"e": 27122,
"s": 27112,
"text": "cpp-queue"
},
{
"code": null,
"e": 27133,
"s": 27122,
"text": "cpp-vector"
},
{
"code": null,
"e": 27157,
"s": 27133,
"text": "Competitive Programming"
},
{
"code": null,
"e": 27163,
"s": 27157,
"text": "Graph"
},
{
"code": null,
"e": 27169,
"s": 27163,
"text": "Graph"
},
{
"code": null,
"e": 27173,
"s": 27169,
"text": "BFS"
},
{
"code": null,
"e": 27271,
"s": 27173,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27280,
"s": 27271,
"text": "Comments"
},
{
"code": null,
"e": 27293,
"s": 27280,
"text": "Old Comments"
},
{
"code": null,
"e": 27331,
"s": 27293,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 27356,
"s": 27331,
"text": "Formatted output in Java"
},
{
"code": null,
"e": 27404,
"s": 27356,
"text": "Algorithm Library | C++ Magicians STL Algorithm"
},
{
"code": null,
"e": 27431,
"s": 27404,
"text": "Use of FLAG in programming"
},
{
"code": null,
"e": 27499,
"s": 27431,
"text": "Setting up Sublime Text for C++ Competitive Programming Environment"
},
{
"code": null,
"e": 27550,
"s": 27499,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 27601,
"s": 27550,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 27659,
"s": 27601,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
}
] |
HTML DOM getBoundingClientRect() method
|
The HTML DOM getBoundingClientRect() is used for returning an element size relative to the position of the viewport. It returns an object of type DOMRect which has eight properties left, top, right, bottom, x, y, width, height. The bounding rectangle position changes when the scrolling position changes.
Following is the syntax for the getBoundingClientRect() method −
element.getBoundingClientRect()
Let us look at an example for the getBoundingClientRect() method −
Live Demo
<!DOCTYPE html>
<html>
<head>
<script>
function RectInfo() {
document.getElementById("Sample").innerHTML="";
var d = document.getElementById("DIV1");
var Rect = d.getBoundingClientRect();
rl = Rect.left;
rt = Rect.top;
rw = Rect.width;
rh = Rect.height;
document.getElementById("Sample").innerHTML +="Left: " + rl + ",<br> Top: " + rt + ",<br> Width: " + rw + ",<br> Height: " + rh;
}
</script>
<style>
#DIV1{
width:350px;
height:250px;
border:2px solid blue;
color:red;
}
</style>
</head>
<body>
<h1>getBoundingClientRect() example</h1>
<div style="height:200px; width:300px; overflow:auto;">
<div id="DIV1">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</div>
</div>
<br>
<button onclick="RectInfo()">GET INFO</button>
<p id="Sample"></p>
</body>
</html>
This will produce the following output −
On clicking the GET INFO button −
In the above example −
We have first created a div of height and width 200px and 300px respectively. It has the overflow property set to auto i.e scrollbars will automatically get added if the content overflows the div. It contains another div with id “DIV1” that has some styling applied to it.
#DIV1{
width:350px;
height:250px;
border:2px solid blue;
color:red;
}
<div style="height:200px; width:300px; overflow:auto;">
<div id="DIV1">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut
labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
laboris nisi ut aliquip ex ea commodo consequat.
</div>
</div>
We have then created a button GET INFO that will execute the RectInfo() method when clicked by the user −
<button onclick="RectInfo()">GET INFO</button>
The RectInfo() method gets the <div> element using the getElementById() method and assigns it to variable d. It then uses the getBoundingClientRect() method on the variable d to return a DOMRect object containing information about the div element. The returned object is assigned to variable Rect.
We then use the left, top, width and height properties of the DOMRect object to display its position and size relative to viewport. This information is displayed in the paragraph with id “Sample” using its innerHTML property −
function RectInfo() {
document.getElementById("Sample").innerHTML="";
var d = document.getElementById("DIV1");
var Rect = d.getBoundingClientRect();
rl = Rect.left;
rt = Rect.top;
rw = Rect.width;
rh = Rect.height;
document.getElementById("Sample").innerHTML +="Left: " + rl + ",<br> Top: " + rt + ",<br> Width: " + rw + ",<br> Height: " + rh;
}
|
[
{
"code": null,
"e": 1367,
"s": 1062,
"text": "The HTML DOM getBoundingClientRect() is used for returning an element size relative to the position of the viewport. It returns an object of type DOMRect which has eight properties left, top, right, bottom, x, y, width, height. The bounding rectangle position changes when the scrolling position changes."
},
{
"code": null,
"e": 1432,
"s": 1367,
"text": "Following is the syntax for the getBoundingClientRect() method −"
},
{
"code": null,
"e": 1464,
"s": 1432,
"text": "element.getBoundingClientRect()"
},
{
"code": null,
"e": 1531,
"s": 1464,
"text": "Let us look at an example for the getBoundingClientRect() method −"
},
{
"code": null,
"e": 1541,
"s": 1531,
"text": "Live Demo"
},
{
"code": null,
"e": 2569,
"s": 1541,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<script>\n function RectInfo() {\n document.getElementById(\"Sample\").innerHTML=\"\";\n var d = document.getElementById(\"DIV1\");\n var Rect = d.getBoundingClientRect();\n rl = Rect.left;\n rt = Rect.top;\n rw = Rect.width;\n rh = Rect.height;\n document.getElementById(\"Sample\").innerHTML +=\"Left: \" + rl + \",<br> Top: \" + rt + \",<br> Width: \" + rw + \",<br> Height: \" + rh;\n }\n</script>\n<style>\n #DIV1{\n width:350px;\n height:250px;\n border:2px solid blue;\n color:red;\n }\n</style>\n</head>\n<body>\n<h1>getBoundingClientRect() example</h1>\n<div style=\"height:200px; width:300px; overflow:auto;\">\n<div id=\"DIV1\">\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\n</div>\n</div>\n<br>\n<button onclick=\"RectInfo()\">GET INFO</button>\n<p id=\"Sample\"></p>\n</body>\n</html>"
},
{
"code": null,
"e": 2610,
"s": 2569,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2644,
"s": 2610,
"text": "On clicking the GET INFO button −"
},
{
"code": null,
"e": 2667,
"s": 2644,
"text": "In the above example −"
},
{
"code": null,
"e": 2940,
"s": 2667,
"text": "We have first created a div of height and width 200px and 300px respectively. It has the overflow property set to auto i.e scrollbars will automatically get added if the content overflows the div. It contains another div with id “DIV1” that has some styling applied to it."
},
{
"code": null,
"e": 3340,
"s": 2940,
"text": "#DIV1{\n width:350px;\n height:250px;\n border:2px solid blue;\n color:red;\n}\n<div style=\"height:200px; width:300px; overflow:auto;\">\n<div id=\"DIV1\">\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut\nlabore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco\nlaboris nisi ut aliquip ex ea commodo consequat.\n</div>\n</div>"
},
{
"code": null,
"e": 3446,
"s": 3340,
"text": "We have then created a button GET INFO that will execute the RectInfo() method when clicked by the user −"
},
{
"code": null,
"e": 3493,
"s": 3446,
"text": "<button onclick=\"RectInfo()\">GET INFO</button>"
},
{
"code": null,
"e": 3791,
"s": 3493,
"text": "The RectInfo() method gets the <div> element using the getElementById() method and assigns it to variable d. It then uses the getBoundingClientRect() method on the variable d to return a DOMRect object containing information about the div element. The returned object is assigned to variable Rect."
},
{
"code": null,
"e": 4018,
"s": 3791,
"text": "We then use the left, top, width and height properties of the DOMRect object to display its position and size relative to viewport. This information is displayed in the paragraph with id “Sample” using its innerHTML property −"
},
{
"code": null,
"e": 4388,
"s": 4018,
"text": "function RectInfo() {\n document.getElementById(\"Sample\").innerHTML=\"\";\n var d = document.getElementById(\"DIV1\");\n var Rect = d.getBoundingClientRect();\n rl = Rect.left;\n rt = Rect.top;\n rw = Rect.width;\n rh = Rect.height;\n document.getElementById(\"Sample\").innerHTML +=\"Left: \" + rl + \",<br> Top: \" + rt + \",<br> Width: \" + rw + \",<br> Height: \" + rh;\n}"
}
] |
Elixir - Operators
|
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. There are a LOT of operators provided by elixir. They are divided in the following categories −
Arithmetic operators
Comparison operators
Boolean operators
Misc operators
The following table shows all the arithmetic operators supported by Elixir language. Assume variable A holds 10 and variable B holds 20, then −
Show Examples
The comparison operators in Elixir are mostly common to those provided in most other languages. The following table sums up comparison operators in Elixir. Assume variable A holds 10 and variable B holds 20, then −
Show Examples
Elixir provides 6 logical operators: and, or, not, &&, || and !. The first three, and or not are strict Boolean operators, meaning that they expect their first argument to be a Boolean. Non Boolean argument will raise an error. While the next three, &&, || and ! are non strict, do not require us to have the first value strictly as a boolean. They work in the same way as their strict counterparts. Assume variable A holds true and variable B holds 20, then −
Show Examples
NOTE −and, or, && and || || are short circuit operators. This means that if the first argument of and is false, then it will not further check for the second one. And if the first argument of or is true, then it will not check for the second one. For example,
false and raise("An error")
#This won't raise an error as raise function wont get executed because of short
#circuiting nature of and operator
Bitwise operators work on bits and perform bit by bit operation. Elixir provides bitwise modules as part of the package Bitwise, so in order to use these, you need to use the bitwise module. To use it, enter the following command in your shell −
use Bitwise
Assume A to be 5 and B to be 6 for the following examples −
Show Examples
Other than the above operators, Elixir also provides a range of other operators like Concatenation Operator, Match Operator, Pin Operator, Pipe Operator, String Match Operator, Code Point Operator, Capture Operator, Ternary Operator that make it quite a powerful language.
Show Examples
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": 2385,
"s": 2182,
"text": "An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. There are a LOT of operators provided by elixir. They are divided in the following categories −"
},
{
"code": null,
"e": 2406,
"s": 2385,
"text": "Arithmetic operators"
},
{
"code": null,
"e": 2427,
"s": 2406,
"text": "Comparison operators"
},
{
"code": null,
"e": 2445,
"s": 2427,
"text": "Boolean operators"
},
{
"code": null,
"e": 2460,
"s": 2445,
"text": "Misc operators"
},
{
"code": null,
"e": 2604,
"s": 2460,
"text": "The following table shows all the arithmetic operators supported by Elixir language. Assume variable A holds 10 and variable B holds 20, then −"
},
{
"code": null,
"e": 2618,
"s": 2604,
"text": "Show Examples"
},
{
"code": null,
"e": 2833,
"s": 2618,
"text": "The comparison operators in Elixir are mostly common to those provided in most other languages. The following table sums up comparison operators in Elixir. Assume variable A holds 10 and variable B holds 20, then −"
},
{
"code": null,
"e": 2847,
"s": 2833,
"text": "Show Examples"
},
{
"code": null,
"e": 3308,
"s": 2847,
"text": "Elixir provides 6 logical operators: and, or, not, &&, || and !. The first three, and or not are strict Boolean operators, meaning that they expect their first argument to be a Boolean. Non Boolean argument will raise an error. While the next three, &&, || and ! are non strict, do not require us to have the first value strictly as a boolean. They work in the same way as their strict counterparts. Assume variable A holds true and variable B holds 20, then −"
},
{
"code": null,
"e": 3322,
"s": 3308,
"text": "Show Examples"
},
{
"code": null,
"e": 3583,
"s": 3322,
"text": "NOTE −and, or, && and || || are short circuit operators. This means that if the first argument of and is false, then it will not further check for the second one. And if the first argument of or is true, then it will not check for the second one. For example, "
},
{
"code": null,
"e": 3728,
"s": 3583,
"text": "false and raise(\"An error\") \n#This won't raise an error as raise function wont get executed because of short\n#circuiting nature of and operator"
},
{
"code": null,
"e": 3974,
"s": 3728,
"text": "Bitwise operators work on bits and perform bit by bit operation. Elixir provides bitwise modules as part of the package Bitwise, so in order to use these, you need to use the bitwise module. To use it, enter the following command in your shell −"
},
{
"code": null,
"e": 3987,
"s": 3974,
"text": "use Bitwise\n"
},
{
"code": null,
"e": 4048,
"s": 3987,
"text": " Assume A to be 5 and B to be 6 for the following examples −"
},
{
"code": null,
"e": 4062,
"s": 4048,
"text": "Show Examples"
},
{
"code": null,
"e": 4336,
"s": 4062,
"text": "Other than the above operators, Elixir also provides a range of other operators like Concatenation Operator, Match Operator, Pin Operator, Pipe Operator, String Match Operator, Code Point Operator, Capture Operator, Ternary Operator that make it quite a powerful language."
},
{
"code": null,
"e": 4350,
"s": 4336,
"text": "Show Examples"
},
{
"code": null,
"e": 4383,
"s": 4350,
"text": "\n 35 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4403,
"s": 4383,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 4436,
"s": 4403,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4476,
"s": 4436,
"text": " Pranjal Srivastava, Harshit Srivastava"
},
{
"code": null,
"e": 4511,
"s": 4476,
"text": "\n 80 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 4531,
"s": 4511,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 4564,
"s": 4531,
"text": "\n 43 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4581,
"s": 4564,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 4588,
"s": 4581,
"text": " Print"
},
{
"code": null,
"e": 4599,
"s": 4588,
"text": " Add Notes"
}
] |
Flip consecutive set bits starting from LSB of a given number - GeeksforGeeks
|
29 Mar, 2022
Given a positive integer N, the task is to find the number that can be obtained by flipping consecutive set bits starting from the LSB in the binary representation of N.
Examples:
Input: N = 39Output: 32Explanation:Binary representation of (39)10 = (100111)2After flipping all consecutive set bits starting from the LSB, the number obtained is (100000)Binary representation of (32)10 is (100000)2Therefore, the number obtained is 32.
Input: N = 4Output: 4Explanation:Binary representation of (4)10 = (100)2Since the LSB is not set, the number remains unchanged.
Naive Approach: The simplest approach is to find the number of consecutive set bits starting from the LSB by performing Logical AND( & ) of N with 1 until N & 1 is not 0 and keep a count of the number of set bits. Then, simply left shift N by the count of set bits. Print the number obtained as the required answer.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the number after// converting 1s from end to 0sint findNumber(int N){ // Count of 1s int count = 0; // AND operation of N and 1 while ((N & 1) == 1) { N = N >> 1; count++; } // Left shift N by count return N << count;} // Driver Codeint main(){ int N = 39; // Function Call cout << findNumber(N); return 0;}
// Java program for the above approachclass GFG{ // Function to find the number after// converting 1s from end to 0sstatic int findNumber(int N){ // Count of 1s int count = 0; // AND operation of N and 1 while ((N & 1) == 1) { N = N >> 1; count++; } // Left shift N by count return N << count;} // Driver Codepublic static void main (String[] args){ int N = 39; // Function Call System.out.println(findNumber(N));}} // This code is contributed by AnkThon
# Python3 program for the above approach # Function to find the number after# converting 1s from end to 0sdef findNumber(N): # Count of 1s count = 0 # AND operation of N and 1 while ((N & 1) == 1): N = N >> 1 count += 1 # Left shift N by count return N << count # Driver Codeif __name__ == "__main__": N = 39 # Function Call print(findNumber(N)) # This code is contributed by AnkThon
// C# program to implement// the above approach using System; class GFG{ // Function to find the number after// converting 1s from end to 0sstatic int findNumber(int N){ // Count of 1s int count = 0; // AND operation of N and 1 while ((N & 1) == 1) { N = N >> 1; count++; } // Left shift N by count return N << count;} // Driver Codepublic static void Main(){ int N = 39; // Function Call Console.WriteLine(findNumber(N));}} // This code is contributed by code_hunt
<script> // Javascript program for the above approach // Function to find the number after// converting 1s from end to 0sfunction findNumber(N){ // Count of 1s let count = 0; // AND operation of N and 1 while ((N & 1) == 1) { N = N >> 1; count++; } // Left shift N by count return N << count;} // Driver Code let N = 39; // Function Call document.write(findNumber(N)); </script>
32
Time Complexity: O(log N)Auxiliary Space: O(1)
Efficient Approach: To optimize trhe above approach, find the Logical AND ( & ) of N and (N + 1). The key observation is that adding 1 to a number makes every continuous set bit from the LSB to become 0. Therefore, N & (N + 1) gives the required number.
Illustration:
N = 39, therefore (N+1)=40
⇒ N = 39 = (100111)
⇒ N+1 = 40 = (101000)
Performing Logical AND(&) operation:
1 0 0 1 1 1
& 1 0 1 0 0 0
----------------
1 0 0 0 0 0 ⇒ 32
----------------
Will this always work? Add 1 to N:
1 0 0 1 1 1
+ 1
-------------
1 0 1 0 0 0
--------------
It can be clearly seen that the continuous set bits from the LSB becomnes unset.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the number after// converting 1s from end to 0sint findNumber(int N){ // Return the logical AND // of N and (N + 1) return N & (N + 1);} // Driver Codeint main(){ int N = 39; // Function Call cout << findNumber(N); return 0;}
// Java program for the above approachimport java.util.*;class GFG{ // Function to find the number after// converting 1s from end to 0sstatic int findNumber(int N){ // Return the logical AND // of N and (N + 1) return N & (N + 1);} // Driver Codepublic static void main(String[] args){ int N = 39; // Function Call System.out.print(findNumber(N));}} // This code is contributed by 29AjayKumar
# Python3 program for the above approach # Function to find the number after# converting 1s from end to 0sdef findNumber(N): # Return the logical AND # of N and (N + 1) return N & (N + 1) # Driver Codeif __name__ == '__main__': N = 39 # Function Call print(findNumber(N)) # This code is contributed by mohit kumar 29
// C# program for the above approachusing System; class GFG{ // Function to find the number after// converting 1s from end to 0sstatic int findNumber(int N){ // Return the logical AND // of N and (N + 1) return N & (N + 1);} // Driver Codepublic static void Main(String[] args){ int N = 39; // Function Call Console.Write(findNumber(N));}} // This code is contributed by 29AjayKumar
<script> // javascript program of the above approach // Function to find the number after// converting 1s from end to 0sfunction findNumber(N){ // Return the logical AND // of N and (N + 1) return N & (N + 1);} // Driver Code let N = 39; // Function Call document.write(findNumber(N)); // This code is contributed by target_2.</script>
32
Time Complexity: O(1)Auxiliary Space: O(1)
mohit kumar 29
ankthon
code_hunt
29AjayKumar
chinmoy1997pal
target_2
sooda367
rajatkumargla19
Bitwise-AND
Technical Scripter 2020
Bit Magic
Greedy
Mathematical
Technical Scripter
Greedy
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Cyclic Redundancy Check and Modulo-2 Division
Little and Big Endian Mystery
Add two numbers without using arithmetic operators
Binary representation of a given number
Program to find whether a given number is power of 2
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Program for array rotation
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Huffman Coding | Greedy Algo-3
|
[
{
"code": null,
"e": 24689,
"s": 24661,
"text": "\n29 Mar, 2022"
},
{
"code": null,
"e": 24859,
"s": 24689,
"text": "Given a positive integer N, the task is to find the number that can be obtained by flipping consecutive set bits starting from the LSB in the binary representation of N."
},
{
"code": null,
"e": 24869,
"s": 24859,
"text": "Examples:"
},
{
"code": null,
"e": 25123,
"s": 24869,
"text": "Input: N = 39Output: 32Explanation:Binary representation of (39)10 = (100111)2After flipping all consecutive set bits starting from the LSB, the number obtained is (100000)Binary representation of (32)10 is (100000)2Therefore, the number obtained is 32."
},
{
"code": null,
"e": 25251,
"s": 25123,
"text": "Input: N = 4Output: 4Explanation:Binary representation of (4)10 = (100)2Since the LSB is not set, the number remains unchanged."
},
{
"code": null,
"e": 25567,
"s": 25251,
"text": "Naive Approach: The simplest approach is to find the number of consecutive set bits starting from the LSB by performing Logical AND( & ) of N with 1 until N & 1 is not 0 and keep a count of the number of set bits. Then, simply left shift N by the count of set bits. Print the number obtained as the required answer."
},
{
"code": null,
"e": 25618,
"s": 25567,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25622,
"s": 25618,
"text": "C++"
},
{
"code": null,
"e": 25627,
"s": 25622,
"text": "Java"
},
{
"code": null,
"e": 25635,
"s": 25627,
"text": "Python3"
},
{
"code": null,
"e": 25638,
"s": 25635,
"text": "C#"
},
{
"code": null,
"e": 25649,
"s": 25638,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the number after// converting 1s from end to 0sint findNumber(int N){ // Count of 1s int count = 0; // AND operation of N and 1 while ((N & 1) == 1) { N = N >> 1; count++; } // Left shift N by count return N << count;} // Driver Codeint main(){ int N = 39; // Function Call cout << findNumber(N); return 0;}",
"e": 26111,
"s": 25649,
"text": null
},
{
"code": "// Java program for the above approachclass GFG{ // Function to find the number after// converting 1s from end to 0sstatic int findNumber(int N){ // Count of 1s int count = 0; // AND operation of N and 1 while ((N & 1) == 1) { N = N >> 1; count++; } // Left shift N by count return N << count;} // Driver Codepublic static void main (String[] args){ int N = 39; // Function Call System.out.println(findNumber(N));}} // This code is contributed by AnkThon",
"e": 26629,
"s": 26111,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find the number after# converting 1s from end to 0sdef findNumber(N): # Count of 1s count = 0 # AND operation of N and 1 while ((N & 1) == 1): N = N >> 1 count += 1 # Left shift N by count return N << count # Driver Codeif __name__ == \"__main__\": N = 39 # Function Call print(findNumber(N)) # This code is contributed by AnkThon",
"e": 27063,
"s": 26629,
"text": null
},
{
"code": "// C# program to implement// the above approach using System; class GFG{ // Function to find the number after// converting 1s from end to 0sstatic int findNumber(int N){ // Count of 1s int count = 0; // AND operation of N and 1 while ((N & 1) == 1) { N = N >> 1; count++; } // Left shift N by count return N << count;} // Driver Codepublic static void Main(){ int N = 39; // Function Call Console.WriteLine(findNumber(N));}} // This code is contributed by code_hunt",
"e": 27598,
"s": 27063,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to find the number after// converting 1s from end to 0sfunction findNumber(N){ // Count of 1s let count = 0; // AND operation of N and 1 while ((N & 1) == 1) { N = N >> 1; count++; } // Left shift N by count return N << count;} // Driver Code let N = 39; // Function Call document.write(findNumber(N)); </script>",
"e": 28044,
"s": 27598,
"text": null
},
{
"code": null,
"e": 28047,
"s": 28044,
"text": "32"
},
{
"code": null,
"e": 28096,
"s": 28049,
"text": "Time Complexity: O(log N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 28350,
"s": 28096,
"text": "Efficient Approach: To optimize trhe above approach, find the Logical AND ( & ) of N and (N + 1). The key observation is that adding 1 to a number makes every continuous set bit from the LSB to become 0. Therefore, N & (N + 1) gives the required number."
},
{
"code": null,
"e": 28364,
"s": 28350,
"text": "Illustration:"
},
{
"code": null,
"e": 28752,
"s": 28364,
"text": "N = 39, therefore (N+1)=40\n⇒ N = 39 = (100111)\n⇒ N+1 = 40 = (101000)\nPerforming Logical AND(&) operation:\n 1 0 0 1 1 1 \n& 1 0 1 0 0 0\n----------------\n 1 0 0 0 0 0 ⇒ 32\n----------------\n\nWill this always work? Add 1 to N:\n 1 0 0 1 1 1\n + 1\n ------------- \n 1 0 1 0 0 0 \n -------------- \nIt can be clearly seen that the continuous set bits from the LSB becomnes unset."
},
{
"code": null,
"e": 28803,
"s": 28752,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28807,
"s": 28803,
"text": "C++"
},
{
"code": null,
"e": 28812,
"s": 28807,
"text": "Java"
},
{
"code": null,
"e": 28820,
"s": 28812,
"text": "Python3"
},
{
"code": null,
"e": 28823,
"s": 28820,
"text": "C#"
},
{
"code": null,
"e": 28834,
"s": 28823,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the number after// converting 1s from end to 0sint findNumber(int N){ // Return the logical AND // of N and (N + 1) return N & (N + 1);} // Driver Codeint main(){ int N = 39; // Function Call cout << findNumber(N); return 0;}",
"e": 29186,
"s": 28834,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to find the number after// converting 1s from end to 0sstatic int findNumber(int N){ // Return the logical AND // of N and (N + 1) return N & (N + 1);} // Driver Codepublic static void main(String[] args){ int N = 39; // Function Call System.out.print(findNumber(N));}} // This code is contributed by 29AjayKumar",
"e": 29601,
"s": 29186,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find the number after# converting 1s from end to 0sdef findNumber(N): # Return the logical AND # of N and (N + 1) return N & (N + 1) # Driver Codeif __name__ == '__main__': N = 39 # Function Call print(findNumber(N)) # This code is contributed by mohit kumar 29",
"e": 29942,
"s": 29601,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to find the number after// converting 1s from end to 0sstatic int findNumber(int N){ // Return the logical AND // of N and (N + 1) return N & (N + 1);} // Driver Codepublic static void Main(String[] args){ int N = 39; // Function Call Console.Write(findNumber(N));}} // This code is contributed by 29AjayKumar",
"e": 30348,
"s": 29942,
"text": null
},
{
"code": "<script> // javascript program of the above approach // Function to find the number after// converting 1s from end to 0sfunction findNumber(N){ // Return the logical AND // of N and (N + 1) return N & (N + 1);} // Driver Code let N = 39; // Function Call document.write(findNumber(N)); // This code is contributed by target_2.</script>",
"e": 30720,
"s": 30348,
"text": null
},
{
"code": null,
"e": 30723,
"s": 30720,
"text": "32"
},
{
"code": null,
"e": 30768,
"s": 30725,
"text": "Time Complexity: O(1)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 30783,
"s": 30768,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 30791,
"s": 30783,
"text": "ankthon"
},
{
"code": null,
"e": 30801,
"s": 30791,
"text": "code_hunt"
},
{
"code": null,
"e": 30813,
"s": 30801,
"text": "29AjayKumar"
},
{
"code": null,
"e": 30828,
"s": 30813,
"text": "chinmoy1997pal"
},
{
"code": null,
"e": 30837,
"s": 30828,
"text": "target_2"
},
{
"code": null,
"e": 30846,
"s": 30837,
"text": "sooda367"
},
{
"code": null,
"e": 30862,
"s": 30846,
"text": "rajatkumargla19"
},
{
"code": null,
"e": 30874,
"s": 30862,
"text": "Bitwise-AND"
},
{
"code": null,
"e": 30898,
"s": 30874,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 30908,
"s": 30898,
"text": "Bit Magic"
},
{
"code": null,
"e": 30915,
"s": 30908,
"text": "Greedy"
},
{
"code": null,
"e": 30928,
"s": 30915,
"text": "Mathematical"
},
{
"code": null,
"e": 30947,
"s": 30928,
"text": "Technical Scripter"
},
{
"code": null,
"e": 30954,
"s": 30947,
"text": "Greedy"
},
{
"code": null,
"e": 30967,
"s": 30954,
"text": "Mathematical"
},
{
"code": null,
"e": 30977,
"s": 30967,
"text": "Bit Magic"
},
{
"code": null,
"e": 31075,
"s": 30977,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31084,
"s": 31075,
"text": "Comments"
},
{
"code": null,
"e": 31097,
"s": 31084,
"text": "Old Comments"
},
{
"code": null,
"e": 31143,
"s": 31097,
"text": "Cyclic Redundancy Check and Modulo-2 Division"
},
{
"code": null,
"e": 31173,
"s": 31143,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 31224,
"s": 31173,
"text": "Add two numbers without using arithmetic operators"
},
{
"code": null,
"e": 31264,
"s": 31224,
"text": "Binary representation of a given number"
},
{
"code": null,
"e": 31317,
"s": 31264,
"text": "Program to find whether a given number is power of 2"
},
{
"code": null,
"e": 31368,
"s": 31317,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 31419,
"s": 31368,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 31446,
"s": 31419,
"text": "Program for array rotation"
},
{
"code": null,
"e": 31504,
"s": 31446,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
}
] |
Active Learning on MNIST — Saving on Labeling | by Andy Bosyi | Towards Data Science
|
Active Learning is a semi-supervised technique that allows labeling less data by selecting the most important samples from the learning process (loss) standpoint It can have a huge impact on the project cost in the case when the amount of data is large and the labeling rate is high. For example, object detection and NLP-NER problems.The article is based on the following code: Active Learning on MNIST
#load 4000 of MNIST data for train and 400 for testing(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()x_full = x_train[:4000] / 255y_full = y_train[:4000]x_test = x_test[:400] /255y_test = y_test[:400]x_full.shape, y_full.shape, x_test.shape, y_test.shape
plt.imshow(x_full[3999])
I will use a subset of MNIST dataset which is 60K pictures of digits with labels and 10K test samples. For the purposes of quicker training, 4000 samples (pictures) are needed for training and 400 for a test (neural network will never see it during the training). For normalization, I divide the grayscale image points by 255.
#build computation graphx = tf.placeholder(tf.float32, [None, 28, 28])x_flat = tf.reshape(x, [-1, 28 * 28])y_ = tf.placeholder(tf.int32, [None])W = tf.Variable(tf.zeros([28 * 28, 10]), tf.float32)b = tf.Variable(tf.zeros([10]), tf.float32)y = tf.matmul(x_flat, W) + by_sm = tf.nn.softmax(y)loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y_, logits=y))train = tf.train.AdamOptimizer(0.1).minimize(loss)accuracy = tf.reduce_mean(tf.cast(tf.equal(y_, tf.cast(tf.argmax(y, 1), tf.int32)), tf.float32))
As a framework, one can use the TensorFlow computation graph that will build ten neurons (for every digit). W and b are the weights for the neurons. A softmax output y_sm will help with the probabilities (confidence) of digits. The loss will be a typical “softmaxed” cross entropy between the predicted and labeled data. The choice for the optimizer is a popular Adam, the learning rate is almost default — 0.1. As a main metric I will use accuracy over test dataset.
def reset(): '''Initialize data sets and session''' global x_labeled, y_labeled, x_unlabeled, y_unlabeled x_labeled = x_full[:0] y_labeled = y_full[:0] x_unlabeled = x_full y_unlabeled = y_full tf.global_variables_initializer().run() tf.local_variables_initializer().run() def fit(): '''Train current labeled dataset until overfit.''' trial_count = 10 acc = sess.run(accuracy, feed_dict={x:x_test, y_:y_test}) weights = sess.run([W, b]) while trial_count > 0: sess.run(train, feed_dict={x:x_labeled, y_:y_labeled}) acc_new = sess.run(accuracy, feed_dict={x:x_test, y_:y_test}) if acc_new <= acc: trial_count -= 1 else: trial_count = 10 weights = sess.run([W, b]) acc = acc_new sess.run([W.assign(weights[0]), b.assign(weights[1])]) acc = sess.run(accuracy, feed_dict={x:x_test, y_:y_test}) print('Labels:', x_labeled.shape[0], '\tAccuracy:', acc)def label_manually(n): '''Human powered labeling (actually copying from the prelabeled MNIST dataset).''' global x_labeled, y_labeled, x_unlabeled, y_unlabeled x_labeled = np.concatenate([x_labeled, x_unlabeled[:n]]) y_labeled = np.concatenate([y_labeled, y_unlabeled[:n]]) x_unlabeled = x_unlabeled[n:] y_unlabeled = y_unlabeled[n:]
Here I define these three procedures for more convenient coding.reset() — empties the labeled dataset, puts all data in the unlabeled dataset and resets the session variables
fit() — runs a training attempting to reach the best accuracy. If it cannot improve during the first ten attempts, the training stops at the last best result. We cannot use just any big number of training epochs as the model tends to quickly overfit or needs an intensive L2 regularization.
label_manually() — this is an emulation of human data labeling. Actually, we take the labels from the MNIST dataset that has been labeled already.
#train full dataset of 1000reset()label_manually(4000)fit()
If we are so lucky as to have enough resources to label the whole dataset, we will receive the 92.25% of accuracy.
#apply clusteringkmeans = tf.contrib.factorization.KMeansClustering(10, use_mini_batch=False)kmeans.train(lambda: tf.train.limit_epochs(x_full.reshape(4000, 784).astype(np.float32), 10))
centers = kmeans.cluster_centers().reshape([10, 28, 28])plt.imshow(np.concatenate([centers[i] for i in range(10)], axis=1))
Here I try to use the k-means clustering to find a group of digits and use this information for automatic labeling. I run the Tensorflow clustering estimator and then visualize the resulting ten centroids. As you can see, the result is far from perfect — digit “9” appears three times, sometimes mixed with “8” and “3”.
#try to run on random 400reset()label_manually(400)fit()
Let’s try to label only 10% of data (400 samples) and we will receive 83.75% of accuracy that is pretty far from 92.25% of the ground truth.
#now try to run on 10reset()label_manually(10)fit()
#pass unlabeled rest 3990 through the early modelres = sess.run(y_sm, feed_dict={x:x_unlabeled})#find less confident samplespmax = np.amax(res, axis=1)pidx = np.argsort(pmax)#sort the unlabeled corpus on the confidencyx_unlabeled = x_unlabeled[pidx]y_unlabeled = y_unlabeled[pidx]plt.plot(pmax[pidx])
Now we will label the same 10% of data (400 samples) using active learning. To do that, we take one batch out of the 10 samples and train a very primitive model. Then, we pass the rest of the data (3990 samples) through this model and evaluate the maximum softmax output. This will show what is the probability that the selected class is the correct answer (in other words, the confidence of the neural network). After sorting, we can see on the plot that the distribution of confidence varies from 20% to 100%. The idea is to select the next batch for labeling exactly from the LESS CONFIDENT samples.
#do the same in a loop for 400 samplesfor i in range(39): label_manually(10) fit() res = sess.run(y_sm, feed_dict={x:x_unlabeled}) pmax = np.amax(res, axis=1) pidx = np.argsort(pmax) x_unlabeled = x_unlabeled[pidx] y_unlabeled = y_unlabeled[pidx]
After running such a procedure for the 40 batches of 10 samples, we can see that the resulting accuracy is almost 90%. This is far more than the 83.75% achieved in the case with randomly labeled data.
#pass rest unlabeled data through the model and try to autolabelres = sess.run(y_sm, feed_dict={x:x_unlabeled})y_autolabeled = res.argmax(axis=1)x_labeled = np.concatenate([x_labeled, x_unlabeled])y_labeled = np.concatenate([y_labeled, y_autolabeled])#train on 400 labeled by active learning and 3600 stochasticly autolabeled datafit()
The classical way would be to run the rest of the dataset through the existing model and automatically label the data. Then, pushing it in the training process would maybe help to better tune the model. In our case though, it did not give us an any better result.
My approach is to do the same but, as in the active learning, taking in consideration the confidence:
#pass rest of unlabeled (3600) data trough the model for automatic labeling and show most confident samplesres = sess.run(y_sm, feed_dict={x:x_unlabeled})y_autolabeled = res.argmax(axis=1)pmax = np.amax(res, axis=1)pidx = np.argsort(pmax)#sort by confidencyx_unlabeled = x_unlabeled[pidx]y_autolabeled = y_autolabeled[pidx]plt.plot(pmax[pidx])
#automatically label 10 most confident sample and train for itx_labeled = np.concatenate([x_labeled, x_unlabeled[-10:]])y_labeled = np.concatenate([y_labeled, y_autolabeled[-10:]])x_unlabeled = x_unlabeled[:-10]fit()
Here we run the rest of unlabeled data through model evaluation and we still can see that the confidence differs for the rest of the samples. Thus, the idea is to take a batch of ten MOST CONFIDENT samples and train the model.
#run rest of unlabelled samples starting from most confidentfor i in range(359): res = sess.run(y_sm, feed_dict={x:x_unlabeled}) y_autolabeled = res.argmax(axis=1) pmax = np.amax(res, axis=1) pidx = np.argsort(pmax) x_unlabeled = x_unlabeled[pidx] y_autolabeled = y_autolabeled[pidx] x_labeled = np.concatenate([x_labeled, x_unlabeled[-10:]]) y_labeled = np.concatenate([y_labeled, y_autolabeled[-10:]]) x_unlabeled = x_unlabeled[:-10] fit()
This process takes some time and gives us extra 0.8% of accuracy.
Experiment Accuracy4000 samples 92.25%400 random samples 83.75%400 active learned samples 89.75% + auto-labeling 90.50%
Of course, this approach has its drawbacks, like the heavy use of computation resources and the fact that a special procedure is required for data labeling mixed with early model evaluation. Also, for the testing purposes data needs to be labeled as well. However, if the cost of a label is high (especially for NLP, CV projects), this method can save a significant amount of resources and drive better project results.
If you have personal questions contact me on Linkedin or Facebook, where sometimes I post short news and thoughts about AI.
I want to thank my colleagues Alex Simkiv, Mykola Kozlenko, Volodymyr Sendetskyi, Viach Bosyi, and Nazar Savchenko for fruitful discussions, cooperation, and helpful tips as well as the entire MindCraft.ai team for their constant support.Andy Bosyi,CEO, MindCraft.aiInformation Technology & Data Science
|
[
{
"code": null,
"e": 576,
"s": 172,
"text": "Active Learning is a semi-supervised technique that allows labeling less data by selecting the most important samples from the learning process (loss) standpoint It can have a huge impact on the project cost in the case when the amount of data is large and the labeling rate is high. For example, object detection and NLP-NER problems.The article is based on the following code: Active Learning on MNIST"
},
{
"code": null,
"e": 858,
"s": 576,
"text": "#load 4000 of MNIST data for train and 400 for testing(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()x_full = x_train[:4000] / 255y_full = y_train[:4000]x_test = x_test[:400] /255y_test = y_test[:400]x_full.shape, y_full.shape, x_test.shape, y_test.shape"
},
{
"code": null,
"e": 883,
"s": 858,
"text": "plt.imshow(x_full[3999])"
},
{
"code": null,
"e": 1210,
"s": 883,
"text": "I will use a subset of MNIST dataset which is 60K pictures of digits with labels and 10K test samples. For the purposes of quicker training, 4000 samples (pictures) are needed for training and 400 for a test (neural network will never see it during the training). For normalization, I divide the grayscale image points by 255."
},
{
"code": null,
"e": 1737,
"s": 1210,
"text": "#build computation graphx = tf.placeholder(tf.float32, [None, 28, 28])x_flat = tf.reshape(x, [-1, 28 * 28])y_ = tf.placeholder(tf.int32, [None])W = tf.Variable(tf.zeros([28 * 28, 10]), tf.float32)b = tf.Variable(tf.zeros([10]), tf.float32)y = tf.matmul(x_flat, W) + by_sm = tf.nn.softmax(y)loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y_, logits=y))train = tf.train.AdamOptimizer(0.1).minimize(loss)accuracy = tf.reduce_mean(tf.cast(tf.equal(y_, tf.cast(tf.argmax(y, 1), tf.int32)), tf.float32))"
},
{
"code": null,
"e": 2205,
"s": 1737,
"text": "As a framework, one can use the TensorFlow computation graph that will build ten neurons (for every digit). W and b are the weights for the neurons. A softmax output y_sm will help with the probabilities (confidence) of digits. The loss will be a typical “softmaxed” cross entropy between the predicted and labeled data. The choice for the optimizer is a popular Adam, the learning rate is almost default — 0.1. As a main metric I will use accuracy over test dataset."
},
{
"code": null,
"e": 3527,
"s": 2205,
"text": "def reset(): '''Initialize data sets and session''' global x_labeled, y_labeled, x_unlabeled, y_unlabeled x_labeled = x_full[:0] y_labeled = y_full[:0] x_unlabeled = x_full y_unlabeled = y_full tf.global_variables_initializer().run() tf.local_variables_initializer().run() def fit(): '''Train current labeled dataset until overfit.''' trial_count = 10 acc = sess.run(accuracy, feed_dict={x:x_test, y_:y_test}) weights = sess.run([W, b]) while trial_count > 0: sess.run(train, feed_dict={x:x_labeled, y_:y_labeled}) acc_new = sess.run(accuracy, feed_dict={x:x_test, y_:y_test}) if acc_new <= acc: trial_count -= 1 else: trial_count = 10 weights = sess.run([W, b]) acc = acc_new sess.run([W.assign(weights[0]), b.assign(weights[1])]) acc = sess.run(accuracy, feed_dict={x:x_test, y_:y_test}) print('Labels:', x_labeled.shape[0], '\\tAccuracy:', acc)def label_manually(n): '''Human powered labeling (actually copying from the prelabeled MNIST dataset).''' global x_labeled, y_labeled, x_unlabeled, y_unlabeled x_labeled = np.concatenate([x_labeled, x_unlabeled[:n]]) y_labeled = np.concatenate([y_labeled, y_unlabeled[:n]]) x_unlabeled = x_unlabeled[n:] y_unlabeled = y_unlabeled[n:]"
},
{
"code": null,
"e": 3702,
"s": 3527,
"text": "Here I define these three procedures for more convenient coding.reset() — empties the labeled dataset, puts all data in the unlabeled dataset and resets the session variables"
},
{
"code": null,
"e": 3993,
"s": 3702,
"text": "fit() — runs a training attempting to reach the best accuracy. If it cannot improve during the first ten attempts, the training stops at the last best result. We cannot use just any big number of training epochs as the model tends to quickly overfit or needs an intensive L2 regularization."
},
{
"code": null,
"e": 4140,
"s": 3993,
"text": "label_manually() — this is an emulation of human data labeling. Actually, we take the labels from the MNIST dataset that has been labeled already."
},
{
"code": null,
"e": 4200,
"s": 4140,
"text": "#train full dataset of 1000reset()label_manually(4000)fit()"
},
{
"code": null,
"e": 4315,
"s": 4200,
"text": "If we are so lucky as to have enough resources to label the whole dataset, we will receive the 92.25% of accuracy."
},
{
"code": null,
"e": 4502,
"s": 4315,
"text": "#apply clusteringkmeans = tf.contrib.factorization.KMeansClustering(10, use_mini_batch=False)kmeans.train(lambda: tf.train.limit_epochs(x_full.reshape(4000, 784).astype(np.float32), 10))"
},
{
"code": null,
"e": 4626,
"s": 4502,
"text": "centers = kmeans.cluster_centers().reshape([10, 28, 28])plt.imshow(np.concatenate([centers[i] for i in range(10)], axis=1))"
},
{
"code": null,
"e": 4946,
"s": 4626,
"text": "Here I try to use the k-means clustering to find a group of digits and use this information for automatic labeling. I run the Tensorflow clustering estimator and then visualize the resulting ten centroids. As you can see, the result is far from perfect — digit “9” appears three times, sometimes mixed with “8” and “3”."
},
{
"code": null,
"e": 5003,
"s": 4946,
"text": "#try to run on random 400reset()label_manually(400)fit()"
},
{
"code": null,
"e": 5144,
"s": 5003,
"text": "Let’s try to label only 10% of data (400 samples) and we will receive 83.75% of accuracy that is pretty far from 92.25% of the ground truth."
},
{
"code": null,
"e": 5196,
"s": 5144,
"text": "#now try to run on 10reset()label_manually(10)fit()"
},
{
"code": null,
"e": 5497,
"s": 5196,
"text": "#pass unlabeled rest 3990 through the early modelres = sess.run(y_sm, feed_dict={x:x_unlabeled})#find less confident samplespmax = np.amax(res, axis=1)pidx = np.argsort(pmax)#sort the unlabeled corpus on the confidencyx_unlabeled = x_unlabeled[pidx]y_unlabeled = y_unlabeled[pidx]plt.plot(pmax[pidx])"
},
{
"code": null,
"e": 6100,
"s": 5497,
"text": "Now we will label the same 10% of data (400 samples) using active learning. To do that, we take one batch out of the 10 samples and train a very primitive model. Then, we pass the rest of the data (3990 samples) through this model and evaluate the maximum softmax output. This will show what is the probability that the selected class is the correct answer (in other words, the confidence of the neural network). After sorting, we can see on the plot that the distribution of confidence varies from 20% to 100%. The idea is to select the next batch for labeling exactly from the LESS CONFIDENT samples."
},
{
"code": null,
"e": 6373,
"s": 6100,
"text": "#do the same in a loop for 400 samplesfor i in range(39): label_manually(10) fit() res = sess.run(y_sm, feed_dict={x:x_unlabeled}) pmax = np.amax(res, axis=1) pidx = np.argsort(pmax) x_unlabeled = x_unlabeled[pidx] y_unlabeled = y_unlabeled[pidx]"
},
{
"code": null,
"e": 6574,
"s": 6373,
"text": "After running such a procedure for the 40 batches of 10 samples, we can see that the resulting accuracy is almost 90%. This is far more than the 83.75% achieved in the case with randomly labeled data."
},
{
"code": null,
"e": 6910,
"s": 6574,
"text": "#pass rest unlabeled data through the model and try to autolabelres = sess.run(y_sm, feed_dict={x:x_unlabeled})y_autolabeled = res.argmax(axis=1)x_labeled = np.concatenate([x_labeled, x_unlabeled])y_labeled = np.concatenate([y_labeled, y_autolabeled])#train on 400 labeled by active learning and 3600 stochasticly autolabeled datafit()"
},
{
"code": null,
"e": 7174,
"s": 6910,
"text": "The classical way would be to run the rest of the dataset through the existing model and automatically label the data. Then, pushing it in the training process would maybe help to better tune the model. In our case though, it did not give us an any better result."
},
{
"code": null,
"e": 7276,
"s": 7174,
"text": "My approach is to do the same but, as in the active learning, taking in consideration the confidence:"
},
{
"code": null,
"e": 7620,
"s": 7276,
"text": "#pass rest of unlabeled (3600) data trough the model for automatic labeling and show most confident samplesres = sess.run(y_sm, feed_dict={x:x_unlabeled})y_autolabeled = res.argmax(axis=1)pmax = np.amax(res, axis=1)pidx = np.argsort(pmax)#sort by confidencyx_unlabeled = x_unlabeled[pidx]y_autolabeled = y_autolabeled[pidx]plt.plot(pmax[pidx])"
},
{
"code": null,
"e": 7837,
"s": 7620,
"text": "#automatically label 10 most confident sample and train for itx_labeled = np.concatenate([x_labeled, x_unlabeled[-10:]])y_labeled = np.concatenate([y_labeled, y_autolabeled[-10:]])x_unlabeled = x_unlabeled[:-10]fit()"
},
{
"code": null,
"e": 8064,
"s": 7837,
"text": "Here we run the rest of unlabeled data through model evaluation and we still can see that the confidence differs for the rest of the samples. Thus, the idea is to take a batch of ten MOST CONFIDENT samples and train the model."
},
{
"code": null,
"e": 8536,
"s": 8064,
"text": "#run rest of unlabelled samples starting from most confidentfor i in range(359): res = sess.run(y_sm, feed_dict={x:x_unlabeled}) y_autolabeled = res.argmax(axis=1) pmax = np.amax(res, axis=1) pidx = np.argsort(pmax) x_unlabeled = x_unlabeled[pidx] y_autolabeled = y_autolabeled[pidx] x_labeled = np.concatenate([x_labeled, x_unlabeled[-10:]]) y_labeled = np.concatenate([y_labeled, y_autolabeled[-10:]]) x_unlabeled = x_unlabeled[:-10] fit()"
},
{
"code": null,
"e": 8602,
"s": 8536,
"text": "This process takes some time and gives us extra 0.8% of accuracy."
},
{
"code": null,
"e": 8722,
"s": 8602,
"text": "Experiment Accuracy4000 samples 92.25%400 random samples 83.75%400 active learned samples 89.75% + auto-labeling 90.50%"
},
{
"code": null,
"e": 9142,
"s": 8722,
"text": "Of course, this approach has its drawbacks, like the heavy use of computation resources and the fact that a special procedure is required for data labeling mixed with early model evaluation. Also, for the testing purposes data needs to be labeled as well. However, if the cost of a label is high (especially for NLP, CV projects), this method can save a significant amount of resources and drive better project results."
},
{
"code": null,
"e": 9266,
"s": 9142,
"text": "If you have personal questions contact me on Linkedin or Facebook, where sometimes I post short news and thoughts about AI."
}
] |
How to change the legend title in ggplot2 in R?
|
In ggplot2, by default the legend title is the title of the grouping column of the data frame. If we want to change that title then scale_color_discrete function. For example, if we have a data frame called df that contains two numerical columns x and y and one grouping column say group then the scatterplot with a different legend title can be created by using the below command −
ggplot(df,aes(x,y,color=group))+geom_point()+scale_color_discrete("Gender")
Consider the below data frame −
Live Demo
> x<-rnorm(20)
> y<-rnorm(20)
> grp<-sample(c("Male","Female"),20,replace=TRUE)
> df<-data.frame(x,y,grp)
> df
x y grp
1 -2.27846496 0.8121008 Male
2 -1.75112768 -0.1718679 Female
3 -0.12504696 -0.3265867 Female
4 0.10895490 -0.2015613 Female
5 -1.51196132 0.8480887 Male
6 1.68028497 -1.1329240 Male
7 -0.65238760 -0.9495177 Male
8 0.84725937 1.4825983 Female
9 0.53645228 2.1630524 Female
10 -2.04814594 0.4503883 Female
11 -0.37741279 -1.1621875 Male
12 0.79303416 -0.1804637 Male
13 -0.02095395 -0.9740427 Male
14 0.61453646 1.0327821 Female
15 -0.32875489 -0.4071753 Male
16 0.94227215 2.0651996 Female
17 1.79740910 0.8630703 Male
18 1.09133101 -0.1053076 Male
19 0.33748223 -0.1238961 Female
20 -0.10264760 1.5338488 Male
Loading ggplot2 package and creating a point chart between x and y with grouping of grp −
> library(ggplot2)
> ggplot(df,aes(x,y,color=grp))+geom_point()
Creating a point chart between x and y with grouping of grp and legend title Gender −
> ggplot(df,aes(x,y,color=grp))+geom_point()+scale_color_discrete("Gender")
|
[
{
"code": null,
"e": 1445,
"s": 1062,
"text": "In ggplot2, by default the legend title is the title of the grouping column of the data frame. If we want to change that title then scale_color_discrete function. For example, if we have a data frame called df that contains two numerical columns x and y and one grouping column say group then the scatterplot with a different legend title can be created by using the below command −"
},
{
"code": null,
"e": 1521,
"s": 1445,
"text": "ggplot(df,aes(x,y,color=group))+geom_point()+scale_color_discrete(\"Gender\")"
},
{
"code": null,
"e": 1553,
"s": 1521,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1563,
"s": 1553,
"text": "Live Demo"
},
{
"code": null,
"e": 1674,
"s": 1563,
"text": "> x<-rnorm(20)\n> y<-rnorm(20)\n> grp<-sample(c(\"Male\",\"Female\"),20,replace=TRUE)\n> df<-data.frame(x,y,grp)\n> df"
},
{
"code": null,
"e": 2367,
"s": 1674,
"text": " x y grp\n1 -2.27846496 0.8121008 Male\n2 -1.75112768 -0.1718679 Female\n3 -0.12504696 -0.3265867 Female\n4 0.10895490 -0.2015613 Female\n5 -1.51196132 0.8480887 Male\n6 1.68028497 -1.1329240 Male\n7 -0.65238760 -0.9495177 Male\n8 0.84725937 1.4825983 Female\n9 0.53645228 2.1630524 Female\n10 -2.04814594 0.4503883 Female\n11 -0.37741279 -1.1621875 Male\n12 0.79303416 -0.1804637 Male\n13 -0.02095395 -0.9740427 Male\n14 0.61453646 1.0327821 Female\n15 -0.32875489 -0.4071753 Male\n16 0.94227215 2.0651996 Female\n17 1.79740910 0.8630703 Male\n18 1.09133101 -0.1053076 Male\n19 0.33748223 -0.1238961 Female\n20 -0.10264760 1.5338488 Male"
},
{
"code": null,
"e": 2457,
"s": 2367,
"text": "Loading ggplot2 package and creating a point chart between x and y with grouping of grp −"
},
{
"code": null,
"e": 2521,
"s": 2457,
"text": "> library(ggplot2)\n> ggplot(df,aes(x,y,color=grp))+geom_point()"
},
{
"code": null,
"e": 2607,
"s": 2521,
"text": "Creating a point chart between x and y with grouping of grp and legend title Gender −"
},
{
"code": null,
"e": 2683,
"s": 2607,
"text": "> ggplot(df,aes(x,y,color=grp))+geom_point()+scale_color_discrete(\"Gender\")"
}
] |
Kotlin - Inheritance
|
Inheritance can be defined as the process where one class acquires the members (methods and properties) of another class. With the use of inheritance the information is made manageable in a hierarchical order.
A class which inherits the members of other class is known as subclass (derived class or child class) and the class whose members are being inherited is known as superclass (base class or parent class).
Inheritance is one of the key features of object-oriented programming which allows user to create a new class from an existing class. Inheritance we can inherit all the features from the base class and can have additional features of its own as well.
All classes in Kotlin have a common superclass called Any, which is the default superclass for a class with no supertypes declared:
class Example // Implicitly inherits from Any
Kotlin superclass Any has three methods: equals(), hashCode(), and toString(). Thus, these methods are defined for all Kotlin classes.
Everything in Kotlin is by default final, hence, we need to use the keyword open in front of the class declaration to make it inheritable for other classes. Kotlin uses operator ":" to inherit a class.
Take a look at the following example of inheritance.
open class ABC {
fun think () {
println("Hey!! i am thiking ")
}
}
class BCD: ABC(){ // inheritence happend using default constructor
}
fun main(args: Array<String>) {
var a = BCD()
a.think()
}
When you run the above Kotlin program, it will generate the following output:
Hey!! i am thiking
Now, what if we want to override the think() method in the child class. Then, we need to consider the following example where we are creating two classes and override one of its function into the child class.
open class ABC {
open fun think () {
println("Hey!! i am thinking ")
}
}
class BCD: ABC() { // inheritance happens using default constructor
override fun think() {
println("I am from Child")
}
}
fun main(args: Array<String>) {
var a = BCD()
a.think()
}
When you run the above Kotlin program, it will generate the following output:
I am from Child
A member marked with keyword override is itself open, so it may be overridden in subclasses. If you want to prohibit re-overriding it then you must make it final as follows:
class BCD: ABC() {
final override fun think() {
println("I am from Child")
}
}
The overriding mechanism works on properties in the same way that it does on methods. Properties declared on a superclass that are then redeclared on a derived class must be prefaced with the keyword override, and they must have a compatible type.
open class ABC {
open val count: Int = 0
open fun think () {
println("Hey!! i am thinking ")
}
}
class BCD: ABC() {
override val count: Int
init{
count = 100
}
override fun think() {
println("I am from Child")
}
fun displayCount(){
println("Count value is $count")
}
}
fun main(args: Array<String>) {
var a = BCD()
a.displayCount()
}
When you run the above Kotlin program, it will generate the following output:
Count value is 100
We can also can use the override keyword as part of the property declaration in a primary constructor. Following example makes the use of primary constructor to override count property, which will take default value as 400 in case we do not pass any value to the constructor:
open class ABC {
open val count: Int = 0
open fun think () {
println("Hey!! i am thinking ")
}
}
class BCD(override val count: Int = 400): ABC() {
override fun think() {
println("I am from Child")
}
fun displayCount(){
println("Count value is $count")
}
}
fun main(args: Array<String>) {
var a = BCD(200)
var b = BCD()
a.displayCount()
b.displayCount()
}
When you run the above Kotlin program, it will generate the following output:
Count value is 200
Count value is 400
When we create an object of a derived class then constructor initialization starts from the base class. Which means first of all base class properties will be initialized, after that any derived class instructor will be called and same applies to any further derived classes.
This means that when the base class constructor is executed, the properties declared or overridden in the derived class have not yet been initialized.
open class Base {
init{
println("I am in Base class")
}
}
open class Child: Base() {
init{
println("I am in Child class")
}
}
class GrandChild: Child() {
init{
println("I am in Grand Child class")
}
}
fun main(args: Array<String>) {
var a = GrandChild()
}
When you run the above Kotlin program, it will generate the following output:
I am in Base class
I am in Child class
I am in Grand Child class
Code in a derived class can call its superclass functions and properties directly using the super keyword:
open class Base() {
open val name:String
init{
name = "Base"
}
open fun displayName(){
println("I am in " + this.name)
}
}
class Child(): Base() {
override fun displayName(){
super.displayName()
println("I am in " + super.name)
}
}
fun main(args: Array<String>) {
var a = Child()
a.displayName()
}
When you run the above Kotlin program, it will generate the following output:
I am in Base
I am in Base
If a child class inherits multiple implementations of the same member from its immediate superclasses, then it must override this member and provide its own implementation.
This is different from a child class which inherits members from a single parent, in such case case it is not mandatory for the child class to provide the implementation of all the open members.
open class Rectangle {
open fun draw() { /* ... */ }
}
interface Polygon {
fun draw() { /* ... */ } // interface members are 'open' by default
}
class Square() : Rectangle(), Polygon {
// The compiler requires draw() to be overridden:
override fun draw() {
super<Rectangle>.draw() // call to Rectangle.draw()
super<Polygon>.draw() // call to Polygon.draw()
}
}
It's fine to inherit from both Rectangle and Polygon, but both of them have their implementations of draw() method, so you need to override draw()in Square and provide a separate implementation for it to eliminate the ambiguity.
Q 1 - Which key is used to make a class inheritable:
A - abstract
B - override
C - open
D - None of the above
Kotlin uses keyword open to make any class or its members inheritable.
Q 2 - Which statement is correct from Kotlin inheritance point of view:
A - Kotlin allows to inherit multiple classes in a child class
B - Kotlin allows to override parent class properties and methods
C - Kotlin initializes properties of the classes in sequence starting from Base class to Child Class and then to Grand Child Class.
D - All the bove
All the given statements are correct from Kotlin inheritance point of view.
Q 3 - How we can access a Kotlin parent class member in the child class?
A - If it is open in the parent class then child class can override it and access it.
B - If it is not open then child class can access it using super.
C - A and B statements are correct
D - We can access Kotlin parent class members in child class without any restrictions.
Given statements A and B are correct regarding accessing parent class members in the child class.
68 Lectures
4.5 hours
Arnab Chakraborty
71 Lectures
5.5 hours
Frahaan Hussain
18 Lectures
1.5 hours
Mahmoud Ramadan
49 Lectures
6 hours
Catalin Stefan
49 Lectures
2.5 hours
Skillbakerystudios
22 Lectures
1 hours
CLEMENT OCHIENG
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2635,
"s": 2425,
"text": "Inheritance can be defined as the process where one class acquires the members (methods and properties) of another class. With the use of inheritance the information is made manageable in a hierarchical order."
},
{
"code": null,
"e": 2838,
"s": 2635,
"text": "A class which inherits the members of other class is known as subclass (derived class or child class) and the class whose members are being inherited is known as superclass (base class or parent class)."
},
{
"code": null,
"e": 3089,
"s": 2838,
"text": "Inheritance is one of the key features of object-oriented programming which allows user to create a new class from an existing class. Inheritance we can inherit all the features from the base class and can have additional features of its own as well."
},
{
"code": null,
"e": 3221,
"s": 3089,
"text": "All classes in Kotlin have a common superclass called Any, which is the default superclass for a class with no supertypes declared:"
},
{
"code": null,
"e": 3268,
"s": 3221,
"text": "class Example // Implicitly inherits from Any\n"
},
{
"code": null,
"e": 3403,
"s": 3268,
"text": "Kotlin superclass Any has three methods: equals(), hashCode(), and toString(). Thus, these methods are defined for all Kotlin classes."
},
{
"code": null,
"e": 3605,
"s": 3403,
"text": "Everything in Kotlin is by default final, hence, we need to use the keyword open in front of the class declaration to make it inheritable for other classes. Kotlin uses operator \":\" to inherit a class."
},
{
"code": null,
"e": 3658,
"s": 3605,
"text": "Take a look at the following example of inheritance."
},
{
"code": null,
"e": 3874,
"s": 3658,
"text": "open class ABC {\n fun think () {\n println(\"Hey!! i am thiking \")\n }\n}\nclass BCD: ABC(){ // inheritence happend using default constructor \n}\n\nfun main(args: Array<String>) {\n var a = BCD()\n a.think()\n}\n"
},
{
"code": null,
"e": 3952,
"s": 3874,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 3973,
"s": 3952,
"text": "Hey!! i am thiking \n"
},
{
"code": null,
"e": 4182,
"s": 3973,
"text": "Now, what if we want to override the think() method in the child class. Then, we need to consider the following example where we are creating two classes and override one of its function into the child class."
},
{
"code": null,
"e": 4468,
"s": 4182,
"text": "open class ABC {\n open fun think () {\n println(\"Hey!! i am thinking \")\n }\n}\nclass BCD: ABC() { // inheritance happens using default constructor \n override fun think() {\n println(\"I am from Child\")\n }\n}\nfun main(args: Array<String>) {\n var a = BCD()\n a.think()\n}\n"
},
{
"code": null,
"e": 4546,
"s": 4468,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 4564,
"s": 4546,
"text": "I am from Child \n"
},
{
"code": null,
"e": 4738,
"s": 4564,
"text": "A member marked with keyword override is itself open, so it may be overridden in subclasses. If you want to prohibit re-overriding it then you must make it final as follows:"
},
{
"code": null,
"e": 4830,
"s": 4738,
"text": "class BCD: ABC() {\n final override fun think() {\n println(\"I am from Child\")\n }\n}\n"
},
{
"code": null,
"e": 5078,
"s": 4830,
"text": "The overriding mechanism works on properties in the same way that it does on methods. Properties declared on a superclass that are then redeclared on a derived class must be prefaced with the keyword override, and they must have a compatible type."
},
{
"code": null,
"e": 5487,
"s": 5078,
"text": "open class ABC {\n open val count: Int = 0\n \n open fun think () {\n println(\"Hey!! i am thinking \")\n }\n}\nclass BCD: ABC() {\n override val count: Int\n \n init{\n count = 100\n }\n\n override fun think() {\n println(\"I am from Child\")\n }\n \n fun displayCount(){\n println(\"Count value is $count\")\n }\n}\nfun main(args: Array<String>) {\n var a = BCD()\n a.displayCount()\n}\n"
},
{
"code": null,
"e": 5565,
"s": 5487,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 5585,
"s": 5565,
"text": "Count value is 100\n"
},
{
"code": null,
"e": 5861,
"s": 5585,
"text": "We can also can use the override keyword as part of the property declaration in a primary constructor. Following example makes the use of primary constructor to override count property, which will take default value as 400 in case we do not pass any value to the constructor:"
},
{
"code": null,
"e": 6277,
"s": 5861,
"text": "open class ABC {\n open val count: Int = 0\n \n open fun think () {\n println(\"Hey!! i am thinking \")\n }\n}\nclass BCD(override val count: Int = 400): ABC() {\n\n override fun think() {\n println(\"I am from Child\")\n }\n \n fun displayCount(){\n println(\"Count value is $count\")\n }\n}\nfun main(args: Array<String>) {\n var a = BCD(200)\n var b = BCD()\n a.displayCount()\n b.displayCount()\n}\n"
},
{
"code": null,
"e": 6355,
"s": 6277,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 6394,
"s": 6355,
"text": "Count value is 200\nCount value is 400\n"
},
{
"code": null,
"e": 6670,
"s": 6394,
"text": "When we create an object of a derived class then constructor initialization starts from the base class. Which means first of all base class properties will be initialized, after that any derived class instructor will be called and same applies to any further derived classes."
},
{
"code": null,
"e": 6821,
"s": 6670,
"text": "This means that when the base class constructor is executed, the properties declared or overridden in the derived class have not yet been initialized."
},
{
"code": null,
"e": 7117,
"s": 6821,
"text": "open class Base {\n init{\n println(\"I am in Base class\")\n }\n}\nopen class Child: Base() {\n init{\n println(\"I am in Child class\")\n }\n}\nclass GrandChild: Child() {\n init{\n println(\"I am in Grand Child class\")\n }\n}\nfun main(args: Array<String>) {\n var a = GrandChild()\n}\n"
},
{
"code": null,
"e": 7195,
"s": 7117,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 7261,
"s": 7195,
"text": "I am in Base class\nI am in Child class\nI am in Grand Child class\n"
},
{
"code": null,
"e": 7368,
"s": 7261,
"text": "Code in a derived class can call its superclass functions and properties directly using the super keyword:"
},
{
"code": null,
"e": 7722,
"s": 7368,
"text": "open class Base() {\n open val name:String\n init{\n name = \"Base\"\n }\n open fun displayName(){\n println(\"I am in \" + this.name)\n }\n}\nclass Child(): Base() {\n override fun displayName(){\n super.displayName()\n println(\"I am in \" + super.name)\n \n }\n}\nfun main(args: Array<String>) {\n var a = Child()\n a.displayName()\n}\n"
},
{
"code": null,
"e": 7800,
"s": 7722,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 7827,
"s": 7800,
"text": "I am in Base\nI am in Base\n"
},
{
"code": null,
"e": 8000,
"s": 7827,
"text": "If a child class inherits multiple implementations of the same member from its immediate superclasses, then it must override this member and provide its own implementation."
},
{
"code": null,
"e": 8195,
"s": 8000,
"text": "This is different from a child class which inherits members from a single parent, in such case case it is not mandatory for the child class to provide the implementation of all the open members."
},
{
"code": null,
"e": 8595,
"s": 8195,
"text": "open class Rectangle {\n open fun draw() { /* ... */ }\n}\n\ninterface Polygon {\n fun draw() { /* ... */ } // interface members are 'open' by default\n}\n\nclass Square() : Rectangle(), Polygon {\n // The compiler requires draw() to be overridden:\n override fun draw() {\n super<Rectangle>.draw() // call to Rectangle.draw()\n super<Polygon>.draw() // call to Polygon.draw()\n }\n}\n"
},
{
"code": null,
"e": 8824,
"s": 8595,
"text": "It's fine to inherit from both Rectangle and Polygon, but both of them have their implementations of draw() method, so you need to override draw()in Square and provide a separate implementation for it to eliminate the ambiguity."
},
{
"code": null,
"e": 8877,
"s": 8824,
"text": "Q 1 - Which key is used to make a class inheritable:"
},
{
"code": null,
"e": 8890,
"s": 8877,
"text": "A - abstract"
},
{
"code": null,
"e": 8903,
"s": 8890,
"text": "B - override"
},
{
"code": null,
"e": 8912,
"s": 8903,
"text": "C - open"
},
{
"code": null,
"e": 8934,
"s": 8912,
"text": "D - None of the above"
},
{
"code": null,
"e": 9005,
"s": 8934,
"text": "Kotlin uses keyword open to make any class or its members inheritable."
},
{
"code": null,
"e": 9077,
"s": 9005,
"text": "Q 2 - Which statement is correct from Kotlin inheritance point of view:"
},
{
"code": null,
"e": 9140,
"s": 9077,
"text": "A - Kotlin allows to inherit multiple classes in a child class"
},
{
"code": null,
"e": 9206,
"s": 9140,
"text": "B - Kotlin allows to override parent class properties and methods"
},
{
"code": null,
"e": 9338,
"s": 9206,
"text": "C - Kotlin initializes properties of the classes in sequence starting from Base class to Child Class and then to Grand Child Class."
},
{
"code": null,
"e": 9355,
"s": 9338,
"text": "D - All the bove"
},
{
"code": null,
"e": 9431,
"s": 9355,
"text": "All the given statements are correct from Kotlin inheritance point of view."
},
{
"code": null,
"e": 9504,
"s": 9431,
"text": "Q 3 - How we can access a Kotlin parent class member in the child class?"
},
{
"code": null,
"e": 9590,
"s": 9504,
"text": "A - If it is open in the parent class then child class can override it and access it."
},
{
"code": null,
"e": 9657,
"s": 9590,
"text": "B - If it is not open then child class can access it using super. "
},
{
"code": null,
"e": 9692,
"s": 9657,
"text": "C - A and B statements are correct"
},
{
"code": null,
"e": 9779,
"s": 9692,
"text": "D - We can access Kotlin parent class members in child class without any restrictions."
},
{
"code": null,
"e": 9877,
"s": 9779,
"text": "Given statements A and B are correct regarding accessing parent class members in the child class."
},
{
"code": null,
"e": 9912,
"s": 9877,
"text": "\n 68 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 9931,
"s": 9912,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 9966,
"s": 9931,
"text": "\n 71 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 9983,
"s": 9966,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 10018,
"s": 9983,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10035,
"s": 10018,
"text": " Mahmoud Ramadan"
},
{
"code": null,
"e": 10068,
"s": 10035,
"text": "\n 49 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 10084,
"s": 10068,
"text": " Catalin Stefan"
},
{
"code": null,
"e": 10119,
"s": 10084,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 10139,
"s": 10119,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 10172,
"s": 10139,
"text": "\n 22 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10189,
"s": 10172,
"text": " CLEMENT OCHIENG"
},
{
"code": null,
"e": 10196,
"s": 10189,
"text": " Print"
},
{
"code": null,
"e": 10207,
"s": 10196,
"text": " Add Notes"
}
] |
How to create input Pop-Ups (Dialog) and get input from user in Java?
|
Use the JOptionPane.showInputDialog() to get input from user in a dialog box like “Which sports you play the most”, “What is your name”, etc. The following is an example to create input Pop-Ups (Dialog) and get input from user −
package my;
import javax.swing.JOptionPane;
public class SwingDemo {
public static void main(String[] args) {
String[] sports = { "Football", "Cricket", "Squash", "Baseball", "Fencing", "Volleyball", "Basketball" };
String res = (String) JOptionPane.showInputDialog(null, "Which sports you play the most?", "Sports",
JOptionPane.PLAIN_MESSAGE, null, sports, sports[0]);
switch (res) {
case "Football" −
System.out.println("I Love Football");
break;
case "Cricket" −
System.out.println("I Love Cricket");
break;
case "Squash" −
System.out.println("I Love Squash");
break;
case "Baseball" −
System.out.println("I Love Baseball");
break;
case "Fencing" −
System.out.println("I Love Fencing");
break;
case "Volleyball" −
System.out.println("I Love Volleyball");
break;
case "Basketball" −
System.out.println("I Love Basketball");
break;
}
}
}
Now select any of the item from above and click OK to display the selected item in the Console.
We selected “Volleyball” −
The option selected above visible in Console −
|
[
{
"code": null,
"e": 1291,
"s": 1062,
"text": "Use the JOptionPane.showInputDialog() to get input from user in a dialog box like “Which sports you play the most”, “What is your name”, etc. The following is an example to create input Pop-Ups (Dialog) and get input from user −"
},
{
"code": null,
"e": 2379,
"s": 1291,
"text": "package my;\nimport javax.swing.JOptionPane;\npublic class SwingDemo {\n public static void main(String[] args) {\n String[] sports = { \"Football\", \"Cricket\", \"Squash\", \"Baseball\", \"Fencing\", \"Volleyball\", \"Basketball\" };\n String res = (String) JOptionPane.showInputDialog(null, \"Which sports you play the most?\", \"Sports\",\n JOptionPane.PLAIN_MESSAGE, null, sports, sports[0]);\n switch (res) {\n case \"Football\" −\n System.out.println(\"I Love Football\");\n break;\n case \"Cricket\" −\n System.out.println(\"I Love Cricket\");\n break;\n case \"Squash\" −\n System.out.println(\"I Love Squash\");\n break;\n case \"Baseball\" −\n System.out.println(\"I Love Baseball\");\n break;\n case \"Fencing\" −\n System.out.println(\"I Love Fencing\");\n break;\n case \"Volleyball\" −\n System.out.println(\"I Love Volleyball\");\n break;\n case \"Basketball\" −\n System.out.println(\"I Love Basketball\");\n break;\n }\n }\n}"
},
{
"code": null,
"e": 2475,
"s": 2379,
"text": "Now select any of the item from above and click OK to display the selected item in the Console."
},
{
"code": null,
"e": 2502,
"s": 2475,
"text": "We selected “Volleyball” −"
},
{
"code": null,
"e": 2549,
"s": 2502,
"text": "The option selected above visible in Console −"
}
] |
Compute sum of digits in all numbers from 1 to n - GeeksforGeeks
|
14 May, 2021
Given a number n, find the sum of digits in all numbers from 1 to n. Examples:
Input: n = 5
Output: Sum of digits in numbers from 1 to 5 = 15
Input: n = 12
Output: Sum of digits in numbers from 1 to 12 = 51
Input: n = 328
Output: Sum of digits in numbers from 1 to 328 = 3241
Naive Solution: A naive solution is to go through every number x from 1 to n and compute the sum in x by traversing all digits of x. Below is the implementation of this idea.
C++
Java
Python3
C#
PHP
Javascript
// A Simple C++ program to compute sum of digits in numbers from 1 to n#include<bits/stdc++.h>using namespace std; int sumOfDigits(int ); // Returns sum of all digits in numbers from 1 to nint sumOfDigitsFrom1ToN(int n){ int result = 0; // initialize result // One by one compute sum of digits in every number from // 1 to n for (int x = 1; x <= n; x++) result += sumOfDigits(x); return result;} // A utility function to compute sum of digits in a// given number xint sumOfDigits(int x){ int sum = 0; while (x != 0) { sum += x %10; x = x /10; } return sum;} // Driver Programint main(){ int n = 328; cout << "Sum of digits in numbers from 1 to " << n << " is " << sumOfDigitsFrom1ToN(n); return 0;}
// A Simple JAVA program to compute sum of// digits in numbers from 1 to nimport java.io.*; class GFG { // Returns sum of all digits in numbers // from 1 to n static int sumOfDigitsFrom1ToN(int n) { int result = 0; // initialize result // One by one compute sum of digits // in every number from 1 to n for (int x = 1; x <= n; x++) result += sumOfDigits(x); return result; } // A utility function to compute sum // of digits in a given number x static int sumOfDigits(int x) { int sum = 0; while (x != 0) { sum += x % 10; x = x / 10; } return sum; } // Driver Program public static void main(String args[]) { int n = 328; System.out.println("Sum of digits in numbers" +" from 1 to " + n + " is " + sumOfDigitsFrom1ToN(n)); }} /*This code is contributed by Nikita Tiwari.*/
# A Simple Python program to compute sum# of digits in numbers from 1 to n # Returns sum of all digits in numbers# from 1 to ndef sumOfDigitsFrom1ToN(n) : result = 0 # initialize result # One by one compute sum of digits # in every number from 1 to n for x in range(1, n+1) : result = result + sumOfDigits(x) return result # A utility function to compute sum of# digits in a given number xdef sumOfDigits(x) : sum = 0 while (x != 0) : sum = sum + x % 10 x = x // 10 return sum # Driver Programn = 328print("Sum of digits in numbers from 1 to", n, "is", sumOfDigitsFrom1ToN(n)) # This code is contributed by Nikita Tiwari.
// A Simple C# program to compute sum of// digits in numbers from 1 to n using System; public class GFG { // Returns sum of all digits in numbers // from 1 to n static int sumOfDigitsFrom1ToN(int n) { // initialize result int result = 0; // One by one compute sum of digits // in every number from 1 to n for (int x = 1; x <= n; x++) result += sumOfDigits(x); return result; } // A utility function to compute sum // of digits in a given number x static int sumOfDigits(int x) { int sum = 0; while (x != 0) { sum += x % 10; x = x / 10; } return sum; } // Driver Program public static void Main() { int n = 328; Console.WriteLine("Sum of digits" + " in numbers from 1 to " + n + " is " + sumOfDigitsFrom1ToN(n)); }} // This code is contributed by shiv_bhakt.
<?php // A Simple php program to compute sum//of digits in numbers from 1 to n // Returns sum of all digits in// numbers from 1 to nfunction sumOfDigitsFrom1ToN($n){ $result = 0; // initialize result // One by one compute sum of digits // in every number from 1 to n for ($x = 1; $x <= $n; $x++) $result += sumOfDigits($x); return $result;} // A utility function to compute sum// of digits in a given number xfunction sumOfDigits($x){ $sum = 0; while ($x != 0) { $sum += $x %10; $x = $x /10; } return $sum;} // Driver Program $n = 328; echo "Sum of digits in numbers from" . " 1 to " . $n . " is " . sumOfDigitsFrom1ToN($n); // This code is contributed by ajit?>
<script> // A Simple Javascript program to compute sum of // digits in numbers from 1 to n // Returns sum of all digits in numbers // from 1 to n function sumOfDigitsFrom1ToN(n) { // initialize result let result = 0; // One by one compute sum of digits // in every number from 1 to n for (let x = 1; x <= n; x++) result += sumOfDigits(x); return result; } // A utility function to compute sum // of digits in a given number x function sumOfDigits(x) { let sum = 0; while (x != 0) { sum += x % 10; x = parseInt(x / 10, 10); } return sum; } let n = 328; document.write("Sum of digits" + " in numbers from 1 to " + n + " is " + sumOfDigitsFrom1ToN(n)); // This code is contributed by divyeshrabadiya07. </script>
Output:
Sum of digits in numbers from 1 to 328 is 3241
Efficient Solution: Above is a naive solution. We can do it more efficiently by finding a pattern.Let us take few examples.
sum(9) = 1 + 2 + 3 + 4 ........... + 9
= 9*10/2
= 45
sum(99) = 45 + (10 + 45) + (20 + 45) + ..... (90 + 45)
= 45*10 + (10 + 20 + 30 ... 90)
= 45*10 + 10(1 + 2 + ... 9)
= 45*10 + 45*10
= sum(9)*10 + 45*10
sum(999) = sum(99)*10 + 45*100
In general, we can compute sum(10d – 1) using the below formula
sum(10d - 1) = sum(10d-1 - 1) * 10 + 45*(10d-1)
In the below implementation, the above formula is implemented using dynamic programming as there are overlapping subproblems. The above formula is one core step of the idea. Below is the complete algorithm
Algorithm: sum(n)
1) Find number of digits minus one in n. Let this value be 'd'.
For 328, d is 2.
2) Compute some of digits in numbers from 1 to 10d - 1.
Let this sum be w. For 328, we compute sum of digits from 1 to
99 using above formula.
3) Find Most significant digit (msd) in n. For 328, msd is 3.
4) Overall sum is sum of following terms
a) Sum of digits in 1 to "msd * 10d - 1". For 328, sum of
digits in numbers from 1 to 299.
For 328, we compute 3*sum(99) + (1 + 2)*100. Note that sum of
sum(299) is sum(99) + sum of digits from 100 to 199 + sum of digits
from 200 to 299.
Sum of 100 to 199 is sum(99) + 1*100 and sum of 299 is sum(99) + 2*100.
In general, this sum can be computed as w*msd + (msd*(msd-1)/2)*10d
b) Sum of digits in msd * 10d to n. For 328, sum of digits in
300 to 328.
For 328, this sum is computed as 3*29 + recursive call "sum(28)"
In general, this sum can be computed as msd * (n % (msd*10d) + 1)
+ sum(n % (10d))
Below is the implementation of the above algorithm.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to compute sum of digits in numbers from 1 to n#include<bits/stdc++.h>using namespace std; // Function to computer sum of digits in numbers from 1 to n// Comments use example of 328 to explain the codeint sumOfDigitsFrom1ToN(int n){ // base case: if n<10 return sum of // first n natural numbers if (n<10) return n*(n+1)/2; // d = number of digits minus one in n. For 328, d is 2 int d = log10(n); // computing sum of digits from 1 to 10^d-1, // d=1 a[0]=0; // d=2 a[1]=sum of digit from 1 to 9 = 45 // d=3 a[2]=sum of digit from 1 to 99 = a[1]*10 + 45*10^1 = 900 // d=4 a[3]=sum of digit from 1 to 999 = a[2]*10 + 45*10^2 = 13500 int *a = new int[d+1]; a[0] = 0, a[1] = 45; for (int i=2; i<=d; i++) a[i] = a[i-1]*10 + 45*ceil(pow(10,i-1)); // computing 10^d int p = ceil(pow(10, d)); // Most significant digit (msd) of n, // For 328, msd is 3 which can be obtained using 328/100 int msd = n/p; // EXPLANATION FOR FIRST and SECOND TERMS IN BELOW LINE OF CODE // First two terms compute sum of digits from 1 to 299 // (sum of digits in range 1-99 stored in a[d]) + // (sum of digits in range 100-199, can be calculated as 1*100 + a[d] // (sum of digits in range 200-299, can be calculated as 2*100 + a[d] // The above sum can be written as 3*a[d] + (1+2)*100 // EXPLANATION FOR THIRD AND FOURTH TERMS IN BELOW LINE OF CODE // The last two terms compute sum of digits in number from 300 to 328 // The third term adds 3*29 to sum as digit 3 occurs in all numbers // from 300 to 328 // The fourth term recursively calls for 28 return msd*a[d] + (msd*(msd-1)/2)*p + msd*(1+n%p) + sumOfDigitsFrom1ToN(n%p);} // Driver Programint main(){ int n = 328; cout << "Sum of digits in numbers from 1 to " << n << " is " << sumOfDigitsFrom1ToN(n); return 0;}
// JAVA program to compute sum of digits// in numbers from 1 to nimport java.io.*;import java.math.*; class GFG{ // Function to computer sum of digits in // numbers from 1 to n. Comments use // example of 328 to explain the code static int sumOfDigitsFrom1ToN(int n) { // base case: if n<10 return sum of // first n natural numbers if (n < 10) return (n * (n + 1) / 2); // d = number of digits minus one in // n. For 328, d is 2 int d = (int)(Math.log10(n)); // computing sum of digits from 1 to 10^d-1, // d=1 a[0]=0; // d=2 a[1]=sum of digit from 1 to 9 = 45 // d=3 a[2]=sum of digit from 1 to 99 = // a[1]*10 + 45*10^1 = 900 // d=4 a[3]=sum of digit from 1 to 999 = // a[2]*10 + 45*10^2 = 13500 int a[] = new int[d+1]; a[0] = 0; a[1] = 45; for (int i = 2; i <= d; i++) a[i] = a[i-1] * 10 + 45 * (int)(Math.ceil(Math.pow(10, i-1))); // computing 10^d int p = (int)(Math.ceil(Math.pow(10, d))); // Most significant digit (msd) of n, // For 328, msd is 3 which can be obtained // using 328/100 int msd = n / p; // EXPLANATION FOR FIRST and SECOND TERMS IN // BELOW LINE OF CODE // First two terms compute sum of digits from // 1 to 299 // (sum of digits in range 1-99 stored in a[d]) + // (sum of digits in range 100-199, can be // calculated as 1*100 + a[d] // (sum of digits in range 200-299, can be // calculated as 2*100 + a[d] // The above sum can be written as 3*a[d] + // (1+2)*100 // EXPLANATION FOR THIRD AND FOURTH TERMS IN // BELOW LINE OF CODE // The last two terms compute sum of digits in // number from 300 to 328. The third term adds // 3*29 to sum as digit 3 occurs in all numbers // from 300 to 328. The fourth term recursively // calls for 28 return (msd * a[d] + (msd * (msd - 1) / 2) * p + msd * (1 + n % p) + sumOfDigitsFrom1ToN(n % p)); } // Driver Program public static void main(String args[]) { int n = 328; System.out.println("Sum of digits in numbers " + "from 1 to " +n + " is " + sumOfDigitsFrom1ToN(n)); }} /*This code is contributed by Nikita Tiwari.*/
# PYTHON 3 program to compute sum of digits# in numbers from 1 to nimport math # Function to computer sum of digits in# numbers from 1 to n. Comments use example# of 328 to explain the codedef sumOfDigitsFrom1ToN( n) : # base case: if n<10 return sum of # first n natural numbers if (n<10) : return (n*(n+1)/2) # d = number of digits minus one in n. # For 328, d is 2 d = (int)(math.log10(n)) """computing sum of digits from 1 to 10^d-1, d=1 a[0]=0; d=2 a[1]=sum of digit from 1 to 9 = 45 d=3 a[2]=sum of digit from 1 to 99 = a[1]*10 + 45*10^1 = 900 d=4 a[3]=sum of digit from 1 to 999 = a[2]*10 + 45*10^2 = 13500""" a = [0] * (d + 1) a[0] = 0 a[1] = 45 for i in range(2, d+1) : a[i] = a[i-1] * 10 + 45 * (int)(math.ceil(math.pow(10,i-1))) # computing 10^d p = (int)(math.ceil(math.pow(10, d))) # Most significant digit (msd) of n, # For 328, msd is 3 which can be obtained # using 328/100 msd = n//p """EXPLANATION FOR FIRST and SECOND TERMS IN BELOW LINE OF CODE First two terms compute sum of digits from 1 to 299 (sum of digits in range 1-99 stored in a[d]) + (sum of digits in range 100-199, can be calculated as 1*100 + a[d]. (sum of digits in range 200-299, can be calculated as 2*100 + a[d] The above sum can be written as 3*a[d] + (1+2)*100 EXPLANATION FOR THIRD AND FOURTH TERMS IN BELOW LINE OF CODE The last two terms compute sum of digits in number from 300 to 328. The third term adds 3*29 to sum as digit 3 occurs in all numbers from 300 to 328. The fourth term recursively calls for 28""" return (int)(msd * a[d] + (msd*(msd-1) // 2) * p + msd * (1 + n % p) + sumOfDigitsFrom1ToN(n % p)) # Driver Programn = 328print("Sum of digits in numbers from 1 to", n ,"is",sumOfDigitsFrom1ToN(n)) # This code is contributed by Nikita Tiwari.
// C# program to compute sum of digits// in numbers from 1 to n using System; public class GFG { // Function to computer sum of digits in // numbers from 1 to n. Comments use // example of 328 to explain the code static int sumOfDigitsFrom1ToN(int n) { // base case: if n<10 return sum of // first n natural numbers if (n < 10) return (n * (n + 1) / 2); // d = number of digits minus one in // n. For 328, d is 2 int d = (int)(Math.Log(n) / Math.Log(10)); // computing sum of digits from 1 to 10^d-1, // d=1 a[0]=0; // d=2 a[1]=sum of digit from 1 to 9 = 45 // d=3 a[2]=sum of digit from 1 to 99 = // a[1]*10 + 45*10^1 = 900 // d=4 a[3]=sum of digit from 1 to 999 = // a[2]*10 + 45*10^2 = 13500 int[] a = new int[d+1]; a[0] = 0; a[1] = 45; for (int i = 2; i <= d; i++) a[i] = a[i-1] * 10 + 45 * (int)(Math.Ceiling(Math.Pow(10, i-1))); // computing 10^d int p = (int)(Math.Ceiling(Math.Pow(10, d))); // Most significant digit (msd) of n, // For 328, msd is 3 which can be obtained // using 328/100 int msd = n / p; // EXPLANATION FOR FIRST and SECOND TERMS IN // BELOW LINE OF CODE // First two terms compute sum of digits from // 1 to 299 // (sum of digits in range 1-99 stored in a[d]) + // (sum of digits in range 100-199, can be // calculated as 1*100 + a[d] // (sum of digits in range 200-299, can be // calculated as 2*100 + a[d] // The above sum can be written as 3*a[d] + // (1+2)*100 // EXPLANATION FOR THIRD AND FOURTH TERMS IN // BELOW LINE OF CODE // The last two terms compute sum of digits in // number from 300 to 328. The third term adds // 3*29 to sum as digit 3 occurs in all numbers // from 300 to 328. The fourth term recursively // calls for 28 return (msd * a[d] + (msd * (msd - 1) / 2) * p + msd * (1 + n % p) + sumOfDigitsFrom1ToN(n % p)); } // Driver Program public static void Main() { int n = 328; Console.WriteLine("Sum of digits in numbers " + "from 1 to " +n + " is " + sumOfDigitsFrom1ToN(n)); }} // This code is contributed by shiv_bhakt.
<?php// PHP program to compute sum of digits// in numbers from 1 to n // Function to computer sum of digits in// numbers from 1 to n. Comments use// example of 328 to explain the codefunction sumOfDigitsFrom1ToN($n){ // base case: if n<10 return sum of // first n natural numbers if ($n < 10) return ($n * ($n + 1) / 2); // d = number of digits minus one in // n. For 328, d is 2 $d = (int)(log10($n)); // computing sum of digits from 1 // to 10^d-1, d=1 a[0]=0; // d=2 a[1]=sum of digit from 1 to 9 = 45 // d=3 a[2]=sum of digit from 1 to 99 = // a[1]*10 + 45*10^1 = 900 // d=4 a[3]=sum of digit from 1 to 999 = // a[2]*10 + 45*10^2 = 13500 $a[$d + 1] = array(); $a[0] = 0; $a[1] = 45; for ($i = 2; $i <= $d; $i++) $a[$i] = $a[$i - 1] * 10 + 45 * (int)(ceil(pow(10, $i - 1))); // computing 10^d $p = (int)(ceil(pow(10, $d))); // Most significant digit (msd) of n, // For 328, msd is 3 which can be obtained // using 328/100 $msd = (int)($n / $p); // EXPLANATION FOR FIRST and SECOND // TERMS IN BELOW LINE OF CODE // First two terms compute sum of // digits from 1 to 299 // (sum of digits in range 1-99 stored // in a[d]) + (sum of digits in range // 100-199, can be calculated as 1*100 + a[d] // (sum of digits in range 200-299, // can be calculated as 2*100 + a[d] // The above sum can be written as // 3*a[d] + (1+2)*100 // EXPLANATION FOR THIRD AND FOURTH // TERMS IN BELOW LINE OF CODE // The last two terms compute sum of digits in // number from 300 to 328. The third term adds // 3*29 to sum as digit 3 occurs in all numbers // from 300 to 328. The fourth term recursively // calls for 28 return ($msd * $a[$d] + ($msd * (int)($msd - 1) / 2) * $p + $msd * (1 + $n % $p) + sumOfDigitsFrom1ToN($n % $p));} // Driver Code$n = 328;echo ("Sum of digits in numbers " ), "from 1 to " , $n , " is ", sumOfDigitsFrom1ToN($n); // This code is contributed by Sachin?>
<script> // Javascript program to compute sum of digits // in numbers from 1 to n // Function to computer sum of digits in // numbers from 1 to n. Comments use // example of 328 to explain the code function sumOfDigitsFrom1ToN(n) { // base case: if n<10 return sum of // first n natural numbers if (n < 10) return (n * (n + 1) / 2); // d = number of digits minus one in // n. For 328, d is 2 let d = parseInt(Math.log(n) / Math.log(10), 10); // computing sum of digits from 1 to 10^d-1, // d=1 a[0]=0; // d=2 a[1]=sum of digit from 1 to 9 = 45 // d=3 a[2]=sum of digit from 1 to 99 = // a[1]*10 + 45*10^1 = 900 // d=4 a[3]=sum of digit from 1 to 999 = // a[2]*10 + 45*10^2 = 13500 let a = new Array(d+1); a[0] = 0; a[1] = 45; for (let i = 2; i <= d; i++) a[i] = a[i-1] * 10 + 45 * parseInt(Math.ceil(Math.pow(10, i-1)), 10); // computing 10^d let p = parseInt(Math.ceil(Math.pow(10, d)), 10); // Most significant digit (msd) of n, // For 328, msd is 3 which can be obtained // using 328/100 let msd = parseInt(n / p, 10); // EXPLANATION FOR FIRST and SECOND TERMS IN // BELOW LINE OF CODE // First two terms compute sum of digits from // 1 to 299 // (sum of digits in range 1-99 stored in a[d]) + // (sum of digits in range 100-199, can be // calculated as 1*100 + a[d] // (sum of digits in range 200-299, can be // calculated as 2*100 + a[d] // The above sum can be written as 3*a[d] + // (1+2)*100 // EXPLANATION FOR THIRD AND FOURTH TERMS IN // BELOW LINE OF CODE // The last two terms compute sum of digits in // number from 300 to 328. The third term adds // 3*29 to sum as digit 3 occurs in all numbers // from 300 to 328. The fourth term recursively // calls for 28 return (msd * a[d] + (msd * (msd - 1) / 2) * p + msd * (1 + n % p) + sumOfDigitsFrom1ToN(n % p)); } let n = 328; document.write("Sum of digits in numbers from 1 to " + n + " is " + sumOfDigitsFrom1ToN(n)); </script>
Output:
Sum of digits in numbers from 1 to 328 is 3241
The efficient algorithm has one more advantage that we need to compute the array ‘a[]’ only once even when we are given multiple inputs.
Improvement: The above implementation takes O(d2) time as each recursive call calculates dp[] array once again. The first call takes O(d), the second call takes O(d-1), the third call O(d-2), and so on. We don’t need to recalculate dp[] array in each recursive call. Below is the modified implementation which works in O(d) time. Where d is a number of digits in the input number.
C++
Java
Python3
C#
Javascript
// C++ program to compute sum of digits// in numbers from 1 to n#include<bits/stdc++.h>using namespace std; int sumOfDigitsFrom1ToNUtil(int n, int a[]){ if (n < 10) return (n * (n + 1) / 2); int d = (int)(log10(n)); int p = (int)(ceil(pow(10, d))); int msd = n / p; return (msd * a[d] + (msd * (msd - 1) / 2) * p + msd * (1 + n % p) + sumOfDigitsFrom1ToNUtil(n % p, a));} // Function to computer sum of digits in// numbers from 1 to nint sumOfDigitsFrom1ToN(int n){ int d = (int)(log10(n)); int a[d + 1]; a[0] = 0; a[1] = 45; for(int i = 2; i <= d; i++) a[i] = a[i - 1] * 10 + 45 * (int)(ceil(pow(10, i - 1))); return sumOfDigitsFrom1ToNUtil(n, a);} // Driver codeint main(){ int n = 328; cout << "Sum of digits in numbers from 1 to " << n << " is "<< sumOfDigitsFrom1ToN(n);} // This code is contributed by ajaykr00kj
// JAVA program to compute sum of digits// in numbers from 1 to nimport java.io.*;import java.math.*; class GFG{ // Function to computer sum of digits in // numbers from 1 to n static int sumOfDigitsFrom1ToN(int n) { int d = (int)(Math.log10(n)); int a[] = new int[d+1]; a[0] = 0; a[1] = 45; for (int i = 2; i <= d; i++) a[i] = a[i-1] * 10 + 45 * (int)(Math.ceil(Math.pow(10, i-1))); return sumOfDigitsFrom1ToNUtil(n, a); } static int sumOfDigitsFrom1ToNUtil(int n, int a[]) { if (n < 10) return (n * (n + 1) / 2); int d = (int)(Math.log10(n)); int p = (int)(Math.ceil(Math.pow(10, d))); int msd = n / p; return (msd * a[d] + (msd * (msd - 1) / 2) * p + msd * (1 + n % p) + sumOfDigitsFrom1ToNUtil(n % p, a)); } // Driver Program public static void main(String args[]) { int n = 328; System.out.println("Sum of digits in numbers " + "from 1 to " +n + " is " + sumOfDigitsFrom1ToN(n)); }} /*This code is contributed by Narendra Jha.*/
# Python program to compute sum of digits# in numbers from 1 to nimport math # Function to computer sum of digits in# numbers from 1 to ndef sumOfDigitsFrom1ToN(n): d = int(math.log(n, 10)) a = [0]*(d + 1) a[0] = 0 a[1] = 45 for i in range(2, d + 1): a[i] = a[i - 1] * 10 + 45 * \ int(math.ceil(pow(10, i - 1))) return sumOfDigitsFrom1ToNUtil(n, a) def sumOfDigitsFrom1ToNUtil(n, a): if (n < 10): return (n * (n + 1)) // 2 d = int(math.log(n,10)) p = int(math.ceil(pow(10, d))) msd = n // p return (msd * a[d] + (msd * (msd - 1) // 2) * p + msd * (1 + n % p) + sumOfDigitsFrom1ToNUtil(n % p, a)) # Driver coden = 328print("Sum of digits in numbers from 1 to",n,"is",sumOfDigitsFrom1ToN(n)) # This code is contributed by shubhamsingh10
// C# program to compute sum of digits// in numbers from 1 to nusing System; class GFG{ // Function to computer sum of digits in // numbers from 1 to n static int sumOfDigitsFrom1ToN(int n) { int d = (int)(Math.Log10(n)); int []a = new int[d+1]; a[0] = 0; a[1] = 45; for (int i = 2; i <= d; i++) a[i] = a[i-1] * 10 + 45 * (int)(Math.Ceiling(Math.Pow(10, i-1))); return sumOfDigitsFrom1ToNUtil(n, a); } static int sumOfDigitsFrom1ToNUtil(int n, int []a) { if (n < 10) return (n * (n + 1) / 2); int d = (int)(Math.Log10(n)); int p = (int)(Math.Ceiling(Math.Pow(10, d))); int msd = n / p; return (msd * a[d] + (msd * (msd - 1) / 2) * p + msd * (1 + n % p) + sumOfDigitsFrom1ToNUtil(n % p, a)); } // Driver code public static void Main(String []args) { int n = 328; Console.WriteLine("Sum of digits in numbers " + "from 1 to " +n + " is " + sumOfDigitsFrom1ToN(n)); }} // This code contributed by Rajput-Ji
<script> // JavaScript program to compute sum of digits// in numbers from 1 to n // Function to computer sum of digits in// numbers from 1 to nfunction sumOfDigitsFrom1ToNUtil( n,a){ if (n < 10) return (n * (n + 1) / 2); var d = (parseInt)(Math.log10(n)); var p = (Math.ceil(Math.pow(10, d))); var msd =(parseInt) (n / p); return (msd * a[d] + (msd * (msd - 1) / 2) * p + msd * (1 + n % p) + sumOfDigitsFrom1ToNUtil(n % p, a));} // Function to computer sum of digits in// numbers from 1 to nfunction sumOfDigitsFrom1ToN( n){ var d =(parseInt)(Math.log10(n)); var a=new Array(d + 1).fill(0); a[0] = 0; a[1] = 45; for(var i = 2; i <= d; i++) a[i] = a[i - 1] * 10 + 45 * (parseInt)(Math.ceil(Math.pow(10, i - 1))); return sumOfDigitsFrom1ToNUtil(n, a);} var n = 328; document.write( "Sum of digits in numbers from 1 to " + n + " is "+ sumOfDigitsFrom1ToN(n)) </script>
Output:
Sum of digits in numbers from 1 to 328 is 3241
This article is computed by Shubham Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Vishal_Khoda
jit_t
Sach_Code
Narendra_Jha
Rajput-Ji
SHUBHAMSINGH10
ajaykr00kj
khushboogoyal499
divyeshrabadiya07
mukesh07
akshitsaxenaa09
number-digits
Arrays
Dynamic Programming
Mathematical
Arrays
Dynamic Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Multidimensional Arrays in Java
Linked List vs Array
Python | Using 2D arrays/lists the right way
Search an element in a sorted and rotated array
0-1 Knapsack Problem | DP-10
Program for Fibonacci numbers
Bellman–Ford Algorithm | DP-23
Longest Common Subsequence | DP-4
Floyd Warshall Algorithm | DP-16
|
[
{
"code": null,
"e": 26375,
"s": 26347,
"text": "\n14 May, 2021"
},
{
"code": null,
"e": 26455,
"s": 26375,
"text": "Given a number n, find the sum of digits in all numbers from 1 to n. Examples: "
},
{
"code": null,
"e": 26654,
"s": 26455,
"text": "Input: n = 5\nOutput: Sum of digits in numbers from 1 to 5 = 15\n\nInput: n = 12\nOutput: Sum of digits in numbers from 1 to 12 = 51\n\nInput: n = 328\nOutput: Sum of digits in numbers from 1 to 328 = 3241"
},
{
"code": null,
"e": 26830,
"s": 26654,
"text": "Naive Solution: A naive solution is to go through every number x from 1 to n and compute the sum in x by traversing all digits of x. Below is the implementation of this idea. "
},
{
"code": null,
"e": 26834,
"s": 26830,
"text": "C++"
},
{
"code": null,
"e": 26839,
"s": 26834,
"text": "Java"
},
{
"code": null,
"e": 26847,
"s": 26839,
"text": "Python3"
},
{
"code": null,
"e": 26850,
"s": 26847,
"text": "C#"
},
{
"code": null,
"e": 26854,
"s": 26850,
"text": "PHP"
},
{
"code": null,
"e": 26865,
"s": 26854,
"text": "Javascript"
},
{
"code": "// A Simple C++ program to compute sum of digits in numbers from 1 to n#include<bits/stdc++.h>using namespace std; int sumOfDigits(int ); // Returns sum of all digits in numbers from 1 to nint sumOfDigitsFrom1ToN(int n){ int result = 0; // initialize result // One by one compute sum of digits in every number from // 1 to n for (int x = 1; x <= n; x++) result += sumOfDigits(x); return result;} // A utility function to compute sum of digits in a// given number xint sumOfDigits(int x){ int sum = 0; while (x != 0) { sum += x %10; x = x /10; } return sum;} // Driver Programint main(){ int n = 328; cout << \"Sum of digits in numbers from 1 to \" << n << \" is \" << sumOfDigitsFrom1ToN(n); return 0;}",
"e": 27636,
"s": 26865,
"text": null
},
{
"code": "// A Simple JAVA program to compute sum of// digits in numbers from 1 to nimport java.io.*; class GFG { // Returns sum of all digits in numbers // from 1 to n static int sumOfDigitsFrom1ToN(int n) { int result = 0; // initialize result // One by one compute sum of digits // in every number from 1 to n for (int x = 1; x <= n; x++) result += sumOfDigits(x); return result; } // A utility function to compute sum // of digits in a given number x static int sumOfDigits(int x) { int sum = 0; while (x != 0) { sum += x % 10; x = x / 10; } return sum; } // Driver Program public static void main(String args[]) { int n = 328; System.out.println(\"Sum of digits in numbers\" +\" from 1 to \" + n + \" is \" + sumOfDigitsFrom1ToN(n)); }} /*This code is contributed by Nikita Tiwari.*/",
"e": 28649,
"s": 27636,
"text": null
},
{
"code": "# A Simple Python program to compute sum# of digits in numbers from 1 to n # Returns sum of all digits in numbers# from 1 to ndef sumOfDigitsFrom1ToN(n) : result = 0 # initialize result # One by one compute sum of digits # in every number from 1 to n for x in range(1, n+1) : result = result + sumOfDigits(x) return result # A utility function to compute sum of# digits in a given number xdef sumOfDigits(x) : sum = 0 while (x != 0) : sum = sum + x % 10 x = x // 10 return sum # Driver Programn = 328print(\"Sum of digits in numbers from 1 to\", n, \"is\", sumOfDigitsFrom1ToN(n)) # This code is contributed by Nikita Tiwari.",
"e": 29332,
"s": 28649,
"text": null
},
{
"code": "// A Simple C# program to compute sum of// digits in numbers from 1 to n using System; public class GFG { // Returns sum of all digits in numbers // from 1 to n static int sumOfDigitsFrom1ToN(int n) { // initialize result int result = 0; // One by one compute sum of digits // in every number from 1 to n for (int x = 1; x <= n; x++) result += sumOfDigits(x); return result; } // A utility function to compute sum // of digits in a given number x static int sumOfDigits(int x) { int sum = 0; while (x != 0) { sum += x % 10; x = x / 10; } return sum; } // Driver Program public static void Main() { int n = 328; Console.WriteLine(\"Sum of digits\" + \" in numbers from 1 to \" + n + \" is \" + sumOfDigitsFrom1ToN(n)); }} // This code is contributed by shiv_bhakt.",
"e": 30374,
"s": 29332,
"text": null
},
{
"code": "<?php // A Simple php program to compute sum//of digits in numbers from 1 to n // Returns sum of all digits in// numbers from 1 to nfunction sumOfDigitsFrom1ToN($n){ $result = 0; // initialize result // One by one compute sum of digits // in every number from 1 to n for ($x = 1; $x <= $n; $x++) $result += sumOfDigits($x); return $result;} // A utility function to compute sum// of digits in a given number xfunction sumOfDigits($x){ $sum = 0; while ($x != 0) { $sum += $x %10; $x = $x /10; } return $sum;} // Driver Program $n = 328; echo \"Sum of digits in numbers from\" . \" 1 to \" . $n . \" is \" . sumOfDigitsFrom1ToN($n); // This code is contributed by ajit?>",
"e": 31129,
"s": 30374,
"text": null
},
{
"code": "<script> // A Simple Javascript program to compute sum of // digits in numbers from 1 to n // Returns sum of all digits in numbers // from 1 to n function sumOfDigitsFrom1ToN(n) { // initialize result let result = 0; // One by one compute sum of digits // in every number from 1 to n for (let x = 1; x <= n; x++) result += sumOfDigits(x); return result; } // A utility function to compute sum // of digits in a given number x function sumOfDigits(x) { let sum = 0; while (x != 0) { sum += x % 10; x = parseInt(x / 10, 10); } return sum; } let n = 328; document.write(\"Sum of digits\" + \" in numbers from 1 to \" + n + \" is \" + sumOfDigitsFrom1ToN(n)); // This code is contributed by divyeshrabadiya07. </script>",
"e": 32164,
"s": 31129,
"text": null
},
{
"code": null,
"e": 32172,
"s": 32164,
"text": "Output:"
},
{
"code": null,
"e": 32219,
"s": 32172,
"text": "Sum of digits in numbers from 1 to 328 is 3241"
},
{
"code": null,
"e": 32344,
"s": 32219,
"text": "Efficient Solution: Above is a naive solution. We can do it more efficiently by finding a pattern.Let us take few examples. "
},
{
"code": null,
"e": 32634,
"s": 32344,
"text": "sum(9) = 1 + 2 + 3 + 4 ........... + 9\n = 9*10/2 \n = 45\n\nsum(99) = 45 + (10 + 45) + (20 + 45) + ..... (90 + 45)\n = 45*10 + (10 + 20 + 30 ... 90)\n = 45*10 + 10(1 + 2 + ... 9)\n = 45*10 + 45*10\n = sum(9)*10 + 45*10 \n\nsum(999) = sum(99)*10 + 45*100"
},
{
"code": null,
"e": 32698,
"s": 32634,
"text": "In general, we can compute sum(10d – 1) using the below formula"
},
{
"code": null,
"e": 32750,
"s": 32698,
"text": " sum(10d - 1) = sum(10d-1 - 1) * 10 + 45*(10d-1) "
},
{
"code": null,
"e": 32956,
"s": 32750,
"text": "In the below implementation, the above formula is implemented using dynamic programming as there are overlapping subproblems. The above formula is one core step of the idea. Below is the complete algorithm"
},
{
"code": null,
"e": 32975,
"s": 32956,
"text": "Algorithm: sum(n) "
},
{
"code": null,
"e": 34016,
"s": 32975,
"text": "1) Find number of digits minus one in n. Let this value be 'd'. \n For 328, d is 2.\n\n2) Compute some of digits in numbers from 1 to 10d - 1. \n Let this sum be w. For 328, we compute sum of digits from 1 to \n 99 using above formula.\n\n3) Find Most significant digit (msd) in n. For 328, msd is 3.\n\n4) Overall sum is sum of following terms\n\n a) Sum of digits in 1 to \"msd * 10d - 1\". For 328, sum of \n digits in numbers from 1 to 299.\n For 328, we compute 3*sum(99) + (1 + 2)*100. Note that sum of\n sum(299) is sum(99) + sum of digits from 100 to 199 + sum of digits\n from 200 to 299. \n Sum of 100 to 199 is sum(99) + 1*100 and sum of 299 is sum(99) + 2*100.\n In general, this sum can be computed as w*msd + (msd*(msd-1)/2)*10d\n\n b) Sum of digits in msd * 10d to n. For 328, sum of digits in \n 300 to 328.\n For 328, this sum is computed as 3*29 + recursive call \"sum(28)\"\n In general, this sum can be computed as msd * (n % (msd*10d) + 1) \n + sum(n % (10d))"
},
{
"code": null,
"e": 34069,
"s": 34016,
"text": "Below is the implementation of the above algorithm. "
},
{
"code": null,
"e": 34073,
"s": 34069,
"text": "C++"
},
{
"code": null,
"e": 34078,
"s": 34073,
"text": "Java"
},
{
"code": null,
"e": 34086,
"s": 34078,
"text": "Python3"
},
{
"code": null,
"e": 34089,
"s": 34086,
"text": "C#"
},
{
"code": null,
"e": 34093,
"s": 34089,
"text": "PHP"
},
{
"code": null,
"e": 34104,
"s": 34093,
"text": "Javascript"
},
{
"code": "// C++ program to compute sum of digits in numbers from 1 to n#include<bits/stdc++.h>using namespace std; // Function to computer sum of digits in numbers from 1 to n// Comments use example of 328 to explain the codeint sumOfDigitsFrom1ToN(int n){ // base case: if n<10 return sum of // first n natural numbers if (n<10) return n*(n+1)/2; // d = number of digits minus one in n. For 328, d is 2 int d = log10(n); // computing sum of digits from 1 to 10^d-1, // d=1 a[0]=0; // d=2 a[1]=sum of digit from 1 to 9 = 45 // d=3 a[2]=sum of digit from 1 to 99 = a[1]*10 + 45*10^1 = 900 // d=4 a[3]=sum of digit from 1 to 999 = a[2]*10 + 45*10^2 = 13500 int *a = new int[d+1]; a[0] = 0, a[1] = 45; for (int i=2; i<=d; i++) a[i] = a[i-1]*10 + 45*ceil(pow(10,i-1)); // computing 10^d int p = ceil(pow(10, d)); // Most significant digit (msd) of n, // For 328, msd is 3 which can be obtained using 328/100 int msd = n/p; // EXPLANATION FOR FIRST and SECOND TERMS IN BELOW LINE OF CODE // First two terms compute sum of digits from 1 to 299 // (sum of digits in range 1-99 stored in a[d]) + // (sum of digits in range 100-199, can be calculated as 1*100 + a[d] // (sum of digits in range 200-299, can be calculated as 2*100 + a[d] // The above sum can be written as 3*a[d] + (1+2)*100 // EXPLANATION FOR THIRD AND FOURTH TERMS IN BELOW LINE OF CODE // The last two terms compute sum of digits in number from 300 to 328 // The third term adds 3*29 to sum as digit 3 occurs in all numbers // from 300 to 328 // The fourth term recursively calls for 28 return msd*a[d] + (msd*(msd-1)/2)*p + msd*(1+n%p) + sumOfDigitsFrom1ToN(n%p);} // Driver Programint main(){ int n = 328; cout << \"Sum of digits in numbers from 1 to \" << n << \" is \" << sumOfDigitsFrom1ToN(n); return 0;}",
"e": 36014,
"s": 34104,
"text": null
},
{
"code": "// JAVA program to compute sum of digits// in numbers from 1 to nimport java.io.*;import java.math.*; class GFG{ // Function to computer sum of digits in // numbers from 1 to n. Comments use // example of 328 to explain the code static int sumOfDigitsFrom1ToN(int n) { // base case: if n<10 return sum of // first n natural numbers if (n < 10) return (n * (n + 1) / 2); // d = number of digits minus one in // n. For 328, d is 2 int d = (int)(Math.log10(n)); // computing sum of digits from 1 to 10^d-1, // d=1 a[0]=0; // d=2 a[1]=sum of digit from 1 to 9 = 45 // d=3 a[2]=sum of digit from 1 to 99 = // a[1]*10 + 45*10^1 = 900 // d=4 a[3]=sum of digit from 1 to 999 = // a[2]*10 + 45*10^2 = 13500 int a[] = new int[d+1]; a[0] = 0; a[1] = 45; for (int i = 2; i <= d; i++) a[i] = a[i-1] * 10 + 45 * (int)(Math.ceil(Math.pow(10, i-1))); // computing 10^d int p = (int)(Math.ceil(Math.pow(10, d))); // Most significant digit (msd) of n, // For 328, msd is 3 which can be obtained // using 328/100 int msd = n / p; // EXPLANATION FOR FIRST and SECOND TERMS IN // BELOW LINE OF CODE // First two terms compute sum of digits from // 1 to 299 // (sum of digits in range 1-99 stored in a[d]) + // (sum of digits in range 100-199, can be // calculated as 1*100 + a[d] // (sum of digits in range 200-299, can be // calculated as 2*100 + a[d] // The above sum can be written as 3*a[d] + // (1+2)*100 // EXPLANATION FOR THIRD AND FOURTH TERMS IN // BELOW LINE OF CODE // The last two terms compute sum of digits in // number from 300 to 328. The third term adds // 3*29 to sum as digit 3 occurs in all numbers // from 300 to 328. The fourth term recursively // calls for 28 return (msd * a[d] + (msd * (msd - 1) / 2) * p + msd * (1 + n % p) + sumOfDigitsFrom1ToN(n % p)); } // Driver Program public static void main(String args[]) { int n = 328; System.out.println(\"Sum of digits in numbers \" + \"from 1 to \" +n + \" is \" + sumOfDigitsFrom1ToN(n)); }} /*This code is contributed by Nikita Tiwari.*/",
"e": 38478,
"s": 36014,
"text": null
},
{
"code": "# PYTHON 3 program to compute sum of digits# in numbers from 1 to nimport math # Function to computer sum of digits in# numbers from 1 to n. Comments use example# of 328 to explain the codedef sumOfDigitsFrom1ToN( n) : # base case: if n<10 return sum of # first n natural numbers if (n<10) : return (n*(n+1)/2) # d = number of digits minus one in n. # For 328, d is 2 d = (int)(math.log10(n)) \"\"\"computing sum of digits from 1 to 10^d-1, d=1 a[0]=0; d=2 a[1]=sum of digit from 1 to 9 = 45 d=3 a[2]=sum of digit from 1 to 99 = a[1]*10 + 45*10^1 = 900 d=4 a[3]=sum of digit from 1 to 999 = a[2]*10 + 45*10^2 = 13500\"\"\" a = [0] * (d + 1) a[0] = 0 a[1] = 45 for i in range(2, d+1) : a[i] = a[i-1] * 10 + 45 * (int)(math.ceil(math.pow(10,i-1))) # computing 10^d p = (int)(math.ceil(math.pow(10, d))) # Most significant digit (msd) of n, # For 328, msd is 3 which can be obtained # using 328/100 msd = n//p \"\"\"EXPLANATION FOR FIRST and SECOND TERMS IN BELOW LINE OF CODE First two terms compute sum of digits from 1 to 299 (sum of digits in range 1-99 stored in a[d]) + (sum of digits in range 100-199, can be calculated as 1*100 + a[d]. (sum of digits in range 200-299, can be calculated as 2*100 + a[d] The above sum can be written as 3*a[d] + (1+2)*100 EXPLANATION FOR THIRD AND FOURTH TERMS IN BELOW LINE OF CODE The last two terms compute sum of digits in number from 300 to 328. The third term adds 3*29 to sum as digit 3 occurs in all numbers from 300 to 328. The fourth term recursively calls for 28\"\"\" return (int)(msd * a[d] + (msd*(msd-1) // 2) * p + msd * (1 + n % p) + sumOfDigitsFrom1ToN(n % p)) # Driver Programn = 328print(\"Sum of digits in numbers from 1 to\", n ,\"is\",sumOfDigitsFrom1ToN(n)) # This code is contributed by Nikita Tiwari.",
"e": 40386,
"s": 38478,
"text": null
},
{
"code": "// C# program to compute sum of digits// in numbers from 1 to n using System; public class GFG { // Function to computer sum of digits in // numbers from 1 to n. Comments use // example of 328 to explain the code static int sumOfDigitsFrom1ToN(int n) { // base case: if n<10 return sum of // first n natural numbers if (n < 10) return (n * (n + 1) / 2); // d = number of digits minus one in // n. For 328, d is 2 int d = (int)(Math.Log(n) / Math.Log(10)); // computing sum of digits from 1 to 10^d-1, // d=1 a[0]=0; // d=2 a[1]=sum of digit from 1 to 9 = 45 // d=3 a[2]=sum of digit from 1 to 99 = // a[1]*10 + 45*10^1 = 900 // d=4 a[3]=sum of digit from 1 to 999 = // a[2]*10 + 45*10^2 = 13500 int[] a = new int[d+1]; a[0] = 0; a[1] = 45; for (int i = 2; i <= d; i++) a[i] = a[i-1] * 10 + 45 * (int)(Math.Ceiling(Math.Pow(10, i-1))); // computing 10^d int p = (int)(Math.Ceiling(Math.Pow(10, d))); // Most significant digit (msd) of n, // For 328, msd is 3 which can be obtained // using 328/100 int msd = n / p; // EXPLANATION FOR FIRST and SECOND TERMS IN // BELOW LINE OF CODE // First two terms compute sum of digits from // 1 to 299 // (sum of digits in range 1-99 stored in a[d]) + // (sum of digits in range 100-199, can be // calculated as 1*100 + a[d] // (sum of digits in range 200-299, can be // calculated as 2*100 + a[d] // The above sum can be written as 3*a[d] + // (1+2)*100 // EXPLANATION FOR THIRD AND FOURTH TERMS IN // BELOW LINE OF CODE // The last two terms compute sum of digits in // number from 300 to 328. The third term adds // 3*29 to sum as digit 3 occurs in all numbers // from 300 to 328. The fourth term recursively // calls for 28 return (msd * a[d] + (msd * (msd - 1) / 2) * p + msd * (1 + n % p) + sumOfDigitsFrom1ToN(n % p)); } // Driver Program public static void Main() { int n = 328; Console.WriteLine(\"Sum of digits in numbers \" + \"from 1 to \" +n + \" is \" + sumOfDigitsFrom1ToN(n)); }} // This code is contributed by shiv_bhakt.",
"e": 42851,
"s": 40386,
"text": null
},
{
"code": "<?php// PHP program to compute sum of digits// in numbers from 1 to n // Function to computer sum of digits in// numbers from 1 to n. Comments use// example of 328 to explain the codefunction sumOfDigitsFrom1ToN($n){ // base case: if n<10 return sum of // first n natural numbers if ($n < 10) return ($n * ($n + 1) / 2); // d = number of digits minus one in // n. For 328, d is 2 $d = (int)(log10($n)); // computing sum of digits from 1 // to 10^d-1, d=1 a[0]=0; // d=2 a[1]=sum of digit from 1 to 9 = 45 // d=3 a[2]=sum of digit from 1 to 99 = // a[1]*10 + 45*10^1 = 900 // d=4 a[3]=sum of digit from 1 to 999 = // a[2]*10 + 45*10^2 = 13500 $a[$d + 1] = array(); $a[0] = 0; $a[1] = 45; for ($i = 2; $i <= $d; $i++) $a[$i] = $a[$i - 1] * 10 + 45 * (int)(ceil(pow(10, $i - 1))); // computing 10^d $p = (int)(ceil(pow(10, $d))); // Most significant digit (msd) of n, // For 328, msd is 3 which can be obtained // using 328/100 $msd = (int)($n / $p); // EXPLANATION FOR FIRST and SECOND // TERMS IN BELOW LINE OF CODE // First two terms compute sum of // digits from 1 to 299 // (sum of digits in range 1-99 stored // in a[d]) + (sum of digits in range // 100-199, can be calculated as 1*100 + a[d] // (sum of digits in range 200-299, // can be calculated as 2*100 + a[d] // The above sum can be written as // 3*a[d] + (1+2)*100 // EXPLANATION FOR THIRD AND FOURTH // TERMS IN BELOW LINE OF CODE // The last two terms compute sum of digits in // number from 300 to 328. The third term adds // 3*29 to sum as digit 3 occurs in all numbers // from 300 to 328. The fourth term recursively // calls for 28 return ($msd * $a[$d] + ($msd * (int)($msd - 1) / 2) * $p + $msd * (1 + $n % $p) + sumOfDigitsFrom1ToN($n % $p));} // Driver Code$n = 328;echo (\"Sum of digits in numbers \" ), \"from 1 to \" , $n , \" is \", sumOfDigitsFrom1ToN($n); // This code is contributed by Sachin?>",
"e": 44898,
"s": 42851,
"text": null
},
{
"code": "<script> // Javascript program to compute sum of digits // in numbers from 1 to n // Function to computer sum of digits in // numbers from 1 to n. Comments use // example of 328 to explain the code function sumOfDigitsFrom1ToN(n) { // base case: if n<10 return sum of // first n natural numbers if (n < 10) return (n * (n + 1) / 2); // d = number of digits minus one in // n. For 328, d is 2 let d = parseInt(Math.log(n) / Math.log(10), 10); // computing sum of digits from 1 to 10^d-1, // d=1 a[0]=0; // d=2 a[1]=sum of digit from 1 to 9 = 45 // d=3 a[2]=sum of digit from 1 to 99 = // a[1]*10 + 45*10^1 = 900 // d=4 a[3]=sum of digit from 1 to 999 = // a[2]*10 + 45*10^2 = 13500 let a = new Array(d+1); a[0] = 0; a[1] = 45; for (let i = 2; i <= d; i++) a[i] = a[i-1] * 10 + 45 * parseInt(Math.ceil(Math.pow(10, i-1)), 10); // computing 10^d let p = parseInt(Math.ceil(Math.pow(10, d)), 10); // Most significant digit (msd) of n, // For 328, msd is 3 which can be obtained // using 328/100 let msd = parseInt(n / p, 10); // EXPLANATION FOR FIRST and SECOND TERMS IN // BELOW LINE OF CODE // First two terms compute sum of digits from // 1 to 299 // (sum of digits in range 1-99 stored in a[d]) + // (sum of digits in range 100-199, can be // calculated as 1*100 + a[d] // (sum of digits in range 200-299, can be // calculated as 2*100 + a[d] // The above sum can be written as 3*a[d] + // (1+2)*100 // EXPLANATION FOR THIRD AND FOURTH TERMS IN // BELOW LINE OF CODE // The last two terms compute sum of digits in // number from 300 to 328. The third term adds // 3*29 to sum as digit 3 occurs in all numbers // from 300 to 328. The fourth term recursively // calls for 28 return (msd * a[d] + (msd * (msd - 1) / 2) * p + msd * (1 + n % p) + sumOfDigitsFrom1ToN(n % p)); } let n = 328; document.write(\"Sum of digits in numbers from 1 to \" + n + \" is \" + sumOfDigitsFrom1ToN(n)); </script>",
"e": 47256,
"s": 44898,
"text": null
},
{
"code": null,
"e": 47264,
"s": 47256,
"text": "Output:"
},
{
"code": null,
"e": 47311,
"s": 47264,
"text": "Sum of digits in numbers from 1 to 328 is 3241"
},
{
"code": null,
"e": 47448,
"s": 47311,
"text": "The efficient algorithm has one more advantage that we need to compute the array ‘a[]’ only once even when we are given multiple inputs."
},
{
"code": null,
"e": 47829,
"s": 47448,
"text": "Improvement: The above implementation takes O(d2) time as each recursive call calculates dp[] array once again. The first call takes O(d), the second call takes O(d-1), the third call O(d-2), and so on. We don’t need to recalculate dp[] array in each recursive call. Below is the modified implementation which works in O(d) time. Where d is a number of digits in the input number."
},
{
"code": null,
"e": 47833,
"s": 47829,
"text": "C++"
},
{
"code": null,
"e": 47838,
"s": 47833,
"text": "Java"
},
{
"code": null,
"e": 47846,
"s": 47838,
"text": "Python3"
},
{
"code": null,
"e": 47849,
"s": 47846,
"text": "C#"
},
{
"code": null,
"e": 47860,
"s": 47849,
"text": "Javascript"
},
{
"code": "// C++ program to compute sum of digits// in numbers from 1 to n#include<bits/stdc++.h>using namespace std; int sumOfDigitsFrom1ToNUtil(int n, int a[]){ if (n < 10) return (n * (n + 1) / 2); int d = (int)(log10(n)); int p = (int)(ceil(pow(10, d))); int msd = n / p; return (msd * a[d] + (msd * (msd - 1) / 2) * p + msd * (1 + n % p) + sumOfDigitsFrom1ToNUtil(n % p, a));} // Function to computer sum of digits in// numbers from 1 to nint sumOfDigitsFrom1ToN(int n){ int d = (int)(log10(n)); int a[d + 1]; a[0] = 0; a[1] = 45; for(int i = 2; i <= d; i++) a[i] = a[i - 1] * 10 + 45 * (int)(ceil(pow(10, i - 1))); return sumOfDigitsFrom1ToNUtil(n, a);} // Driver codeint main(){ int n = 328; cout << \"Sum of digits in numbers from 1 to \" << n << \" is \"<< sumOfDigitsFrom1ToN(n);} // This code is contributed by ajaykr00kj",
"e": 48795,
"s": 47860,
"text": null
},
{
"code": "// JAVA program to compute sum of digits// in numbers from 1 to nimport java.io.*;import java.math.*; class GFG{ // Function to computer sum of digits in // numbers from 1 to n static int sumOfDigitsFrom1ToN(int n) { int d = (int)(Math.log10(n)); int a[] = new int[d+1]; a[0] = 0; a[1] = 45; for (int i = 2; i <= d; i++) a[i] = a[i-1] * 10 + 45 * (int)(Math.ceil(Math.pow(10, i-1))); return sumOfDigitsFrom1ToNUtil(n, a); } static int sumOfDigitsFrom1ToNUtil(int n, int a[]) { if (n < 10) return (n * (n + 1) / 2); int d = (int)(Math.log10(n)); int p = (int)(Math.ceil(Math.pow(10, d))); int msd = n / p; return (msd * a[d] + (msd * (msd - 1) / 2) * p + msd * (1 + n % p) + sumOfDigitsFrom1ToNUtil(n % p, a)); } // Driver Program public static void main(String args[]) { int n = 328; System.out.println(\"Sum of digits in numbers \" + \"from 1 to \" +n + \" is \" + sumOfDigitsFrom1ToN(n)); }} /*This code is contributed by Narendra Jha.*/",
"e": 49969,
"s": 48795,
"text": null
},
{
"code": "# Python program to compute sum of digits# in numbers from 1 to nimport math # Function to computer sum of digits in# numbers from 1 to ndef sumOfDigitsFrom1ToN(n): d = int(math.log(n, 10)) a = [0]*(d + 1) a[0] = 0 a[1] = 45 for i in range(2, d + 1): a[i] = a[i - 1] * 10 + 45 * \\ int(math.ceil(pow(10, i - 1))) return sumOfDigitsFrom1ToNUtil(n, a) def sumOfDigitsFrom1ToNUtil(n, a): if (n < 10): return (n * (n + 1)) // 2 d = int(math.log(n,10)) p = int(math.ceil(pow(10, d))) msd = n // p return (msd * a[d] + (msd * (msd - 1) // 2) * p + msd * (1 + n % p) + sumOfDigitsFrom1ToNUtil(n % p, a)) # Driver coden = 328print(\"Sum of digits in numbers from 1 to\",n,\"is\",sumOfDigitsFrom1ToN(n)) # This code is contributed by shubhamsingh10",
"e": 50788,
"s": 49969,
"text": null
},
{
"code": "// C# program to compute sum of digits// in numbers from 1 to nusing System; class GFG{ // Function to computer sum of digits in // numbers from 1 to n static int sumOfDigitsFrom1ToN(int n) { int d = (int)(Math.Log10(n)); int []a = new int[d+1]; a[0] = 0; a[1] = 45; for (int i = 2; i <= d; i++) a[i] = a[i-1] * 10 + 45 * (int)(Math.Ceiling(Math.Pow(10, i-1))); return sumOfDigitsFrom1ToNUtil(n, a); } static int sumOfDigitsFrom1ToNUtil(int n, int []a) { if (n < 10) return (n * (n + 1) / 2); int d = (int)(Math.Log10(n)); int p = (int)(Math.Ceiling(Math.Pow(10, d))); int msd = n / p; return (msd * a[d] + (msd * (msd - 1) / 2) * p + msd * (1 + n % p) + sumOfDigitsFrom1ToNUtil(n % p, a)); } // Driver code public static void Main(String []args) { int n = 328; Console.WriteLine(\"Sum of digits in numbers \" + \"from 1 to \" +n + \" is \" + sumOfDigitsFrom1ToN(n)); }} // This code contributed by Rajput-Ji",
"e": 51934,
"s": 50788,
"text": null
},
{
"code": "<script> // JavaScript program to compute sum of digits// in numbers from 1 to n // Function to computer sum of digits in// numbers from 1 to nfunction sumOfDigitsFrom1ToNUtil( n,a){ if (n < 10) return (n * (n + 1) / 2); var d = (parseInt)(Math.log10(n)); var p = (Math.ceil(Math.pow(10, d))); var msd =(parseInt) (n / p); return (msd * a[d] + (msd * (msd - 1) / 2) * p + msd * (1 + n % p) + sumOfDigitsFrom1ToNUtil(n % p, a));} // Function to computer sum of digits in// numbers from 1 to nfunction sumOfDigitsFrom1ToN( n){ var d =(parseInt)(Math.log10(n)); var a=new Array(d + 1).fill(0); a[0] = 0; a[1] = 45; for(var i = 2; i <= d; i++) a[i] = a[i - 1] * 10 + 45 * (parseInt)(Math.ceil(Math.pow(10, i - 1))); return sumOfDigitsFrom1ToNUtil(n, a);} var n = 328; document.write( \"Sum of digits in numbers from 1 to \" + n + \" is \"+ sumOfDigitsFrom1ToN(n)) </script>",
"e": 52914,
"s": 51934,
"text": null
},
{
"code": null,
"e": 52922,
"s": 52914,
"text": "Output:"
},
{
"code": null,
"e": 52969,
"s": 52922,
"text": "Sum of digits in numbers from 1 to 328 is 3241"
},
{
"code": null,
"e": 53137,
"s": 52969,
"text": "This article is computed by Shubham Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 53150,
"s": 53137,
"text": "Vishal_Khoda"
},
{
"code": null,
"e": 53156,
"s": 53150,
"text": "jit_t"
},
{
"code": null,
"e": 53166,
"s": 53156,
"text": "Sach_Code"
},
{
"code": null,
"e": 53179,
"s": 53166,
"text": "Narendra_Jha"
},
{
"code": null,
"e": 53189,
"s": 53179,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 53204,
"s": 53189,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 53215,
"s": 53204,
"text": "ajaykr00kj"
},
{
"code": null,
"e": 53232,
"s": 53215,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 53250,
"s": 53232,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 53259,
"s": 53250,
"text": "mukesh07"
},
{
"code": null,
"e": 53275,
"s": 53259,
"text": "akshitsaxenaa09"
},
{
"code": null,
"e": 53289,
"s": 53275,
"text": "number-digits"
},
{
"code": null,
"e": 53296,
"s": 53289,
"text": "Arrays"
},
{
"code": null,
"e": 53316,
"s": 53296,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 53329,
"s": 53316,
"text": "Mathematical"
},
{
"code": null,
"e": 53336,
"s": 53329,
"text": "Arrays"
},
{
"code": null,
"e": 53356,
"s": 53336,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 53369,
"s": 53356,
"text": "Mathematical"
},
{
"code": null,
"e": 53467,
"s": 53369,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 53490,
"s": 53467,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 53522,
"s": 53490,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 53543,
"s": 53522,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 53588,
"s": 53543,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 53636,
"s": 53588,
"text": "Search an element in a sorted and rotated array"
},
{
"code": null,
"e": 53665,
"s": 53636,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 53695,
"s": 53665,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 53726,
"s": 53695,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 53760,
"s": 53726,
"text": "Longest Common Subsequence | DP-4"
}
] |
Generate a string consisting of characters 'a' and 'b' that satisfy the given conditions - GeeksforGeeks
|
28 May, 2021
Given two integers A and B, the task is to generate and print a string str such that:
str must only contain the characters ‘a’ and ‘b’.str has length A + B and the occurrence of character ‘a’ is equal to A and the occurrence of character ‘b’ is equal to BThe sub-strings “aaa” or “bbb” must not occur in str.
str must only contain the characters ‘a’ and ‘b’.
str has length A + B and the occurrence of character ‘a’ is equal to A and the occurrence of character ‘b’ is equal to B
The sub-strings “aaa” or “bbb” must not occur in str.
Note that for the given values of A and B, a valid string can always be generated.Examples:
Input: A = 1, B = 2 Output: abb “abb”, “bab” and “bba” are all valid strings.Input: A = 4, B = 1 Output: aabaa
Approach:
If occurrence(a) > occurrence(b) then append “aab”
If occurrence(b) > occurrence(a) then append “bba”
If occurrence(a) = occurrence(b) then append “ab”
Since we reduce the difference between the occurrences of ‘a’ and ‘b’ by at most 1 in each iteration so “bba” and “aab” are guaranteed not to be followed by “aab” and “bba” respectively.Below is the implementation of the above approach:
C++
Java
Python 3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to generate and print the required stringvoid generateString(int A, int B){ string rt; while (0 < A || 0 < B) { // More 'b', append "bba" if (A < B) { if (0 < B--) rt.push_back('b'); if (0 < B--) rt.push_back('b'); if (0 < A--) rt.push_back('a'); } // More 'a', append "aab" else if (B < A) { if (0 < A--) rt.push_back('a'); if (0 < A--) rt.push_back('a'); if (0 < B--) rt.push_back('b'); } // Equal number of 'a' and 'b' // append "ab" else { if (0 < A--) rt.push_back('a'); if (0 < B--) rt.push_back('b'); } } cout << rt;} // Driver codeint main(){ int A = 2, B = 6; generateString(A, B); return 0;}
// Java implementation of the approachclass GFG{ // Function to generate and // print the required string static void generateString(int A, int B) { String rt = ""; while (0 < A || 0 < B) { // More 'b', append "bba" if (A < B) { if (0 < B--) { rt += ('b'); } if (0 < B--) { rt += ('b'); } if (0 < A--) { rt += ('a'); } } // More 'a', append "aab" else if (B < A) { if (0 < A--) { rt += ('a'); } if (0 < A--) { rt += ('a'); } if (0 < B--) { rt += ('b'); } } // Equal number of 'a' and 'b' // append "ab" else { if (0 < A--) { rt += ('a'); } if (0 < B--) { rt += ('b'); } } } System.out.println(rt); } // Driver code public static void main(String[] args) { int A = 2, B = 6; generateString(A, B); }} // This code is contributed// by PrinciRaj1992
# Python 3 implementation of the approach # Function to generate and print# the required stringdef generateString(A, B): rt = "" while (0 < A or 0 < B) : # More 'b', append "bba" if (A < B) : if (0 < B): rt = rt +'b' B -= 1 if (0 < B): rt += 'b' B -= 1 if (0 < A): rt += 'a' A -= 1 # More 'a', append "aab" elif (B < A): if (0 < A): rt += 'a' A -= 1 if (0 < A): rt += 'a' A -= 1 if (0 < B): rt += 'b' B -= 1 # Equal number of 'a' and 'b' # append "ab" else : if (0 < A): rt += 'a' A -= 1 if (0 < B): rt += 'b' B -= 1 print(rt) # Driver codeif __name__ == "__main__": A = 2 B = 6 generateString(A, B) # This code is contributed by ita_c
// C# implementation of the approachusing System; class GFG{ // Function to generate and // print the required string static void generateString(int A, int B) { string rt = ""; while (0 < A || 0 < B) { // More 'b', append "bba" if (A < B) { if (0 < B--) { rt += ('b'); } if (0 < B--) { rt += ('b'); } if (0 < A--) { rt += ('a'); } } // More 'a', append "aab" else if (B < A) { if (0 < A--) { rt += ('a'); } if (0 < A--) { rt += ('a'); } if (0 < B--) { rt += ('b'); } } // Equal number of 'a' and 'b' // append "ab" else { if (0 < A--) { rt += ('a'); } if (0 < B--) { rt += ('b'); } } } Console.WriteLine(rt); } // Driver code public static void Main() { int A = 2, B = 6; generateString(A, B); }} // This code is contributed by Ryuga
<?php// PHP implementation of the approach // Function to generate and// print the required stringfunction generateString($A, $B){ $rt = ""; while (0 < $A || 0 < $B) { // More 'b', append "bba" if ($A < $B) { if (0 < $B--) { $rt .= ('b'); } if (0 < $B--) { $rt .= ('b'); } if (0 < $A--) { $rt .= ('a'); } } // More 'a', append "aab" else if ($B < $A) { if (0 < $A--) { $rt .= ('a'); } if (0 < $A--) { $rt .= ('a'); } if (0 < $B--) { $rt .= ('b'); } } // Equal number of 'a' and 'b' // append "ab" else { if (0 < $A--) { $rt .= ('a'); } if (0 < $B--) { $rt .= ('b'); } } } echo($rt);} // Driver code$A = 2; $B = 6;generateString($A, $B); // This code is contributed// by Code Mech?>
<script>// Javascript implementation of the approach // Function to generate and // print the required stringfunction generateString(A,B){ let rt = ""; while (0 < A || 0 < B) { // More 'b', append "bba" if (A < B) { if (0 < B--) { rt += ('b'); } if (0 < B--) { rt += ('b'); } if (0 < A--) { rt += ('a'); } } // More 'a', append "aab" else if (B < A) { if (0 < A--) { rt += ('a'); } if (0 < A--) { rt += ('a'); } if (0 < B--) { rt += ('b'); } } // Equal number of 'a' and 'b' // append "ab" else { if (0 < A--) { rt += ('a'); } if (0 < B--) { rt += ('b'); } } } document.write(rt);} // Driver codelet A = 2, B = 6;generateString(A, B); // This code is contributed by avanitrachhadiya2155</script>
bbabbabb
princiraj1992
ankthon
ukasp
Code_Mech
avanitrachhadiya2155
Constructive Algorithms
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 50 String Coding Problems for Interviews
Naive algorithm for Pattern Searching
Vigenère Cipher
Count words in a given string
Hill Cipher
How to Append a Character to a String in C
Convert character array to string in C++
Program to count occurrence of a given character in a string
sprintf() in C
Converting Roman Numerals to Decimal lying between 1 to 3999
|
[
{
"code": null,
"e": 24854,
"s": 24826,
"text": "\n28 May, 2021"
},
{
"code": null,
"e": 24942,
"s": 24854,
"text": "Given two integers A and B, the task is to generate and print a string str such that: "
},
{
"code": null,
"e": 25165,
"s": 24942,
"text": "str must only contain the characters ‘a’ and ‘b’.str has length A + B and the occurrence of character ‘a’ is equal to A and the occurrence of character ‘b’ is equal to BThe sub-strings “aaa” or “bbb” must not occur in str."
},
{
"code": null,
"e": 25215,
"s": 25165,
"text": "str must only contain the characters ‘a’ and ‘b’."
},
{
"code": null,
"e": 25336,
"s": 25215,
"text": "str has length A + B and the occurrence of character ‘a’ is equal to A and the occurrence of character ‘b’ is equal to B"
},
{
"code": null,
"e": 25390,
"s": 25336,
"text": "The sub-strings “aaa” or “bbb” must not occur in str."
},
{
"code": null,
"e": 25484,
"s": 25390,
"text": "Note that for the given values of A and B, a valid string can always be generated.Examples: "
},
{
"code": null,
"e": 25597,
"s": 25484,
"text": "Input: A = 1, B = 2 Output: abb “abb”, “bab” and “bba” are all valid strings.Input: A = 4, B = 1 Output: aabaa "
},
{
"code": null,
"e": 25611,
"s": 25599,
"text": "Approach: "
},
{
"code": null,
"e": 25662,
"s": 25611,
"text": "If occurrence(a) > occurrence(b) then append “aab”"
},
{
"code": null,
"e": 25713,
"s": 25662,
"text": "If occurrence(b) > occurrence(a) then append “bba”"
},
{
"code": null,
"e": 25763,
"s": 25713,
"text": "If occurrence(a) = occurrence(b) then append “ab”"
},
{
"code": null,
"e": 26002,
"s": 25763,
"text": "Since we reduce the difference between the occurrences of ‘a’ and ‘b’ by at most 1 in each iteration so “bba” and “aab” are guaranteed not to be followed by “aab” and “bba” respectively.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26006,
"s": 26002,
"text": "C++"
},
{
"code": null,
"e": 26011,
"s": 26006,
"text": "Java"
},
{
"code": null,
"e": 26020,
"s": 26011,
"text": "Python 3"
},
{
"code": null,
"e": 26023,
"s": 26020,
"text": "C#"
},
{
"code": null,
"e": 26027,
"s": 26023,
"text": "PHP"
},
{
"code": null,
"e": 26038,
"s": 26027,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to generate and print the required stringvoid generateString(int A, int B){ string rt; while (0 < A || 0 < B) { // More 'b', append \"bba\" if (A < B) { if (0 < B--) rt.push_back('b'); if (0 < B--) rt.push_back('b'); if (0 < A--) rt.push_back('a'); } // More 'a', append \"aab\" else if (B < A) { if (0 < A--) rt.push_back('a'); if (0 < A--) rt.push_back('a'); if (0 < B--) rt.push_back('b'); } // Equal number of 'a' and 'b' // append \"ab\" else { if (0 < A--) rt.push_back('a'); if (0 < B--) rt.push_back('b'); } } cout << rt;} // Driver codeint main(){ int A = 2, B = 6; generateString(A, B); return 0;}",
"e": 27037,
"s": 26038,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Function to generate and // print the required string static void generateString(int A, int B) { String rt = \"\"; while (0 < A || 0 < B) { // More 'b', append \"bba\" if (A < B) { if (0 < B--) { rt += ('b'); } if (0 < B--) { rt += ('b'); } if (0 < A--) { rt += ('a'); } } // More 'a', append \"aab\" else if (B < A) { if (0 < A--) { rt += ('a'); } if (0 < A--) { rt += ('a'); } if (0 < B--) { rt += ('b'); } } // Equal number of 'a' and 'b' // append \"ab\" else { if (0 < A--) { rt += ('a'); } if (0 < B--) { rt += ('b'); } } } System.out.println(rt); } // Driver code public static void main(String[] args) { int A = 2, B = 6; generateString(A, B); }} // This code is contributed// by PrinciRaj1992",
"e": 28543,
"s": 27037,
"text": null
},
{
"code": "# Python 3 implementation of the approach # Function to generate and print# the required stringdef generateString(A, B): rt = \"\" while (0 < A or 0 < B) : # More 'b', append \"bba\" if (A < B) : if (0 < B): rt = rt +'b' B -= 1 if (0 < B): rt += 'b' B -= 1 if (0 < A): rt += 'a' A -= 1 # More 'a', append \"aab\" elif (B < A): if (0 < A): rt += 'a' A -= 1 if (0 < A): rt += 'a' A -= 1 if (0 < B): rt += 'b' B -= 1 # Equal number of 'a' and 'b' # append \"ab\" else : if (0 < A): rt += 'a' A -= 1 if (0 < B): rt += 'b' B -= 1 print(rt) # Driver codeif __name__ == \"__main__\": A = 2 B = 6 generateString(A, B) # This code is contributed by ita_c",
"e": 29583,
"s": 28543,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to generate and // print the required string static void generateString(int A, int B) { string rt = \"\"; while (0 < A || 0 < B) { // More 'b', append \"bba\" if (A < B) { if (0 < B--) { rt += ('b'); } if (0 < B--) { rt += ('b'); } if (0 < A--) { rt += ('a'); } } // More 'a', append \"aab\" else if (B < A) { if (0 < A--) { rt += ('a'); } if (0 < A--) { rt += ('a'); } if (0 < B--) { rt += ('b'); } } // Equal number of 'a' and 'b' // append \"ab\" else { if (0 < A--) { rt += ('a'); } if (0 < B--) { rt += ('b'); } } } Console.WriteLine(rt); } // Driver code public static void Main() { int A = 2, B = 6; generateString(A, B); }} // This code is contributed by Ryuga",
"e": 31077,
"s": 29583,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function to generate and// print the required stringfunction generateString($A, $B){ $rt = \"\"; while (0 < $A || 0 < $B) { // More 'b', append \"bba\" if ($A < $B) { if (0 < $B--) { $rt .= ('b'); } if (0 < $B--) { $rt .= ('b'); } if (0 < $A--) { $rt .= ('a'); } } // More 'a', append \"aab\" else if ($B < $A) { if (0 < $A--) { $rt .= ('a'); } if (0 < $A--) { $rt .= ('a'); } if (0 < $B--) { $rt .= ('b'); } } // Equal number of 'a' and 'b' // append \"ab\" else { if (0 < $A--) { $rt .= ('a'); } if (0 < $B--) { $rt .= ('b'); } } } echo($rt);} // Driver code$A = 2; $B = 6;generateString($A, $B); // This code is contributed// by Code Mech?>",
"e": 32268,
"s": 31077,
"text": null
},
{
"code": "<script>// Javascript implementation of the approach // Function to generate and // print the required stringfunction generateString(A,B){ let rt = \"\"; while (0 < A || 0 < B) { // More 'b', append \"bba\" if (A < B) { if (0 < B--) { rt += ('b'); } if (0 < B--) { rt += ('b'); } if (0 < A--) { rt += ('a'); } } // More 'a', append \"aab\" else if (B < A) { if (0 < A--) { rt += ('a'); } if (0 < A--) { rt += ('a'); } if (0 < B--) { rt += ('b'); } } // Equal number of 'a' and 'b' // append \"ab\" else { if (0 < A--) { rt += ('a'); } if (0 < B--) { rt += ('b'); } } } document.write(rt);} // Driver codelet A = 2, B = 6;generateString(A, B); // This code is contributed by avanitrachhadiya2155</script>",
"e": 33688,
"s": 32268,
"text": null
},
{
"code": null,
"e": 33697,
"s": 33688,
"text": "bbabbabb"
},
{
"code": null,
"e": 33713,
"s": 33699,
"text": "princiraj1992"
},
{
"code": null,
"e": 33721,
"s": 33713,
"text": "ankthon"
},
{
"code": null,
"e": 33727,
"s": 33721,
"text": "ukasp"
},
{
"code": null,
"e": 33737,
"s": 33727,
"text": "Code_Mech"
},
{
"code": null,
"e": 33758,
"s": 33737,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 33782,
"s": 33758,
"text": "Constructive Algorithms"
},
{
"code": null,
"e": 33790,
"s": 33782,
"text": "Strings"
},
{
"code": null,
"e": 33798,
"s": 33790,
"text": "Strings"
},
{
"code": null,
"e": 33896,
"s": 33798,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33941,
"s": 33896,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 33979,
"s": 33941,
"text": "Naive algorithm for Pattern Searching"
},
{
"code": null,
"e": 33996,
"s": 33979,
"text": "Vigenère Cipher"
},
{
"code": null,
"e": 34026,
"s": 33996,
"text": "Count words in a given string"
},
{
"code": null,
"e": 34038,
"s": 34026,
"text": "Hill Cipher"
},
{
"code": null,
"e": 34081,
"s": 34038,
"text": "How to Append a Character to a String in C"
},
{
"code": null,
"e": 34122,
"s": 34081,
"text": "Convert character array to string in C++"
},
{
"code": null,
"e": 34183,
"s": 34122,
"text": "Program to count occurrence of a given character in a string"
},
{
"code": null,
"e": 34198,
"s": 34183,
"text": "sprintf() in C"
}
] |
Simulating the NBA: 2021–22 Season Results | by Jake Mitchell | Towards Data Science
|
With the start of the NBA 2021–22 Preseason approaching quickly, I set out to simulate every team’s 82 games, plus the postseason, to find the league’s best and worst performances.
Similar to my NFL Season Simulation, all 30 teams have a rating. This year’s range starts at 1304 (Cleveland Cavaliers) and goes to 1752 (Milwaukee Bucks) with every other team somewhere in between.
Every team’s chance of winning a matchup is determined by this rating. Take the season opener as an example: The Bucks (1752) at home against the Nets (1717).
Using these equations, the Bucks have a 55.20% chance to win, while the Nets have a 44.80% chance to win.
A random number generator decides the winner, and then both ratings are adjusted based on if they were the underdog or not. The Bucks beating the Nets would increase their rating less than if the Nets beat the Bucks, purely because the Bucks are expected to win. This allows for teams to gain momentum throughout a season. The code for this is shown below:
for i = 1:length(home_schedule)Ha = 1/(1+10^((team_data(home_schedule(i),1) - team_data(away_schedule(i),1) + 2.5) * -1/400)); % approx home team chance of winningAa = 1/(1+10^((-1 * team_data(home_schedule(i),1) + team_data(away_schedule(i),1)) * -1/400)); % approx away team chance of winningT = Ha + Aa - 1; % chance of a tieH = Ha - T/2; % adjusted home team winning chancesA = Aa - T/2; % adjusted away team winning chancesteam_data(home_schedule(i),1) = team_data(home_schedule(i),1) + 20 * (HW - H); % adjusts home team's ranking based on resultteam_data(away_schedule(i),1) = team_data(away_schedule(i),1) + 20 * (AW - A); % adjusts away team's ranking based on resultend
This pattern is applied to all 1,230 games to decide the postseason schedule. The NBA postseason consists of 10 teams from each conference. The top 6 teams from each are automatically placed into the first round, while seeds 7–10 play in a small bracket to decide the 7th and 8th seed. Once all 8 teams from both conferences are determined, the postseason commences like a standard bracket, with the winners of both conference finals meeting at the championship game. Each matchup is a best of 7 series, with the higher seed getting the home games in game numbers 1,2,5, and 7 (if necessary).
All the data for regular season records, postseason records, and playoff chances are documented along the way as the season is repeated 50,000 times.
Below shows the most likely regular season record for all 30 teams, along with the statistics after 50,000 simulated seasons. The minimum and maximum columns represent the least and most amount of wins in a season for that team. The 10%, 50%, and 90% are the percentiles for all 50,000 simulations.
The Miami Heat are expected to go 43–39, with a 10% chance that they win less than 33 games and 10% chance that they win more than 55 games. This leaves them with an 80% chance they win between 33 and 55 games.
Each team’s playoff chances are shown below:
The first column represents the chances of that team finishing in the top 10 of that conference, meaning that they made the playoffs. The next column is the chance that a team makes the first round games (top 8).
Only one team did not win a single championship out of all 50,000 games, the Cleveland Cavaliers. The Orlando Magic and Oklahoma City Thunder both only won one championship.
The top 3 favorites to win the NBA Finals are the Milwaukee Bucks (16.150%), the Los Angeles Clippers (12.158%), and the Phoenix Suns (11.802%).
I was also interested in the odds that a team has the best or worst season in NBA history. The chance that at least one team beats the season wins record is 6.44%, with the Milwaukee Bucks accounting for 34.70% of those seasons. The next two likely teams are the Los Angeles Clippers (14.20%) and the Phoenix Suns (13.77%).
The chance that at least one team beats the season losses record is 12.08%, with the Cleveland Cavaliers accounting for 40.31% of those seasons. The next two likely teams are the Orlando Magic (19.20%) and the Oklahoma City Thunder (16.55%).
Out of all 50,000 simulated seasons, only one team has a chance to beat both the season wins and losses record. The Golden State Warriors have a 0.026% chance to lose the most games in NBA history, but a 0.031% chance to win the most games in NBA history.
This NBA season simulation showed that the Milwaukee Bucks are clear favorites for this year’s NBA Finals (16.15%), even with the Western Conference accounting for the majority of the championships won (54.05%).
The odds of a team having the worst season in NBA history are nearly twice as much as a team having the best season in NBA history.
Only one team won zero championships over all 50,000 simulations, and that is the Cleveland Cavaliers with an expected record of 17–65.
If this type of content interests you, I recommend reading my other article on professional sports simulations, The NFL Simulation.
|
[
{
"code": null,
"e": 352,
"s": 171,
"text": "With the start of the NBA 2021–22 Preseason approaching quickly, I set out to simulate every team’s 82 games, plus the postseason, to find the league’s best and worst performances."
},
{
"code": null,
"e": 551,
"s": 352,
"text": "Similar to my NFL Season Simulation, all 30 teams have a rating. This year’s range starts at 1304 (Cleveland Cavaliers) and goes to 1752 (Milwaukee Bucks) with every other team somewhere in between."
},
{
"code": null,
"e": 710,
"s": 551,
"text": "Every team’s chance of winning a matchup is determined by this rating. Take the season opener as an example: The Bucks (1752) at home against the Nets (1717)."
},
{
"code": null,
"e": 816,
"s": 710,
"text": "Using these equations, the Bucks have a 55.20% chance to win, while the Nets have a 44.80% chance to win."
},
{
"code": null,
"e": 1173,
"s": 816,
"text": "A random number generator decides the winner, and then both ratings are adjusted based on if they were the underdog or not. The Bucks beating the Nets would increase their rating less than if the Nets beat the Bucks, purely because the Bucks are expected to win. This allows for teams to gain momentum throughout a season. The code for this is shown below:"
},
{
"code": null,
"e": 1853,
"s": 1173,
"text": "for i = 1:length(home_schedule)Ha = 1/(1+10^((team_data(home_schedule(i),1) - team_data(away_schedule(i),1) + 2.5) * -1/400)); % approx home team chance of winningAa = 1/(1+10^((-1 * team_data(home_schedule(i),1) + team_data(away_schedule(i),1)) * -1/400)); % approx away team chance of winningT = Ha + Aa - 1; % chance of a tieH = Ha - T/2; % adjusted home team winning chancesA = Aa - T/2; % adjusted away team winning chancesteam_data(home_schedule(i),1) = team_data(home_schedule(i),1) + 20 * (HW - H); % adjusts home team's ranking based on resultteam_data(away_schedule(i),1) = team_data(away_schedule(i),1) + 20 * (AW - A); % adjusts away team's ranking based on resultend"
},
{
"code": null,
"e": 2446,
"s": 1853,
"text": "This pattern is applied to all 1,230 games to decide the postseason schedule. The NBA postseason consists of 10 teams from each conference. The top 6 teams from each are automatically placed into the first round, while seeds 7–10 play in a small bracket to decide the 7th and 8th seed. Once all 8 teams from both conferences are determined, the postseason commences like a standard bracket, with the winners of both conference finals meeting at the championship game. Each matchup is a best of 7 series, with the higher seed getting the home games in game numbers 1,2,5, and 7 (if necessary)."
},
{
"code": null,
"e": 2596,
"s": 2446,
"text": "All the data for regular season records, postseason records, and playoff chances are documented along the way as the season is repeated 50,000 times."
},
{
"code": null,
"e": 2895,
"s": 2596,
"text": "Below shows the most likely regular season record for all 30 teams, along with the statistics after 50,000 simulated seasons. The minimum and maximum columns represent the least and most amount of wins in a season for that team. The 10%, 50%, and 90% are the percentiles for all 50,000 simulations."
},
{
"code": null,
"e": 3106,
"s": 2895,
"text": "The Miami Heat are expected to go 43–39, with a 10% chance that they win less than 33 games and 10% chance that they win more than 55 games. This leaves them with an 80% chance they win between 33 and 55 games."
},
{
"code": null,
"e": 3151,
"s": 3106,
"text": "Each team’s playoff chances are shown below:"
},
{
"code": null,
"e": 3364,
"s": 3151,
"text": "The first column represents the chances of that team finishing in the top 10 of that conference, meaning that they made the playoffs. The next column is the chance that a team makes the first round games (top 8)."
},
{
"code": null,
"e": 3538,
"s": 3364,
"text": "Only one team did not win a single championship out of all 50,000 games, the Cleveland Cavaliers. The Orlando Magic and Oklahoma City Thunder both only won one championship."
},
{
"code": null,
"e": 3683,
"s": 3538,
"text": "The top 3 favorites to win the NBA Finals are the Milwaukee Bucks (16.150%), the Los Angeles Clippers (12.158%), and the Phoenix Suns (11.802%)."
},
{
"code": null,
"e": 4007,
"s": 3683,
"text": "I was also interested in the odds that a team has the best or worst season in NBA history. The chance that at least one team beats the season wins record is 6.44%, with the Milwaukee Bucks accounting for 34.70% of those seasons. The next two likely teams are the Los Angeles Clippers (14.20%) and the Phoenix Suns (13.77%)."
},
{
"code": null,
"e": 4249,
"s": 4007,
"text": "The chance that at least one team beats the season losses record is 12.08%, with the Cleveland Cavaliers accounting for 40.31% of those seasons. The next two likely teams are the Orlando Magic (19.20%) and the Oklahoma City Thunder (16.55%)."
},
{
"code": null,
"e": 4505,
"s": 4249,
"text": "Out of all 50,000 simulated seasons, only one team has a chance to beat both the season wins and losses record. The Golden State Warriors have a 0.026% chance to lose the most games in NBA history, but a 0.031% chance to win the most games in NBA history."
},
{
"code": null,
"e": 4717,
"s": 4505,
"text": "This NBA season simulation showed that the Milwaukee Bucks are clear favorites for this year’s NBA Finals (16.15%), even with the Western Conference accounting for the majority of the championships won (54.05%)."
},
{
"code": null,
"e": 4849,
"s": 4717,
"text": "The odds of a team having the worst season in NBA history are nearly twice as much as a team having the best season in NBA history."
},
{
"code": null,
"e": 4985,
"s": 4849,
"text": "Only one team won zero championships over all 50,000 simulations, and that is the Cleveland Cavaliers with an expected record of 17–65."
}
] |
Count of N digit numbers not having given prefixes - GeeksforGeeks
|
24 Nov, 2021
Given an integer N and a vector of strings prefixes[], the task is to calculate the total possible strings of length N from characters ‘0’ to ‘9’. such that the given prefixes cannot be used in any of the strings.
Examples:
Input: N = 3, prefixes = {“42”}Output: 990Explanation: All string except{“420”, “421”, “422”, “423”, “424”, “425”, “426”, “427”, “428”, “429”} are valid.
Input: N = 5, prefixes[] = { “0”, “1”, “911” }Output: 79900
Approach: The total possible strings with length are (10^N) as for each place in a string there are 10 choices of the character. Instead of calculating total good strings, subtract total bad strings from total strings. Before iterating over the prefixes merge prefixes with the same starting character as the bigger length prefix might lead to subtraction of some repetitions. Follow the steps below to solve the problem:
Initialize the variable total as 10N.
Initialize a map<int, vector<string>> mp[].
Iterate over the range [0, M) using the variable i and perform the following tasks:Push the value of prefixes[i] in the vector of map mp[prefixes[i]-‘0’].
Push the value of prefixes[i] in the vector of map mp[prefixes[i]-‘0’].
Initialize the vector new_prefixes[].
Traverse over the map mp[] using the variable x and perform the following tasks:Initialize the variable mn as N.Traverse the vector x.second using the variable p and perform the following tasks:Set the value of mn as the minimum of mn or p.length().Traverse the vector x.second using the variable p and perform the following tasks:If p.length() is less than equal to mn, then push p into the vector new_prefixes[].
Initialize the variable mn as N.
Traverse the vector x.second using the variable p and perform the following tasks:Set the value of mn as the minimum of mn or p.length().
Set the value of mn as the minimum of mn or p.length().
Traverse the vector x.second using the variable p and perform the following tasks:If p.length() is less than equal to mn, then push p into the vector new_prefixes[].
If p.length() is less than equal to mn, then push p into the vector new_prefixes[].
Iterate over the range [0, new_prefixes.size()) using the variable i and perform the following tasks:Subtract the value int(pow(10, N – new_prefixes[i].length())+ 0.5) from the variable total.
Subtract the value int(pow(10, N – new_prefixes[i].length())+ 0.5) from the variable total.
After performing the above steps, print the value of total as the answer.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program to implement the above approach#include <bits/stdc++.h>using namespace std; // Change int to long long in case of overflow!!// Function to calculate total strings of length// N without the given prefixesint totalGoodStrings(int N, vector<string> prefixes){ // Calculate total strings present int total = int(pow(10, N) + 0.5); // Make a map and insert the prefixes with same // character in a vector map<int, vector<string> > mp; for (int i = 0; i < prefixes.size(); i++) { mp[prefixes[i][0] - '0'] .push_back(prefixes[i]); } // Make a new vector of prefixes strings vector<string> new_prefixes; // Iterate for each starting character for (auto x : mp) { int mn = N; // Iterate through the vector to calculate // minimum size prefix for (auto p : x.second) { mn = min(mn, int(p.length())); } // Take all the minimum prefixes in the new // vector of prefixes for (string p : x.second) { if (p.length() > mn) { continue; } new_prefixes.push_back(p); } } // Iterate through the new prefixes for (int i = 0; i < new_prefixes.size(); i++) { // Subtract bad strings total -= int(pow(10, N - new_prefixes[i].length()) + 0.5); } return total;} // Driver Codeint main(){ int N = 5; vector<string> prefixes = { "1", "0", "911" }; cout << totalGoodStrings(N, prefixes); return 0;}
// Java Program to implement the above approachimport java.util.ArrayList;import java.util.HashMap; class GFG{ // Change int to long long in case of overflow!! // Function to calculate total strings of length // N without the given prefixes public static int totalGoodStrings(int N, String[] prefixes) { // Calculate total strings present int total = (int) (Math.pow(10, N) + 0.5); // Make a map and insert the prefixes with same // character in a vector HashMap<Integer, ArrayList<String>> mp = new HashMap<Integer, ArrayList<String>>(); for (int i = 0; i < prefixes.length; i++) { int key = (int) prefixes[i].charAt(0) - (int) '0'; if (mp.containsKey(key)) { ArrayList<String> temp = mp.get(key); temp.add(prefixes[i]); mp.put(key, temp); } else { ArrayList<String> temp = new ArrayList<String>(); temp.add(prefixes[i]); mp.put(key, temp); } } // Make a new vector of prefixes strings ArrayList<String> new_prefixes = new ArrayList<String>(); // Iterate for each starting character for (Integer x : mp.keySet()) { int mn = N; // Iterate through the vector to calculate // minimum size prefix for (String p : mp.get(x)) { mn = Math.min(mn, p.length()); } // Take all the minimum prefixes in the new // vector of prefixes for (String p : mp.get(x)) { if (p.length() > mn) { continue; } new_prefixes.add(p); } } // Iterate through the new prefixes for (int i = 0; i < new_prefixes.size(); i++) { // Subtract bad strings total -= (int) (Math.pow(10, N - new_prefixes.get(i).length()) + 0.5); } return total; } // Driver Code public static void main(String args[]) { int N = 5; String[] prefixes = { "1", "0", "911" }; System.out.println(totalGoodStrings(N, prefixes)); }} // This code is contributed by gfgking.
# python Program to implement the above approachimport math # Change int to long long in case of overflow!!# Function to calculate total strings of length# N without the given prefixesdef totalGoodStrings(N, prefixes): # Calculate total strings present total = int(math.pow(10, N) + 0.5) # Make a map and insert the prefixes with same # character in a vector mp = {} for i in range(0, len(prefixes)): if (ord(prefixes[i][0]) - ord('0')) in mp: mp[ord(prefixes[i][0]) - ord('0')].append(prefixes[i]) else: mp[ord(prefixes[i][0]) - ord('0')] = [prefixes[i]] # Make a new vector of prefixes strings new_prefixes = [] # Iterate for each starting character for x in mp: mn = N # Iterate through the vector to calculate # minimum size prefix for p in mp[x]: mn = min(mn, len(p)) # Take all the minimum prefixes in the new # vector of prefixes for p in mp[x]: if (len(p) > mn): continue new_prefixes.append(p) # Iterate through the new prefixes for i in range(0, len(new_prefixes)): # Subtract bad strings total -= int(pow(10, N - len(new_prefixes[i])) + 0.5) return total # Driver Codeif __name__ == "__main__": N = 5 prefixes = ["1", "0", "911"] print(totalGoodStrings(N, prefixes)) # This code is contributed by rakeshsahni
// C# Program to implement the above approachusing System;using System.Collections.Generic;class GFG { // Change int to long long in case of overflow!! // Function to calculate total strings of length // N without the given prefixes public static int totalGoodStrings(int N, string[] prefixes) { // Calculate total strings present int total = (int)(Math.Pow(10, N) + 0.5); // Make a map and insert the prefixes with same // character in a vector Dictionary<int, List<string> > mp = new Dictionary<int, List<string> >(); for (int i = 0; i < prefixes.Length; i++) { int key = (int)prefixes[i][0] - (int)'0'; if (mp.ContainsKey(key)) { List<string> temp = mp[key]; temp.Add(prefixes[i]); mp[key] = temp; } else { List<string> temp = new List<string>(); temp.Add(prefixes[i]); mp[key] = temp; } } // Make a new vector of prefixes strings List<string> new_prefixes = new List<string>(); // Iterate for each starting character foreach(int x in mp.Keys) { int mn = N; // Iterate through the vector to calculate // minimum size prefix foreach(string p in mp[x]) { mn = Math.Min(mn, p.Length); } // Take all the minimum prefixes in the new // vector of prefixes foreach(string p in mp[x]) { if (p.Length > mn) { continue; } new_prefixes.Add(p); } } // Iterate through the new prefixes for (int i = 0; i < new_prefixes.Count; i++) { // Subtract bad strings total -= (int)(Math.Pow( 10, N - new_prefixes[i].Length) + 0.5); } return total; } // Driver Code public static void Main(string[] args) { int N = 5; string[] prefixes = { "1", "0", "911" }; Console.WriteLine(totalGoodStrings(N, prefixes)); }} // This code is contributed by ukasp.
// Javascript Program to implement the above approach // Change int to long long in case of overflow!!// Function to calculate total strings of length// N without the given prefixesfunction totalGoodStrings(N, prefixes) { // Calculate total strings present let total = Math.floor(Math.pow(10, N) + 0.5); // Make a map and insert the prefixes with same // character in a vector let mp = new Map(); for (let i = 0; i < prefixes.length; i++) { let key = prefixes[i][0] - '0'.charCodeAt(0); if (mp.has(key)) { let temp = mp.get(key); temp.push(prefixes[i]) mp.set(key, temp) } else { mp.set(key, [prefixes[i]]) } } // Make a new vector of prefixes strings let new_prefixes = []; // Iterate for each starting character for (x of mp) { let mn = N; // Iterate through the vector to calculate // minimum size prefix for (p of x[1]) { mn = Math.min(mn, p.length); } // Take all the minimum prefixes in the new // vector of prefixes for (p of x[1]) { if (p.length > mn) { continue; } new_prefixes.push(p); } } // Iterate through the new prefixes for (let i = 0; i < new_prefixes.length; i++) { // Subtract bad strings total -= Math.floor(Math.pow(10, N - new_prefixes[i].length) + 0.5); } return total;} // Driver Code let N = 5; let prefixes = ["1", "0", "911"]; document.write(totalGoodStrings(N, prefixes)) // This code is contributed by saurabh_jaiswal.
79900
Time Complexity: O(M), where M is the size of the vector prefixes[]Auxiliary Space: O(M*K), where K is the maximum length of a string
rakeshsahni
_saurabh_jaiswal
gfgking
ukasp
combionatrics
prefix
Combinatorial
Mathematical
Strings
Strings
Mathematical
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Combinations with repetitions
Ways to sum to N using Natural Numbers up to K with repetitions allowed
Largest number by rearranging digits of a given positive or negative number
Generate all possible combinations of at most X characters from a given array
Given number of matches played, find number of teams in tournament
Program for Fibonacci numbers
C++ Data Types
Set in C++ Standard Template Library (STL)
Program to find GCD or HCF of two numbers
Coin Change | DP-7
|
[
{
"code": null,
"e": 25452,
"s": 25424,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 25666,
"s": 25452,
"text": "Given an integer N and a vector of strings prefixes[], the task is to calculate the total possible strings of length N from characters ‘0’ to ‘9’. such that the given prefixes cannot be used in any of the strings."
},
{
"code": null,
"e": 25677,
"s": 25666,
"text": "Examples: "
},
{
"code": null,
"e": 25831,
"s": 25677,
"text": "Input: N = 3, prefixes = {“42”}Output: 990Explanation: All string except{“420”, “421”, “422”, “423”, “424”, “425”, “426”, “427”, “428”, “429”} are valid."
},
{
"code": null,
"e": 25891,
"s": 25831,
"text": "Input: N = 5, prefixes[] = { “0”, “1”, “911” }Output: 79900"
},
{
"code": null,
"e": 26313,
"s": 25891,
"text": "Approach: The total possible strings with length are (10^N) as for each place in a string there are 10 choices of the character. Instead of calculating total good strings, subtract total bad strings from total strings. Before iterating over the prefixes merge prefixes with the same starting character as the bigger length prefix might lead to subtraction of some repetitions. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 26351,
"s": 26313,
"text": "Initialize the variable total as 10N."
},
{
"code": null,
"e": 26395,
"s": 26351,
"text": "Initialize a map<int, vector<string>> mp[]."
},
{
"code": null,
"e": 26550,
"s": 26395,
"text": "Iterate over the range [0, M) using the variable i and perform the following tasks:Push the value of prefixes[i] in the vector of map mp[prefixes[i]-‘0’]."
},
{
"code": null,
"e": 26622,
"s": 26550,
"text": "Push the value of prefixes[i] in the vector of map mp[prefixes[i]-‘0’]."
},
{
"code": null,
"e": 26660,
"s": 26622,
"text": "Initialize the vector new_prefixes[]."
},
{
"code": null,
"e": 27075,
"s": 26660,
"text": "Traverse over the map mp[] using the variable x and perform the following tasks:Initialize the variable mn as N.Traverse the vector x.second using the variable p and perform the following tasks:Set the value of mn as the minimum of mn or p.length().Traverse the vector x.second using the variable p and perform the following tasks:If p.length() is less than equal to mn, then push p into the vector new_prefixes[]."
},
{
"code": null,
"e": 27108,
"s": 27075,
"text": "Initialize the variable mn as N."
},
{
"code": null,
"e": 27246,
"s": 27108,
"text": "Traverse the vector x.second using the variable p and perform the following tasks:Set the value of mn as the minimum of mn or p.length()."
},
{
"code": null,
"e": 27302,
"s": 27246,
"text": "Set the value of mn as the minimum of mn or p.length()."
},
{
"code": null,
"e": 27468,
"s": 27302,
"text": "Traverse the vector x.second using the variable p and perform the following tasks:If p.length() is less than equal to mn, then push p into the vector new_prefixes[]."
},
{
"code": null,
"e": 27552,
"s": 27468,
"text": "If p.length() is less than equal to mn, then push p into the vector new_prefixes[]."
},
{
"code": null,
"e": 27745,
"s": 27552,
"text": "Iterate over the range [0, new_prefixes.size()) using the variable i and perform the following tasks:Subtract the value int(pow(10, N – new_prefixes[i].length())+ 0.5) from the variable total."
},
{
"code": null,
"e": 27837,
"s": 27745,
"text": "Subtract the value int(pow(10, N – new_prefixes[i].length())+ 0.5) from the variable total."
},
{
"code": null,
"e": 27911,
"s": 27837,
"text": "After performing the above steps, print the value of total as the answer."
},
{
"code": null,
"e": 27963,
"s": 27911,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27967,
"s": 27963,
"text": "C++"
},
{
"code": null,
"e": 27972,
"s": 27967,
"text": "Java"
},
{
"code": null,
"e": 27980,
"s": 27972,
"text": "Python3"
},
{
"code": null,
"e": 27983,
"s": 27980,
"text": "C#"
},
{
"code": null,
"e": 27994,
"s": 27983,
"text": "Javascript"
},
{
"code": "// C++ Program to implement the above approach#include <bits/stdc++.h>using namespace std; // Change int to long long in case of overflow!!// Function to calculate total strings of length// N without the given prefixesint totalGoodStrings(int N, vector<string> prefixes){ // Calculate total strings present int total = int(pow(10, N) + 0.5); // Make a map and insert the prefixes with same // character in a vector map<int, vector<string> > mp; for (int i = 0; i < prefixes.size(); i++) { mp[prefixes[i][0] - '0'] .push_back(prefixes[i]); } // Make a new vector of prefixes strings vector<string> new_prefixes; // Iterate for each starting character for (auto x : mp) { int mn = N; // Iterate through the vector to calculate // minimum size prefix for (auto p : x.second) { mn = min(mn, int(p.length())); } // Take all the minimum prefixes in the new // vector of prefixes for (string p : x.second) { if (p.length() > mn) { continue; } new_prefixes.push_back(p); } } // Iterate through the new prefixes for (int i = 0; i < new_prefixes.size(); i++) { // Subtract bad strings total -= int(pow(10, N - new_prefixes[i].length()) + 0.5); } return total;} // Driver Codeint main(){ int N = 5; vector<string> prefixes = { \"1\", \"0\", \"911\" }; cout << totalGoodStrings(N, prefixes); return 0;}",
"e": 29556,
"s": 27994,
"text": null
},
{
"code": "// Java Program to implement the above approachimport java.util.ArrayList;import java.util.HashMap; class GFG{ // Change int to long long in case of overflow!! // Function to calculate total strings of length // N without the given prefixes public static int totalGoodStrings(int N, String[] prefixes) { // Calculate total strings present int total = (int) (Math.pow(10, N) + 0.5); // Make a map and insert the prefixes with same // character in a vector HashMap<Integer, ArrayList<String>> mp = new HashMap<Integer, ArrayList<String>>(); for (int i = 0; i < prefixes.length; i++) { int key = (int) prefixes[i].charAt(0) - (int) '0'; if (mp.containsKey(key)) { ArrayList<String> temp = mp.get(key); temp.add(prefixes[i]); mp.put(key, temp); } else { ArrayList<String> temp = new ArrayList<String>(); temp.add(prefixes[i]); mp.put(key, temp); } } // Make a new vector of prefixes strings ArrayList<String> new_prefixes = new ArrayList<String>(); // Iterate for each starting character for (Integer x : mp.keySet()) { int mn = N; // Iterate through the vector to calculate // minimum size prefix for (String p : mp.get(x)) { mn = Math.min(mn, p.length()); } // Take all the minimum prefixes in the new // vector of prefixes for (String p : mp.get(x)) { if (p.length() > mn) { continue; } new_prefixes.add(p); } } // Iterate through the new prefixes for (int i = 0; i < new_prefixes.size(); i++) { // Subtract bad strings total -= (int) (Math.pow(10, N - new_prefixes.get(i).length()) + 0.5); } return total; } // Driver Code public static void main(String args[]) { int N = 5; String[] prefixes = { \"1\", \"0\", \"911\" }; System.out.println(totalGoodStrings(N, prefixes)); }} // This code is contributed by gfgking.",
"e": 31502,
"s": 29556,
"text": null
},
{
"code": "# python Program to implement the above approachimport math # Change int to long long in case of overflow!!# Function to calculate total strings of length# N without the given prefixesdef totalGoodStrings(N, prefixes): # Calculate total strings present total = int(math.pow(10, N) + 0.5) # Make a map and insert the prefixes with same # character in a vector mp = {} for i in range(0, len(prefixes)): if (ord(prefixes[i][0]) - ord('0')) in mp: mp[ord(prefixes[i][0]) - ord('0')].append(prefixes[i]) else: mp[ord(prefixes[i][0]) - ord('0')] = [prefixes[i]] # Make a new vector of prefixes strings new_prefixes = [] # Iterate for each starting character for x in mp: mn = N # Iterate through the vector to calculate # minimum size prefix for p in mp[x]: mn = min(mn, len(p)) # Take all the minimum prefixes in the new # vector of prefixes for p in mp[x]: if (len(p) > mn): continue new_prefixes.append(p) # Iterate through the new prefixes for i in range(0, len(new_prefixes)): # Subtract bad strings total -= int(pow(10, N - len(new_prefixes[i])) + 0.5) return total # Driver Codeif __name__ == \"__main__\": N = 5 prefixes = [\"1\", \"0\", \"911\"] print(totalGoodStrings(N, prefixes)) # This code is contributed by rakeshsahni",
"e": 32955,
"s": 31502,
"text": null
},
{
"code": "// C# Program to implement the above approachusing System;using System.Collections.Generic;class GFG { // Change int to long long in case of overflow!! // Function to calculate total strings of length // N without the given prefixes public static int totalGoodStrings(int N, string[] prefixes) { // Calculate total strings present int total = (int)(Math.Pow(10, N) + 0.5); // Make a map and insert the prefixes with same // character in a vector Dictionary<int, List<string> > mp = new Dictionary<int, List<string> >(); for (int i = 0; i < prefixes.Length; i++) { int key = (int)prefixes[i][0] - (int)'0'; if (mp.ContainsKey(key)) { List<string> temp = mp[key]; temp.Add(prefixes[i]); mp[key] = temp; } else { List<string> temp = new List<string>(); temp.Add(prefixes[i]); mp[key] = temp; } } // Make a new vector of prefixes strings List<string> new_prefixes = new List<string>(); // Iterate for each starting character foreach(int x in mp.Keys) { int mn = N; // Iterate through the vector to calculate // minimum size prefix foreach(string p in mp[x]) { mn = Math.Min(mn, p.Length); } // Take all the minimum prefixes in the new // vector of prefixes foreach(string p in mp[x]) { if (p.Length > mn) { continue; } new_prefixes.Add(p); } } // Iterate through the new prefixes for (int i = 0; i < new_prefixes.Count; i++) { // Subtract bad strings total -= (int)(Math.Pow( 10, N - new_prefixes[i].Length) + 0.5); } return total; } // Driver Code public static void Main(string[] args) { int N = 5; string[] prefixes = { \"1\", \"0\", \"911\" }; Console.WriteLine(totalGoodStrings(N, prefixes)); }} // This code is contributed by ukasp.",
"e": 35251,
"s": 32955,
"text": null
},
{
"code": "// Javascript Program to implement the above approach // Change int to long long in case of overflow!!// Function to calculate total strings of length// N without the given prefixesfunction totalGoodStrings(N, prefixes) { // Calculate total strings present let total = Math.floor(Math.pow(10, N) + 0.5); // Make a map and insert the prefixes with same // character in a vector let mp = new Map(); for (let i = 0; i < prefixes.length; i++) { let key = prefixes[i][0] - '0'.charCodeAt(0); if (mp.has(key)) { let temp = mp.get(key); temp.push(prefixes[i]) mp.set(key, temp) } else { mp.set(key, [prefixes[i]]) } } // Make a new vector of prefixes strings let new_prefixes = []; // Iterate for each starting character for (x of mp) { let mn = N; // Iterate through the vector to calculate // minimum size prefix for (p of x[1]) { mn = Math.min(mn, p.length); } // Take all the minimum prefixes in the new // vector of prefixes for (p of x[1]) { if (p.length > mn) { continue; } new_prefixes.push(p); } } // Iterate through the new prefixes for (let i = 0; i < new_prefixes.length; i++) { // Subtract bad strings total -= Math.floor(Math.pow(10, N - new_prefixes[i].length) + 0.5); } return total;} // Driver Code let N = 5; let prefixes = [\"1\", \"0\", \"911\"]; document.write(totalGoodStrings(N, prefixes)) // This code is contributed by saurabh_jaiswal.",
"e": 36717,
"s": 35251,
"text": null
},
{
"code": null,
"e": 36723,
"s": 36717,
"text": "79900"
},
{
"code": null,
"e": 36857,
"s": 36723,
"text": "Time Complexity: O(M), where M is the size of the vector prefixes[]Auxiliary Space: O(M*K), where K is the maximum length of a string"
},
{
"code": null,
"e": 36869,
"s": 36857,
"text": "rakeshsahni"
},
{
"code": null,
"e": 36886,
"s": 36869,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 36894,
"s": 36886,
"text": "gfgking"
},
{
"code": null,
"e": 36900,
"s": 36894,
"text": "ukasp"
},
{
"code": null,
"e": 36914,
"s": 36900,
"text": "combionatrics"
},
{
"code": null,
"e": 36921,
"s": 36914,
"text": "prefix"
},
{
"code": null,
"e": 36935,
"s": 36921,
"text": "Combinatorial"
},
{
"code": null,
"e": 36948,
"s": 36935,
"text": "Mathematical"
},
{
"code": null,
"e": 36956,
"s": 36948,
"text": "Strings"
},
{
"code": null,
"e": 36964,
"s": 36956,
"text": "Strings"
},
{
"code": null,
"e": 36977,
"s": 36964,
"text": "Mathematical"
},
{
"code": null,
"e": 36991,
"s": 36977,
"text": "Combinatorial"
},
{
"code": null,
"e": 37089,
"s": 36991,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37098,
"s": 37089,
"text": "Comments"
},
{
"code": null,
"e": 37111,
"s": 37098,
"text": "Old Comments"
},
{
"code": null,
"e": 37141,
"s": 37111,
"text": "Combinations with repetitions"
},
{
"code": null,
"e": 37213,
"s": 37141,
"text": "Ways to sum to N using Natural Numbers up to K with repetitions allowed"
},
{
"code": null,
"e": 37289,
"s": 37213,
"text": "Largest number by rearranging digits of a given positive or negative number"
},
{
"code": null,
"e": 37367,
"s": 37289,
"text": "Generate all possible combinations of at most X characters from a given array"
},
{
"code": null,
"e": 37434,
"s": 37367,
"text": "Given number of matches played, find number of teams in tournament"
},
{
"code": null,
"e": 37464,
"s": 37434,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 37479,
"s": 37464,
"text": "C++ Data Types"
},
{
"code": null,
"e": 37522,
"s": 37479,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 37564,
"s": 37522,
"text": "Program to find GCD or HCF of two numbers"
}
] |
Adding Legend to Multiple Line Plots with ggplot in R - GeeksforGeeks
|
23 Aug, 2021
In this article, we are going to see how can we add a legend to multiple line plots with ggplot in the R programming language.
For a plot that contains more than one line plot, a legend is created by default if the col attribute is used. All the changes made in the appearance of the line plots will also reflect in the legend.
Syntax: ggplot(df, aes(x, y, col=”name of the column to differentiate on the basis of”))
Let us first visualize how the curve will appear as default.
Example: Default plot
R
library("ggplot2") function1<- function(x){x**2}function2<-function(x){x**3}function3<-function(x){x/2}function4<-function(x){2*(x**3)+(x**2)-(x/2)} df=data.frame(x=-2:2, values=c(function1(-2:2), function2(-2:2), function3(-2:2), function4(-2:2)), fun=rep(c("function1","function2","function3","function4"))) ggplot(df,aes(x,values,col=fun))+geom_line()
Output:
Various changes made to the lines will appear in the legends as well, let’s see how:
To change color by default, the above plot will be produced, now suppose we manually want to add colors to the line, for that any of the given functions- scale_color_manual(), scale_color_brewer(), and scale_color_grey().
Example: changing color of the lines
R
library("ggplot2") function1<- function(x){x**2}function2<-function(x){x**3}function3<-function(x){x/2}function4<-function(x){2*(x**3)+(x**2)-(x/2)} df=data.frame(x=-2:2, values=c(function1(-2:2), function2(-2:2), function3(-2:2), function4(-2:2)), fun=rep(c("function1","function2", "function3","function4"))) ggplot(df,aes(x,values,col=fun))+geom_line()+ scale_color_manual(values=c("green","yellow","red","grey"))
Output:
For this, the size attribute is used with a specific value. The changes will be reflected in the legend too.
Example:
R
library("ggplot2") function1<- function(x){x**2}function2<-function(x){x**3}function3<-function(x){x/2}function4<-function(x){2*(x**3)+(x**2)-(x/2)} df=data.frame(x=-2:2, values=c(function1(-2:2), function2(-2:2), function3(-2:2), function4(-2:2)), fun=rep(c("function1","function2", "function3","function4")) ) ggplot(df,aes(x,values,col=fun))+geom_line(size=3)
Output:
Line type of the plots can be changed using any of the given functions- scale_linetype_manual(), or by default through the use of linetype keyword.
Example:
R
library("ggplot2") function1<- function(x){x**2}function2<-function(x){x**3}function3<-function(x){x/2}function4<-function(x){2*(x**3)+(x**2)-(x/2)} df=data.frame(x=-2:2, values=c(function1(-2:2), function2(-2:2), function3(-2:2), function4(-2:2)), fun=rep(c("function1","function2", "function3","function4"))) ggplot(df,aes(x,values, group=fun, color=fun, linetype=fun))+geom_line(size=1)+scale_linetype_manual(values = c("solid","dotted","dashed","twodash"))+scale_color_manual(values=c("red","green","blue","black"))
Output:
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to import an Excel File into R ?
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
R - if statement
Replace Specific Characters in String in R
How to change the order of bars in bar chart in R ?
|
[
{
"code": null,
"e": 25242,
"s": 25214,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 25370,
"s": 25242,
"text": "In this article, we are going to see how can we add a legend to multiple line plots with ggplot in the R programming language. "
},
{
"code": null,
"e": 25571,
"s": 25370,
"text": "For a plot that contains more than one line plot, a legend is created by default if the col attribute is used. All the changes made in the appearance of the line plots will also reflect in the legend."
},
{
"code": null,
"e": 25660,
"s": 25571,
"text": "Syntax: ggplot(df, aes(x, y, col=”name of the column to differentiate on the basis of”))"
},
{
"code": null,
"e": 25721,
"s": 25660,
"text": "Let us first visualize how the curve will appear as default."
},
{
"code": null,
"e": 25743,
"s": 25721,
"text": "Example: Default plot"
},
{
"code": null,
"e": 25745,
"s": 25743,
"text": "R"
},
{
"code": "library(\"ggplot2\") function1<- function(x){x**2}function2<-function(x){x**3}function3<-function(x){x/2}function4<-function(x){2*(x**3)+(x**2)-(x/2)} df=data.frame(x=-2:2, values=c(function1(-2:2), function2(-2:2), function3(-2:2), function4(-2:2)), fun=rep(c(\"function1\",\"function2\",\"function3\",\"function4\"))) ggplot(df,aes(x,values,col=fun))+geom_line()",
"e": 26195,
"s": 25745,
"text": null
},
{
"code": null,
"e": 26203,
"s": 26195,
"text": "Output:"
},
{
"code": null,
"e": 26288,
"s": 26203,
"text": "Various changes made to the lines will appear in the legends as well, let’s see how:"
},
{
"code": null,
"e": 26510,
"s": 26288,
"text": "To change color by default, the above plot will be produced, now suppose we manually want to add colors to the line, for that any of the given functions- scale_color_manual(), scale_color_brewer(), and scale_color_grey()."
},
{
"code": null,
"e": 26547,
"s": 26510,
"text": "Example: changing color of the lines"
},
{
"code": null,
"e": 26549,
"s": 26547,
"text": "R"
},
{
"code": "library(\"ggplot2\") function1<- function(x){x**2}function2<-function(x){x**3}function3<-function(x){x/2}function4<-function(x){2*(x**3)+(x**2)-(x/2)} df=data.frame(x=-2:2, values=c(function1(-2:2), function2(-2:2), function3(-2:2), function4(-2:2)), fun=rep(c(\"function1\",\"function2\", \"function3\",\"function4\"))) ggplot(df,aes(x,values,col=fun))+geom_line()+ scale_color_manual(values=c(\"green\",\"yellow\",\"red\",\"grey\"))",
"e": 27085,
"s": 26549,
"text": null
},
{
"code": null,
"e": 27093,
"s": 27085,
"text": "Output:"
},
{
"code": null,
"e": 27202,
"s": 27093,
"text": "For this, the size attribute is used with a specific value. The changes will be reflected in the legend too."
},
{
"code": null,
"e": 27211,
"s": 27202,
"text": "Example:"
},
{
"code": null,
"e": 27213,
"s": 27211,
"text": "R"
},
{
"code": "library(\"ggplot2\") function1<- function(x){x**2}function2<-function(x){x**3}function3<-function(x){x/2}function4<-function(x){2*(x**3)+(x**2)-(x/2)} df=data.frame(x=-2:2, values=c(function1(-2:2), function2(-2:2), function3(-2:2), function4(-2:2)), fun=rep(c(\"function1\",\"function2\", \"function3\",\"function4\")) ) ggplot(df,aes(x,values,col=fun))+geom_line(size=3)",
"e": 27707,
"s": 27213,
"text": null
},
{
"code": null,
"e": 27715,
"s": 27707,
"text": "Output:"
},
{
"code": null,
"e": 27863,
"s": 27715,
"text": "Line type of the plots can be changed using any of the given functions- scale_linetype_manual(), or by default through the use of linetype keyword."
},
{
"code": null,
"e": 27872,
"s": 27863,
"text": "Example:"
},
{
"code": null,
"e": 27874,
"s": 27872,
"text": "R"
},
{
"code": "library(\"ggplot2\") function1<- function(x){x**2}function2<-function(x){x**3}function3<-function(x){x/2}function4<-function(x){2*(x**3)+(x**2)-(x/2)} df=data.frame(x=-2:2, values=c(function1(-2:2), function2(-2:2), function3(-2:2), function4(-2:2)), fun=rep(c(\"function1\",\"function2\", \"function3\",\"function4\"))) ggplot(df,aes(x,values, group=fun, color=fun, linetype=fun))+geom_line(size=1)+scale_linetype_manual(values = c(\"solid\",\"dotted\",\"dashed\",\"twodash\"))+scale_color_manual(values=c(\"red\",\"green\",\"blue\",\"black\"))",
"e": 28512,
"s": 27874,
"text": null
},
{
"code": null,
"e": 28520,
"s": 28512,
"text": "Output:"
},
{
"code": null,
"e": 28527,
"s": 28520,
"text": "Picked"
},
{
"code": null,
"e": 28536,
"s": 28527,
"text": "R-ggplot"
},
{
"code": null,
"e": 28547,
"s": 28536,
"text": "R Language"
},
{
"code": null,
"e": 28645,
"s": 28547,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28654,
"s": 28645,
"text": "Comments"
},
{
"code": null,
"e": 28667,
"s": 28654,
"text": "Old Comments"
},
{
"code": null,
"e": 28719,
"s": 28667,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28757,
"s": 28719,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 28792,
"s": 28757,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 28850,
"s": 28792,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28887,
"s": 28850,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 28936,
"s": 28887,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 28986,
"s": 28936,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 29003,
"s": 28986,
"text": "R - if statement"
},
{
"code": null,
"e": 29046,
"s": 29003,
"text": "Replace Specific Characters in String in R"
}
] |
ReactJS – Component vs PureComponent
|
In this article, we are going to see the difference between Component and PureComponent. In ReactJS, Components are widely used to make an App more efficient and effective to use.
ReactJS provides two different ways to use components – Component or PureComponent.
It is the type of component which re-renders itself every time when the props passed to it changes or its parent component re-renders.
Our first component in the following example is App. This component is the parent of the Comp1 component. We are creating Comp1 separately and just adding it inside the JSX tree in our App component. Only the App component needs to be exported.
App.jsx
import React from 'react';
class App extends React.Component {
constructor() {
super();
this.state = { color: '#000' };
}
render() {
return (
<div>
<h1 style={{ color: this.state.color }}>Tutorialspoint</h1>
<button onClick={() => this.setState({ color: '#ff0000' })}>
Change Color
</button>
<Comp1 />
</div>
);
}
}
class Comp1 extends React.Component {
render() {
alert('Comp1 component is called');
return (
<div>
<h1>Simply Easy Learning</h1>
</div>
);
}
}
export default App;
The above code will generate the following result.
It is the type of component which re-renders only when the props passed to it changes and not even if its parent component re-renders or if the shouldComponentUpdate()method is called. It is greatly used to enhance the performance of a web application.
In the following example, we are going to use the PureComponent with Comp1 component so that it only re-renders if the props passed to it changes.
App.jsx
import React from 'react';
class App extends React.Component {
constructor() {
super();
this.state = { color: '#000' };
}
render() {
return (
<div>
<h1 style={{ color: this.state.color }}>Tutorialspoint</h1>
<button onClick={() => this.setState({ color: '#ff0000' })}>
Change Color
</button>
<Comp1 />
</div>
);
}
}
class Comp1 extends React.PureComponent {
render() {
alert('Comp1 component is called');
return (
<div>
<h1>Simply Easy Learning</h1>
</div>
);
}
}
export default App;
The above code will generate the following result.
|
[
{
"code": null,
"e": 1242,
"s": 1062,
"text": "In this article, we are going to see the difference between Component and PureComponent. In ReactJS, Components are widely used to make an App more efficient and effective to use."
},
{
"code": null,
"e": 1326,
"s": 1242,
"text": "ReactJS provides two different ways to use components – Component or PureComponent."
},
{
"code": null,
"e": 1461,
"s": 1326,
"text": "It is the type of component which re-renders itself every time when the props passed to it changes or its parent component re-renders."
},
{
"code": null,
"e": 1706,
"s": 1461,
"text": "Our first component in the following example is App. This component is the parent of the Comp1 component. We are creating Comp1 separately and just adding it inside the JSX tree in our App component. Only the App component needs to be exported."
},
{
"code": null,
"e": 1714,
"s": 1706,
"text": "App.jsx"
},
{
"code": null,
"e": 2343,
"s": 1714,
"text": "import React from 'react';\n\nclass App extends React.Component {\n constructor() {\n super();\n this.state = { color: '#000' };\n }\n render() {\n return (\n <div>\n <h1 style={{ color: this.state.color }}>Tutorialspoint</h1>\n <button onClick={() => this.setState({ color: '#ff0000' })}>\n Change Color\n </button>\n <Comp1 />\n </div>\n );\n }\n}\n\nclass Comp1 extends React.Component {\n render() {\n alert('Comp1 component is called');\n return (\n <div>\n <h1>Simply Easy Learning</h1>\n </div>\n );\n }\n}\nexport default App;"
},
{
"code": null,
"e": 2394,
"s": 2343,
"text": "The above code will generate the following result."
},
{
"code": null,
"e": 2647,
"s": 2394,
"text": "It is the type of component which re-renders only when the props passed to it changes and not even if its parent component re-renders or if the shouldComponentUpdate()method is called. It is greatly used to enhance the performance of a web application."
},
{
"code": null,
"e": 2794,
"s": 2647,
"text": "In the following example, we are going to use the PureComponent with Comp1 component so that it only re-renders if the props passed to it changes."
},
{
"code": null,
"e": 2802,
"s": 2794,
"text": "App.jsx"
},
{
"code": null,
"e": 3458,
"s": 2802,
"text": "import React from 'react';\nclass App extends React.Component {\n constructor() {\n super();\n this.state = { color: '#000' };\n }\n render() {\n return (\n <div>\n <h1 style={{ color: this.state.color }}>Tutorialspoint</h1>\n <button onClick={() => this.setState({ color: '#ff0000' })}>\n Change Color\n </button>\n <Comp1 />\n </div>\n );\n }\n}\n\nclass Comp1 extends React.PureComponent {\n render() {\n alert('Comp1 component is called');\n return (\n <div>\n <h1>Simply Easy Learning</h1>\n </div>\n );\n }\n}\nexport default App;"
},
{
"code": null,
"e": 3509,
"s": 3458,
"text": "The above code will generate the following result."
}
] |
Exploring the US Cars Dataset. Exploratory Data Analysis of the US... | by Sadrach Pierre, Ph.D. | Towards Data Science
|
The US Cars Dataset contains scraped data from the online North American Car auction. It contains information about 28 car brands for sale in the US. In this post, we will perform exploratory data analysis on the US Cars Dataset. The data can be found here.
Let’s get started!
First, let’s import the Pandas library
import pandas as pd
Next, let’s remove the default display limits for Pandas data frames:
pd.set_option('display.max_columns', None)
Now, let’s read the data into a data frame:
df = pd.read_csv("USA_cars_datasets.csv")
Let’s print the list of columns in the data:
print(list(df.columns))
We can also take a look at the number of rows in the data:
print("Number of rows: ", len(df))
Next, let’s print the first five rows of data:
print(df.head())
We can see that there are several categorical columns. Let’s define a function that takes as input a data frame, column name, and limit. When called, it prints a dictionary of categorical values and how frequently they appear:
from collections import Counterdef return_counter(data_frame, column_name, limit): print(dict(Counter(data_frame[column_name] .values).most_common(limit)))
Let’s apply our function to the ‘brand’ column and limit our results to the five most common values:
return_counter(df, 'brand', 5)
As we can see, we have 1,235 Fords, 432 Dodges , 312 Nissans, 297 Chevrolets, and 42 GMCs.
Let’s apply our function to the ‘color’ column:
return_counter(df, 'color', 5)
Now, let’s look at the brands of white cars :
df_d1 = df[df['color'] =='white']print(set(df_d1['brand']))
We can also look at the most common brands for white cars:
print(dict(Counter(df_d1['brand']).most_common(5)))
We see that most of the white cars are Fords, Dodges, and Chevrolets.
We can also look at the most common states where white cars are being sold:
print(dict(Counter(df_d1['state']).most_common(5)))
Next, it would be useful to generate summary statistics from numerical columns like ‘duration’. Let’s define a function that takes a data frame, a categorical column, and a numerical column. The mean and standard deviation of the numerical column for each category is stored in a data frame and the data frame is sorted in descending order according to the mean. This is useful if you want to quickly see if certain categories have higher or lower mean and/or standard deviation values for a particular numerical column.
def return_statistics(data_frame, categorical_column, numerical_column): mean = [] std = [] field = [] for i in set(list(data_frame[categorical_column].values)): new_data = data_frame[data_frame[categorical_column] == i] field.append(i) mean.append(new_data[numerical_column].mean()) std.append(new_data[numerical_column].std()) df = pd.DataFrame({'{}'.format(categorical_column): field, 'mean {}'.format(numerical_column): mean, 'std in {}'.format(numerical_column): std}) df.sort_values('mean {}'.format(numerical_column), inplace = True, ascending = False) df.dropna(inplace = True) return df
Let’s call our function with categorical column ‘brand’ and numerical column ‘price’:
stats = return_statistics(df, 'brand', 'price')print(stats.head(15))
Next, we will use boxplots to visualize the distribution in numeric values based on the minimum, maximum, median, first quartile, and third quartile.
Similar to the summary statistics function, this function takes a data frame, categorical column, and numerical column and displays boxplots for the most common categories based on the limit:
import matplotlib.pyplot as pltdef get_boxplot_of_categories(data_frame, categorical_column, numerical_column, limit): import seaborn as sns from collections import Counter keys = [] for i in dict(Counter(df[categorical_column].values).most_common(limit)): keys.append(i) print(keys) df_new = df[df[categorical_column].isin(keys)] sns.set() sns.boxplot(x = df_new[categorical_column], y = df_new[numerical_column]) plt.show()
Let’s generate boxplots for ‘price’ in the 5 most commonly occurring ‘brand’ categories:
get_boxplot_of_categories(df, 'listed_in', 'duration', 5)
Finally, let’s define a function that takes a data frame and a numerical column as input and displays a histogram:
def get_histogram(data_frame, numerical_column): df_new = data_frame df_new[numerical_column].hist(bins=100) plt.title('{} histogram'.format(numerical_column)) plt.show()
Let’s call the function with the data frame and generate a histogram from ‘price’:
get_histogram(df, 'price')
I will stop here but please feel free to play around with the data and code yourself.
To summarize, in this post we went over several methods for analyzing the US Cars Dataset. This included defining functions for generating summary statistics like the mean, standard deviation, and counts for categorical values. We also defined functions for visualizing data with boxplots and histograms. I hope this post was useful/interesting. The code from this post is available on GitHub. Thank you for reading!
|
[
{
"code": null,
"e": 429,
"s": 171,
"text": "The US Cars Dataset contains scraped data from the online North American Car auction. It contains information about 28 car brands for sale in the US. In this post, we will perform exploratory data analysis on the US Cars Dataset. The data can be found here."
},
{
"code": null,
"e": 448,
"s": 429,
"text": "Let’s get started!"
},
{
"code": null,
"e": 487,
"s": 448,
"text": "First, let’s import the Pandas library"
},
{
"code": null,
"e": 507,
"s": 487,
"text": "import pandas as pd"
},
{
"code": null,
"e": 577,
"s": 507,
"text": "Next, let’s remove the default display limits for Pandas data frames:"
},
{
"code": null,
"e": 620,
"s": 577,
"text": "pd.set_option('display.max_columns', None)"
},
{
"code": null,
"e": 664,
"s": 620,
"text": "Now, let’s read the data into a data frame:"
},
{
"code": null,
"e": 706,
"s": 664,
"text": "df = pd.read_csv(\"USA_cars_datasets.csv\")"
},
{
"code": null,
"e": 751,
"s": 706,
"text": "Let’s print the list of columns in the data:"
},
{
"code": null,
"e": 775,
"s": 751,
"text": "print(list(df.columns))"
},
{
"code": null,
"e": 834,
"s": 775,
"text": "We can also take a look at the number of rows in the data:"
},
{
"code": null,
"e": 869,
"s": 834,
"text": "print(\"Number of rows: \", len(df))"
},
{
"code": null,
"e": 916,
"s": 869,
"text": "Next, let’s print the first five rows of data:"
},
{
"code": null,
"e": 933,
"s": 916,
"text": "print(df.head())"
},
{
"code": null,
"e": 1160,
"s": 933,
"text": "We can see that there are several categorical columns. Let’s define a function that takes as input a data frame, column name, and limit. When called, it prints a dictionary of categorical values and how frequently they appear:"
},
{
"code": null,
"e": 1318,
"s": 1160,
"text": "from collections import Counterdef return_counter(data_frame, column_name, limit): print(dict(Counter(data_frame[column_name] .values).most_common(limit)))"
},
{
"code": null,
"e": 1419,
"s": 1318,
"text": "Let’s apply our function to the ‘brand’ column and limit our results to the five most common values:"
},
{
"code": null,
"e": 1450,
"s": 1419,
"text": "return_counter(df, 'brand', 5)"
},
{
"code": null,
"e": 1541,
"s": 1450,
"text": "As we can see, we have 1,235 Fords, 432 Dodges , 312 Nissans, 297 Chevrolets, and 42 GMCs."
},
{
"code": null,
"e": 1589,
"s": 1541,
"text": "Let’s apply our function to the ‘color’ column:"
},
{
"code": null,
"e": 1620,
"s": 1589,
"text": "return_counter(df, 'color', 5)"
},
{
"code": null,
"e": 1666,
"s": 1620,
"text": "Now, let’s look at the brands of white cars :"
},
{
"code": null,
"e": 1726,
"s": 1666,
"text": "df_d1 = df[df['color'] =='white']print(set(df_d1['brand']))"
},
{
"code": null,
"e": 1785,
"s": 1726,
"text": "We can also look at the most common brands for white cars:"
},
{
"code": null,
"e": 1837,
"s": 1785,
"text": "print(dict(Counter(df_d1['brand']).most_common(5)))"
},
{
"code": null,
"e": 1907,
"s": 1837,
"text": "We see that most of the white cars are Fords, Dodges, and Chevrolets."
},
{
"code": null,
"e": 1983,
"s": 1907,
"text": "We can also look at the most common states where white cars are being sold:"
},
{
"code": null,
"e": 2035,
"s": 1983,
"text": "print(dict(Counter(df_d1['state']).most_common(5)))"
},
{
"code": null,
"e": 2556,
"s": 2035,
"text": "Next, it would be useful to generate summary statistics from numerical columns like ‘duration’. Let’s define a function that takes a data frame, a categorical column, and a numerical column. The mean and standard deviation of the numerical column for each category is stored in a data frame and the data frame is sorted in descending order according to the mean. This is useful if you want to quickly see if certain categories have higher or lower mean and/or standard deviation values for a particular numerical column."
},
{
"code": null,
"e": 3204,
"s": 2556,
"text": "def return_statistics(data_frame, categorical_column, numerical_column): mean = [] std = [] field = [] for i in set(list(data_frame[categorical_column].values)): new_data = data_frame[data_frame[categorical_column] == i] field.append(i) mean.append(new_data[numerical_column].mean()) std.append(new_data[numerical_column].std()) df = pd.DataFrame({'{}'.format(categorical_column): field, 'mean {}'.format(numerical_column): mean, 'std in {}'.format(numerical_column): std}) df.sort_values('mean {}'.format(numerical_column), inplace = True, ascending = False) df.dropna(inplace = True) return df"
},
{
"code": null,
"e": 3290,
"s": 3204,
"text": "Let’s call our function with categorical column ‘brand’ and numerical column ‘price’:"
},
{
"code": null,
"e": 3359,
"s": 3290,
"text": "stats = return_statistics(df, 'brand', 'price')print(stats.head(15))"
},
{
"code": null,
"e": 3509,
"s": 3359,
"text": "Next, we will use boxplots to visualize the distribution in numeric values based on the minimum, maximum, median, first quartile, and third quartile."
},
{
"code": null,
"e": 3701,
"s": 3509,
"text": "Similar to the summary statistics function, this function takes a data frame, categorical column, and numerical column and displays boxplots for the most common categories based on the limit:"
},
{
"code": null,
"e": 4161,
"s": 3701,
"text": "import matplotlib.pyplot as pltdef get_boxplot_of_categories(data_frame, categorical_column, numerical_column, limit): import seaborn as sns from collections import Counter keys = [] for i in dict(Counter(df[categorical_column].values).most_common(limit)): keys.append(i) print(keys) df_new = df[df[categorical_column].isin(keys)] sns.set() sns.boxplot(x = df_new[categorical_column], y = df_new[numerical_column]) plt.show()"
},
{
"code": null,
"e": 4250,
"s": 4161,
"text": "Let’s generate boxplots for ‘price’ in the 5 most commonly occurring ‘brand’ categories:"
},
{
"code": null,
"e": 4308,
"s": 4250,
"text": "get_boxplot_of_categories(df, 'listed_in', 'duration', 5)"
},
{
"code": null,
"e": 4423,
"s": 4308,
"text": "Finally, let’s define a function that takes a data frame and a numerical column as input and displays a histogram:"
},
{
"code": null,
"e": 4606,
"s": 4423,
"text": "def get_histogram(data_frame, numerical_column): df_new = data_frame df_new[numerical_column].hist(bins=100) plt.title('{} histogram'.format(numerical_column)) plt.show()"
},
{
"code": null,
"e": 4689,
"s": 4606,
"text": "Let’s call the function with the data frame and generate a histogram from ‘price’:"
},
{
"code": null,
"e": 4716,
"s": 4689,
"text": "get_histogram(df, 'price')"
},
{
"code": null,
"e": 4802,
"s": 4716,
"text": "I will stop here but please feel free to play around with the data and code yourself."
}
] |
Default exports vs Named exports in JavaScript.
|
There can be only one default export per file and we can assign it any name when importing it to the other file. However, there can be multiple named exports in a file and they are imported using the name that were used to export.
Following is the code showing difference between default exports and named exports in JavaScript −
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 18px;
font-weight: 500;
color: rebeccapurple;
}
</style>
</head>
<body>
<h1>Default export vs Named Export</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above export function as named and default export</h3>
<script src="script.js" type="module">
</script>
</body>
</html>
sample.js
export default function testImport(){
return 'Module testImport has been imported'+'';
}
export function tellTime(){
return new Date();
}
script.js
import defaultExport from "./sample.js";
import {tellTime} from "./sample.js";
let resultEle = document.querySelector('.result');
document.querySelector('.Btn').addEventListener('click',()=>{
resultEle.innerHTML+=defaultExport();
resultEle.innerHTML+=tellTime();
})
The above code will produce the following output −
On clicking the ‘CLICK HERE’ button −
|
[
{
"code": null,
"e": 1293,
"s": 1062,
"text": "There can be only one default export per file and we can assign it any name when importing it to the other file. However, there can be multiple named exports in a file and they are imported using the name that were used to export."
},
{
"code": null,
"e": 1392,
"s": 1293,
"text": "Following is the code showing difference between default exports and named exports in JavaScript −"
},
{
"code": null,
"e": 2006,
"s": 1392,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 18px;\n font-weight: 500;\n color: rebeccapurple;\n }\n</style>\n</head>\n<body>\n<h1>Default export vs Named Export</h1>\n<div class=\"result\"></div>\n<button class=\"Btn\">CLICK HERE</button>\n<h3>Click on the above export function as named and default export</h3>\n<script src=\"script.js\" type=\"module\">\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2016,
"s": 2006,
"text": "sample.js"
},
{
"code": null,
"e": 2160,
"s": 2016,
"text": "export default function testImport(){\n return 'Module testImport has been imported'+'';\n}\nexport function tellTime(){\n return new Date();\n}"
},
{
"code": null,
"e": 2170,
"s": 2160,
"text": "script.js"
},
{
"code": null,
"e": 2442,
"s": 2170,
"text": "import defaultExport from \"./sample.js\";\nimport {tellTime} from \"./sample.js\";\nlet resultEle = document.querySelector('.result');\ndocument.querySelector('.Btn').addEventListener('click',()=>{\n resultEle.innerHTML+=defaultExport();\n resultEle.innerHTML+=tellTime();\n})"
},
{
"code": null,
"e": 2493,
"s": 2442,
"text": "The above code will produce the following output −"
},
{
"code": null,
"e": 2531,
"s": 2493,
"text": "On clicking the ‘CLICK HERE’ button −"
}
] |
Adaptive Moving Average in Python. | by Sofien Kaabar, CFA | Towards Data Science
|
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.
Moving averages are one of the simplest and most effective tools in detecting changes in trend. They are also used in creating trading strategies based on crossovers. Pretty much every trader uses them and includes them in her decision-making process. In this article, we will skim through the basic known moving averages and then present the slightly more complex Kaufman Adapative Moving Average — KAMA.
I have just published a new book after the success of New Technical Indicators in Python. It features a more complete description and addition of complex trading strategies with a Github page dedicated to the continuously updated code. If you feel that this interests you, feel free to visit the below link, or if you prefer to buy the PDF version, you could contact me on Linkedin.
www.amazon.com
The three most common moving averages are:
Simple moving average.
Exponential moving average.
Smoothed moving average.
We will go through each one, define it, code it, and chart it before we move on to the KAMA.
Simple moving average
As the name suggests, this is your plain simple average that is used everywhere in statistics and basically any other part in our lives. It is simply the total values of the observations divided by the number of observations. Mathematically speaking, it can be written down as:
In python, we can define a function that calculates moving averages as follows:
def ma(Data, period, onwhat, where): for i in range(len(Data)): try: Data[i, where] = (Data[i - period:i + 1, onwhat].mean()) except IndexError: pass return Data
The function takes your data structure represented by the Data variable, the moving average period (20, 60, 200, etc.) represented by the period variable, what do you want to apply it on (on OHLC data structures, choose 3 for close prices because python indexing starts at zero) represented by the onwhat variable, and the where variable is where do you want the moving average column to appear. Note that you must have an array of more than 4 columns for this to work, because it doesn’t automatically create a new column, but simply populate it.
Exponential moving average
As opposed to the simple moving average that gives equal weights to all observations, the exponential moving average gives more weight to the more recent observations. It reacts more than the simple moving average with regards to recent movements. Mathematically speaking, it can be written down as:
The smoothing factor is often 2. Note, that if we increase the smoothing factor (also known as alpha) then, the more recent observations will have more weight. In python language, we can define a function that calculates the EMA as follows:
def ema(Data, alpha, window, what, whereSMA, whereEMA): # alpha is the smoothing factor # window is the lookback period # what is the column that needs to have its average calculated # where is where to put the exponential moving average alpha = alpha / (window + 1.0) beta = 1 - alpha # First value is a simple SMA Data[window - 1, whereSMA] = np.mean(Data[:window - 1, what]) # Calculating first EMA Data[window, whereEMA] = (Data[window, what] * alpha) + (Data[window - 1, whereSMA] * beta)# Calculating the rest of EMA for i in range(window + 1, len(Data)): try: Data[i, whereEMA] = (Data[i, what] * alpha) + (Data[i - 1, whereEMA] * beta) except IndexError: pass return Data
The function is self-explanatory as it merely reproduces the EMA function presented above.
If you are also interested by more technical indicators and using Python to create strategies, then my best-selling book on Technical Indicators may interest you:
www.amazon.com
Smoothed moving average
This moving average takes into account the general picture and is less impacted by recent movements. It’s my favourite trend-following indicator. Mathematically speaking, it can be found by simply multiplying the Days variable in the EMA function by 2 and subtract 1. This means that to transform an exponential moving average into a smoothed one, we follow this equation in python language, that transforms the exponential moving average into a smoothed one:
smoothed = (exponential * 2) - 1 # From exponential to smoothed
The KAMA has been created to reduce the noise and whipsaw effects. It works the same as other moving averages do and follows the same intuition. The generation of false trading signals is one of the problems with moving averages and this is due to short-term sudden fluctuations that bias the calculation. The KAMA’s primary objective is to reduce as much noise as possible.
The first concept we should measure is the Efficiency Ratio which is the absolute change of the current close relative to the change in the past 10 periods divided by a type of volatility calculated in a special manner. We can say that the Efficiency Ratio is the change divided by volatility.
Then we calculate a smoothing constant based on the following formula:
Finally, to calculate the KAMA we use the below formula:
The calculation may seem complicated but it is easily automated and you do not have to think about it much. Let us see how to code it in Python and then proceed by seeing some examples.
def kama(Data, what, where, change): # Change from previous period for i in range(len(Data)): Data[i, where] = abs(Data[i, what] - Data[i - 1, what]) Data[0, where] = 0 # Sum of changes for i in range(len(Data)): Data[i, where + 1] = (Data[i - change + 1:i + 1, where].sum()) # Volatility for i in range(len(Data)): Data[i, where + 2] = abs(Data[i, 3] - Data[i - 10, 3]) Data = Data[11:, ] # Efficiency Ratio Data[:, where + 3] = Data[:, where + 2] / Data[:, where + 1] for i in range(len(Data)): Data[i, where + 4] = np.square(Data[i, where + 3] * 0.6666666666666666667) for i in range(len(Data)): Data[i, where + 5] = Data[i - 1, where + 5] + (Data[i, where + 4] * (Data[i, 3] - Data[i - 1, where + 5])) Data[11, where + 5] = 0
The below chart illustrates what the above function can give us. Notice the more stable tendency of the KAMA relative to other moving averages. It is an improvement with regards to whipsaws and false breaks.
The KAMA can also be used to detect the start of new trends. For instance, we can plot a long-term KAMA with a short-term KAMA and trade on their crossovers. If the default settings are 10-period, we can try a 30-period KAMA and see what it gives us.
plt.plot(Asset1[-500:, 3], color = 'black', label = 'EURUSD')plt.plot(Asset1[-500:, 4], color = 'blue', label = '10-period KAMA')plt.plot(Asset1[-500:, 5], color = 'purple', label = '30-period KAMA')plt.grid()plt.legend()
Using the above chart, we can say that when the two KAMA’s are flat, the market is ranging and when a trend starts, we should follow their respective crossover such as that when the 30-period KAMA is above the 10-period KAMA, a bearish trend is in progress until a crossover happens. This in turn can be a valuable signal to us. If you are interested in trend-following strategies, you can check out the below article:
medium.com
Now, let us plot a simple moving average and compare it to a same period KAMA. Visibly, the latter provides a better and more accurate picture of what is going on and that is because it takes volatility into account . Now I am not saying you should replace the simple moving average with the KAMA but it may seem like a good idea to include it in the framework.
Being a fan of adaptive and exponential moving averages, I encourage you to experiment with this technique. KAMA provides valuable support and resistance levels that can be used to complement your trading system. It is not meant to be used as a sole contributor to generate trading signals but it is valuable in confirming them.
|
[
{
"code": null,
"e": 471,
"s": 171,
"text": "Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details."
},
{
"code": null,
"e": 877,
"s": 471,
"text": "Moving averages are one of the simplest and most effective tools in detecting changes in trend. They are also used in creating trading strategies based on crossovers. Pretty much every trader uses them and includes them in her decision-making process. In this article, we will skim through the basic known moving averages and then present the slightly more complex Kaufman Adapative Moving Average — KAMA."
},
{
"code": null,
"e": 1260,
"s": 877,
"text": "I have just published a new book after the success of New Technical Indicators in Python. It features a more complete description and addition of complex trading strategies with a Github page dedicated to the continuously updated code. If you feel that this interests you, feel free to visit the below link, or if you prefer to buy the PDF version, you could contact me on Linkedin."
},
{
"code": null,
"e": 1275,
"s": 1260,
"text": "www.amazon.com"
},
{
"code": null,
"e": 1318,
"s": 1275,
"text": "The three most common moving averages are:"
},
{
"code": null,
"e": 1341,
"s": 1318,
"text": "Simple moving average."
},
{
"code": null,
"e": 1369,
"s": 1341,
"text": "Exponential moving average."
},
{
"code": null,
"e": 1394,
"s": 1369,
"text": "Smoothed moving average."
},
{
"code": null,
"e": 1487,
"s": 1394,
"text": "We will go through each one, define it, code it, and chart it before we move on to the KAMA."
},
{
"code": null,
"e": 1509,
"s": 1487,
"text": "Simple moving average"
},
{
"code": null,
"e": 1787,
"s": 1509,
"text": "As the name suggests, this is your plain simple average that is used everywhere in statistics and basically any other part in our lives. It is simply the total values of the observations divided by the number of observations. Mathematically speaking, it can be written down as:"
},
{
"code": null,
"e": 1867,
"s": 1787,
"text": "In python, we can define a function that calculates moving averages as follows:"
},
{
"code": null,
"e": 2099,
"s": 1867,
"text": "def ma(Data, period, onwhat, where): for i in range(len(Data)): try: Data[i, where] = (Data[i - period:i + 1, onwhat].mean()) except IndexError: pass return Data"
},
{
"code": null,
"e": 2647,
"s": 2099,
"text": "The function takes your data structure represented by the Data variable, the moving average period (20, 60, 200, etc.) represented by the period variable, what do you want to apply it on (on OHLC data structures, choose 3 for close prices because python indexing starts at zero) represented by the onwhat variable, and the where variable is where do you want the moving average column to appear. Note that you must have an array of more than 4 columns for this to work, because it doesn’t automatically create a new column, but simply populate it."
},
{
"code": null,
"e": 2674,
"s": 2647,
"text": "Exponential moving average"
},
{
"code": null,
"e": 2974,
"s": 2674,
"text": "As opposed to the simple moving average that gives equal weights to all observations, the exponential moving average gives more weight to the more recent observations. It reacts more than the simple moving average with regards to recent movements. Mathematically speaking, it can be written down as:"
},
{
"code": null,
"e": 3215,
"s": 2974,
"text": "The smoothing factor is often 2. Note, that if we increase the smoothing factor (also known as alpha) then, the more recent observations will have more weight. In python language, we can define a function that calculates the EMA as follows:"
},
{
"code": null,
"e": 4008,
"s": 3215,
"text": "def ema(Data, alpha, window, what, whereSMA, whereEMA): # alpha is the smoothing factor # window is the lookback period # what is the column that needs to have its average calculated # where is where to put the exponential moving average alpha = alpha / (window + 1.0) beta = 1 - alpha # First value is a simple SMA Data[window - 1, whereSMA] = np.mean(Data[:window - 1, what]) # Calculating first EMA Data[window, whereEMA] = (Data[window, what] * alpha) + (Data[window - 1, whereSMA] * beta)# Calculating the rest of EMA for i in range(window + 1, len(Data)): try: Data[i, whereEMA] = (Data[i, what] * alpha) + (Data[i - 1, whereEMA] * beta) except IndexError: pass return Data"
},
{
"code": null,
"e": 4099,
"s": 4008,
"text": "The function is self-explanatory as it merely reproduces the EMA function presented above."
},
{
"code": null,
"e": 4262,
"s": 4099,
"text": "If you are also interested by more technical indicators and using Python to create strategies, then my best-selling book on Technical Indicators may interest you:"
},
{
"code": null,
"e": 4277,
"s": 4262,
"text": "www.amazon.com"
},
{
"code": null,
"e": 4301,
"s": 4277,
"text": "Smoothed moving average"
},
{
"code": null,
"e": 4761,
"s": 4301,
"text": "This moving average takes into account the general picture and is less impacted by recent movements. It’s my favourite trend-following indicator. Mathematically speaking, it can be found by simply multiplying the Days variable in the EMA function by 2 and subtract 1. This means that to transform an exponential moving average into a smoothed one, we follow this equation in python language, that transforms the exponential moving average into a smoothed one:"
},
{
"code": null,
"e": 4825,
"s": 4761,
"text": "smoothed = (exponential * 2) - 1 # From exponential to smoothed"
},
{
"code": null,
"e": 5200,
"s": 4825,
"text": "The KAMA has been created to reduce the noise and whipsaw effects. It works the same as other moving averages do and follows the same intuition. The generation of false trading signals is one of the problems with moving averages and this is due to short-term sudden fluctuations that bias the calculation. The KAMA’s primary objective is to reduce as much noise as possible."
},
{
"code": null,
"e": 5494,
"s": 5200,
"text": "The first concept we should measure is the Efficiency Ratio which is the absolute change of the current close relative to the change in the past 10 periods divided by a type of volatility calculated in a special manner. We can say that the Efficiency Ratio is the change divided by volatility."
},
{
"code": null,
"e": 5565,
"s": 5494,
"text": "Then we calculate a smoothing constant based on the following formula:"
},
{
"code": null,
"e": 5622,
"s": 5565,
"text": "Finally, to calculate the KAMA we use the below formula:"
},
{
"code": null,
"e": 5808,
"s": 5622,
"text": "The calculation may seem complicated but it is easily automated and you do not have to think about it much. Let us see how to code it in Python and then proceed by seeing some examples."
},
{
"code": null,
"e": 6667,
"s": 5808,
"text": "def kama(Data, what, where, change): # Change from previous period for i in range(len(Data)): Data[i, where] = abs(Data[i, what] - Data[i - 1, what]) Data[0, where] = 0 # Sum of changes for i in range(len(Data)): Data[i, where + 1] = (Data[i - change + 1:i + 1, where].sum()) # Volatility for i in range(len(Data)): Data[i, where + 2] = abs(Data[i, 3] - Data[i - 10, 3]) Data = Data[11:, ] # Efficiency Ratio Data[:, where + 3] = Data[:, where + 2] / Data[:, where + 1] for i in range(len(Data)): Data[i, where + 4] = np.square(Data[i, where + 3] * 0.6666666666666666667) for i in range(len(Data)): Data[i, where + 5] = Data[i - 1, where + 5] + (Data[i, where + 4] * (Data[i, 3] - Data[i - 1, where + 5])) Data[11, where + 5] = 0"
},
{
"code": null,
"e": 6875,
"s": 6667,
"text": "The below chart illustrates what the above function can give us. Notice the more stable tendency of the KAMA relative to other moving averages. It is an improvement with regards to whipsaws and false breaks."
},
{
"code": null,
"e": 7126,
"s": 6875,
"text": "The KAMA can also be used to detect the start of new trends. For instance, we can plot a long-term KAMA with a short-term KAMA and trade on their crossovers. If the default settings are 10-period, we can try a 30-period KAMA and see what it gives us."
},
{
"code": null,
"e": 7348,
"s": 7126,
"text": "plt.plot(Asset1[-500:, 3], color = 'black', label = 'EURUSD')plt.plot(Asset1[-500:, 4], color = 'blue', label = '10-period KAMA')plt.plot(Asset1[-500:, 5], color = 'purple', label = '30-period KAMA')plt.grid()plt.legend()"
},
{
"code": null,
"e": 7767,
"s": 7348,
"text": "Using the above chart, we can say that when the two KAMA’s are flat, the market is ranging and when a trend starts, we should follow their respective crossover such as that when the 30-period KAMA is above the 10-period KAMA, a bearish trend is in progress until a crossover happens. This in turn can be a valuable signal to us. If you are interested in trend-following strategies, you can check out the below article:"
},
{
"code": null,
"e": 7778,
"s": 7767,
"text": "medium.com"
},
{
"code": null,
"e": 8140,
"s": 7778,
"text": "Now, let us plot a simple moving average and compare it to a same period KAMA. Visibly, the latter provides a better and more accurate picture of what is going on and that is because it takes volatility into account . Now I am not saying you should replace the simple moving average with the KAMA but it may seem like a good idea to include it in the framework."
}
] |
How to create multiple styles inside a TextView in Android?
|
This example demonstrates how do I create multiple styles inside a TextView in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_above="@id/textView2"
android:layout_marginBottom="16dp"
android:id="@+id/textView1"
android:textSize="16dp"
android:padding="4dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16dp"
android:padding="4dp"
android:layout_centerInParent="true"/>
<TextView
android:layout_below="@id/textView2"
android:layout_marginTop="16dp"
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16dp"
android:padding="4dp"/>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView1, textView2, textView3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1 = findViewById(R.id.textView1);
textView2 = findViewById(R.id.textView2);
textView1.setText(Html.fromHtml("Multiple style inside android textView: bold text: "
+ "<b>bold text</b>, italic text: <i>italic text</i>, small font: <small>small "
+ "text</small>, "
+ "font color: <font color=\"blue\">Text Color</font>, "
+ "font color with bold text: <fontcolor=\"green\"><b>Bold with font "
+ "color</b></font>"));
Spanned text = Html.fromHtml("Multiple style inside android textView: bold text: "
+ "<b>bold text</b>, "
+ "italic text: <i>italic text</i>, small font: <small>small text</small>, font "
+ "color: <font color=\"blue\">Text Color</font>, "
+ "font color with bold text: <fontcolor=\"green\"><b>Bold with font "
+ "color</b></font>");
textView2.setText(text);
textView3 = findViewById(R.id.textView3);
textView3.setText(Html.fromHtml(getString(R.string.textStyle)));
}
}
Step 4 − Open res/values/strings.xml and add the following code −
<resources>
<string name="app_name">Sample</string>
<string name="textStyle">
<![CDATA[
Multiple style inside android textView: bold text: <b>bold
text</b>, italicText text: <i>italic text</i>, small font:
<small>small text</small>,
font color: <font color="blue"<Text Color</font<, font
color with bold text: <font color="green"><b>Bold with font
color</b></font>
]]>
</string>
</resources>
Step 5 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
|
[
{
"code": null,
"e": 1150,
"s": 1062,
"text": "This example demonstrates how do I create multiple styles inside a TextView in android."
},
{
"code": null,
"e": 1279,
"s": 1150,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1344,
"s": 1279,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2469,
"s": 1344,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_above=\"@id/textView2\"\n android:layout_marginBottom=\"16dp\"\n android:id=\"@+id/textView1\"\n android:textSize=\"16dp\"\n android:padding=\"4dp\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"/>\n <TextView\n android:id=\"@+id/textView2\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:textSize=\"16dp\"\n android:padding=\"4dp\"\n android:layout_centerInParent=\"true\"/>\n <TextView\n android:layout_below=\"@id/textView2\"\n android:layout_marginTop=\"16dp\"\n android:id=\"@+id/textView3\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:textSize=\"16dp\"\n android:padding=\"4dp\"/>\n</RelativeLayout>"
},
{
"code": null,
"e": 2526,
"s": 2469,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3971,
"s": 2526,
"text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.text.Html;\nimport android.text.Spanned;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n TextView textView1, textView2, textView3;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView1 = findViewById(R.id.textView1);\n textView2 = findViewById(R.id.textView2);\n textView1.setText(Html.fromHtml(\"Multiple style inside android textView: bold text: \"\n + \"<b>bold text</b>, italic text: <i>italic text</i>, small font: <small>small \"\n + \"text</small>, \"\n + \"font color: <font color=\\\"blue\\\">Text Color</font>, \"\n + \"font color with bold text: <fontcolor=\\\"green\\\"><b>Bold with font \"\n + \"color</b></font>\"));\n Spanned text = Html.fromHtml(\"Multiple style inside android textView: bold text: \"\n + \"<b>bold text</b>, \"\n + \"italic text: <i>italic text</i>, small font: <small>small text</small>, font \"\n + \"color: <font color=\\\"blue\\\">Text Color</font>, \"\n + \"font color with bold text: <fontcolor=\\\"green\\\"><b>Bold with font \"\n + \"color</b></font>\");\n textView2.setText(text);\n textView3 = findViewById(R.id.textView3);\n textView3.setText(Html.fromHtml(getString(R.string.textStyle)));\n }\n}"
},
{
"code": null,
"e": 4037,
"s": 3971,
"text": "Step 4 − Open res/values/strings.xml and add the following code −"
},
{
"code": null,
"e": 4501,
"s": 4037,
"text": "<resources>\n<string name=\"app_name\">Sample</string>\n <string name=\"textStyle\">\n <![CDATA[\n Multiple style inside android textView: bold text: <b>bold\n text</b>, italicText text: <i>italic text</i>, small font:\n <small>small text</small>,\n font color: <font color=\"blue\"<Text Color</font<, font\n color with bold text: <font color=\"green\"><b>Bold with font\n color</b></font>\n ]]>\n </string>\n</resources>"
},
{
"code": null,
"e": 4556,
"s": 4501,
"text": "Step 5 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 5226,
"s": 4556,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 5573,
"s": 5226,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 5614,
"s": 5573,
"text": "Click here to download the project code."
}
] |
Constructing a nested JSON object in JavaScript
|
We have a special kind of string that contains characters in couple, like this −
const str = "AABBCCDDEE";
We are required to construct an object based on this string which should look like this −
const obj = {
code: "AA",
sub: {
code: "BB",
sub: {
code: "CC",
sub: {
code: "DD",
sub: {
code: "EE",
sub: {}
}
}
}
}
};
Notice that for each unique couple in the string we have a new sub object and the code property at any level represents a specific couple.
We can solve this problem using a recursive approach.
We will recursively iterate over the string to pick specific couple and assign a new sub object for it.
Therefore, let’s write the code for this function −
The code for this will be −
const str = "AABBCCDDEE";
const constructObject = str => {
const res = {};
let ref = res;
while(str){
const words = str.substring(0, 2);
str = str.substr(2, str.length);
ref.code = words;
ref.sub = {};
ref = ref.sub;
};
return res;
};
console.log(JSON.stringify(constructObject(str), undefined, 4));
The output in the console will be −
{
"code": "AA",
"sub": {
"code": "BB",
"sub": {
"code": "CC",
"sub": {
"code": "DD",
"sub": {
"code": "EE",
"sub": {}
}
}
}
}
}
|
[
{
"code": null,
"e": 1143,
"s": 1062,
"text": "We have a special kind of string that contains characters in couple, like this −"
},
{
"code": null,
"e": 1169,
"s": 1143,
"text": "const str = \"AABBCCDDEE\";"
},
{
"code": null,
"e": 1259,
"s": 1169,
"text": "We are required to construct an object based on this string which should look like this −"
},
{
"code": null,
"e": 1500,
"s": 1259,
"text": "const obj = {\n code: \"AA\",\n sub: {\n code: \"BB\",\n sub: {\n code: \"CC\",\n sub: {\n code: \"DD\",\n sub: {\n code: \"EE\",\n sub: {}\n }\n }\n }\n }\n};"
},
{
"code": null,
"e": 1639,
"s": 1500,
"text": "Notice that for each unique couple in the string we have a new sub object and the code property at any level represents a specific couple."
},
{
"code": null,
"e": 1693,
"s": 1639,
"text": "We can solve this problem using a recursive approach."
},
{
"code": null,
"e": 1797,
"s": 1693,
"text": "We will recursively iterate over the string to pick specific couple and assign a new sub object for it."
},
{
"code": null,
"e": 1849,
"s": 1797,
"text": "Therefore, let’s write the code for this function −"
},
{
"code": null,
"e": 1877,
"s": 1849,
"text": "The code for this will be −"
},
{
"code": null,
"e": 2222,
"s": 1877,
"text": "const str = \"AABBCCDDEE\";\nconst constructObject = str => {\n const res = {};\n let ref = res;\n while(str){\n const words = str.substring(0, 2);\n str = str.substr(2, str.length);\n ref.code = words;\n ref.sub = {};\n ref = ref.sub;\n };\n return res;\n};\nconsole.log(JSON.stringify(constructObject(str), undefined, 4));"
},
{
"code": null,
"e": 2258,
"s": 2222,
"text": "The output in the console will be −"
},
{
"code": null,
"e": 2506,
"s": 2258,
"text": "{\n \"code\": \"AA\",\n \"sub\": {\n \"code\": \"BB\",\n \"sub\": {\n \"code\": \"CC\",\n \"sub\": {\n \"code\": \"DD\",\n \"sub\": {\n \"code\": \"EE\",\n \"sub\": {}\n }\n }\n }\n }\n}"
}
] |
C# DateTime to add days to the current date
|
Firstly, get the current date.
DateTime.Today
Now, use AddDays() method to add days to the current date. Here, we are adding 10 days to the current date.
DateTime.Today.AddDays(10)
Let us see the complete code −
Live Demo
using System;
using System.Linq;
public class Demo {
public static void Main() {
Console.WriteLine("Today = {0}", DateTime.Today);
Console.WriteLine("Add 10 Days = {0}", DateTime.Today.AddDays(10));
}
}
Today = 9/11/2018 12:00:00 AM
Add 10 Days = 9/21/2018 12:00:00 AM
|
[
{
"code": null,
"e": 1093,
"s": 1062,
"text": "Firstly, get the current date."
},
{
"code": null,
"e": 1108,
"s": 1093,
"text": "DateTime.Today"
},
{
"code": null,
"e": 1216,
"s": 1108,
"text": "Now, use AddDays() method to add days to the current date. Here, we are adding 10 days to the current date."
},
{
"code": null,
"e": 1243,
"s": 1216,
"text": "DateTime.Today.AddDays(10)"
},
{
"code": null,
"e": 1274,
"s": 1243,
"text": "Let us see the complete code −"
},
{
"code": null,
"e": 1285,
"s": 1274,
"text": " Live Demo"
},
{
"code": null,
"e": 1506,
"s": 1285,
"text": "using System;\nusing System.Linq;\npublic class Demo {\n public static void Main() {\n Console.WriteLine(\"Today = {0}\", DateTime.Today);\n Console.WriteLine(\"Add 10 Days = {0}\", DateTime.Today.AddDays(10));\n }\n}"
},
{
"code": null,
"e": 1572,
"s": 1506,
"text": "Today = 9/11/2018 12:00:00 AM\nAdd 10 Days = 9/21/2018 12:00:00 AM"
}
] |
What is compile time polymorphism in C#?
|
Polymorphism can be static or dynamic. In static polymorphism, the response to a function is determined at the compile time. In dynamic polymorphism, it is decided at run-time.
The linking of a function with an object during compile time is called early binding. It is also called static binding. C# provides two techniques to implement static polymorphism. They are Function overloading and Operator overloading.
In function overloading you can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list.
The following is an example showing how to implement function overloading in C# −
Live Demo
using System;
namespace PolymorphismApplication {
class Printdata {
void print(int i) {
Console.WriteLine("Printing int: {0}", i );
}
void print(double f) {
Console.WriteLine("Printing float: {0}" , f);
}
void print(string s) {
Console.WriteLine("Printing string: {0}", s);
}
static void Main(string[] args) {
Printdata p = new Printdata();
// Call print to print integer
p.print(5);
// Call print to print float
p.print(500.263);
// Call print to print string
p.print("Hello C++");
Console.ReadKey();
}
}
}
Printing int: 5
Printing float: 500.263
Printing string: Hello C++
|
[
{
"code": null,
"e": 1239,
"s": 1062,
"text": "Polymorphism can be static or dynamic. In static polymorphism, the response to a function is determined at the compile time. In dynamic polymorphism, it is decided at run-time."
},
{
"code": null,
"e": 1476,
"s": 1239,
"text": "The linking of a function with an object during compile time is called early binding. It is also called static binding. C# provides two techniques to implement static polymorphism. They are Function overloading and Operator overloading."
},
{
"code": null,
"e": 1705,
"s": 1476,
"text": "In function overloading you can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list."
},
{
"code": null,
"e": 1787,
"s": 1705,
"text": "The following is an example showing how to implement function overloading in C# −"
},
{
"code": null,
"e": 1798,
"s": 1787,
"text": " Live Demo"
},
{
"code": null,
"e": 2466,
"s": 1798,
"text": "using System;\n\nnamespace PolymorphismApplication {\n class Printdata {\n void print(int i) {\n Console.WriteLine(\"Printing int: {0}\", i );\n }\n\n void print(double f) {\n Console.WriteLine(\"Printing float: {0}\" , f);\n }\n\n void print(string s) {\n Console.WriteLine(\"Printing string: {0}\", s);\n }\n\n static void Main(string[] args) {\n Printdata p = new Printdata();\n\n // Call print to print integer\n p.print(5);\n\n // Call print to print float\n p.print(500.263);\n\n // Call print to print string\n p.print(\"Hello C++\");\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 2533,
"s": 2466,
"text": "Printing int: 5\nPrinting float: 500.263\nPrinting string: Hello C++"
}
] |
What is Model Complexity? Compare Linear Regression to Decision Trees to Random Forests | by Susan Maina | Towards Data Science
|
A machine learning model is a system that learns the relationship between the input (independent) features and the target (dependent) feature of a dataset to be useful in making predictions in the future. To test the effectiveness of the model, a completely new similar dataset is introduced which only contains the input features, and the model should predict the target variable based on the insights it gained during training. An appropriate performance metric is then used to compare how good the predicted values are compared to the actual target values. In this article, we are going to test the effectiveness of 3 popular models that vary in complexity;
Linear regressionDecision TreeRandom Forest
Linear regression
Decision Tree
Random Forest
We are then going to check the their performances using two metric systems: Mean squared error, and Mean absolute error.
To accomplish the above we need a dataset, and we are going to create a brand new one ourselves. To understand why I created my own dataset, let us first understand what machine learning is. Machine learning is the process of identifying patterns in data. You can think of a pattern as the ‘way that things work’. Machine learning does this by understanding the relationship between the features (X) and the label (y). Some patterns are simple for example high temperatures leading to increased ice cream sales is a simple linear relationship, while others are complex such as details about a house and how they affect the house price, and this is where machine learning shines. In my case, I created a dataset where the relationship between the X and y features is a cosine curve.
In general, everything has a certain way in which it works and a great model should reveal this pattern. In our case, the ‘true state’ is the cosine curve which is y=cos(x). We will then add some noise to simulate ‘real state’ values, since the real world situations are never perfect.
The first step is to initialize our x values. I used np.linspace(start, end, length). We want our axis to start at 0, end at 2*pi (which is 6.3), and have 100 evenly spaced steps.
x = np.linspace(0, 2*np.pi, 100)
To get the true cosine curve above, I used y=np.cos(x). However, we will add noise in the data all around the cos curve to create our simulated y values.
true_y = np.cos(x)
To create the noise, I used np.random.normal(mean,std,length). This creates normally distributed random values which are centered around the mean, and only vary from the mean by the std(standard deviation). I used 0 for the mean and 0.5 for the std. I set a random seed of 567 so that the generated sample noise was reproducible, otherwise every time the code was run, new data would be generated.
np.random.seed(567)noise = np.random.normal(0, 0.5, 100)
The last step was to add the true y mapping to the noise to create our target variable y.
y = np.cos(x) + noise
Now our values are ready and we will create a dataframe to hold the x and y values. We will call this dataframe train, since this will be the training set to train our models on.
train = pd.DataFrame({'x':x, 'y':y})
Now we can plot both the cosine curve (true relationship) and our simulated train data.
plt.scatter(train.x, train.y)plt.plot(train.x, np.cos(train.x), color='k')plt.xlabel('x')plt.ylabel('y')plt.show()
Test set
We will also simulate a test set. This will be important for testing the effectiveness of the model, by checking how well it can predict y values using unseen x values from the test set. We create the test set exactly the same way as the train, except for the noise which we will create using a different random seed of 765.
x = np.linspace(0, 2*np.pi, 100)np.random.seed(765)noise = np.random.normal(0, 0.5, 100)y = np.cos(x)+noisetest = pd.DataFrame({'x':x, 'y':y})
Let us plot the train (blue dots) and test (red dots) sets together.
This model fits a straight line through the data. y^=β0+β1x is the formula for representing a simple linear regression model; β0 is the y intercept and β1 is the coefficient for x, or the slope of the line. y^ is the predicted value. The intercept and the coefficient are learnt from the data by the model. Therefore the model’s task is to get the best estimates of β0 and β1 that represent the true patterns in the data.
I used sci-kit learn to implement the model. First we import the library then initialize an instance of the model.
from sklearn.linear_model import LinearRegressionbasic_linear_model = LinearRegression()
Next we separate our features (x) from the target variable (y) in the dataset. I used df.drop(‘y’,axis=1). It is common practice to just drop (remove) the target feature and use the rest of the columns as the input features.
features = train.drop('y', axis=1)target = train.y
The final step is to fit the model to the data. This is also called training the model and the best estimates of β0 and β1 are determined.
basic_linear_model.fit(features, target)
You can get the β0 and β1 by calling the intercept_ and coef_ methods of the linear regression model.
print(basic_linear_model.intercept_)print(basic_linear_model.coef_)### Results0.09271652228649466[-0.0169538]
To make predictions we use model.predict(features). The underlying function is β0+β1x and therefore our predictions are represented by a straight line which we can plot, together with our simulated data set.
y_preds = basic_linear_model.predict(features)plt.scatter(df.x, df.y)plt.plot(df.x, y_preds, 'k')plt.show()
As observed, the linear regression model assumes a linear relationship in the data, which is not a good representation for our data.
Polynomial Linear Regression — adding complexity
Unlike a simple linear regression, polynomial models add curves to the data by adding a polynomial factor of x for example x2.
Let us first create a second-order polynomial model, by adding x2 as another column to our data set. We will call the new column x2 and the formula now is y^=β0 + β1x + β2x2.
I created a copy of the data frame to preserve the original. To get x2, I used np.power(value,power)
df2 = train.copy()df2['x2'] = np.power(df2['x'], 2)
Create reusable function: To avoid a lot of code, I created a function that initializes a model, separates the data set into features and target variables, then plots the predictions from the model. The function takes in a dataframe and a model, and returns the trained model.
def model_fitter(data, model): features = data.drop('y', axis=1) target = data.y model.fit(features, target) y_preds = model.predict(features) plt.scatter(data.x, data.y) plt.plot(data.x, y_preds, 'r--') return model
Let us now call the function and create our second-order polynomial model.
polynomial_second_order = model_fitter(df2, LinearRegression())
Wow, look at that! It models the curve in the data very well. But we will know more when we make predictions on completely new unseen data.
I also created a more complex third-order polynomial model whose results turned out almost identical to the second-order model. As a general rule, if two models perform equally well, it is better to choose the less complex model as it usually generalizes better to new data.
Decision trees build a model by splitting the data into subsets based on the target variable. This branching nature allows for very complex relationships in the data. We will first create a Decision tree that does not have any parameters. This will create an unconstrained decision tree that will keep splitting into smaller and smaller subsets until the final leaf nodes have only 1 value.
Let us see this concept in code:
from sklearn.tree import DecisionTreeRegressordecision_tree_unconstrained = model_fitter(train,DecisionTreeRegressor())
The lines represent our predicted values, and clearly the model has completely learnt the train data and predicted all the points perfectly. This is called overfitting and this model will not be able to generalize well when provided with new data. The idea for a model is to ignore the noise and learn the actual signal, but this model learnt the noise as well.
Constrained decision tree by depth
We will add some complexity to our decision tree by limiting the number of levels that the tree can go down to. In our case, we will set a maximum depth of 3, meaning the tree will only be able to branch down 3 levels then arrive at a prediction.
decision_tree_by_depth = model_fitter(train,DecisionTreeRegressor(max_depth = 3))
This was a better performance. You can see the branching nature of the decision tree by the steps, unlike the smooth curve of the polynomial linear regression. Let us use another parameter to constraint the model.
Constrained decision tree by leaf
Here we will set the minimum number of samples that each leaf can have before reaching a prediction to 5. This means that the smallest subset will have 5 values of x, preventing the scenario we had with the unconstrained decision tree which had one sample per leaf node.
decision_tree_by_leaf = model_fitter(train,DecisionTreeRegressor(min_samples_leaf = 5))
There are several parameters you can use with decision trees. The process of choosing the best model parameters is called hyperparameter optimization or tuning.
You can think of a random forest as an ensemble of decision trees.
Random forests train many decision trees in parallel. Each decision tree is trained on only a random subset of observations, and the predictions are combined into one decision tree. This is very effective in preventing overfitting. We need to set a random_state when initializing the model to get reproducible results because each tree is trained on a random set of observations.
from sklearn.ensemble import RandomForestRegressorrandom_forest_unconstrained = model_fitter(train,RandomForestRegressor(random_state=111))
The unconstrained random forest is still overfit, but not as much as the unconstrained decision tree.
We can also constraint the random forest the same way we did the decision tree; max_depth=3 and min_samples_leaf=5.
random_forest_by_depth = model_fitter(train, RandomForestRegressor(random_state=111,max_depth=3))
random_forest_by_leaf = model_fitter(train, RandomForestRegressor(random_state=111, min_samples_leaf=5))
As observed with the constrained random forests above, there is a general smoothing effect of the predictions curve compared to the decision trees which appear as steps. This is because random forest trees are trained on subsets of the observations, then these predictions are combined creating better generalized predictions.
We have only explored two parameters of random forests; max_depth and min_samples_leaf. Find the expansive list here.
We will evaluate our models using two commonly used metrics for regression machine learning: the mean squared error (MSE) and mean absolute error (MAE). MSE takes the average of the squared errors, and larger errors are scaled up therefore penalized more because of the exponent. MAE takes the average of the absolute errors. A lower MSE and MAE is preferred.
MSE is generally a bit faster to calculate, while MAE is easier to interpret.
from sklearn.metrics import mean_squared_errorfrom sklearn.metrics import mean_absolute_error
Let us now make predictions on our test data. I created a function to automate this. The function takes in a test dataset, the trained model, and the name to be printed. It separates the test set into features and target variable, makes predictions on the test set, calculates the MAE and MSE, and prints them.
def model_performance(data, model, name): test_features = data.drop('y', axis=1) test_target = data.y test_preds = model.predict(test_features) mae = mean_absolute_error(test_preds, test_target) mse = mean_squared_error(test_preds, test_target) print(name) print('MAE', np.round(mae,3)) print('MSE', np.round(mse, 3))
For the second order polynomial linear model, we need to engineer the same features as those for the train data set by adding another column to our test data that contains x2 values. We will first create a copy of the test data then add the x2 column.
test2 = test.copy()test2['x2'] = np.power(test2.x, 2)
Now we will run the function for every model and return the mean squared errors and mean absolute errors.
model_performance(test, basic_linear_model, 'Basic linear regression')model_performance(test2, polynomial_second_order, 'Second Order Polynomial Model')model_performance(test, decision_tree_unconstrained, 'Uncontrained Decision Tree Model')model_performance(test, decision_tree_by_depth, 'Decision Tree Constrained by max_depth = 3')model_performance(test, decision_tree_by_leaf, 'Decision Tree Constrained by min_samples_leaf = 5')model_performance(test, random_forest_unconstrained, 'Unconstrained Random Forest')model_performance(test, random_forest_by_depth, 'Random Forest Constrained by max_depth = 3')model_performance(test, random_forest_by_leaf, 'Random Forest Constrained by min_samples_leaf = 5')
Below are the results
Basic linear regressionMAE 0.677MSE 0.669Second Order Polynomial ModelMAE 0.427MSE 0.277Uncontrained Decision Tree ModelMAE 0.523MSE 0.434Decision Tree Constrained by max_depth = 3MAE 0.441MSE 0.289Decision Tree Constrained by min_samples_leaf = 5MAE 0.427MSE 0.287Unconstrained Random ForestMAE 0.47MSE 0.333Random Forest Constrained by max_depth = 3MAE 0.424MSE 0.28Random Forest Constrained by min_samples_leaf = 5MAE 0.416MSE 0.276
We can see that for the two metrics, The Random Forest constrained by leaf has the lowest error, hence the best performing. As expected, the simple linear regression was the worst performing as the data clearly lacked a linear relationship. However the second-order polynomial model was the second best performing model, even though the curve seemed to fit so well. This goes to show why the random forest is so vastly used in applied machine learning.
In this article, we simulated a training and testing data set, fit various models (linear models and tree-based models) and explored various model complexities; from simple linear models to higher-order polynomial models as well as constrained decision trees and random forests. For your on practice, you can simulate a dataset based on other functions such as sine with y=np.sin(x) or tangent; y=np.tan(x). Get the complete code here on github.
|
[
{
"code": null,
"e": 833,
"s": 172,
"text": "A machine learning model is a system that learns the relationship between the input (independent) features and the target (dependent) feature of a dataset to be useful in making predictions in the future. To test the effectiveness of the model, a completely new similar dataset is introduced which only contains the input features, and the model should predict the target variable based on the insights it gained during training. An appropriate performance metric is then used to compare how good the predicted values are compared to the actual target values. In this article, we are going to test the effectiveness of 3 popular models that vary in complexity;"
},
{
"code": null,
"e": 877,
"s": 833,
"text": "Linear regressionDecision TreeRandom Forest"
},
{
"code": null,
"e": 895,
"s": 877,
"text": "Linear regression"
},
{
"code": null,
"e": 909,
"s": 895,
"text": "Decision Tree"
},
{
"code": null,
"e": 923,
"s": 909,
"text": "Random Forest"
},
{
"code": null,
"e": 1044,
"s": 923,
"text": "We are then going to check the their performances using two metric systems: Mean squared error, and Mean absolute error."
},
{
"code": null,
"e": 1826,
"s": 1044,
"text": "To accomplish the above we need a dataset, and we are going to create a brand new one ourselves. To understand why I created my own dataset, let us first understand what machine learning is. Machine learning is the process of identifying patterns in data. You can think of a pattern as the ‘way that things work’. Machine learning does this by understanding the relationship between the features (X) and the label (y). Some patterns are simple for example high temperatures leading to increased ice cream sales is a simple linear relationship, while others are complex such as details about a house and how they affect the house price, and this is where machine learning shines. In my case, I created a dataset where the relationship between the X and y features is a cosine curve."
},
{
"code": null,
"e": 2112,
"s": 1826,
"text": "In general, everything has a certain way in which it works and a great model should reveal this pattern. In our case, the ‘true state’ is the cosine curve which is y=cos(x). We will then add some noise to simulate ‘real state’ values, since the real world situations are never perfect."
},
{
"code": null,
"e": 2292,
"s": 2112,
"text": "The first step is to initialize our x values. I used np.linspace(start, end, length). We want our axis to start at 0, end at 2*pi (which is 6.3), and have 100 evenly spaced steps."
},
{
"code": null,
"e": 2326,
"s": 2292,
"text": "x = np.linspace(0, 2*np.pi, 100) "
},
{
"code": null,
"e": 2480,
"s": 2326,
"text": "To get the true cosine curve above, I used y=np.cos(x). However, we will add noise in the data all around the cos curve to create our simulated y values."
},
{
"code": null,
"e": 2499,
"s": 2480,
"text": "true_y = np.cos(x)"
},
{
"code": null,
"e": 2897,
"s": 2499,
"text": "To create the noise, I used np.random.normal(mean,std,length). This creates normally distributed random values which are centered around the mean, and only vary from the mean by the std(standard deviation). I used 0 for the mean and 0.5 for the std. I set a random seed of 567 so that the generated sample noise was reproducible, otherwise every time the code was run, new data would be generated."
},
{
"code": null,
"e": 2954,
"s": 2897,
"text": "np.random.seed(567)noise = np.random.normal(0, 0.5, 100)"
},
{
"code": null,
"e": 3044,
"s": 2954,
"text": "The last step was to add the true y mapping to the noise to create our target variable y."
},
{
"code": null,
"e": 3066,
"s": 3044,
"text": "y = np.cos(x) + noise"
},
{
"code": null,
"e": 3245,
"s": 3066,
"text": "Now our values are ready and we will create a dataframe to hold the x and y values. We will call this dataframe train, since this will be the training set to train our models on."
},
{
"code": null,
"e": 3282,
"s": 3245,
"text": "train = pd.DataFrame({'x':x, 'y':y})"
},
{
"code": null,
"e": 3370,
"s": 3282,
"text": "Now we can plot both the cosine curve (true relationship) and our simulated train data."
},
{
"code": null,
"e": 3485,
"s": 3370,
"text": "plt.scatter(train.x, train.y)plt.plot(train.x, np.cos(train.x), color='k')plt.xlabel('x')plt.ylabel('y')plt.show()"
},
{
"code": null,
"e": 3494,
"s": 3485,
"text": "Test set"
},
{
"code": null,
"e": 3819,
"s": 3494,
"text": "We will also simulate a test set. This will be important for testing the effectiveness of the model, by checking how well it can predict y values using unseen x values from the test set. We create the test set exactly the same way as the train, except for the noise which we will create using a different random seed of 765."
},
{
"code": null,
"e": 3962,
"s": 3819,
"text": "x = np.linspace(0, 2*np.pi, 100)np.random.seed(765)noise = np.random.normal(0, 0.5, 100)y = np.cos(x)+noisetest = pd.DataFrame({'x':x, 'y':y})"
},
{
"code": null,
"e": 4031,
"s": 3962,
"text": "Let us plot the train (blue dots) and test (red dots) sets together."
},
{
"code": null,
"e": 4453,
"s": 4031,
"text": "This model fits a straight line through the data. y^=β0+β1x is the formula for representing a simple linear regression model; β0 is the y intercept and β1 is the coefficient for x, or the slope of the line. y^ is the predicted value. The intercept and the coefficient are learnt from the data by the model. Therefore the model’s task is to get the best estimates of β0 and β1 that represent the true patterns in the data."
},
{
"code": null,
"e": 4568,
"s": 4453,
"text": "I used sci-kit learn to implement the model. First we import the library then initialize an instance of the model."
},
{
"code": null,
"e": 4657,
"s": 4568,
"text": "from sklearn.linear_model import LinearRegressionbasic_linear_model = LinearRegression()"
},
{
"code": null,
"e": 4882,
"s": 4657,
"text": "Next we separate our features (x) from the target variable (y) in the dataset. I used df.drop(‘y’,axis=1). It is common practice to just drop (remove) the target feature and use the rest of the columns as the input features."
},
{
"code": null,
"e": 4933,
"s": 4882,
"text": "features = train.drop('y', axis=1)target = train.y"
},
{
"code": null,
"e": 5072,
"s": 4933,
"text": "The final step is to fit the model to the data. This is also called training the model and the best estimates of β0 and β1 are determined."
},
{
"code": null,
"e": 5113,
"s": 5072,
"text": "basic_linear_model.fit(features, target)"
},
{
"code": null,
"e": 5215,
"s": 5113,
"text": "You can get the β0 and β1 by calling the intercept_ and coef_ methods of the linear regression model."
},
{
"code": null,
"e": 5325,
"s": 5215,
"text": "print(basic_linear_model.intercept_)print(basic_linear_model.coef_)### Results0.09271652228649466[-0.0169538]"
},
{
"code": null,
"e": 5533,
"s": 5325,
"text": "To make predictions we use model.predict(features). The underlying function is β0+β1x and therefore our predictions are represented by a straight line which we can plot, together with our simulated data set."
},
{
"code": null,
"e": 5641,
"s": 5533,
"text": "y_preds = basic_linear_model.predict(features)plt.scatter(df.x, df.y)plt.plot(df.x, y_preds, 'k')plt.show()"
},
{
"code": null,
"e": 5774,
"s": 5641,
"text": "As observed, the linear regression model assumes a linear relationship in the data, which is not a good representation for our data."
},
{
"code": null,
"e": 5823,
"s": 5774,
"text": "Polynomial Linear Regression — adding complexity"
},
{
"code": null,
"e": 5950,
"s": 5823,
"text": "Unlike a simple linear regression, polynomial models add curves to the data by adding a polynomial factor of x for example x2."
},
{
"code": null,
"e": 6125,
"s": 5950,
"text": "Let us first create a second-order polynomial model, by adding x2 as another column to our data set. We will call the new column x2 and the formula now is y^=β0 + β1x + β2x2."
},
{
"code": null,
"e": 6226,
"s": 6125,
"text": "I created a copy of the data frame to preserve the original. To get x2, I used np.power(value,power)"
},
{
"code": null,
"e": 6278,
"s": 6226,
"text": "df2 = train.copy()df2['x2'] = np.power(df2['x'], 2)"
},
{
"code": null,
"e": 6555,
"s": 6278,
"text": "Create reusable function: To avoid a lot of code, I created a function that initializes a model, separates the data set into features and target variables, then plots the predictions from the model. The function takes in a dataframe and a model, and returns the trained model."
},
{
"code": null,
"e": 6793,
"s": 6555,
"text": "def model_fitter(data, model): features = data.drop('y', axis=1) target = data.y model.fit(features, target) y_preds = model.predict(features) plt.scatter(data.x, data.y) plt.plot(data.x, y_preds, 'r--') return model"
},
{
"code": null,
"e": 6868,
"s": 6793,
"text": "Let us now call the function and create our second-order polynomial model."
},
{
"code": null,
"e": 6932,
"s": 6868,
"text": "polynomial_second_order = model_fitter(df2, LinearRegression())"
},
{
"code": null,
"e": 7072,
"s": 6932,
"text": "Wow, look at that! It models the curve in the data very well. But we will know more when we make predictions on completely new unseen data."
},
{
"code": null,
"e": 7347,
"s": 7072,
"text": "I also created a more complex third-order polynomial model whose results turned out almost identical to the second-order model. As a general rule, if two models perform equally well, it is better to choose the less complex model as it usually generalizes better to new data."
},
{
"code": null,
"e": 7738,
"s": 7347,
"text": "Decision trees build a model by splitting the data into subsets based on the target variable. This branching nature allows for very complex relationships in the data. We will first create a Decision tree that does not have any parameters. This will create an unconstrained decision tree that will keep splitting into smaller and smaller subsets until the final leaf nodes have only 1 value."
},
{
"code": null,
"e": 7771,
"s": 7738,
"text": "Let us see this concept in code:"
},
{
"code": null,
"e": 7891,
"s": 7771,
"text": "from sklearn.tree import DecisionTreeRegressordecision_tree_unconstrained = model_fitter(train,DecisionTreeRegressor())"
},
{
"code": null,
"e": 8253,
"s": 7891,
"text": "The lines represent our predicted values, and clearly the model has completely learnt the train data and predicted all the points perfectly. This is called overfitting and this model will not be able to generalize well when provided with new data. The idea for a model is to ignore the noise and learn the actual signal, but this model learnt the noise as well."
},
{
"code": null,
"e": 8288,
"s": 8253,
"text": "Constrained decision tree by depth"
},
{
"code": null,
"e": 8535,
"s": 8288,
"text": "We will add some complexity to our decision tree by limiting the number of levels that the tree can go down to. In our case, we will set a maximum depth of 3, meaning the tree will only be able to branch down 3 levels then arrive at a prediction."
},
{
"code": null,
"e": 8617,
"s": 8535,
"text": "decision_tree_by_depth = model_fitter(train,DecisionTreeRegressor(max_depth = 3))"
},
{
"code": null,
"e": 8831,
"s": 8617,
"text": "This was a better performance. You can see the branching nature of the decision tree by the steps, unlike the smooth curve of the polynomial linear regression. Let us use another parameter to constraint the model."
},
{
"code": null,
"e": 8865,
"s": 8831,
"text": "Constrained decision tree by leaf"
},
{
"code": null,
"e": 9136,
"s": 8865,
"text": "Here we will set the minimum number of samples that each leaf can have before reaching a prediction to 5. This means that the smallest subset will have 5 values of x, preventing the scenario we had with the unconstrained decision tree which had one sample per leaf node."
},
{
"code": null,
"e": 9224,
"s": 9136,
"text": "decision_tree_by_leaf = model_fitter(train,DecisionTreeRegressor(min_samples_leaf = 5))"
},
{
"code": null,
"e": 9385,
"s": 9224,
"text": "There are several parameters you can use with decision trees. The process of choosing the best model parameters is called hyperparameter optimization or tuning."
},
{
"code": null,
"e": 9452,
"s": 9385,
"text": "You can think of a random forest as an ensemble of decision trees."
},
{
"code": null,
"e": 9832,
"s": 9452,
"text": "Random forests train many decision trees in parallel. Each decision tree is trained on only a random subset of observations, and the predictions are combined into one decision tree. This is very effective in preventing overfitting. We need to set a random_state when initializing the model to get reproducible results because each tree is trained on a random set of observations."
},
{
"code": null,
"e": 9972,
"s": 9832,
"text": "from sklearn.ensemble import RandomForestRegressorrandom_forest_unconstrained = model_fitter(train,RandomForestRegressor(random_state=111))"
},
{
"code": null,
"e": 10074,
"s": 9972,
"text": "The unconstrained random forest is still overfit, but not as much as the unconstrained decision tree."
},
{
"code": null,
"e": 10190,
"s": 10074,
"text": "We can also constraint the random forest the same way we did the decision tree; max_depth=3 and min_samples_leaf=5."
},
{
"code": null,
"e": 10288,
"s": 10190,
"text": "random_forest_by_depth = model_fitter(train, RandomForestRegressor(random_state=111,max_depth=3))"
},
{
"code": null,
"e": 10393,
"s": 10288,
"text": "random_forest_by_leaf = model_fitter(train, RandomForestRegressor(random_state=111, min_samples_leaf=5))"
},
{
"code": null,
"e": 10720,
"s": 10393,
"text": "As observed with the constrained random forests above, there is a general smoothing effect of the predictions curve compared to the decision trees which appear as steps. This is because random forest trees are trained on subsets of the observations, then these predictions are combined creating better generalized predictions."
},
{
"code": null,
"e": 10838,
"s": 10720,
"text": "We have only explored two parameters of random forests; max_depth and min_samples_leaf. Find the expansive list here."
},
{
"code": null,
"e": 11198,
"s": 10838,
"text": "We will evaluate our models using two commonly used metrics for regression machine learning: the mean squared error (MSE) and mean absolute error (MAE). MSE takes the average of the squared errors, and larger errors are scaled up therefore penalized more because of the exponent. MAE takes the average of the absolute errors. A lower MSE and MAE is preferred."
},
{
"code": null,
"e": 11276,
"s": 11198,
"text": "MSE is generally a bit faster to calculate, while MAE is easier to interpret."
},
{
"code": null,
"e": 11370,
"s": 11276,
"text": "from sklearn.metrics import mean_squared_errorfrom sklearn.metrics import mean_absolute_error"
},
{
"code": null,
"e": 11681,
"s": 11370,
"text": "Let us now make predictions on our test data. I created a function to automate this. The function takes in a test dataset, the trained model, and the name to be printed. It separates the test set into features and target variable, makes predictions on the test set, calculates the MAE and MSE, and prints them."
},
{
"code": null,
"e": 12024,
"s": 11681,
"text": "def model_performance(data, model, name): test_features = data.drop('y', axis=1) test_target = data.y test_preds = model.predict(test_features) mae = mean_absolute_error(test_preds, test_target) mse = mean_squared_error(test_preds, test_target) print(name) print('MAE', np.round(mae,3)) print('MSE', np.round(mse, 3))"
},
{
"code": null,
"e": 12276,
"s": 12024,
"text": "For the second order polynomial linear model, we need to engineer the same features as those for the train data set by adding another column to our test data that contains x2 values. We will first create a copy of the test data then add the x2 column."
},
{
"code": null,
"e": 12330,
"s": 12276,
"text": "test2 = test.copy()test2['x2'] = np.power(test2.x, 2)"
},
{
"code": null,
"e": 12436,
"s": 12330,
"text": "Now we will run the function for every model and return the mean squared errors and mean absolute errors."
},
{
"code": null,
"e": 13144,
"s": 12436,
"text": "model_performance(test, basic_linear_model, 'Basic linear regression')model_performance(test2, polynomial_second_order, 'Second Order Polynomial Model')model_performance(test, decision_tree_unconstrained, 'Uncontrained Decision Tree Model')model_performance(test, decision_tree_by_depth, 'Decision Tree Constrained by max_depth = 3')model_performance(test, decision_tree_by_leaf, 'Decision Tree Constrained by min_samples_leaf = 5')model_performance(test, random_forest_unconstrained, 'Unconstrained Random Forest')model_performance(test, random_forest_by_depth, 'Random Forest Constrained by max_depth = 3')model_performance(test, random_forest_by_leaf, 'Random Forest Constrained by min_samples_leaf = 5')"
},
{
"code": null,
"e": 13166,
"s": 13144,
"text": "Below are the results"
},
{
"code": null,
"e": 13602,
"s": 13166,
"text": "Basic linear regressionMAE 0.677MSE 0.669Second Order Polynomial ModelMAE 0.427MSE 0.277Uncontrained Decision Tree ModelMAE 0.523MSE 0.434Decision Tree Constrained by max_depth = 3MAE 0.441MSE 0.289Decision Tree Constrained by min_samples_leaf = 5MAE 0.427MSE 0.287Unconstrained Random ForestMAE 0.47MSE 0.333Random Forest Constrained by max_depth = 3MAE 0.424MSE 0.28Random Forest Constrained by min_samples_leaf = 5MAE 0.416MSE 0.276"
},
{
"code": null,
"e": 14055,
"s": 13602,
"text": "We can see that for the two metrics, The Random Forest constrained by leaf has the lowest error, hence the best performing. As expected, the simple linear regression was the worst performing as the data clearly lacked a linear relationship. However the second-order polynomial model was the second best performing model, even though the curve seemed to fit so well. This goes to show why the random forest is so vastly used in applied machine learning."
}
] |
Checked vs Unchecked exceptions in Java
|
A checked exception is an exception that occurs at the compile time, these are also called as compile time exceptions. These exceptions cannot simply be ignored at the time of compilation, the programmer should take care of (handle) these exceptions.
For example, if you use FileReader class in your program to read data from a file, if the file specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the compiler prompts the programmer to handle the exception.
Live Demo
import java.io.File;
import java.io.FileReader;
public class FilenotFound_Demo {
public static void main(String args[]) {
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}
If you try to compile the above program, you will get the following exceptions.
C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
FileReader fr = new FileReader(file);
^
1 error
Note − Since the methods read() and close() of FileReader class throws IOException, you can observe that the compiler notifies to handle IOException, along with FileNotFoundException.
An unchecked exception is an exception that occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation.
For example, if you have declared an array of size 5 in your program, and trying to call the 6th element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs.
Live Demo
public class Unchecked_Demo {
public static void main(String args[]) {
int num[] = {1, 2, 3, 4};
System.out.println(num[5]);
}
}
If you compile and execute the above program, you will get the following exception.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)
|
[
{
"code": null,
"e": 1313,
"s": 1062,
"text": "A checked exception is an exception that occurs at the compile time, these are also called as compile time exceptions. These exceptions cannot simply be ignored at the time of compilation, the programmer should take care of (handle) these exceptions."
},
{
"code": null,
"e": 1554,
"s": 1313,
"text": "For example, if you use FileReader class in your program to read data from a file, if the file specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the compiler prompts the programmer to handle the exception."
},
{
"code": null,
"e": 1564,
"s": 1554,
"text": "Live Demo"
},
{
"code": null,
"e": 1796,
"s": 1564,
"text": "import java.io.File;\nimport java.io.FileReader;\n\npublic class FilenotFound_Demo {\n\n public static void main(String args[]) { \n File file = new File(\"E://file.txt\");\n FileReader fr = new FileReader(file); \n }\n}"
},
{
"code": null,
"e": 1876,
"s": 1796,
"text": "If you try to compile the above program, you will get the following exceptions."
},
{
"code": null,
"e": 2105,
"s": 1876,
"text": "C:\\>javac FilenotFound_Demo.java\nFilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught or declared to be thrown\n FileReader fr = new FileReader(file); \n ^\n1 error"
},
{
"code": null,
"e": 2289,
"s": 2105,
"text": "Note − Since the methods read() and close() of FileReader class throws IOException, you can observe that the compiler notifies to handle IOException, along with FileNotFoundException."
},
{
"code": null,
"e": 2550,
"s": 2289,
"text": "An unchecked exception is an exception that occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation."
},
{
"code": null,
"e": 2724,
"s": 2550,
"text": "For example, if you have declared an array of size 5 in your program, and trying to call the 6th element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs."
},
{
"code": null,
"e": 2734,
"s": 2724,
"text": "Live Demo"
},
{
"code": null,
"e": 2882,
"s": 2734,
"text": "public class Unchecked_Demo {\n\n public static void main(String args[]) {\n int num[] = {1, 2, 3, 4};\n System.out.println(num[5]);\n }\n}"
},
{
"code": null,
"e": 2966,
"s": 2882,
"text": "If you compile and execute the above program, you will get the following exception."
},
{
"code": null,
"e": 3097,
"s": 2966,
"text": "Exception in thread \"main\" java.lang.ArrayIndexOutOfBoundsException: 5\n at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)"
}
] |
C Number System - Decimal, Binary, Octal and Hex - onlinetutorialspoint
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we are going to learn about the various number systems.
In computers, we normally use four different numbering systems – Decimal, Binary, Octal, and Hexadecimal.
The decimal system is a number system that is used in our day-to-day applications like business, etc. In this system the symbols 0,1,2,3,4,5,6,7,8,9 are used to denote various numbers.
In the binary number system, 0’s and 1’s are the only symbols that are used to represent numbers of all magnitudes. For example, a normal decimal number 7 (seven) is represented in binary as 111. The binary system is mostly used in computers and other computing devices.
A number in a particular base is written as (Number)base. For example, (17)10 is a decimal number (Seventeen), and (10001)2 is a binary number 10001 which actually represents a decimal number whose value is 17.
Since the decimal number system is more commonly used the decimal number (35)10 is simply written as 35. However, if the same number has to be represented in the binary system, it is written as (100011)2.
Similarly, the octal number system uses 8 as its base. It is generally used to display digits and in representing file permissions under UNIX/Linux Operating Systems.
Hexadecimal system or Hex is a number system that uses 16 as a base to represent numbers.
The numbers that we use daily belong to the Decimal System. For example, 0,1,2,3,4,.....,9999,.....etc. It is also called a base – 10 system.
It is called the base – 10 number system because it uses 10 unique digits from 0 to 9 to represent any number.
A base (also called the radix) is the number of unique digits or symbols (including 0) that are used to represent a given number.
In a decimal system (where the base is 10), a total of 10 digits (0,1,2,3,4,5,6,7,8, and 9) are used to represent a number of any magnitude. For example, One hundred and Thirty-Five is represented as 135, where
135 = (1 * 10 2) + (3 * 10 1) + (5 * 10 0)
135 = (1 * 100) + (3 * 10) + (5 * 1)
In a similar way, fractions are represented with base – 10 being raised to a negative power.
The binary number system is used both in mathematics and digital electronics. The binary number system or base – 2 numeral system represents numeric values using only two symbols – Zero (0) and One (1).
Computers have circuits (logic gates) that can be either of the two states: OFF or ON. These two states are represented by Zero (0) and One (1) respectively. It is for this reason that computation in systems is performed using a binary number system (base – 2) where all numbers are represented using 0’s and 1’s.
Each binary digit, i.e., Zero (0) or One (1) is called a bit (known as a binary digit). A collection of 8 such bits is called a Byte.
In computer terminology, different names have been given to multiples of 210 ( i.e., 1024 times the currently existing value ), as shown in the table given below:
In computer text, images, music, videos, or any type of data is eventually stored in binary format on the disk.
In the binary system, a total of 2 digits (0 and 1) are used to represent a number of any magnitude.
For example, Zero is represented as 0, where
0 = (0 * 2 0) = (0 * 1)
Similarly, One is represented as 1, where
1 = (1 * 2 0) = (1 * 1)
Now, let us represent the following numbers in binary format:
Two (2): Since 0 and 1 are the only digits the can be used to represent 2, let’s divide 2 by 2 write the quotient and remainder as follows:
[quotient][remainder], i.e., : [1][0]
2 = (1 * 2 1) + (0 * 2 0 ) = (2) + (0)
Three (3): Since 0 and 1 are the only digits the can be used to represent 3, let’s divide 3 by 2 write the quotient and remainder as follows:
[quotient][remainder], i.e., : [1][1]
3 = (1 * 2 1) + (1 * 2 0 ) = (2) + (1)
Seventeen (17): Since 0 and 1 are the only digits the can be used to represent 17, let’s divide 17 by 2 write the quotient and remainder as follows:
[quotient][remainder], i.e., :[8][1], by repeating the above logic for 8 (8 = [4][0]), 4(4 = [2][0]),2(2 = [1][0]) ,and 1(1 = [0][1]), we finally get [1][0][0][0][1].
17 = (1 * 2 4) + (0 * 2 3) + (0 * 2 2) + (0 * 2 1) + (1 * 2 0)
17 = (16) + (0) + (0) + (0) + (1)
In C, binary numbers are prefixed with a leading 0b (or 0B) (digit zero followed by char ‘b’). For example, to store a binary value of four into a variable binary_Four, we write
int binary_Four = 0b100;
The numbering system which uses base – 8 is called the Octal system. A base (also known as radix) is the number of unique digits or symbols (including 0) that are used to represent a given number.
In the octal system (or the base – 8 system), a total of 8 digits (0, 1, 2, 3, 4, 5, 6, and 7) are used to represent a number of any size (magnitude).
For example, Zero is represented as 0, where
0 = (0 * 8 0) = (0 * 1)
Similarly, numbers 1, 2,..., and 7 are represented below:
1 = (1 * 8 0) = (1 * 1)
2 = (2 * 8 0) = (2 * 1)
......
7 = (7 * 8 0) = (7 * 1)
Now, let us represent the following numbers in the octal system:
Eighteen (18): Since 0 to 7 are only digits that can be used to represent 18, let us divide 18 by 8 and write the quotient and remainder as follows:
[quotient][remainder], i.e.,: [2][2]
18 = (2 * 8 1) + (2 * 8 0) = (16) + (2)
Four Hundred and Twenty-One (421): Since 0 to 7 are only digits that can be used to represent 421, let us divide 421 by 8 and write the quotient and remainder as follows:
[quotient][remainder], i.e.,: [52] [5] (further dividing 52 by 8 we get [6][4]), which is [6][4][5]
421 = (6 * 8 2) + (4 * 8 1) + (5 * 8 0) = (384) + (32) + (5)
In order to differentiate from decimal numbers, octal numbers are prefixed a leading 0 (zero).
For example, to store an octal value of seven into a variable octal_Seven, we write
int octal_Seven = 07;
Similarly, if we want to store an octal representation of a decimal number 9 in a variable number_Nine, we write
int number_Nine = 011;
The largest digit in the octal system is (7)8. Number (7)8 in binary is represented as (111)2. In the binary system, three binary digits (bits) are being used to represent the highest octal digit. While converting an octal number to a binary number, three bits are used to represent each octal digit.
The following table shows the conversion of each octal digit into its corresponding binary digits.
For example, an octal number 0246 is converted to its corresponding binary form as
Octal number -> 2 4 6
Binary number -> 010 100 110
Hence 0246 is (010100110)2.
Similarly, while converting a binary number into its octal form, the binary number is divided into groups of 3 digits each, starting from the extreme right side of the given number. Each of the three binary digits is replaced with their corresponding octal digits.
If the group of binary digits to the extreme left side of the number do not have three digits, the required number of zeros are added as a prefix to get three binary digits. For example, let us convert a binary number 1101100 into its corresponding octal number.
Binary Number -> 1 101 100
Binary Number -> 001 101 100 //After prefixing zeros on the extreme left side of the group
Octal Number -> 1 5 4
Hence, the octal equivalent of the given binary 1101100 is 0154.
The number system which uses base – 16 is called hexadecimal system or simply hex. A base (also known as radix) is the number of unique digits or symbols (including 0) that are used to represent a given number.
In the hexadecimal system (or base – 16 number system), a total of 16 symbols are used. Digits from 0 (zero) to 9 (nine) are used to represent values from 0 to 9 respectively and alphabets A, B, C, D, E and F (or a, b, c, d, e, and f) are used to represent values from 10 to 15 respectively.
In many programming languages 0x is used as a prefix to denote a hexadecimal representation.
For example, in the hexadecimal number system, the value of zero is represented as 0x0, where
0 = (0 * 16 0) = (0 * 1)
Similarly,
1 = (1 * 16 0) = (1 * 1)
2 = (2 * 16 0) = (2 * 1)
.....
15 = F = (15 * 16 0) = (15 * 1)
Now, let us represent the following numbers in the hexadecimal system:
Decimal number Eighteen (18):
Since one can use only 0 to 9 and alphabets A to F to represent 18.
Let’s divide 18 by 16 and write the quotient and remainder as follows:
[quotient][remainder], i.e., [1][2]
18 = 0x12 = (1 * 161) + (2 * 16 0) = (16) + (2)
One Hundred and Sixty (160).
Since one can use only 0 to 9 and alphabets A to F to represent 160.
Let’s divide 160 by 16 and write the quotient and remainder as follows:
[quotient][remainder], i.e., [10][0], [A][0] (since 10 is represented by A)
160 = 0xA0 = (10 * 161) + (0 * 16 0) = (160) + (0)
Note that both uppercase and lowercase letters can be used when representing hexadecimal values. For example,
int hex_Hundred_and_Sixty = 0xA0; // or 0Xa0,however 0xA0 is preferred.
The highest digit in hex is (F)16. The number (F)16 in binary is represented as (1111)2. Here, four binary digits (bits) are used to represent the highest hexadecimal digit. In hex to binary conversion, four bits are used to represent each hex digit.
The following table shows the conversion of each hex digit into its corresponding binary digits.
For example, hexadecimal number 0x5AF6 is converted into its corresponding binary form as follows:
Hex Number -> 5 A F 6
Binary Number -> 0101 1010 1111 0110
Hence, 0x5AF6 is (0101101011110110)2.
Similarly while converting a binary into hex number, the binary number is the first divided into groups of 4 digits each starting from the extreme right side. Each of the four binary digits is replaced with their corresponding hex digits.
If the group to the extreme left side of binary digits does not have four digits, the required number of zeros are added as a prefix to make a group of four binary digits.
For example, let us convert the following binary 1101100 number into hex.
Binary Number -> 110 1100
Binary Number -> 0110 1100 //After prefixing zeros in the left-most group
Hexal number -> 6 C
Hence, the hex equivalent of the given binary 1101100 is 0x6C.
Wiki – Number Systems
Wiki – Decimal Number System
Wiki – Binary Number System
Happy Learning 🙂
Binary To Decimal Conversion Java Program
Decimal To Octal Conversion Java Program
Octal To Decimal Conversion Java Program
Python Number Systems Example
Decimal To Binary Conversion Java Program
Decimal To Hex Conversion Java Program
Binary To Hexadecimal Conversion Java Program
Convert any Number to Python Binary Number
Java Program For Binary Addition
Binary Literals Java 7 Example Tutorials
Java Program for Check Octal Number
Binary Search using Java
PHP Data types Example Tutorials
Underscores in Numeric Literals Java 7
C Program – Sum of digits of given number till single digit
Binary To Decimal Conversion Java Program
Decimal To Octal Conversion Java Program
Octal To Decimal Conversion Java Program
Python Number Systems Example
Decimal To Binary Conversion Java Program
Decimal To Hex Conversion Java Program
Binary To Hexadecimal Conversion Java Program
Convert any Number to Python Binary Number
Java Program For Binary Addition
Binary Literals Java 7 Example Tutorials
Java Program for Check Octal Number
Binary Search using Java
PHP Data types Example Tutorials
Underscores in Numeric Literals Java 7
C Program – Sum of digits of given number till single digit
Δ
C – Introduction
C – Features
C – Variables & Keywords
C – Program Structure
C – Comment Lines & Tokens
C – Number System
C – Local and Global Variables
C – Scope & Lifetime of Variables
C – Data Types
C – Integer Data Types
C – Floating Data Types
C – Derived, Defined Data Types
C – Type Conversions
C – Arithmetic Operators
C – Bitwise Operators
C – Logical Operators
C – Comma and sizeof Operators
C – Operator Precedence and Associativity
C – Relational Operators
C Flow Control – if, if-else, nested if-else, if-else-if
C – Switch Case
C Iterative – for, while, dowhile loops
C Unconditional – break, continue, goto statements
C – Expressions and Statements
C – Header Files & Preprocessor Directives
C – One Dimensional Arrays
C – Multi Dimensional Arrays
C – Pointers Basics
C – Pointers with Arrays
C – Functions
C – How to Pass Arrays to Functions
C – Categories of Functions
C – User defined Functions
C – Formal and Actual Arguments
C – Recursion functions
C – Structures Part -1
C – Structures Part -2
C – Unions
C – File Handling
C – File Operations
C – Dynamic Memory Allocation
C Program – Fibonacci Series
C Program – Prime or Not
C Program – Factorial of Number
C Program – Even or Odd
C Program – Sum of digits till Single Digit
C Program – Sum of digits
C Program – Reverse of a number
C Program – Armstrong Numbers
C Program – Print prime Numbers
C Program – GCD of two Numbers
C Program – Number Palindrome or Not
C Program – Find Largest and Smallest number in an Array
C Program – Add elements of an Array
C Program – Addition of Matrices
C Program – Multiplication of Matrices
C Program – Reverse of an Array
C Program – Bubble Sort
C Program – Add and Sub without using + –
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 472,
"s": 398,
"text": "In this tutorial, we are going to learn about the various number systems."
},
{
"code": null,
"e": 578,
"s": 472,
"text": "In computers, we normally use four different numbering systems – Decimal, Binary, Octal, and Hexadecimal."
},
{
"code": null,
"e": 763,
"s": 578,
"text": "The decimal system is a number system that is used in our day-to-day applications like business, etc. In this system the symbols 0,1,2,3,4,5,6,7,8,9 are used to denote various numbers."
},
{
"code": null,
"e": 1034,
"s": 763,
"text": "In the binary number system, 0’s and 1’s are the only symbols that are used to represent numbers of all magnitudes. For example, a normal decimal number 7 (seven) is represented in binary as 111. The binary system is mostly used in computers and other computing devices."
},
{
"code": null,
"e": 1245,
"s": 1034,
"text": "A number in a particular base is written as (Number)base. For example, (17)10 is a decimal number (Seventeen), and (10001)2 is a binary number 10001 which actually represents a decimal number whose value is 17."
},
{
"code": null,
"e": 1450,
"s": 1245,
"text": "Since the decimal number system is more commonly used the decimal number (35)10 is simply written as 35. However, if the same number has to be represented in the binary system, it is written as (100011)2."
},
{
"code": null,
"e": 1617,
"s": 1450,
"text": "Similarly, the octal number system uses 8 as its base. It is generally used to display digits and in representing file permissions under UNIX/Linux Operating Systems."
},
{
"code": null,
"e": 1707,
"s": 1617,
"text": "Hexadecimal system or Hex is a number system that uses 16 as a base to represent numbers."
},
{
"code": null,
"e": 1849,
"s": 1707,
"text": "The numbers that we use daily belong to the Decimal System. For example, 0,1,2,3,4,.....,9999,.....etc. It is also called a base – 10 system."
},
{
"code": null,
"e": 1960,
"s": 1849,
"text": "It is called the base – 10 number system because it uses 10 unique digits from 0 to 9 to represent any number."
},
{
"code": null,
"e": 2090,
"s": 1960,
"text": "A base (also called the radix) is the number of unique digits or symbols (including 0) that are used to represent a given number."
},
{
"code": null,
"e": 2301,
"s": 2090,
"text": "In a decimal system (where the base is 10), a total of 10 digits (0,1,2,3,4,5,6,7,8, and 9) are used to represent a number of any magnitude. For example, One hundred and Thirty-Five is represented as 135, where"
},
{
"code": null,
"e": 2344,
"s": 2301,
"text": "135 = (1 * 10 2) + (3 * 10 1) + (5 * 10 0)"
},
{
"code": null,
"e": 2381,
"s": 2344,
"text": "135 = (1 * 100) + (3 * 10) + (5 * 1)"
},
{
"code": null,
"e": 2474,
"s": 2381,
"text": "In a similar way, fractions are represented with base – 10 being raised to a negative power."
},
{
"code": null,
"e": 2677,
"s": 2474,
"text": "The binary number system is used both in mathematics and digital electronics. The binary number system or base – 2 numeral system represents numeric values using only two symbols – Zero (0) and One (1)."
},
{
"code": null,
"e": 2991,
"s": 2677,
"text": "Computers have circuits (logic gates) that can be either of the two states: OFF or ON. These two states are represented by Zero (0) and One (1) respectively. It is for this reason that computation in systems is performed using a binary number system (base – 2) where all numbers are represented using 0’s and 1’s."
},
{
"code": null,
"e": 3125,
"s": 2991,
"text": "Each binary digit, i.e., Zero (0) or One (1) is called a bit (known as a binary digit). A collection of 8 such bits is called a Byte."
},
{
"code": null,
"e": 3288,
"s": 3125,
"text": "In computer terminology, different names have been given to multiples of 210 ( i.e., 1024 times the currently existing value ), as shown in the table given below:"
},
{
"code": null,
"e": 3400,
"s": 3288,
"text": "In computer text, images, music, videos, or any type of data is eventually stored in binary format on the disk."
},
{
"code": null,
"e": 3501,
"s": 3400,
"text": "In the binary system, a total of 2 digits (0 and 1) are used to represent a number of any magnitude."
},
{
"code": null,
"e": 3546,
"s": 3501,
"text": "For example, Zero is represented as 0, where"
},
{
"code": null,
"e": 3570,
"s": 3546,
"text": "0 = (0 * 2 0) = (0 * 1)"
},
{
"code": null,
"e": 3612,
"s": 3570,
"text": "Similarly, One is represented as 1, where"
},
{
"code": null,
"e": 3636,
"s": 3612,
"text": "1 = (1 * 2 0) = (1 * 1)"
},
{
"code": null,
"e": 3698,
"s": 3636,
"text": "Now, let us represent the following numbers in binary format:"
},
{
"code": null,
"e": 3838,
"s": 3698,
"text": "Two (2): Since 0 and 1 are the only digits the can be used to represent 2, let’s divide 2 by 2 write the quotient and remainder as follows:"
},
{
"code": null,
"e": 3876,
"s": 3838,
"text": "[quotient][remainder], i.e., : [1][0]"
},
{
"code": null,
"e": 3915,
"s": 3876,
"text": "2 = (1 * 2 1) + (0 * 2 0 ) = (2) + (0)"
},
{
"code": null,
"e": 4057,
"s": 3915,
"text": "Three (3): Since 0 and 1 are the only digits the can be used to represent 3, let’s divide 3 by 2 write the quotient and remainder as follows:"
},
{
"code": null,
"e": 4095,
"s": 4057,
"text": "[quotient][remainder], i.e., : [1][1]"
},
{
"code": null,
"e": 4134,
"s": 4095,
"text": "3 = (1 * 2 1) + (1 * 2 0 ) = (2) + (1)"
},
{
"code": null,
"e": 4283,
"s": 4134,
"text": "Seventeen (17): Since 0 and 1 are the only digits the can be used to represent 17, let’s divide 17 by 2 write the quotient and remainder as follows:"
},
{
"code": null,
"e": 4451,
"s": 4283,
"text": "[quotient][remainder], i.e., :[8][1], by repeating the above logic for 8 (8 = [4][0]), 4(4 = [2][0]),2(2 = [1][0]) ,and 1(1 = [0][1]), we finally get [1][0][0][0][1]."
},
{
"code": null,
"e": 4514,
"s": 4451,
"text": "17 = (1 * 2 4) + (0 * 2 3) + (0 * 2 2) + (0 * 2 1) + (1 * 2 0)"
},
{
"code": null,
"e": 4583,
"s": 4514,
"text": "17 = (16) + (0) + (0) + (0) + (1)"
},
{
"code": null,
"e": 4761,
"s": 4583,
"text": "In C, binary numbers are prefixed with a leading 0b (or 0B) (digit zero followed by char ‘b’). For example, to store a binary value of four into a variable binary_Four, we write"
},
{
"code": null,
"e": 4786,
"s": 4761,
"text": "int binary_Four = 0b100;"
},
{
"code": null,
"e": 4983,
"s": 4786,
"text": "The numbering system which uses base – 8 is called the Octal system. A base (also known as radix) is the number of unique digits or symbols (including 0) that are used to represent a given number."
},
{
"code": null,
"e": 5134,
"s": 4983,
"text": "In the octal system (or the base – 8 system), a total of 8 digits (0, 1, 2, 3, 4, 5, 6, and 7) are used to represent a number of any size (magnitude)."
},
{
"code": null,
"e": 5179,
"s": 5134,
"text": "For example, Zero is represented as 0, where"
},
{
"code": null,
"e": 5203,
"s": 5179,
"text": "0 = (0 * 8 0) = (0 * 1)"
},
{
"code": null,
"e": 5261,
"s": 5203,
"text": "Similarly, numbers 1, 2,..., and 7 are represented below:"
},
{
"code": null,
"e": 5285,
"s": 5261,
"text": "1 = (1 * 8 0) = (1 * 1)"
},
{
"code": null,
"e": 5309,
"s": 5285,
"text": "2 = (2 * 8 0) = (2 * 1)"
},
{
"code": null,
"e": 5316,
"s": 5309,
"text": "......"
},
{
"code": null,
"e": 5340,
"s": 5316,
"text": "7 = (7 * 8 0) = (7 * 1)"
},
{
"code": null,
"e": 5405,
"s": 5340,
"text": "Now, let us represent the following numbers in the octal system:"
},
{
"code": null,
"e": 5554,
"s": 5405,
"text": "Eighteen (18): Since 0 to 7 are only digits that can be used to represent 18, let us divide 18 by 8 and write the quotient and remainder as follows:"
},
{
"code": null,
"e": 5591,
"s": 5554,
"text": "[quotient][remainder], i.e.,: [2][2]"
},
{
"code": null,
"e": 5631,
"s": 5591,
"text": "18 = (2 * 8 1) + (2 * 8 0) = (16) + (2)"
},
{
"code": null,
"e": 5802,
"s": 5631,
"text": "Four Hundred and Twenty-One (421): Since 0 to 7 are only digits that can be used to represent 421, let us divide 421 by 8 and write the quotient and remainder as follows:"
},
{
"code": null,
"e": 5902,
"s": 5802,
"text": "[quotient][remainder], i.e.,: [52] [5] (further dividing 52 by 8 we get [6][4]), which is [6][4][5]"
},
{
"code": null,
"e": 5963,
"s": 5902,
"text": "421 = (6 * 8 2) + (4 * 8 1) + (5 * 8 0) = (384) + (32) + (5)"
},
{
"code": null,
"e": 6058,
"s": 5963,
"text": "In order to differentiate from decimal numbers, octal numbers are prefixed a leading 0 (zero)."
},
{
"code": null,
"e": 6142,
"s": 6058,
"text": "For example, to store an octal value of seven into a variable octal_Seven, we write"
},
{
"code": null,
"e": 6165,
"s": 6142,
"text": "int octal_Seven = 07;\n"
},
{
"code": null,
"e": 6278,
"s": 6165,
"text": "Similarly, if we want to store an octal representation of a decimal number 9 in a variable number_Nine, we write"
},
{
"code": null,
"e": 6302,
"s": 6278,
"text": "int number_Nine = 011;\n"
},
{
"code": null,
"e": 6603,
"s": 6302,
"text": "The largest digit in the octal system is (7)8. Number (7)8 in binary is represented as (111)2. In the binary system, three binary digits (bits) are being used to represent the highest octal digit. While converting an octal number to a binary number, three bits are used to represent each octal digit."
},
{
"code": null,
"e": 6702,
"s": 6603,
"text": "The following table shows the conversion of each octal digit into its corresponding binary digits."
},
{
"code": null,
"e": 6785,
"s": 6702,
"text": "For example, an octal number 0246 is converted to its corresponding binary form as"
},
{
"code": null,
"e": 6868,
"s": 6785,
"text": "Octal number -> 2 4 6\nBinary number -> 010 100 110"
},
{
"code": null,
"e": 6897,
"s": 6868,
"text": "Hence 0246 is (010100110)2."
},
{
"code": null,
"e": 7162,
"s": 6897,
"text": "Similarly, while converting a binary number into its octal form, the binary number is divided into groups of 3 digits each, starting from the extreme right side of the given number. Each of the three binary digits is replaced with their corresponding octal digits."
},
{
"code": null,
"e": 7425,
"s": 7162,
"text": "If the group of binary digits to the extreme left side of the number do not have three digits, the required number of zeros are added as a prefix to get three binary digits. For example, let us convert a binary number 1101100 into its corresponding octal number."
},
{
"code": null,
"e": 7616,
"s": 7425,
"text": "Binary Number -> 1 101 100\nBinary Number -> 001 101 100 //After prefixing zeros on the extreme left side of the group\nOctal Number -> 1 5 4"
},
{
"code": null,
"e": 7681,
"s": 7616,
"text": "Hence, the octal equivalent of the given binary 1101100 is 0154."
},
{
"code": null,
"e": 7892,
"s": 7681,
"text": "The number system which uses base – 16 is called hexadecimal system or simply hex. A base (also known as radix) is the number of unique digits or symbols (including 0) that are used to represent a given number."
},
{
"code": null,
"e": 8184,
"s": 7892,
"text": "In the hexadecimal system (or base – 16 number system), a total of 16 symbols are used. Digits from 0 (zero) to 9 (nine) are used to represent values from 0 to 9 respectively and alphabets A, B, C, D, E and F (or a, b, c, d, e, and f) are used to represent values from 10 to 15 respectively."
},
{
"code": null,
"e": 8277,
"s": 8184,
"text": "In many programming languages 0x is used as a prefix to denote a hexadecimal representation."
},
{
"code": null,
"e": 8371,
"s": 8277,
"text": "For example, in the hexadecimal number system, the value of zero is represented as 0x0, where"
},
{
"code": null,
"e": 8396,
"s": 8371,
"text": "0 = (0 * 16 0) = (0 * 1)"
},
{
"code": null,
"e": 8407,
"s": 8396,
"text": "Similarly,"
},
{
"code": null,
"e": 8432,
"s": 8407,
"text": "1 = (1 * 16 0) = (1 * 1)"
},
{
"code": null,
"e": 8457,
"s": 8432,
"text": "2 = (2 * 16 0) = (2 * 1)"
},
{
"code": null,
"e": 8463,
"s": 8457,
"text": "....."
},
{
"code": null,
"e": 8495,
"s": 8463,
"text": "15 = F = (15 * 16 0) = (15 * 1)"
},
{
"code": null,
"e": 8566,
"s": 8495,
"text": "Now, let us represent the following numbers in the hexadecimal system:"
},
{
"code": null,
"e": 8596,
"s": 8566,
"text": "Decimal number Eighteen (18):"
},
{
"code": null,
"e": 8664,
"s": 8596,
"text": "Since one can use only 0 to 9 and alphabets A to F to represent 18."
},
{
"code": null,
"e": 8735,
"s": 8664,
"text": "Let’s divide 18 by 16 and write the quotient and remainder as follows:"
},
{
"code": null,
"e": 8771,
"s": 8735,
"text": "[quotient][remainder], i.e., [1][2]"
},
{
"code": null,
"e": 8819,
"s": 8771,
"text": "18 = 0x12 = (1 * 161) + (2 * 16 0) = (16) + (2)"
},
{
"code": null,
"e": 8848,
"s": 8819,
"text": "One Hundred and Sixty (160)."
},
{
"code": null,
"e": 8917,
"s": 8848,
"text": "Since one can use only 0 to 9 and alphabets A to F to represent 160."
},
{
"code": null,
"e": 8989,
"s": 8917,
"text": "Let’s divide 160 by 16 and write the quotient and remainder as follows:"
},
{
"code": null,
"e": 9065,
"s": 8989,
"text": "[quotient][remainder], i.e., [10][0], [A][0] (since 10 is represented by A)"
},
{
"code": null,
"e": 9116,
"s": 9065,
"text": "160 = 0xA0 = (10 * 161) + (0 * 16 0) = (160) + (0)"
},
{
"code": null,
"e": 9226,
"s": 9116,
"text": "Note that both uppercase and lowercase letters can be used when representing hexadecimal values. For example,"
},
{
"code": null,
"e": 9298,
"s": 9226,
"text": "int hex_Hundred_and_Sixty = 0xA0; // or 0Xa0,however 0xA0 is preferred."
},
{
"code": null,
"e": 9549,
"s": 9298,
"text": "The highest digit in hex is (F)16. The number (F)16 in binary is represented as (1111)2. Here, four binary digits (bits) are used to represent the highest hexadecimal digit. In hex to binary conversion, four bits are used to represent each hex digit."
},
{
"code": null,
"e": 9646,
"s": 9549,
"text": "The following table shows the conversion of each hex digit into its corresponding binary digits."
},
{
"code": null,
"e": 9745,
"s": 9646,
"text": "For example, hexadecimal number 0x5AF6 is converted into its corresponding binary form as follows:"
},
{
"code": null,
"e": 9835,
"s": 9745,
"text": "Hex Number -> 5 A F 6\nBinary Number -> 0101 1010 1111 0110"
},
{
"code": null,
"e": 9873,
"s": 9835,
"text": "Hence, 0x5AF6 is (0101101011110110)2."
},
{
"code": null,
"e": 10112,
"s": 9873,
"text": "Similarly while converting a binary into hex number, the binary number is the first divided into groups of 4 digits each starting from the extreme right side. Each of the four binary digits is replaced with their corresponding hex digits."
},
{
"code": null,
"e": 10284,
"s": 10112,
"text": "If the group to the extreme left side of binary digits does not have four digits, the required number of zeros are added as a prefix to make a group of four binary digits."
},
{
"code": null,
"e": 10358,
"s": 10284,
"text": "For example, let us convert the following binary 1101100 number into hex."
},
{
"code": null,
"e": 10505,
"s": 10358,
"text": "Binary Number -> 110 1100\nBinary Number -> 0110 1100 //After prefixing zeros in the left-most group\nHexal number -> 6 C"
},
{
"code": null,
"e": 10568,
"s": 10505,
"text": "Hence, the hex equivalent of the given binary 1101100 is 0x6C."
},
{
"code": null,
"e": 10590,
"s": 10568,
"text": "Wiki – Number Systems"
},
{
"code": null,
"e": 10619,
"s": 10590,
"text": "Wiki – Decimal Number System"
},
{
"code": null,
"e": 10647,
"s": 10619,
"text": "Wiki – Binary Number System"
},
{
"code": null,
"e": 10664,
"s": 10647,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 11257,
"s": 10664,
"text": "\nBinary To Decimal Conversion Java Program\nDecimal To Octal Conversion Java Program\nOctal To Decimal Conversion Java Program\nPython Number Systems Example\nDecimal To Binary Conversion Java Program\nDecimal To Hex Conversion Java Program\nBinary To Hexadecimal Conversion Java Program\nConvert any Number to Python Binary Number\nJava Program For Binary Addition\nBinary Literals Java 7 Example Tutorials\nJava Program for Check Octal Number\nBinary Search using Java\nPHP Data types Example Tutorials\nUnderscores in Numeric Literals Java 7\nC Program – Sum of digits of given number till single digit\n"
},
{
"code": null,
"e": 11299,
"s": 11257,
"text": "Binary To Decimal Conversion Java Program"
},
{
"code": null,
"e": 11340,
"s": 11299,
"text": "Decimal To Octal Conversion Java Program"
},
{
"code": null,
"e": 11381,
"s": 11340,
"text": "Octal To Decimal Conversion Java Program"
},
{
"code": null,
"e": 11411,
"s": 11381,
"text": "Python Number Systems Example"
},
{
"code": null,
"e": 11453,
"s": 11411,
"text": "Decimal To Binary Conversion Java Program"
},
{
"code": null,
"e": 11492,
"s": 11453,
"text": "Decimal To Hex Conversion Java Program"
},
{
"code": null,
"e": 11538,
"s": 11492,
"text": "Binary To Hexadecimal Conversion Java Program"
},
{
"code": null,
"e": 11581,
"s": 11538,
"text": "Convert any Number to Python Binary Number"
},
{
"code": null,
"e": 11614,
"s": 11581,
"text": "Java Program For Binary Addition"
},
{
"code": null,
"e": 11655,
"s": 11614,
"text": "Binary Literals Java 7 Example Tutorials"
},
{
"code": null,
"e": 11691,
"s": 11655,
"text": "Java Program for Check Octal Number"
},
{
"code": null,
"e": 11716,
"s": 11691,
"text": "Binary Search using Java"
},
{
"code": null,
"e": 11749,
"s": 11716,
"text": "PHP Data types Example Tutorials"
},
{
"code": null,
"e": 11788,
"s": 11749,
"text": "Underscores in Numeric Literals Java 7"
},
{
"code": null,
"e": 11848,
"s": 11788,
"text": "C Program – Sum of digits of given number till single digit"
},
{
"code": null,
"e": 11854,
"s": 11852,
"text": "Δ"
},
{
"code": null,
"e": 11872,
"s": 11854,
"text": " C – Introduction"
},
{
"code": null,
"e": 11886,
"s": 11872,
"text": " C – Features"
},
{
"code": null,
"e": 11912,
"s": 11886,
"text": " C – Variables & Keywords"
},
{
"code": null,
"e": 11935,
"s": 11912,
"text": " C – Program Structure"
},
{
"code": null,
"e": 11964,
"s": 11935,
"text": " C – Comment Lines & Tokens"
},
{
"code": null,
"e": 11983,
"s": 11964,
"text": " C – Number System"
},
{
"code": null,
"e": 12015,
"s": 11983,
"text": " C – Local and Global Variables"
},
{
"code": null,
"e": 12050,
"s": 12015,
"text": " C – Scope & Lifetime of Variables"
},
{
"code": null,
"e": 12066,
"s": 12050,
"text": " C – Data Types"
},
{
"code": null,
"e": 12090,
"s": 12066,
"text": " C – Integer Data Types"
},
{
"code": null,
"e": 12115,
"s": 12090,
"text": " C – Floating Data Types"
},
{
"code": null,
"e": 12148,
"s": 12115,
"text": " C – Derived, Defined Data Types"
},
{
"code": null,
"e": 12170,
"s": 12148,
"text": " C – Type Conversions"
},
{
"code": null,
"e": 12196,
"s": 12170,
"text": " C – Arithmetic Operators"
},
{
"code": null,
"e": 12219,
"s": 12196,
"text": " C – Bitwise Operators"
},
{
"code": null,
"e": 12242,
"s": 12219,
"text": " C – Logical Operators"
},
{
"code": null,
"e": 12275,
"s": 12242,
"text": " C – Comma and sizeof Operators"
},
{
"code": null,
"e": 12318,
"s": 12275,
"text": " C – Operator Precedence and Associativity"
},
{
"code": null,
"e": 12344,
"s": 12318,
"text": " C – Relational Operators"
},
{
"code": null,
"e": 12402,
"s": 12344,
"text": " C Flow Control – if, if-else, nested if-else, if-else-if"
},
{
"code": null,
"e": 12419,
"s": 12402,
"text": " C – Switch Case"
},
{
"code": null,
"e": 12460,
"s": 12419,
"text": " C Iterative – for, while, dowhile loops"
},
{
"code": null,
"e": 12512,
"s": 12460,
"text": " C Unconditional – break, continue, goto statements"
},
{
"code": null,
"e": 12544,
"s": 12512,
"text": " C – Expressions and Statements"
},
{
"code": null,
"e": 12588,
"s": 12544,
"text": " C – Header Files & Preprocessor Directives"
},
{
"code": null,
"e": 12616,
"s": 12588,
"text": " C – One Dimensional Arrays"
},
{
"code": null,
"e": 12646,
"s": 12616,
"text": " C – Multi Dimensional Arrays"
},
{
"code": null,
"e": 12667,
"s": 12646,
"text": " C – Pointers Basics"
},
{
"code": null,
"e": 12693,
"s": 12667,
"text": " C – Pointers with Arrays"
},
{
"code": null,
"e": 12708,
"s": 12693,
"text": " C – Functions"
},
{
"code": null,
"e": 12745,
"s": 12708,
"text": " C – How to Pass Arrays to Functions"
},
{
"code": null,
"e": 12774,
"s": 12745,
"text": " C – Categories of Functions"
},
{
"code": null,
"e": 12802,
"s": 12774,
"text": " C – User defined Functions"
},
{
"code": null,
"e": 12835,
"s": 12802,
"text": " C – Formal and Actual Arguments"
},
{
"code": null,
"e": 12860,
"s": 12835,
"text": " C – Recursion functions"
},
{
"code": null,
"e": 12884,
"s": 12860,
"text": " C – Structures Part -1"
},
{
"code": null,
"e": 12908,
"s": 12884,
"text": " C – Structures Part -2"
},
{
"code": null,
"e": 12920,
"s": 12908,
"text": " C – Unions"
},
{
"code": null,
"e": 12939,
"s": 12920,
"text": " C – File Handling"
},
{
"code": null,
"e": 12960,
"s": 12939,
"text": " C – File Operations"
},
{
"code": null,
"e": 12991,
"s": 12960,
"text": " C – Dynamic Memory Allocation"
},
{
"code": null,
"e": 13021,
"s": 12991,
"text": " C Program – Fibonacci Series"
},
{
"code": null,
"e": 13047,
"s": 13021,
"text": " C Program – Prime or Not"
},
{
"code": null,
"e": 13080,
"s": 13047,
"text": " C Program – Factorial of Number"
},
{
"code": null,
"e": 13105,
"s": 13080,
"text": " C Program – Even or Odd"
},
{
"code": null,
"e": 13150,
"s": 13105,
"text": " C Program – Sum of digits till Single Digit"
},
{
"code": null,
"e": 13177,
"s": 13150,
"text": " C Program – Sum of digits"
},
{
"code": null,
"e": 13210,
"s": 13177,
"text": " C Program – Reverse of a number"
},
{
"code": null,
"e": 13241,
"s": 13210,
"text": " C Program – Armstrong Numbers"
},
{
"code": null,
"e": 13274,
"s": 13241,
"text": " C Program – Print prime Numbers"
},
{
"code": null,
"e": 13306,
"s": 13274,
"text": " C Program – GCD of two Numbers"
},
{
"code": null,
"e": 13344,
"s": 13306,
"text": " C Program – Number Palindrome or Not"
},
{
"code": null,
"e": 13402,
"s": 13344,
"text": " C Program – Find Largest and Smallest number in an Array"
},
{
"code": null,
"e": 13440,
"s": 13402,
"text": " C Program – Add elements of an Array"
},
{
"code": null,
"e": 13474,
"s": 13440,
"text": " C Program – Addition of Matrices"
},
{
"code": null,
"e": 13514,
"s": 13474,
"text": " C Program – Multiplication of Matrices"
},
{
"code": null,
"e": 13547,
"s": 13514,
"text": " C Program – Reverse of an Array"
},
{
"code": null,
"e": 13572,
"s": 13547,
"text": " C Program – Bubble Sort"
}
] |
Matplotlib.axes.Axes.update() in Python - GeeksforGeeks
|
30 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.update() function in axes module of matplotlib library is used to update this artist’s properties from the dictionary props.
Syntax: Axes.update(self, props)
Parameters: This method accepts the following parameters.
props: This parameter is the dictionary of the properties.
Returns: This method does not return any value.
Below examples illustrate the matplotlib.axes.Axes.update() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np np.random.seed(10**7)geeks = np.random.randn(100) fig, ax = plt.subplots()ax.acorr(geeks, usevlines = True, normed = True, maxlags = 80, lw = 3) ax.grid(True) prop = {'xticks': np.array([-10., -5., 0., 5., 10. ]), 'yticks': np.array([-0.2, 0.2, 0.6, 1., 1.4]), 'ylabel': None, 'xlabel': None} ax.update(prop) fig.suptitle('matplotlib.axes.Axes.update()\ function Example', fontweight ="bold") plt.show()
Output:
Example 2:
# Implementation of matplotlib function import numpy as np import matplotlib.pyplot as plt xx = np.random.rand(16, 30) fig, ax = plt.subplots() m = ax.pcolor(xx) m.set_zorder(-20)prop = {'autoscalex_on': False}w = ax.update(prop) fig.suptitle('matplotlib.axes.Axes.update()\function Example', fontweight ="bold") plt.show()
Output:
Matplotlib axes-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Read a file line by line in Python
Python OOPs Concepts
Different ways to create Pandas Dataframe
sum() function in Python
How to Install PIP on Windows ?
Stack in Python
Bar Plot in Matplotlib
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 24390,
"s": 24362,
"text": "\n30 Apr, 2020"
},
{
"code": null,
"e": 24690,
"s": 24390,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute."
},
{
"code": null,
"e": 24824,
"s": 24690,
"text": "The Axes.update() function in axes module of matplotlib library is used to update this artist’s properties from the dictionary props."
},
{
"code": null,
"e": 24857,
"s": 24824,
"text": "Syntax: Axes.update(self, props)"
},
{
"code": null,
"e": 24915,
"s": 24857,
"text": "Parameters: This method accepts the following parameters."
},
{
"code": null,
"e": 24974,
"s": 24915,
"text": "props: This parameter is the dictionary of the properties."
},
{
"code": null,
"e": 25022,
"s": 24974,
"text": "Returns: This method does not return any value."
},
{
"code": null,
"e": 25111,
"s": 25022,
"text": "Below examples illustrate the matplotlib.axes.Axes.update() function in matplotlib.axes:"
},
{
"code": null,
"e": 25122,
"s": 25111,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np np.random.seed(10**7)geeks = np.random.randn(100) fig, ax = plt.subplots()ax.acorr(geeks, usevlines = True, normed = True, maxlags = 80, lw = 3) ax.grid(True) prop = {'xticks': np.array([-10., -5., 0., 5., 10. ]), 'yticks': np.array([-0.2, 0.2, 0.6, 1., 1.4]), 'ylabel': None, 'xlabel': None} ax.update(prop) fig.suptitle('matplotlib.axes.Axes.update()\\ function Example', fontweight =\"bold\") plt.show() ",
"e": 25669,
"s": 25122,
"text": null
},
{
"code": null,
"e": 25677,
"s": 25669,
"text": "Output:"
},
{
"code": null,
"e": 25688,
"s": 25677,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib function import numpy as np import matplotlib.pyplot as plt xx = np.random.rand(16, 30) fig, ax = plt.subplots() m = ax.pcolor(xx) m.set_zorder(-20)prop = {'autoscalex_on': False}w = ax.update(prop) fig.suptitle('matplotlib.axes.Axes.update()\\function Example', fontweight =\"bold\") plt.show() ",
"e": 26031,
"s": 25688,
"text": null
},
{
"code": null,
"e": 26039,
"s": 26031,
"text": "Output:"
},
{
"code": null,
"e": 26061,
"s": 26039,
"text": "Matplotlib axes-class"
},
{
"code": null,
"e": 26079,
"s": 26061,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 26086,
"s": 26079,
"text": "Python"
},
{
"code": null,
"e": 26184,
"s": 26086,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26193,
"s": 26184,
"text": "Comments"
},
{
"code": null,
"e": 26206,
"s": 26193,
"text": "Old Comments"
},
{
"code": null,
"e": 26224,
"s": 26206,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26246,
"s": 26224,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26281,
"s": 26246,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26302,
"s": 26281,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 26344,
"s": 26302,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26369,
"s": 26344,
"text": "sum() function in Python"
},
{
"code": null,
"e": 26401,
"s": 26369,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26417,
"s": 26401,
"text": "Stack in Python"
},
{
"code": null,
"e": 26440,
"s": 26417,
"text": "Bar Plot in Matplotlib"
}
] |
How to show legend elements horizontally in Matplotlib?
|
To show legend elements horizontally, we can take the following steps
Set the figure size and adjust the padding between and around the subplots.
Using plot() method, plot lines with the labels line1, line2 and line3.
Place a legend on the figure using legend() method, with number of labels for ncol value in the argument.
To display the figure, use show() method.
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
line1, = plt.plot([1, 2, 3], label="line1")
line2, = plt.plot([3, 2, 1], label="line2")
line3, = plt.plot([2, 3, 1], label="line3")
plt.legend(ncol=3, loc="upper right")
plt.show()
|
[
{
"code": null,
"e": 1132,
"s": 1062,
"text": "To show legend elements horizontally, we can take the following steps"
},
{
"code": null,
"e": 1208,
"s": 1132,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1280,
"s": 1208,
"text": "Using plot() method, plot lines with the labels line1, line2 and line3."
},
{
"code": null,
"e": 1386,
"s": 1280,
"text": "Place a legend on the figure using legend() method, with number of labels for ncol value in the argument."
},
{
"code": null,
"e": 1428,
"s": 1386,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1735,
"s": 1428,
"text": "from matplotlib import pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nline1, = plt.plot([1, 2, 3], label=\"line1\")\nline2, = plt.plot([3, 2, 1], label=\"line2\")\nline3, = plt.plot([2, 3, 1], label=\"line3\")\nplt.legend(ncol=3, loc=\"upper right\")\nplt.show()"
}
] |
How to develop a speech recognizer in android without Google API?
|
This example demonstrates how do I develop a speech recognizer in android without Google API.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerInParent="true"
android:src="@drawable/ic_mic" />
<ProgressBar
android:id="@+id/progressBar1" style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/toggleButton1"
android:layout_marginTop="28dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/progressBar1"
android:layout_centerHorizontal="true"
android:layout_marginTop="47dp" />
<ToggleButton
android:id="@+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:text="ToggleButton" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
package app.com.sample;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements
RecognitionListener {
private static final int REQUEST_RECORD_PERMISSION = 100;
private TextView returnedText;
private ToggleButton toggleButton;
private ProgressBar progressBar;
private SpeechRecognizer speech = null;
private Intent recognizerIntent;
private String LOG_TAG = "VoiceRecognitionActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
returnedText = findViewById(R.id.textView1);
progressBar = findViewById(R.id.progressBar1);
toggleButton = findViewById(R.id.toggleButton1);
progressBar.setVisibility(View.INVISIBLE);
speech = SpeechRecognizer.createSpeechRecognizer(this);
Log.i(LOG_TAG, "isRecognitionAvailable: " + SpeechRecognizer.isRecognitionAvailable(this));
speech.setRecognitionListener(this);
recognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE,"US-en");
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3);
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
progressBar.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(true);
ActivityCompat.requestPermissions (MainActivity.this, new String[]{Manifest.permission.RECORD_AUDIO},
REQUEST_RECORD_PERMISSION);
} else {
progressBar.setIndeterminate(false);
progressBar.setVisibility(View.INVISIBLE);
speech.stopListening();
}
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_RECORD_PERMISSION:
if (grantResults.length > 0 && grantResults[0]== PackageManager.PERMISSION_GRANTED) {
speech.startListening(recognizerIntent);
} else {
Toast.makeText(MainActivity.this, "Permission Denied!", Toast .LENGTH_SHORT).show();
}
}
}
@Override
public void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onStop() {
super.onStop();
if (speech != null) {
speech.destroy();
Log.i(LOG_TAG, "destroy");
}
}
@Override
public void onBeginningOfSpeech() {
Log.i(LOG_TAG, "onBeginningOfSpeech");
progressBar.setIndeterminate(false);
progressBar.setMax(10);
}
@Override
public void onBufferReceived(byte[] buffer) {
Log.i(LOG_TAG, "onBufferReceived: " + buffer);
}
@Override
public void onEndOfSpeech() {
Log.i(LOG_TAG, "onEndOfSpeech");
progressBar.setIndeterminate(true);
toggleButton.setChecked(false);
}
@Override
public void onError(int errorCode) {
String errorMessage = getErrorText(errorCode);
Log.d(LOG_TAG, "FAILED " + errorMessage);
returnedText.setText(errorMessage);
toggleButton.setChecked(false);
}
@Override
public void onEvent(int arg0, Bundle arg1) {
Log.i(LOG_TAG, "onEvent");
}
@Override
public void onPartialResults(Bundle arg0) {
Log.i(LOG_TAG, "onPartialResults");
}
@Override
public void onReadyForSpeech(Bundle arg0) {
Log.i(LOG_TAG, "onReadyForSpeech");
}
@Override
public void onResults(Bundle results) {
Log.i(LOG_TAG, "onResults");
ArrayList<String> matches = results .getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
String text = "";
for (String result : matches)
text = result + "\n";
returnedText.setText(text);
}
@Override
public void onRmsChanged(float rmsdB) {
Log.i(LOG_TAG, "onRmsChanged: " + rmsdB);
progressBar.setProgress((int) rmsdB);
}
public static String getErrorText(int errorCode) {
String message;
switch (errorCode) {
case SpeechRecognizer.ERROR_AUDIO:
message = "Audio recording error";
break;
case SpeechRecognizer.ERROR_CLIENT:
message = "Client side error";
break;
case
SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
message = "Insufficient permissions";
break;
case SpeechRecognizer.ERROR_NETWORK:
message = "Network error";
break;
case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
message = "Network timeout";
break;
case SpeechRecognizer.ERROR_NO_MATCH:
message = "No match";
break;
case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
message = "RecognitionService busy";
break;
case SpeechRecognizer.ERROR_SERVER:
message = "error from server";
break;
case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
message = "No speech input";
break;
default:
message = "Didn't understand, please try
again.";
break;
}
return message;
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
|
[
{
"code": null,
"e": 1156,
"s": 1062,
"text": "This example demonstrates how do I develop a speech recognizer in android without Google API."
},
{
"code": null,
"e": 1285,
"s": 1156,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1350,
"s": 1285,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2758,
"s": 1350,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\" >\n <ImageView\n android:id=\"@+id/imageView1\"\n android:layout_width=\"200dp\"\n android:layout_height=\"200dp\"\n android:layout_centerInParent=\"true\"\n android:src=\"@drawable/ic_mic\" />\n <ProgressBar\n android:id=\"@+id/progressBar1\" style=\"?android:attr/progressBarStyleHorizontal\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentLeft=\"true\"\n android:layout_below=\"@+id/toggleButton1\"\n android:layout_marginTop=\"28dp\"\n android:paddingLeft=\"10dp\"\n android:paddingRight=\"10dp\" />\n <TextView\n android:id=\"@+id/textView1\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@+id/progressBar1\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"47dp\" />\n <ToggleButton\n android:id=\"@+id/toggleButton1\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"26dp\"\n android:text=\"ToggleButton\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2815,
"s": 2758,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 9129,
"s": 2815,
"text": "package app.com.sample;\nimport android.Manifest;\nimport android.content.Intent;\nimport android.content.pm.PackageManager;\nimport android.os.Bundle;\nimport android.speech.RecognitionListener;\nimport android.speech.RecognizerIntent;\nimport android.speech.SpeechRecognizer;\nimport android.support.annotation.NonNull;\nimport android.support.v4.app.ActivityCompat;\nimport android.support.v7.app.AppCompatActivity;\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.CompoundButton;\nimport android.widget.ProgressBar;\nimport android.widget.TextView;\nimport android.widget.Toast;\nimport android.widget.ToggleButton;\nimport java.util.ArrayList;\npublic class MainActivity extends AppCompatActivity implements\nRecognitionListener {\n private static final int REQUEST_RECORD_PERMISSION = 100;\n private TextView returnedText;\n private ToggleButton toggleButton;\n private ProgressBar progressBar;\n private SpeechRecognizer speech = null;\n private Intent recognizerIntent;\n private String LOG_TAG = \"VoiceRecognitionActivity\";\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n returnedText = findViewById(R.id.textView1);\n progressBar = findViewById(R.id.progressBar1);\n toggleButton = findViewById(R.id.toggleButton1);\n progressBar.setVisibility(View.INVISIBLE);\n speech = SpeechRecognizer.createSpeechRecognizer(this);\n Log.i(LOG_TAG, \"isRecognitionAvailable: \" + SpeechRecognizer.isRecognitionAvailable(this));\n speech.setRecognitionListener(this);\n recognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);\n recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE,\"US-en\");\n recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);\n recognizerIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3);\n toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {\n @Override\n public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {\n if (isChecked) {\n progressBar.setVisibility(View.VISIBLE);\n progressBar.setIndeterminate(true);\n ActivityCompat.requestPermissions (MainActivity.this, new String[]{Manifest.permission.RECORD_AUDIO},\n REQUEST_RECORD_PERMISSION);\n } else {\n progressBar.setIndeterminate(false);\n progressBar.setVisibility(View.INVISIBLE);\n speech.stopListening();\n }\n }\n });\n }\n @Override\n public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {\n super.onRequestPermissionsResult(requestCode, permissions, grantResults);\n switch (requestCode) {\n case REQUEST_RECORD_PERMISSION:\n if (grantResults.length > 0 && grantResults[0]== PackageManager.PERMISSION_GRANTED) {\n speech.startListening(recognizerIntent);\n } else {\n Toast.makeText(MainActivity.this, \"Permission Denied!\", Toast .LENGTH_SHORT).show();\n }\n }\n }\n @Override\n public void onResume() {\n super.onResume();\n }\n @Override\n protected void onPause() {\n super.onPause();\n }\n @Override\n protected void onStop() {\n super.onStop();\n if (speech != null) {\n speech.destroy();\n Log.i(LOG_TAG, \"destroy\");\n }\n }\n @Override\n public void onBeginningOfSpeech() {\n Log.i(LOG_TAG, \"onBeginningOfSpeech\");\n progressBar.setIndeterminate(false);\n progressBar.setMax(10);\n }\n @Override\n public void onBufferReceived(byte[] buffer) {\n Log.i(LOG_TAG, \"onBufferReceived: \" + buffer);\n }\n @Override\n public void onEndOfSpeech() {\n Log.i(LOG_TAG, \"onEndOfSpeech\");\n progressBar.setIndeterminate(true);\n toggleButton.setChecked(false);\n }\n @Override\n public void onError(int errorCode) {\n String errorMessage = getErrorText(errorCode);\n Log.d(LOG_TAG, \"FAILED \" + errorMessage);\n returnedText.setText(errorMessage);\n toggleButton.setChecked(false);\n }\n @Override\n public void onEvent(int arg0, Bundle arg1) {\n Log.i(LOG_TAG, \"onEvent\");\n }\n @Override\n public void onPartialResults(Bundle arg0) {\n Log.i(LOG_TAG, \"onPartialResults\");\n }\n @Override\n public void onReadyForSpeech(Bundle arg0) {\n Log.i(LOG_TAG, \"onReadyForSpeech\");\n }\n @Override\n public void onResults(Bundle results) {\n Log.i(LOG_TAG, \"onResults\");\n ArrayList<String> matches = results .getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);\n String text = \"\";\n for (String result : matches)\n text = result + \"\\n\";\n returnedText.setText(text);\n }\n @Override\n public void onRmsChanged(float rmsdB) {\n Log.i(LOG_TAG, \"onRmsChanged: \" + rmsdB);\n progressBar.setProgress((int) rmsdB);\n }\n public static String getErrorText(int errorCode) {\n String message;\n switch (errorCode) {\n case SpeechRecognizer.ERROR_AUDIO:\n message = \"Audio recording error\";\n break;\n case SpeechRecognizer.ERROR_CLIENT:\n message = \"Client side error\";\n break;\n case\n SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:\n message = \"Insufficient permissions\";\n break;\n case SpeechRecognizer.ERROR_NETWORK:\n message = \"Network error\";\n break;\n case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:\n message = \"Network timeout\";\n break;\n case SpeechRecognizer.ERROR_NO_MATCH:\n message = \"No match\";\n break;\n case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:\n message = \"RecognitionService busy\";\n break;\n case SpeechRecognizer.ERROR_SERVER:\n message = \"error from server\";\n break;\n case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:\n message = \"No speech input\";\n break;\n default:\n message = \"Didn't understand, please try\n again.\";\n break;\n }\n return message;\n }\n}"
},
{
"code": null,
"e": 9184,
"s": 9129,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 9989,
"s": 9184,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <uses-permission android:name=\"android.permission.RECORD_AUDIO\"/>\n <uses-permission android:name=\"android.permission.INTERNET\" />\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 10336,
"s": 9989,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 10377,
"s": 10336,
"text": "Click here to download the project code."
}
] |
Writing to file in Python - GeeksforGeeks
|
25 Nov, 2019
Python provides inbuilt functions for creating, writing and reading files. There are two types of files that can be handled in python, normal text files and binary files (written in binary language, 0s and 1s).
Text files: In this type of file, Each line of text is terminated with a special character called EOL (End of Line), which is the new line character (‘\n’) in python by default.
Binary files: In this type of file, there is no terminator for a line and the data is stored after converting it into machine-understandable binary language.
Note: To know more about file handling click here.
Table of content
Access mode
Opening a file
Closing a file
Writing to fileAppending to a fileWith statement
Appending to a file
With statement
Access modes govern the type of operations possible in the opened file. It refers to how the file will be used once it’s opened. These modes also define the location of the File Handle in the file. File handle is like a cursor, which defines from where the data has to be read or written in the file. Different access modes for reading a file are –
Write Only (‘w’) : Open the file for writing. For an existing file, the data is truncated and over-written. The handle is positioned at the beginning of the file. Creates the file if the file does not exist.Write and Read (‘w+’) : Open the file for reading and writing. For an existing file, data is truncated and over-written. The handle is positioned at the beginning of the file.Append Only (‘a’) : Open the file for writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
Write Only (‘w’) : Open the file for writing. For an existing file, the data is truncated and over-written. The handle is positioned at the beginning of the file. Creates the file if the file does not exist.
Write and Read (‘w+’) : Open the file for reading and writing. For an existing file, data is truncated and over-written. The handle is positioned at the beginning of the file.
Append Only (‘a’) : Open the file for writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
Note: To know more about access mode click here.
It is done using the open() function. No module is required to be imported for this function.
Syntax:
File_object = open(r"File_Name", "Access_Mode")
The file should exist in the same directory as the python program file else, full address of the file should be written on place of filename.
Note: The r is placed before filename to prevent the characters in filename string to be treated as special character. For example, if there is \temp in the file address, then \t is treated as the tab character and error is raised of invalid address. The r makes the string raw, that is, it tells that the string is without any special characters. The r can be ignored if the file is in same directory and address is not being placed.
# Open function to open the file "MyFile1.txt" # (same directory) in read mode and file1 = open("MyFile.txt", "w") # store its reference in the variable file1 # and "MyFile2.txt" in D:\Text in file2 file2 = open(r"D:\Text\MyFile2.txt", "w+")
Here, file1 is created as object for MyFile1 and file2 as object for MyFile2.
close() function closes the file and frees the memory space acquired by that file. It is used at the time when the file is no longer needed or if it is to be opened in a different file mode.
Syntax:
File_object.close()
# Opening and Closing a file "MyFile.txt" # for object name file1. file1 = open("MyFile.txt", "w") file1.close()
There are two ways to write in a file.
write() : Inserts the string str1 in a single line in the text file.File_object.write(str1)
writelines() : For a list of string elements, each string is inserted in the text file. Used to insert multiple strings at a single time.File_object.writelines(L) for L = [str1, str2, str3]
write() : Inserts the string str1 in a single line in the text file.File_object.write(str1)
File_object.write(str1)
writelines() : For a list of string elements, each string is inserted in the text file. Used to insert multiple strings at a single time.File_object.writelines(L) for L = [str1, str2, str3]
File_object.writelines(L) for L = [str1, str2, str3]
Note: ‘\n’ is treated as a special character of two bytes.
Example:
# Python program to demonstrate# writing to file # Opening a filefile1 = open('myfile.txt', 'w')L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]s = "Hello\n" # Writing a string to filefile1.write(s) # Writing multiple strings# at a timefile1.writelines(L) # Closing filefile1.close() # Checking if the data is# written to file or notfile1 = open('myfile.txt', 'r')print(file1.read())file1.close()
Output:
Hello
This is Delhi
This is Paris
This is London
When the file is opened in append mode, the handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data. Let’s see the below example to clarify the difference between write mode and append mode.
# Python program to illustrate# Append vs write modefile1 = open("myfile.txt", "w")L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]file1.writelines(L)file1.close() # Append-adds at lastfile1 = open("myfile.txt", "a") # append modefile1.write("Today \n")file1.close() file1 = open("myfile.txt", "r")print("Output of Readlines after appending")print(file1.read())print()file1.close() # Write-Overwritesfile1 = open("myfile.txt", "w") # write modefile1.write("Tomorrow \n")file1.close() file1 = open("myfile.txt", "r")print("Output of Readlines after writing")print(file1.read())print()file1.close()
Output:
Output of Readlines after appending
This is Delhi
This is Paris
This is London
Today
Output of Readlines after writing
Tomorrow
with statement in Python is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. Unlike the above implementations, there is no need to call file.close() when using with statement. The with statement itself ensures proper acquisition and release of resources.
Syntax:
with open filename as file:
# Program to show various ways to# write data to a file using with statement L = ["This is Delhi \n", "This is Paris \n", "This is London \n"] # Writing to filewith open("myfile.txt", "w") as file1: # Writing data to a file file1.write("Hello \n") file1.writelines(L) # Reading from filewith open("myfile.txt", "r+") as file1: # Reading form a file print(file1.read())
Output:
Hello
This is Delhi
This is Paris
This is London
Note: To know more about with statement click here.
python-file-handling
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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": 41161,
"s": 41133,
"text": "\n25 Nov, 2019"
},
{
"code": null,
"e": 41372,
"s": 41161,
"text": "Python provides inbuilt functions for creating, writing and reading files. There are two types of files that can be handled in python, normal text files and binary files (written in binary language, 0s and 1s)."
},
{
"code": null,
"e": 41550,
"s": 41372,
"text": "Text files: In this type of file, Each line of text is terminated with a special character called EOL (End of Line), which is the new line character (‘\\n’) in python by default."
},
{
"code": null,
"e": 41708,
"s": 41550,
"text": "Binary files: In this type of file, there is no terminator for a line and the data is stored after converting it into machine-understandable binary language."
},
{
"code": null,
"e": 41759,
"s": 41708,
"text": "Note: To know more about file handling click here."
},
{
"code": null,
"e": 41776,
"s": 41759,
"text": "Table of content"
},
{
"code": null,
"e": 41788,
"s": 41776,
"text": "Access mode"
},
{
"code": null,
"e": 41803,
"s": 41788,
"text": "Opening a file"
},
{
"code": null,
"e": 41818,
"s": 41803,
"text": "Closing a file"
},
{
"code": null,
"e": 41867,
"s": 41818,
"text": "Writing to fileAppending to a fileWith statement"
},
{
"code": null,
"e": 41887,
"s": 41867,
"text": "Appending to a file"
},
{
"code": null,
"e": 41902,
"s": 41887,
"text": "With statement"
},
{
"code": null,
"e": 42251,
"s": 41902,
"text": "Access modes govern the type of operations possible in the opened file. It refers to how the file will be used once it’s opened. These modes also define the location of the File Handle in the file. File handle is like a cursor, which defines from where the data has to be read or written in the file. Different access modes for reading a file are –"
},
{
"code": null,
"e": 42848,
"s": 42251,
"text": "Write Only (‘w’) : Open the file for writing. For an existing file, the data is truncated and over-written. The handle is positioned at the beginning of the file. Creates the file if the file does not exist.Write and Read (‘w+’) : Open the file for reading and writing. For an existing file, data is truncated and over-written. The handle is positioned at the beginning of the file.Append Only (‘a’) : Open the file for writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data."
},
{
"code": null,
"e": 43056,
"s": 42848,
"text": "Write Only (‘w’) : Open the file for writing. For an existing file, the data is truncated and over-written. The handle is positioned at the beginning of the file. Creates the file if the file does not exist."
},
{
"code": null,
"e": 43232,
"s": 43056,
"text": "Write and Read (‘w+’) : Open the file for reading and writing. For an existing file, data is truncated and over-written. The handle is positioned at the beginning of the file."
},
{
"code": null,
"e": 43447,
"s": 43232,
"text": "Append Only (‘a’) : Open the file for writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data."
},
{
"code": null,
"e": 43496,
"s": 43447,
"text": "Note: To know more about access mode click here."
},
{
"code": null,
"e": 43590,
"s": 43496,
"text": "It is done using the open() function. No module is required to be imported for this function."
},
{
"code": null,
"e": 43598,
"s": 43590,
"text": "Syntax:"
},
{
"code": null,
"e": 43647,
"s": 43598,
"text": "File_object = open(r\"File_Name\", \"Access_Mode\")\n"
},
{
"code": null,
"e": 43789,
"s": 43647,
"text": "The file should exist in the same directory as the python program file else, full address of the file should be written on place of filename."
},
{
"code": null,
"e": 44224,
"s": 43789,
"text": "Note: The r is placed before filename to prevent the characters in filename string to be treated as special character. For example, if there is \\temp in the file address, then \\t is treated as the tab character and error is raised of invalid address. The r makes the string raw, that is, it tells that the string is without any special characters. The r can be ignored if the file is in same directory and address is not being placed."
},
{
"code": "# Open function to open the file \"MyFile1.txt\" # (same directory) in read mode and file1 = open(\"MyFile.txt\", \"w\") # store its reference in the variable file1 # and \"MyFile2.txt\" in D:\\Text in file2 file2 = open(r\"D:\\Text\\MyFile2.txt\", \"w+\") ",
"e": 44473,
"s": 44224,
"text": null
},
{
"code": null,
"e": 44551,
"s": 44473,
"text": "Here, file1 is created as object for MyFile1 and file2 as object for MyFile2."
},
{
"code": null,
"e": 44742,
"s": 44551,
"text": "close() function closes the file and frees the memory space acquired by that file. It is used at the time when the file is no longer needed or if it is to be opened in a different file mode."
},
{
"code": null,
"e": 44750,
"s": 44742,
"text": "Syntax:"
},
{
"code": null,
"e": 44771,
"s": 44750,
"text": "File_object.close()\n"
},
{
"code": "# Opening and Closing a file \"MyFile.txt\" # for object name file1. file1 = open(\"MyFile.txt\", \"w\") file1.close() ",
"e": 44885,
"s": 44771,
"text": null
},
{
"code": null,
"e": 44924,
"s": 44885,
"text": "There are two ways to write in a file."
},
{
"code": null,
"e": 45208,
"s": 44924,
"text": "write() : Inserts the string str1 in a single line in the text file.File_object.write(str1)\nwritelines() : For a list of string elements, each string is inserted in the text file. Used to insert multiple strings at a single time.File_object.writelines(L) for L = [str1, str2, str3] \n"
},
{
"code": null,
"e": 45301,
"s": 45208,
"text": "write() : Inserts the string str1 in a single line in the text file.File_object.write(str1)\n"
},
{
"code": null,
"e": 45326,
"s": 45301,
"text": "File_object.write(str1)\n"
},
{
"code": null,
"e": 45518,
"s": 45326,
"text": "writelines() : For a list of string elements, each string is inserted in the text file. Used to insert multiple strings at a single time.File_object.writelines(L) for L = [str1, str2, str3] \n"
},
{
"code": null,
"e": 45573,
"s": 45518,
"text": "File_object.writelines(L) for L = [str1, str2, str3] \n"
},
{
"code": null,
"e": 45632,
"s": 45573,
"text": "Note: ‘\\n’ is treated as a special character of two bytes."
},
{
"code": null,
"e": 45641,
"s": 45632,
"text": "Example:"
},
{
"code": "# Python program to demonstrate# writing to file # Opening a filefile1 = open('myfile.txt', 'w')L = [\"This is Delhi \\n\", \"This is Paris \\n\", \"This is London \\n\"]s = \"Hello\\n\" # Writing a string to filefile1.write(s) # Writing multiple strings# at a timefile1.writelines(L) # Closing filefile1.close() # Checking if the data is# written to file or notfile1 = open('myfile.txt', 'r')print(file1.read())file1.close()",
"e": 46060,
"s": 45641,
"text": null
},
{
"code": null,
"e": 46068,
"s": 46060,
"text": "Output:"
},
{
"code": null,
"e": 46118,
"s": 46068,
"text": "Hello\nThis is Delhi\nThis is Paris\nThis is London\n"
},
{
"code": null,
"e": 46374,
"s": 46118,
"text": "When the file is opened in append mode, the handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data. Let’s see the below example to clarify the difference between write mode and append mode."
},
{
"code": "# Python program to illustrate# Append vs write modefile1 = open(\"myfile.txt\", \"w\")L = [\"This is Delhi \\n\", \"This is Paris \\n\", \"This is London \\n\"]file1.writelines(L)file1.close() # Append-adds at lastfile1 = open(\"myfile.txt\", \"a\") # append modefile1.write(\"Today \\n\")file1.close() file1 = open(\"myfile.txt\", \"r\")print(\"Output of Readlines after appending\")print(file1.read())print()file1.close() # Write-Overwritesfile1 = open(\"myfile.txt\", \"w\") # write modefile1.write(\"Tomorrow \\n\")file1.close() file1 = open(\"myfile.txt\", \"r\")print(\"Output of Readlines after writing\")print(file1.read())print()file1.close()",
"e": 46994,
"s": 46374,
"text": null
},
{
"code": null,
"e": 47002,
"s": 46994,
"text": "Output:"
},
{
"code": null,
"e": 47133,
"s": 47002,
"text": "Output of Readlines after appending\nThis is Delhi\nThis is Paris\nThis is London\nToday\n\n\nOutput of Readlines after writing\nTomorrow\n"
},
{
"code": null,
"e": 47483,
"s": 47133,
"text": "with statement in Python is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. Unlike the above implementations, there is no need to call file.close() when using with statement. The with statement itself ensures proper acquisition and release of resources."
},
{
"code": null,
"e": 47491,
"s": 47483,
"text": "Syntax:"
},
{
"code": null,
"e": 47520,
"s": 47491,
"text": "with open filename as file:\n"
},
{
"code": "# Program to show various ways to# write data to a file using with statement L = [\"This is Delhi \\n\", \"This is Paris \\n\", \"This is London \\n\"] # Writing to filewith open(\"myfile.txt\", \"w\") as file1: # Writing data to a file file1.write(\"Hello \\n\") file1.writelines(L) # Reading from filewith open(\"myfile.txt\", \"r+\") as file1: # Reading form a file print(file1.read())",
"e": 47907,
"s": 47520,
"text": null
},
{
"code": null,
"e": 47915,
"s": 47907,
"text": "Output:"
},
{
"code": null,
"e": 47965,
"s": 47915,
"text": "Hello\nThis is Delhi\nThis is Paris\nThis is London\n"
},
{
"code": null,
"e": 48017,
"s": 47965,
"text": "Note: To know more about with statement click here."
},
{
"code": null,
"e": 48038,
"s": 48017,
"text": "python-file-handling"
},
{
"code": null,
"e": 48045,
"s": 48038,
"text": "Python"
},
{
"code": null,
"e": 48143,
"s": 48045,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 48152,
"s": 48143,
"text": "Comments"
},
{
"code": null,
"e": 48165,
"s": 48152,
"text": "Old Comments"
},
{
"code": null,
"e": 48193,
"s": 48165,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 48243,
"s": 48193,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 48265,
"s": 48243,
"text": "Python map() function"
},
{
"code": null,
"e": 48309,
"s": 48265,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 48344,
"s": 48309,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 48366,
"s": 48344,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 48398,
"s": 48366,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 48428,
"s": 48398,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 48470,
"s": 48428,
"text": "Different ways to create Pandas Dataframe"
}
] |
Find the highest 3 values in a dictionary in Python program
|
In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given a dictionary, and we need to print the 3 highest value in a dictionary.
There are two approaches as discussed below
Live Demo
# collections module
from collections import Counter
# Dictionary
my_dict = {'T': 23, 'U': 22, 'T': 21,'O': 20, 'R': 32, 'S': 99}
k = Counter(my_dict)
# 3 highest values
high = k.most_common(3)
print("Dictionary with 3 highest values:")
print("Keys : Values")
for i in high:
print(i[0]," : ",i[1]," ")
Dictionary with 3 highest values:
Keys : Values
S : 99
R : 32
U : 22
Here the mostcommon() method returns a list of the n most common elements and their counts from the most common to the least.
Live Demo
# nlargest module
from heapq import nlargest
# Dictionary
my_dict = {'T': 23, 'U': 22, 'T': 21,'O': 20, 'R': 32, 'S': 99}
ThreeHighest = nlargest(3, my_dict, key = my_dict.get)
print("Dictionary with 3 highest values:")
print("Keys : Values")
for val in ThreeHighest:
print(val, " : ", my_dict.get(val))
Dictionary with 3 highest values:
Keys : Values
S : 99
R : 32
U : 22
Here we used the n largest element that takes up three arguments, one is the no of elements to be selected and the other two arguments i.e. dictionary and its keys.
In this article, we have learned how we can find the highest 3 values in a dictionary
|
[
{
"code": null,
"e": 1150,
"s": 1062,
"text": "In this article, we will learn about the solution to the problem statement given below."
},
{
"code": null,
"e": 1255,
"s": 1150,
"text": "Problem statement − We are given a dictionary, and we need to print the 3 highest value in a dictionary."
},
{
"code": null,
"e": 1299,
"s": 1255,
"text": "There are two approaches as discussed below"
},
{
"code": null,
"e": 1310,
"s": 1299,
"text": " Live Demo"
},
{
"code": null,
"e": 1615,
"s": 1310,
"text": "# collections module\nfrom collections import Counter\n# Dictionary\nmy_dict = {'T': 23, 'U': 22, 'T': 21,'O': 20, 'R': 32, 'S': 99}\nk = Counter(my_dict)\n# 3 highest values\nhigh = k.most_common(3)\nprint(\"Dictionary with 3 highest values:\")\nprint(\"Keys : Values\")\nfor i in high:\n print(i[0],\" : \",i[1],\" \")"
},
{
"code": null,
"e": 1684,
"s": 1615,
"text": "Dictionary with 3 highest values:\nKeys : Values\nS : 99\nR : 32\nU : 22"
},
{
"code": null,
"e": 1810,
"s": 1684,
"text": "Here the mostcommon() method returns a list of the n most common elements and their counts from the most common to the least."
},
{
"code": null,
"e": 1821,
"s": 1810,
"text": " Live Demo"
},
{
"code": null,
"e": 2128,
"s": 1821,
"text": "# nlargest module\nfrom heapq import nlargest\n# Dictionary\nmy_dict = {'T': 23, 'U': 22, 'T': 21,'O': 20, 'R': 32, 'S': 99}\nThreeHighest = nlargest(3, my_dict, key = my_dict.get)\nprint(\"Dictionary with 3 highest values:\")\nprint(\"Keys : Values\")\nfor val in ThreeHighest:\n print(val, \" : \", my_dict.get(val))"
},
{
"code": null,
"e": 2206,
"s": 2128,
"text": "Dictionary with 3 highest values:\nKeys : Values\nS : 99\nR : 32\nU : 22"
},
{
"code": null,
"e": 2371,
"s": 2206,
"text": "Here we used the n largest element that takes up three arguments, one is the no of elements to be selected and the other two arguments i.e. dictionary and its keys."
},
{
"code": null,
"e": 2457,
"s": 2371,
"text": "In this article, we have learned how we can find the highest 3 values in a dictionary"
}
] |
md5sum - Unix, Linux Command
|
md5sum - compute and check MD5 message digest.
md5sum [OPTION]... [FILE]...
md5sum [OPTION]... [FILE]...
md5sum produces for each input file a 128-bit "finger-print" or "message-digest" or it can check with the output of a former run whether the message digests are still the same (i.e. whether the files changed).
Example-1:
To Calculate / Compute md5sum :
$ md5sum file.txt
output:
3b85ec9ab2984b91070128be6aae25eb file.txt
Example-2:
Calculate or compute md5sum for the input given through STDIN:
$ md5sum -
test
output:
d8e8fca2dc0f896fd7cb4cb0031ba249 -
Example-3:
Compute and Verify checksum of files :
$ md5sum *.txt
output:bbd166fee3f3f624286c4d85dc1994f8 abc.txt
50dcf8c353827eef464cb79f55018d6c xyz.txt
$ md5sum *.txt > txtmd5sum.md5
$ md5sum -c txtmd5sum.md5
abc.txt: OK
xyz.txt: OK
If there is a change in any of the file, you will get the
“computed checksums did NOT match” warning message.
i.e:
md5sum: WARNING: 1 of 3 computed checksums did NOT match
Example-4:
To read in binary mode(md5sum -b file_path):
$ md5sum 1.txt
output:
764efa883dda1e11db47671c4a3bbd9e 1.txt
$ md5sum -b 1.txt
764efa883dda1e11db47671c4a3bbd9e *1.txt
$ md5sum --binary 1.txt
764efa883dda1e11db47671c4a3bbd9e *1.txt
“-b” option is equivalent to “–binary” option.
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": 10624,
"s": 10577,
"text": "md5sum - compute and check MD5 message digest."
},
{
"code": null,
"e": 10656,
"s": 10624,
"text": " md5sum [OPTION]... [FILE]... \n"
},
{
"code": null,
"e": 10687,
"s": 10656,
"text": " md5sum [OPTION]... [FILE]... "
},
{
"code": null,
"e": 10902,
"s": 10687,
"text": "md5sum produces for each input file a 128-bit \"finger-print\" or \"message-digest\" or it can check with the output of a former run whether the message digests are still the same (i.e. whether the files changed)."
},
{
"code": null,
"e": 10913,
"s": 10902,
"text": "Example-1:"
},
{
"code": null,
"e": 10945,
"s": 10913,
"text": "To Calculate / Compute md5sum :"
},
{
"code": null,
"e": 10963,
"s": 10945,
"text": "$ md5sum file.txt"
},
{
"code": null,
"e": 10971,
"s": 10963,
"text": "output:"
},
{
"code": null,
"e": 11015,
"s": 10971,
"text": "3b85ec9ab2984b91070128be6aae25eb file.txt\n"
},
{
"code": null,
"e": 11026,
"s": 11015,
"text": "Example-2:"
},
{
"code": null,
"e": 11089,
"s": 11026,
"text": "Calculate or compute md5sum for the input given through STDIN:"
},
{
"code": null,
"e": 11100,
"s": 11089,
"text": "$ md5sum -"
},
{
"code": null,
"e": 11105,
"s": 11100,
"text": "test"
},
{
"code": null,
"e": 11113,
"s": 11105,
"text": "output:"
},
{
"code": null,
"e": 11150,
"s": 11113,
"text": "d8e8fca2dc0f896fd7cb4cb0031ba249 -\n"
},
{
"code": null,
"e": 11161,
"s": 11150,
"text": "Example-3:"
},
{
"code": null,
"e": 11200,
"s": 11161,
"text": "Compute and Verify checksum of files :"
},
{
"code": null,
"e": 11215,
"s": 11200,
"text": "$ md5sum *.txt"
},
{
"code": null,
"e": 11565,
"s": 11215,
"text": "output:bbd166fee3f3f624286c4d85dc1994f8 abc.txt\n50dcf8c353827eef464cb79f55018d6c xyz.txt\n\n$ md5sum *.txt > txtmd5sum.md5\n\n$ md5sum -c txtmd5sum.md5 \nabc.txt: OK\nxyz.txt: OK\n\nIf there is a change in any of the file, you will get the\n “computed checksums did NOT match” warning message.\ni.e:\nmd5sum: WARNING: 1 of 3 computed checksums did NOT match\n"
},
{
"code": null,
"e": 11576,
"s": 11565,
"text": "Example-4:"
},
{
"code": null,
"e": 11621,
"s": 11576,
"text": "To read in binary mode(md5sum -b file_path):"
},
{
"code": null,
"e": 11636,
"s": 11621,
"text": "$ md5sum 1.txt"
},
{
"code": null,
"e": 11644,
"s": 11636,
"text": "output:"
},
{
"code": null,
"e": 11858,
"s": 11644,
"text": "764efa883dda1e11db47671c4a3bbd9e 1.txt\n\n$ md5sum -b 1.txt \n764efa883dda1e11db47671c4a3bbd9e *1.txt\n\n$ md5sum --binary 1.txt \n764efa883dda1e11db47671c4a3bbd9e *1.txt\n\n“-b” option is equivalent to “–binary” option."
},
{
"code": null,
"e": 11893,
"s": 11858,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 11921,
"s": 11893,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 11955,
"s": 11921,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 11972,
"s": 11955,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 12005,
"s": 11972,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 12016,
"s": 12005,
"text": " Pradeep D"
},
{
"code": null,
"e": 12051,
"s": 12016,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 12067,
"s": 12051,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 12100,
"s": 12067,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 12112,
"s": 12100,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 12144,
"s": 12112,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 12152,
"s": 12144,
"text": " Uplatz"
},
{
"code": null,
"e": 12159,
"s": 12152,
"text": " Print"
},
{
"code": null,
"e": 12170,
"s": 12159,
"text": " Add Notes"
}
] |
In-Depth Look At Data Structures In Julia | by Emmett Boudreau | Towards Data Science
|
Video For This article:
Github repository
Notebook
In the previous iteration of the comprehensive Julia tutorials, we went over how to use Julia’s multiple dispatch with types and functions. Multiple dispatch is a simple system used to apply different types to different function calls under the same method argument. The key component in that structure is types, and more specifically, data types.
Datatypes are the bread and butter of computer programming. Any programming work is going to involve manipulating, moving, and working with basic datatypes. Types themselves that are created in the language are simply containers for other types that are usually data types.
The first kind of data we can store inside of the Julia programming language is a basic datatype. Basic datatypes include data such as numbers, text, characters, and boolean.
A boolean, or bool type is a type that indicates whether or not a condition is true. Booleans can be represented with both a true/false value that ultimately condenses into a 1 or a 0, or just an integer (1 or 0) that represents the condition of the type.
typeof(true)Bool
Likewise, we can also assert booleans to integers representing true or false in the Julia language:
Bool(1)true
The integer datatype in programming parallels the integer datatype in mathematics. An integer is a whole number with no fractional value. Typically, whenever we are working with integers in Julia, we will be working with the Int64 datatype. This means that the integer has 64-bits. Alternatively, there are also Int32s and BigInts.
typeof(5)Int64
Floats are integers with a second number beyond the decimal point, or a fractional value. Floats can be thought of as two separate pieces of data, the integer before the fractional value, and the fractional value coming in after the integer.
typeof(5.5)Float64
Complex floats come into play quite frequently inside of the Julia language. A complex float is simply a float that has values that are both imaginary as well as real. It is important to note that this means that these types are not real. Often scientific computing is going to require a real datatype, as a result you might need to assert some complexes to floats.
typeof(5.5 + 5.5im)Complex(Float64)
The “ im” in the second part of this datatype denotes that the numbers prior are imaginary.
Big datatypes on the other hand, are real numbers but go beyond the capabilities of most 64-bit applications with integers and floats and are accurate. This is a significant exclusivity to the Julia language, as it allows for enormous integer and float datatypes to be passed through multiple functions without a problem — something that few languages are capable of.
# Big Intbig(51515235151351335)# Big Floatbig(5.4172473471347374147)
The symbol datatype is another great thing that the Julia language has pulled from the functional paradigm. Symbols can be used to represent everything from parameters to dictionary keys — and they are reasonably good at their job. In general, the symbol datatype is a great thing to have in a programming language because it can be used as a representation for essentially anything, hence the name: Symbol. Symbols can be written in Julia by simply placing a colon in front of a key-word, for example:
typeof(:Symbol)Symbol
Strings are a fairly simple concept to wrap ones head around — a string is a set of consecutive unicode/ascii characters that make up a composition of chars. As demonstrated in part 3 — Loops, strings can be looped through to reveal the next datatype, chars. If you have yet to read part 3, you can check it out here:
towardsdatascience.com
Strings are delimited with quotation marks. Chars, on the other hand are delimited with apostrophes.
typeof("Hello")Stringtypeof('h')char
Floats are used to represent characters in ASCII. As a result, we can always asset chars into floats:
float('5')
Fun fact: This is how LabelEncoding works
All categorical, vector and matrix data is simply going to act as a container for other types. Consider the example of an array which is comprised of multiple datatypes, such as integers, floats, booleans, or strings.
element_wise = [5, 10, 15, 15]
This new array is an array containing 4 Int64s. We can index them with numbers based on their position in the array:
element_wise[1] == 5trueelement_wise[2] == 10true
We can also see this demonstrated in the type:
typeof(element_wise)Array{Int64, 1}
Why brackets are important:
You might have noticed that whenever an array is created, it is typically within the bounds of square brackets. Without these brackets, the type of this collection of data would be a Tuple. Although I didn’t go into depth on tuples, they are a datatype that is quite valid — but certainly not what you want to have if you need an array.
h = 5,10,15,20typeof(h)NTuple{4, Int64}
Furthermore, a lack of using brackets can make it impossible for a function to understand which parameters are corresponding to which variable. Consider the append!() method. The append! method takes two parameters, firstly whatever data you would like to append to, and secondly the data you would like to append to it. This works if we were to use brackets, as the array is seen as one argument. However, using comma will present an ArgumentError.
parameters v vappend!([5,10], 15) parameters v v vappend!(5,10,15)
In Julia, dictionaries need to be explicitly defined as such — otherwise it will return a tuple. This is a very valuable and dynamic type, and that is further exemplified when working with data-sets or JSON data.
data = Dict(:A => [5,10,15], :B => [11, 12, 13)
Using a dictionary, we can call data by calling corresponding symbol keys, in this example:
data[:A][5, 10, 15]
Pairs are actually tuple types, but it is important to realize that a pair is a tuple, but a tuple is not a pair. A pair is the same exact thing that we used to access parts of our dictionary a second ago, and can be created in the same way:
key = :A => [5,10,15]
Sets are simply unique values extracted from a type. For example, if we were to assert the set type to an array, we would get each of the unique values in that array:
arr = [5, 5, 7, 7, 6, 4, 5]set = Set(arr)println(set)[5, 7, 6, 4]
Tuples are generalized structures for datatypes that don’t necessarily have a defined structure. Tuples can be thought of as a less-organized array.
h = 5, 10, 15
Sometimes working with raw datatypes can be tedious and exhausting, especially whenever a function needs to work with many parameters. This is where structs come in. Creating a struct will make a new type that can hold arbitrary and predefined data structures. We can create a struct by using the struct keyword, followed by a definition and data.
struct typer h vend
With this type, we can now assign a new variable to it, providing the necessary data as parameters for the constructor:
w = typer(5, 10)
In this instance, the struct typer is our new type that holds the data h and v. We can access this data by calling struct.data:
typer.h5typer.v10
We can also pass this new type through a function, for example adding our h and v data from our typer struct:
function addtyper(typer) return(typer.h + typer.v)end
It is important to note that the data in constructed types in the Julia language will be immutable. This can be changed by placing the keyword mutable before the type:
mutable struct typer h vend
Datatypes are consistently a very important thing in programming, and this issue is felt further in the world of data science. Most of programming is simply using data structures and constructed types to work with datatypes. That being said, understanding datatypes is very important to a programmer. There are lots of types in Julia, and some that you can construct yourself, but learning how to utilize and manipulate these types is going to be the key to being a great programmer.
|
[
{
"code": null,
"e": 196,
"s": 172,
"text": "Video For This article:"
},
{
"code": null,
"e": 214,
"s": 196,
"text": "Github repository"
},
{
"code": null,
"e": 223,
"s": 214,
"text": "Notebook"
},
{
"code": null,
"e": 571,
"s": 223,
"text": "In the previous iteration of the comprehensive Julia tutorials, we went over how to use Julia’s multiple dispatch with types and functions. Multiple dispatch is a simple system used to apply different types to different function calls under the same method argument. The key component in that structure is types, and more specifically, data types."
},
{
"code": null,
"e": 845,
"s": 571,
"text": "Datatypes are the bread and butter of computer programming. Any programming work is going to involve manipulating, moving, and working with basic datatypes. Types themselves that are created in the language are simply containers for other types that are usually data types."
},
{
"code": null,
"e": 1020,
"s": 845,
"text": "The first kind of data we can store inside of the Julia programming language is a basic datatype. Basic datatypes include data such as numbers, text, characters, and boolean."
},
{
"code": null,
"e": 1276,
"s": 1020,
"text": "A boolean, or bool type is a type that indicates whether or not a condition is true. Booleans can be represented with both a true/false value that ultimately condenses into a 1 or a 0, or just an integer (1 or 0) that represents the condition of the type."
},
{
"code": null,
"e": 1293,
"s": 1276,
"text": "typeof(true)Bool"
},
{
"code": null,
"e": 1393,
"s": 1293,
"text": "Likewise, we can also assert booleans to integers representing true or false in the Julia language:"
},
{
"code": null,
"e": 1405,
"s": 1393,
"text": "Bool(1)true"
},
{
"code": null,
"e": 1737,
"s": 1405,
"text": "The integer datatype in programming parallels the integer datatype in mathematics. An integer is a whole number with no fractional value. Typically, whenever we are working with integers in Julia, we will be working with the Int64 datatype. This means that the integer has 64-bits. Alternatively, there are also Int32s and BigInts."
},
{
"code": null,
"e": 1752,
"s": 1737,
"text": "typeof(5)Int64"
},
{
"code": null,
"e": 1994,
"s": 1752,
"text": "Floats are integers with a second number beyond the decimal point, or a fractional value. Floats can be thought of as two separate pieces of data, the integer before the fractional value, and the fractional value coming in after the integer."
},
{
"code": null,
"e": 2013,
"s": 1994,
"text": "typeof(5.5)Float64"
},
{
"code": null,
"e": 2379,
"s": 2013,
"text": "Complex floats come into play quite frequently inside of the Julia language. A complex float is simply a float that has values that are both imaginary as well as real. It is important to note that this means that these types are not real. Often scientific computing is going to require a real datatype, as a result you might need to assert some complexes to floats."
},
{
"code": null,
"e": 2415,
"s": 2379,
"text": "typeof(5.5 + 5.5im)Complex(Float64)"
},
{
"code": null,
"e": 2507,
"s": 2415,
"text": "The “ im” in the second part of this datatype denotes that the numbers prior are imaginary."
},
{
"code": null,
"e": 2875,
"s": 2507,
"text": "Big datatypes on the other hand, are real numbers but go beyond the capabilities of most 64-bit applications with integers and floats and are accurate. This is a significant exclusivity to the Julia language, as it allows for enormous integer and float datatypes to be passed through multiple functions without a problem — something that few languages are capable of."
},
{
"code": null,
"e": 2944,
"s": 2875,
"text": "# Big Intbig(51515235151351335)# Big Floatbig(5.4172473471347374147)"
},
{
"code": null,
"e": 3447,
"s": 2944,
"text": "The symbol datatype is another great thing that the Julia language has pulled from the functional paradigm. Symbols can be used to represent everything from parameters to dictionary keys — and they are reasonably good at their job. In general, the symbol datatype is a great thing to have in a programming language because it can be used as a representation for essentially anything, hence the name: Symbol. Symbols can be written in Julia by simply placing a colon in front of a key-word, for example:"
},
{
"code": null,
"e": 3469,
"s": 3447,
"text": "typeof(:Symbol)Symbol"
},
{
"code": null,
"e": 3787,
"s": 3469,
"text": "Strings are a fairly simple concept to wrap ones head around — a string is a set of consecutive unicode/ascii characters that make up a composition of chars. As demonstrated in part 3 — Loops, strings can be looped through to reveal the next datatype, chars. If you have yet to read part 3, you can check it out here:"
},
{
"code": null,
"e": 3810,
"s": 3787,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3911,
"s": 3810,
"text": "Strings are delimited with quotation marks. Chars, on the other hand are delimited with apostrophes."
},
{
"code": null,
"e": 3948,
"s": 3911,
"text": "typeof(\"Hello\")Stringtypeof('h')char"
},
{
"code": null,
"e": 4050,
"s": 3948,
"text": "Floats are used to represent characters in ASCII. As a result, we can always asset chars into floats:"
},
{
"code": null,
"e": 4061,
"s": 4050,
"text": "float('5')"
},
{
"code": null,
"e": 4103,
"s": 4061,
"text": "Fun fact: This is how LabelEncoding works"
},
{
"code": null,
"e": 4321,
"s": 4103,
"text": "All categorical, vector and matrix data is simply going to act as a container for other types. Consider the example of an array which is comprised of multiple datatypes, such as integers, floats, booleans, or strings."
},
{
"code": null,
"e": 4352,
"s": 4321,
"text": "element_wise = [5, 10, 15, 15]"
},
{
"code": null,
"e": 4469,
"s": 4352,
"text": "This new array is an array containing 4 Int64s. We can index them with numbers based on their position in the array:"
},
{
"code": null,
"e": 4519,
"s": 4469,
"text": "element_wise[1] == 5trueelement_wise[2] == 10true"
},
{
"code": null,
"e": 4566,
"s": 4519,
"text": "We can also see this demonstrated in the type:"
},
{
"code": null,
"e": 4602,
"s": 4566,
"text": "typeof(element_wise)Array{Int64, 1}"
},
{
"code": null,
"e": 4630,
"s": 4602,
"text": "Why brackets are important:"
},
{
"code": null,
"e": 4967,
"s": 4630,
"text": "You might have noticed that whenever an array is created, it is typically within the bounds of square brackets. Without these brackets, the type of this collection of data would be a Tuple. Although I didn’t go into depth on tuples, they are a datatype that is quite valid — but certainly not what you want to have if you need an array."
},
{
"code": null,
"e": 5007,
"s": 4967,
"text": "h = 5,10,15,20typeof(h)NTuple{4, Int64}"
},
{
"code": null,
"e": 5457,
"s": 5007,
"text": "Furthermore, a lack of using brackets can make it impossible for a function to understand which parameters are corresponding to which variable. Consider the append!() method. The append! method takes two parameters, firstly whatever data you would like to append to, and secondly the data you would like to append to it. This works if we were to use brackets, as the array is seen as one argument. However, using comma will present an ArgumentError."
},
{
"code": null,
"e": 5559,
"s": 5457,
"text": " parameters v vappend!([5,10], 15) parameters v v vappend!(5,10,15)"
},
{
"code": null,
"e": 5772,
"s": 5559,
"text": "In Julia, dictionaries need to be explicitly defined as such — otherwise it will return a tuple. This is a very valuable and dynamic type, and that is further exemplified when working with data-sets or JSON data."
},
{
"code": null,
"e": 5820,
"s": 5772,
"text": "data = Dict(:A => [5,10,15], :B => [11, 12, 13)"
},
{
"code": null,
"e": 5912,
"s": 5820,
"text": "Using a dictionary, we can call data by calling corresponding symbol keys, in this example:"
},
{
"code": null,
"e": 5932,
"s": 5912,
"text": "data[:A][5, 10, 15]"
},
{
"code": null,
"e": 6174,
"s": 5932,
"text": "Pairs are actually tuple types, but it is important to realize that a pair is a tuple, but a tuple is not a pair. A pair is the same exact thing that we used to access parts of our dictionary a second ago, and can be created in the same way:"
},
{
"code": null,
"e": 6196,
"s": 6174,
"text": "key = :A => [5,10,15]"
},
{
"code": null,
"e": 6363,
"s": 6196,
"text": "Sets are simply unique values extracted from a type. For example, if we were to assert the set type to an array, we would get each of the unique values in that array:"
},
{
"code": null,
"e": 6429,
"s": 6363,
"text": "arr = [5, 5, 7, 7, 6, 4, 5]set = Set(arr)println(set)[5, 7, 6, 4]"
},
{
"code": null,
"e": 6578,
"s": 6429,
"text": "Tuples are generalized structures for datatypes that don’t necessarily have a defined structure. Tuples can be thought of as a less-organized array."
},
{
"code": null,
"e": 6592,
"s": 6578,
"text": "h = 5, 10, 15"
},
{
"code": null,
"e": 6940,
"s": 6592,
"text": "Sometimes working with raw datatypes can be tedious and exhausting, especially whenever a function needs to work with many parameters. This is where structs come in. Creating a struct will make a new type that can hold arbitrary and predefined data structures. We can create a struct by using the struct keyword, followed by a definition and data."
},
{
"code": null,
"e": 6966,
"s": 6940,
"text": "struct typer h vend"
},
{
"code": null,
"e": 7086,
"s": 6966,
"text": "With this type, we can now assign a new variable to it, providing the necessary data as parameters for the constructor:"
},
{
"code": null,
"e": 7103,
"s": 7086,
"text": "w = typer(5, 10)"
},
{
"code": null,
"e": 7231,
"s": 7103,
"text": "In this instance, the struct typer is our new type that holds the data h and v. We can access this data by calling struct.data:"
},
{
"code": null,
"e": 7249,
"s": 7231,
"text": "typer.h5typer.v10"
},
{
"code": null,
"e": 7359,
"s": 7249,
"text": "We can also pass this new type through a function, for example adding our h and v data from our typer struct:"
},
{
"code": null,
"e": 7416,
"s": 7359,
"text": "function addtyper(typer) return(typer.h + typer.v)end"
},
{
"code": null,
"e": 7584,
"s": 7416,
"text": "It is important to note that the data in constructed types in the Julia language will be immutable. This can be changed by placing the keyword mutable before the type:"
},
{
"code": null,
"e": 7618,
"s": 7584,
"text": "mutable struct typer h vend"
}
] |
Classifying Movie Reviews With Natural Language Framework | by Anupam Chugh | Towards Data Science
|
Apple showed some good progress in the field of Natural Language Processing during WWDC 2019. They’ve brought enhancements in both Text Classification And Word Tagging, the two pillars of NLP.
In this article, we’ll be discussing the advancements in Text Classification only, which deals with classifying input text to a set of predefined class labels.
This year, Apple brings in the transfer learning technique for text classifiers model training. Transfer learning pays heed to the semantics of the overall context of the text and is able to figure out cases where the same word has different meanings in different parts of the text.
Though state of the art transfer learning is better equipped for semantic analysis, it does take a bit longer time to train than a say, maximum entropy algorithm.
Apple also introduces built-in sentiment analysis this year. Using the NLP framework, now you get a score in the range -1 to 1 signifying the degree of sentiment.
Here’s a sample code showing how NLP’s built-in sentiment analysis predicts the sentiment score in a string:
import NaturalLanguagetagger.string = textlet (sentiment, _) = tagger.tag(at: text.startIndex, unit: .paragraph, scheme: .sentimentScore)print(sentiment.rawValue)
The built-in sentiment analysis is pretty accurate as we can see below:
In the next sections, we’ll be using Rotten Tomatoes dataset to create a Text Classifier Core ML Model using Create ML and deploy it in our Natural Language Framework.
Converting the CSV dataset to Train Test Folders.
Training the dataset using Create ML.
Deploying the Core ML model in the Natural Language Framework with SwiftUI.
Our dataset is a CSV file as shown below:
The following python script is used to split the CSV into training and test data folders:
import osimport pandas as pddf = pd.read_csv("rotten_tomatoes_reviews.csv", nrows=50000)df.columns = ["freshness", "review"]# Split data into training and testing sets by labeltrain = df.sample(frac=0.8, random_state=42)train_good = train[train.freshness == 1]train_bad = train.drop(train_good.index)test = df.drop(train.index)test_good = test[test.freshness == 1]test_bad = test.drop(test_good.index)# Create folders for dataos.mkdir("train"); os.mkdir("test")os.mkdir("train/good"); os.mkdir("train/bad")os.mkdir("test/good"); os.mkdir("test/bad")#Write out datadef write_text(path, df): for i, r in df.iterrows(): with open(path + str(i) + ".txt", "w") as f: f.write(r["review"])write_text("train/good/", train_good)write_text("train/bad/", train_bad)write_text("test/good/", test_good)write_text("test/bad/", test_bad)
For the sake of simplicity and time, we’ll parse the first 50000 rows out of the 4,80,000 Rotten Tomato review and split the dataset into the standard 80–20 ratio for the train and test folder.
Once the CSV is split into the respective folders, we can launch our Create ML application which has now got an independent entity this year.
Create a new Text Classifier Model Project in Create ML and add the training folder. You can choose any of the techniques to train your model and go have a cup of coffee while the training and validation happens. It took me 4 hours to get a Transfer learning model trained.
Here’s an illustration that compares the model metrics across the two techniques in Text Classification:
The transfer learning based model extrapolates better. Though you can try achieving better accuracy by increasing the dataset size(TL model training took four hours on a dataset of 15000 texts for me).
Alternatively, you can create your model programmatically using Create ML. Just pass the desired algorithm in the argument ModelParameters .
init(trainingData: MLTextClassifier.DataSource, parameters: MLTextClassifier.ModelParameters)
Once the model is trained and tested, hop onto the Output tab in Create ML and enter texts to run predictions. The following illustration shows some of the predictions I ran.
Now our model is ready to be deployed for natural language processing.
Create a new Xcode SwiftUI based project and drag and drop the Core ML model we’d created earlier.
We’ll be developing an application that shows a list of texts(typically Rotten Tomato reviews) on which we’ll run our Core ML Model using NLP to determine whether it was a rot or not(good or bad review).
Also, we’ll be running NLP’s built-in sentiment analysis to know how it predicts the Rotten Tomato reviews and see how accurate the degree of sentiment and the CoreML predictions are.
The following code shows how to feed a Core ML model into the Natural Language Framework:
import NaturalLanguagelet predictor = try NLModel(mlModel: ReviewClassifier().model)predictor.predictedLabel(for: "Fight Club was a master piece. One of it's kind cinema.")
Let’s start off by creating a SwiftUI List that’s populated using a Reviews structure that conforms to the Identifiable protocol.
In the above code, we’ve added navigation links to the List items that takes them to the ReviewDetail view which we shall see next:
The above code is straightforward. We’ve added two SwiftUI buttons that evaluate the text for sentiment analysis and how good or bad the review is, respectively.
In return, we get the following outcome in our SwiftUI preview:
NLP’s built-in sentiment analysis did a pretty fine job with a dataset it’s largely not familiar with. At the same time, our Core ML model performed decently with the Natural Language Framework in determining whether the reviewer loved the film or panned it.
So that sums up Core ML and Natural Language Framework. We saw how the built-in sentiment analysis is such a powerful tool in language processing.
The full source code along with the python script for parsing the CSV is available in this Github Repository. Also, it contains models built using max entropy and transfer learning. You can try playing around with them and see which fits the bill better.
That’s it for this one. I hope you enjoyed reading and model training!
|
[
{
"code": null,
"e": 365,
"s": 172,
"text": "Apple showed some good progress in the field of Natural Language Processing during WWDC 2019. They’ve brought enhancements in both Text Classification And Word Tagging, the two pillars of NLP."
},
{
"code": null,
"e": 525,
"s": 365,
"text": "In this article, we’ll be discussing the advancements in Text Classification only, which deals with classifying input text to a set of predefined class labels."
},
{
"code": null,
"e": 808,
"s": 525,
"text": "This year, Apple brings in the transfer learning technique for text classifiers model training. Transfer learning pays heed to the semantics of the overall context of the text and is able to figure out cases where the same word has different meanings in different parts of the text."
},
{
"code": null,
"e": 971,
"s": 808,
"text": "Though state of the art transfer learning is better equipped for semantic analysis, it does take a bit longer time to train than a say, maximum entropy algorithm."
},
{
"code": null,
"e": 1134,
"s": 971,
"text": "Apple also introduces built-in sentiment analysis this year. Using the NLP framework, now you get a score in the range -1 to 1 signifying the degree of sentiment."
},
{
"code": null,
"e": 1243,
"s": 1134,
"text": "Here’s a sample code showing how NLP’s built-in sentiment analysis predicts the sentiment score in a string:"
},
{
"code": null,
"e": 1406,
"s": 1243,
"text": "import NaturalLanguagetagger.string = textlet (sentiment, _) = tagger.tag(at: text.startIndex, unit: .paragraph, scheme: .sentimentScore)print(sentiment.rawValue)"
},
{
"code": null,
"e": 1478,
"s": 1406,
"text": "The built-in sentiment analysis is pretty accurate as we can see below:"
},
{
"code": null,
"e": 1646,
"s": 1478,
"text": "In the next sections, we’ll be using Rotten Tomatoes dataset to create a Text Classifier Core ML Model using Create ML and deploy it in our Natural Language Framework."
},
{
"code": null,
"e": 1696,
"s": 1646,
"text": "Converting the CSV dataset to Train Test Folders."
},
{
"code": null,
"e": 1734,
"s": 1696,
"text": "Training the dataset using Create ML."
},
{
"code": null,
"e": 1810,
"s": 1734,
"text": "Deploying the Core ML model in the Natural Language Framework with SwiftUI."
},
{
"code": null,
"e": 1852,
"s": 1810,
"text": "Our dataset is a CSV file as shown below:"
},
{
"code": null,
"e": 1942,
"s": 1852,
"text": "The following python script is used to split the CSV into training and test data folders:"
},
{
"code": null,
"e": 2786,
"s": 1942,
"text": "import osimport pandas as pddf = pd.read_csv(\"rotten_tomatoes_reviews.csv\", nrows=50000)df.columns = [\"freshness\", \"review\"]# Split data into training and testing sets by labeltrain = df.sample(frac=0.8, random_state=42)train_good = train[train.freshness == 1]train_bad = train.drop(train_good.index)test = df.drop(train.index)test_good = test[test.freshness == 1]test_bad = test.drop(test_good.index)# Create folders for dataos.mkdir(\"train\"); os.mkdir(\"test\")os.mkdir(\"train/good\"); os.mkdir(\"train/bad\")os.mkdir(\"test/good\"); os.mkdir(\"test/bad\")#Write out datadef write_text(path, df): for i, r in df.iterrows(): with open(path + str(i) + \".txt\", \"w\") as f: f.write(r[\"review\"])write_text(\"train/good/\", train_good)write_text(\"train/bad/\", train_bad)write_text(\"test/good/\", test_good)write_text(\"test/bad/\", test_bad)"
},
{
"code": null,
"e": 2980,
"s": 2786,
"text": "For the sake of simplicity and time, we’ll parse the first 50000 rows out of the 4,80,000 Rotten Tomato review and split the dataset into the standard 80–20 ratio for the train and test folder."
},
{
"code": null,
"e": 3122,
"s": 2980,
"text": "Once the CSV is split into the respective folders, we can launch our Create ML application which has now got an independent entity this year."
},
{
"code": null,
"e": 3396,
"s": 3122,
"text": "Create a new Text Classifier Model Project in Create ML and add the training folder. You can choose any of the techniques to train your model and go have a cup of coffee while the training and validation happens. It took me 4 hours to get a Transfer learning model trained."
},
{
"code": null,
"e": 3501,
"s": 3396,
"text": "Here’s an illustration that compares the model metrics across the two techniques in Text Classification:"
},
{
"code": null,
"e": 3703,
"s": 3501,
"text": "The transfer learning based model extrapolates better. Though you can try achieving better accuracy by increasing the dataset size(TL model training took four hours on a dataset of 15000 texts for me)."
},
{
"code": null,
"e": 3844,
"s": 3703,
"text": "Alternatively, you can create your model programmatically using Create ML. Just pass the desired algorithm in the argument ModelParameters ."
},
{
"code": null,
"e": 3938,
"s": 3844,
"text": "init(trainingData: MLTextClassifier.DataSource, parameters: MLTextClassifier.ModelParameters)"
},
{
"code": null,
"e": 4113,
"s": 3938,
"text": "Once the model is trained and tested, hop onto the Output tab in Create ML and enter texts to run predictions. The following illustration shows some of the predictions I ran."
},
{
"code": null,
"e": 4184,
"s": 4113,
"text": "Now our model is ready to be deployed for natural language processing."
},
{
"code": null,
"e": 4283,
"s": 4184,
"text": "Create a new Xcode SwiftUI based project and drag and drop the Core ML model we’d created earlier."
},
{
"code": null,
"e": 4487,
"s": 4283,
"text": "We’ll be developing an application that shows a list of texts(typically Rotten Tomato reviews) on which we’ll run our Core ML Model using NLP to determine whether it was a rot or not(good or bad review)."
},
{
"code": null,
"e": 4671,
"s": 4487,
"text": "Also, we’ll be running NLP’s built-in sentiment analysis to know how it predicts the Rotten Tomato reviews and see how accurate the degree of sentiment and the CoreML predictions are."
},
{
"code": null,
"e": 4761,
"s": 4671,
"text": "The following code shows how to feed a Core ML model into the Natural Language Framework:"
},
{
"code": null,
"e": 4934,
"s": 4761,
"text": "import NaturalLanguagelet predictor = try NLModel(mlModel: ReviewClassifier().model)predictor.predictedLabel(for: \"Fight Club was a master piece. One of it's kind cinema.\")"
},
{
"code": null,
"e": 5064,
"s": 4934,
"text": "Let’s start off by creating a SwiftUI List that’s populated using a Reviews structure that conforms to the Identifiable protocol."
},
{
"code": null,
"e": 5196,
"s": 5064,
"text": "In the above code, we’ve added navigation links to the List items that takes them to the ReviewDetail view which we shall see next:"
},
{
"code": null,
"e": 5358,
"s": 5196,
"text": "The above code is straightforward. We’ve added two SwiftUI buttons that evaluate the text for sentiment analysis and how good or bad the review is, respectively."
},
{
"code": null,
"e": 5422,
"s": 5358,
"text": "In return, we get the following outcome in our SwiftUI preview:"
},
{
"code": null,
"e": 5681,
"s": 5422,
"text": "NLP’s built-in sentiment analysis did a pretty fine job with a dataset it’s largely not familiar with. At the same time, our Core ML model performed decently with the Natural Language Framework in determining whether the reviewer loved the film or panned it."
},
{
"code": null,
"e": 5828,
"s": 5681,
"text": "So that sums up Core ML and Natural Language Framework. We saw how the built-in sentiment analysis is such a powerful tool in language processing."
},
{
"code": null,
"e": 6083,
"s": 5828,
"text": "The full source code along with the python script for parsing the CSV is available in this Github Repository. Also, it contains models built using max entropy and transfer learning. You can try playing around with them and see which fits the bill better."
}
] |
How to use PowerShell break statement in foreach loop?
|
You can use the PowerShell Break statement with the foreach loop as mentioned below.
foreach($obj in (Get-ChildItem D:\Temp)){
Write-Output $obj
if($obj.Name -eq "cars.xml"){Break}
}
Directory: D:\Temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 13-12-2019 09:52GPO_backup
d----- 24-11-2018 11:31 LGPO
-a---- 27-01-2020 22:21 13962 Alias1
-a---- 26-01-2020 19:20 13818 aliases.txt
-a---- 07-05-2018 23:00301 cars.xml
In the above example, when the file name matches the cars.xml then the loop gets terminated.
|
[
{
"code": null,
"e": 1147,
"s": 1062,
"text": "You can use the PowerShell Break statement with the foreach loop as mentioned below."
},
{
"code": null,
"e": 1251,
"s": 1147,
"text": "foreach($obj in (Get-ChildItem D:\\Temp)){\n Write-Output $obj\n if($obj.Name -eq \"cars.xml\"){Break}\n}"
},
{
"code": null,
"e": 1589,
"s": 1251,
"text": "Directory: D:\\Temp\nMode LastWriteTime Length Name\n---- ------------- ------ ----\nd----- 13-12-2019 09:52GPO_backup\nd----- 24-11-2018 11:31 LGPO\n-a---- 27-01-2020 22:21 13962 Alias1\n-a---- 26-01-2020 19:20 13818 aliases.txt\n-a---- 07-05-2018 23:00301 cars.xml"
},
{
"code": null,
"e": 1682,
"s": 1589,
"text": "In the above example, when the file name matches the cars.xml then the loop gets terminated."
}
] |
Google Maps - Zoom
|
You can increase or decrease the zoom value of a map by modifying the value of the zoom attribute in the the map options.
We can increase or decrease the zoom value of the map using the zoom option. Given below is the syntax to change the zoom value of the current map.
var mapOptions = {
zoom:required zoom value
};
The following code will display the roadmap of the city Vishakhapatnam with a zoom value of 6.
<!DOCTYPE html>
<html>
<head>
<script src = "https://maps.googleapis.com/maps/api/js"></script>
<script>
function loadMap() {
var mapOptions = {
center:new google.maps.LatLng(17.609993, 83.221436),
zoom:6,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("sample"),mapOptions);
}
</script>
</head>
<body onload = "loadMap()">
<div id = "sample" style = "width:587px; height:400px;"></div>
</body>
</html>
It will produce the following output −
The following code will display the roadmap of the city Vishakhapatnam with a zoom value of 10.
<!DOCTYPE html>
<html>
<head>
<script src = "https://maps.googleapis.com/maps/api/js"></script>
<script>
function loadMap() {
var mapOptions = {
center:new google.maps.LatLng(17.609993, 83.221436),
zoom:10,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("sample"),mapOptions);
}
</script>
</head>
<body onload = "loadMap()">
<div id = "sample" style = "width:587px; height:400px;"></div>
</body>
</html>
It will produce the following output −
20 Lectures
2.5 hours
Asif Hussain
7 Lectures
1 hours
Aditya Kulkarni
33 Lectures
2.5 hours
Sasha Miller
22 Lectures
1.5 hours
Zach Miller
16 Lectures
1.5 hours
Sasha Miller
23 Lectures
2.5 hours
Sasha Miller
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1954,
"s": 1832,
"text": "You can increase or decrease the zoom value of a map by modifying the value of the zoom attribute in the the map options."
},
{
"code": null,
"e": 2102,
"s": 1954,
"text": "We can increase or decrease the zoom value of the map using the zoom option. Given below is the syntax to change the zoom value of the current map."
},
{
"code": null,
"e": 2152,
"s": 2102,
"text": "var mapOptions = {\n zoom:required zoom value\n};"
},
{
"code": null,
"e": 2247,
"s": 2152,
"text": "The following code will display the roadmap of the city Vishakhapatnam with a zoom value of 6."
},
{
"code": null,
"e": 2878,
"s": 2247,
"text": "<!DOCTYPE html>\n<html>\n \n <head>\n <script src = \"https://maps.googleapis.com/maps/api/js\"></script>\n \n <script>\n function loadMap() {\n\t\t\t\n var mapOptions = {\n center:new google.maps.LatLng(17.609993, 83.221436),\n zoom:6,\n mapTypeId:google.maps.MapTypeId.ROADMAP\n };\n \n var map = new google.maps.Map(document.getElementById(\"sample\"),mapOptions);\n }\n </script>\n \n </head>\n \n <body onload = \"loadMap()\">\n <div id = \"sample\" style = \"width:587px; height:400px;\"></div>\n </body>\n \n</html>"
},
{
"code": null,
"e": 2917,
"s": 2878,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 3013,
"s": 2917,
"text": "The following code will display the roadmap of the city Vishakhapatnam with a zoom value of 10."
},
{
"code": null,
"e": 3637,
"s": 3013,
"text": "<!DOCTYPE html>\n<html>\n \n <head>\n <script src = \"https://maps.googleapis.com/maps/api/js\"></script>\n \n <script>\n function loadMap() {\n\t\t\t\n var mapOptions = {\n center:new google.maps.LatLng(17.609993, 83.221436),\n zoom:10,\n mapTypeId:google.maps.MapTypeId.ROADMAP\n };\n\t\t\t\t\n var map = new google.maps.Map(document.getElementById(\"sample\"),mapOptions);\n }\n </script>\n \n </head>\n \n <body onload = \"loadMap()\">\n <div id = \"sample\" style = \"width:587px; height:400px;\"></div>\n </body>\n \n</html>"
},
{
"code": null,
"e": 3676,
"s": 3637,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 3711,
"s": 3676,
"text": "\n 20 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3725,
"s": 3711,
"text": " Asif Hussain"
},
{
"code": null,
"e": 3757,
"s": 3725,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3774,
"s": 3757,
"text": " Aditya Kulkarni"
},
{
"code": null,
"e": 3809,
"s": 3774,
"text": "\n 33 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3823,
"s": 3809,
"text": " Sasha Miller"
},
{
"code": null,
"e": 3858,
"s": 3823,
"text": "\n 22 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3871,
"s": 3858,
"text": " Zach Miller"
},
{
"code": null,
"e": 3906,
"s": 3871,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3920,
"s": 3906,
"text": " Sasha Miller"
},
{
"code": null,
"e": 3955,
"s": 3920,
"text": "\n 23 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3969,
"s": 3955,
"text": " Sasha Miller"
},
{
"code": null,
"e": 3976,
"s": 3969,
"text": " Print"
},
{
"code": null,
"e": 3987,
"s": 3976,
"text": " Add Notes"
}
] |
Animate Data Using Python. View Live Data With Just MatPlotLib | by Bruce Ironhardt | Towards Data Science
|
The goal of this guide is to show you how to update a graph in real-time. This can be used for a variety of applications like visualizing live data from sensors or tracking stock prices.
In this tutorial, the data will be static but can easily be used on live data. You’ll, of course, need to have MatPlotlib and Pandas installed on your local machine or virtual environment.
‘FuncAnimation’ is the method that we’ll be using to update the graph continuously giving it that live effect.
We will be using MatPlotLib in this tutorial to generate our graphs and the panda's library to read CSV files.
We’re going to create a subplot to make it easier for us to draw on the same plot over and over again.
The animation(i) method is what we’ll use to draw our line over and over again. This method will be called by the FuncAnimation method from the MatPlotLib library over and over again until you decide to terminate the program.
In this example, I’ll be using a static file pulled off the internet. This file gives us the 2014 stock price for Apple.
Here’s how our dummy data will look:
Now to mimick live data instead of plotting the whole graph in one go, what I’ll instead do is plot each row. This gives us the illusionary live data.
Remember that the animation(i) function will be called every iteration. Each time its called i goes up by one. This line, AAPL_STOCK[0:i]['AAPL_x'] , will return the rows corresponding to the iteration we’re on.
For example, on iteration 1 we will return the just the first row in the dataset. On the nth iteration, we will return the nth row (and all rows before it) in the dataset.
To draw the line to the graph, we just need to call ax.plot(x,y). We also call ax.clear() to clear the line generated before. We do this to not draw lines over each other after each iteration.
You may have noticed that we read the CSV in our loop. The reason we need to do this is that if new data was added to the CSV we could read it and draw it to our graph.
If you were using a text file instead, you could append values to x and y at each iteration. For example:
To run the animation we just need to use the following.
animation = FuncAnimation(fig, func=animation, interval=1000)plt.show()
Here, the `FuncAnimation` will continuously run our animation program. interval is used to determine the delay between updates. Currently, its set to 1000 milliseconds but it can be as fast or as slow as you need it to be.
Here’s all the code:
So, here I just removed some data from the CSV we were working with above.
Then once the graph updated to the end of the dataset I copied in some new data and saved the file. The graph then updated with all the new data that I just added. In this case, it updated pretty quickly but only cause the interval time was set to 100ms.
If you liked this guide you can check out some other cool articles if written below! If you have any questions feel free to leave a comment and I can try and help you out.
|
[
{
"code": null,
"e": 359,
"s": 172,
"text": "The goal of this guide is to show you how to update a graph in real-time. This can be used for a variety of applications like visualizing live data from sensors or tracking stock prices."
},
{
"code": null,
"e": 548,
"s": 359,
"text": "In this tutorial, the data will be static but can easily be used on live data. You’ll, of course, need to have MatPlotlib and Pandas installed on your local machine or virtual environment."
},
{
"code": null,
"e": 659,
"s": 548,
"text": "‘FuncAnimation’ is the method that we’ll be using to update the graph continuously giving it that live effect."
},
{
"code": null,
"e": 770,
"s": 659,
"text": "We will be using MatPlotLib in this tutorial to generate our graphs and the panda's library to read CSV files."
},
{
"code": null,
"e": 873,
"s": 770,
"text": "We’re going to create a subplot to make it easier for us to draw on the same plot over and over again."
},
{
"code": null,
"e": 1099,
"s": 873,
"text": "The animation(i) method is what we’ll use to draw our line over and over again. This method will be called by the FuncAnimation method from the MatPlotLib library over and over again until you decide to terminate the program."
},
{
"code": null,
"e": 1220,
"s": 1099,
"text": "In this example, I’ll be using a static file pulled off the internet. This file gives us the 2014 stock price for Apple."
},
{
"code": null,
"e": 1257,
"s": 1220,
"text": "Here’s how our dummy data will look:"
},
{
"code": null,
"e": 1408,
"s": 1257,
"text": "Now to mimick live data instead of plotting the whole graph in one go, what I’ll instead do is plot each row. This gives us the illusionary live data."
},
{
"code": null,
"e": 1620,
"s": 1408,
"text": "Remember that the animation(i) function will be called every iteration. Each time its called i goes up by one. This line, AAPL_STOCK[0:i]['AAPL_x'] , will return the rows corresponding to the iteration we’re on."
},
{
"code": null,
"e": 1792,
"s": 1620,
"text": "For example, on iteration 1 we will return the just the first row in the dataset. On the nth iteration, we will return the nth row (and all rows before it) in the dataset."
},
{
"code": null,
"e": 1985,
"s": 1792,
"text": "To draw the line to the graph, we just need to call ax.plot(x,y). We also call ax.clear() to clear the line generated before. We do this to not draw lines over each other after each iteration."
},
{
"code": null,
"e": 2154,
"s": 1985,
"text": "You may have noticed that we read the CSV in our loop. The reason we need to do this is that if new data was added to the CSV we could read it and draw it to our graph."
},
{
"code": null,
"e": 2260,
"s": 2154,
"text": "If you were using a text file instead, you could append values to x and y at each iteration. For example:"
},
{
"code": null,
"e": 2316,
"s": 2260,
"text": "To run the animation we just need to use the following."
},
{
"code": null,
"e": 2388,
"s": 2316,
"text": "animation = FuncAnimation(fig, func=animation, interval=1000)plt.show()"
},
{
"code": null,
"e": 2611,
"s": 2388,
"text": "Here, the `FuncAnimation` will continuously run our animation program. interval is used to determine the delay between updates. Currently, its set to 1000 milliseconds but it can be as fast or as slow as you need it to be."
},
{
"code": null,
"e": 2632,
"s": 2611,
"text": "Here’s all the code:"
},
{
"code": null,
"e": 2707,
"s": 2632,
"text": "So, here I just removed some data from the CSV we were working with above."
},
{
"code": null,
"e": 2962,
"s": 2707,
"text": "Then once the graph updated to the end of the dataset I copied in some new data and saved the file. The graph then updated with all the new data that I just added. In this case, it updated pretty quickly but only cause the interval time was set to 100ms."
}
] |
5 types of plots that will help you with time series analysis | by Eryk Lewinson | Towards Data Science
|
While starting any project related to time series (and not only), one of the very first steps is to visualize the data. We do so to inspect the data we are dealing with and learn something about it, for example:
are there any patterns in the data?
are there any unusual observations (outliers)?
do the properties of the series of observations change over time (non-stationarity)?
are there any relationships between the variables?
And that is only the beginning. The characteristics of the data that we learn from answering those questions should be then incorporated into the modeling approach we want to follow. Otherwise, we risk having a poor model that is not able to capture the special traits of the data we have. And as we learned time and time again — garbage in, garbage out.
In this article, I present a few types of plots that are very helpful while working with time series and briefly describe how we can interpret the results.
Traditionally, we need to load all the required Python libraries. We do that in the following snippet.
In this article, we will take a look at the famous Airline Passengers dataset, which you probably have already seen a few times in other articles or statistical handbooks/classes. It’s very popular due to the simplicity of the observable patterns in it. That is also why it will serve its purpose well to illustrate different types of plots used for time series analysis.
The dataset is also included in one of the plotting libraries we will use today — seaborn. We load the data by running the following lines. Additionally, we combine the year and month column to create a report_date field, which is a datatime.date object.
Having prepared the data, we will take a look at different types of plots used for time series analysis.
A time plot is basically a line plot showing the evolution of the time series over time. We can use it as the starting point of the analysis to get some basic understanding of the data, for example, in terms of trend/seasonality/outliers, etc.
The easiest approach is to directly use the plot method of a pd.DataFrame.
In the plot, we can observe an increasing trend over the years and clear seasonality in the form of the spikes during the summer months caused by vacation time.
The code could be further simplified by specifying the index of the DataFrame — then there is no need to specify the x axis. TIP: You can also change the default (matplotlib) backend of the plot method by running the following line:
pd.options.plotting.backend = "plotly"
By doing so, you will generate the exact same plot as the one above, however, it will use plotly to make the plot interactive. Definitely helpful when you want to inspect particular observations or when you want to zoom in on a certain time period.
For completeness’ sake, you can also easily use seaborn to generate the time plot:
In the past, there was a dedicated sns.tsplot function, however, it was deprecated in favor of the lineplot.
A seasonal plot is very similar to the time plot, with the exception that the data is plotted against the individual seasons. Choosing the definition of the season is up to the analyst and in our particular case, the season is simply the month. We can generate the seasonal plot by running the following code.
We can see that instead of plotting all 11 years as a one long series, we plot the same data per month. By doing so, we can clearly see the following:
the previously mentioned seasonal patterns with the spikes in summer months,
the trend, as the number of passengers is increasing yearly.
Additionally, a seasonal plot is especially useful for identifying the years in which the patterns change.
Alternatively, we can use a handy function from the statsmodels library to create a month_plot.
The information conveyed on this plot is very similar to the previous one, just the grouping is different. Aside from patterns over the years, we can also conveniently see the average values per month.
Lastly, we can also come up with a very similar plot, but this time per quarter. We only need to resample the data to quarterly frequency first and then use the quarter_plot function.
This is a variation of the seasonal plot, with the difference that it uses polar coordinates. Personally, I prefer the traditional seasonal plot, however, I am sure it is also useful for some specific cases.
The very same plot could have been generated using matplotlib + seaborn, however, I try to follow the pragmatist approach. If it is possible to generate the plot much faster with a dedicated and well-established library such as plotly (or plotly_express), then I am strongly in favor of such a solution. And as an extra bonus we do get the interactivity for free!
Before actually showing the plot, I believe it makes sense to give a brief introduction to time series decomposition. In general, it provides a useful model for thinking about time series and facilitates a better understanding of the data. Decomposition assumes that a time series can be broken down into a combination of the following components:
level — the average value of the series,
trend — an increasing/decreasing pattern in the series,
seasonality — a repeating short-term cycle in the series,
noise — the random, unexplainable variation.
Where all time series have the level and noise components, while the trend and seasonality are optional.
What is left to add is that there are two main types of decomposition models:
additive — it assumes that the components above are added together (linear model). The changes over time are more or less constant.
multiplicative — it assumes that the components are multiplied by each other. Hence, the changes over time are non-linear and not constant, so they can increase/decrease with time. An example could be exponential growth.
With that much introduction, we can try an automatic decomposition approach. To do so, we use the seasonal_decompose function from the statsmodels library. For our case, when looking at the time plot we can see that there is monthly seasonality (12 periods, but that can be determined automatically given there is a timestamp index in the DataFrame) and the changes over time are not constant (increasing), so we will go with the multiplicative model.
In the plot we see the actual series in the first part, then the trend component, the seasonal one, and lastly the residuals (error term). The residuals close to 1 in the multiplicative model suggest a good fit. Bear in mind that they should be close to 0 for the additive one.
As always with automatic approaches, we should do a simple sanity check and do not trust the results blindly. For this simple example, we can see the confirmation of what we initially suspected about the time series.
When measuring the correlation between the time series and its lagged values (from previous points in time) we are talking about autocorrelation. There are two types of autocorrelation plots we can use.
The autocorrelation function (ACF) shows the value of the correlation coefficient between the series and its lagged values. The ACF considers all of the components of the time series (mentioned in the decomposition part) while finding the correlations. That is why it’s known as the complete auto-correlation plot.
In contrast, the partial autocorrelation function (PACF) looks at the correlation between the residuals (the remainder after removing the effects explained by the previous lags) and the following lag value. This way, we effectively remove the already found variations before we find the next correlation. In practice, a high partial correlation indicates that there is some information in the residual that can be modeled by the next lag. So we might consider keeping that lag as a feature in our model.
We plot both ACF and PACF using the following snippet.
In the ACF plot, we can see that there are significant autocorrelations (above the 95% confidence interval, corresponding to the default 5% significance level). There are also some significant autocorrelations in the PACF plot.
Normally, the autocorrelations plots are often used for determining the stationarity of the time series or choosing the hyperparameters of the ARIMA class models, but these are topics for another article.
In this article, I showed 5 types of plots that will most likely come in handy while working with time series. The list is by no means exhaustive and often the choice of plots depends on the problem we are working on. For example, for stock price data we might want to visualize the candlestick chart instead of the regular time plot.
You can find the code used for this article on my GitHub. As always, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments.
In early 2020 I published a book on using Python for solving practical tasks in the financial domain. If you are interested, I posted an article introducing the contents of the book. You can get the book on Amazon or Packt’s website.
Hyndman, R.J., & Athanasopoulos, G. (2018) Forecasting: principles and practice, 2nd edition, OTexts: Melbourne, Australia. OTexts.com/fpp2.
|
[
{
"code": null,
"e": 384,
"s": 172,
"text": "While starting any project related to time series (and not only), one of the very first steps is to visualize the data. We do so to inspect the data we are dealing with and learn something about it, for example:"
},
{
"code": null,
"e": 420,
"s": 384,
"text": "are there any patterns in the data?"
},
{
"code": null,
"e": 467,
"s": 420,
"text": "are there any unusual observations (outliers)?"
},
{
"code": null,
"e": 552,
"s": 467,
"text": "do the properties of the series of observations change over time (non-stationarity)?"
},
{
"code": null,
"e": 603,
"s": 552,
"text": "are there any relationships between the variables?"
},
{
"code": null,
"e": 958,
"s": 603,
"text": "And that is only the beginning. The characteristics of the data that we learn from answering those questions should be then incorporated into the modeling approach we want to follow. Otherwise, we risk having a poor model that is not able to capture the special traits of the data we have. And as we learned time and time again — garbage in, garbage out."
},
{
"code": null,
"e": 1114,
"s": 958,
"text": "In this article, I present a few types of plots that are very helpful while working with time series and briefly describe how we can interpret the results."
},
{
"code": null,
"e": 1217,
"s": 1114,
"text": "Traditionally, we need to load all the required Python libraries. We do that in the following snippet."
},
{
"code": null,
"e": 1589,
"s": 1217,
"text": "In this article, we will take a look at the famous Airline Passengers dataset, which you probably have already seen a few times in other articles or statistical handbooks/classes. It’s very popular due to the simplicity of the observable patterns in it. That is also why it will serve its purpose well to illustrate different types of plots used for time series analysis."
},
{
"code": null,
"e": 1844,
"s": 1589,
"text": "The dataset is also included in one of the plotting libraries we will use today — seaborn. We load the data by running the following lines. Additionally, we combine the year and month column to create a report_date field, which is a datatime.date object."
},
{
"code": null,
"e": 1949,
"s": 1844,
"text": "Having prepared the data, we will take a look at different types of plots used for time series analysis."
},
{
"code": null,
"e": 2193,
"s": 1949,
"text": "A time plot is basically a line plot showing the evolution of the time series over time. We can use it as the starting point of the analysis to get some basic understanding of the data, for example, in terms of trend/seasonality/outliers, etc."
},
{
"code": null,
"e": 2268,
"s": 2193,
"text": "The easiest approach is to directly use the plot method of a pd.DataFrame."
},
{
"code": null,
"e": 2429,
"s": 2268,
"text": "In the plot, we can observe an increasing trend over the years and clear seasonality in the form of the spikes during the summer months caused by vacation time."
},
{
"code": null,
"e": 2662,
"s": 2429,
"text": "The code could be further simplified by specifying the index of the DataFrame — then there is no need to specify the x axis. TIP: You can also change the default (matplotlib) backend of the plot method by running the following line:"
},
{
"code": null,
"e": 2701,
"s": 2662,
"text": "pd.options.plotting.backend = \"plotly\""
},
{
"code": null,
"e": 2950,
"s": 2701,
"text": "By doing so, you will generate the exact same plot as the one above, however, it will use plotly to make the plot interactive. Definitely helpful when you want to inspect particular observations or when you want to zoom in on a certain time period."
},
{
"code": null,
"e": 3033,
"s": 2950,
"text": "For completeness’ sake, you can also easily use seaborn to generate the time plot:"
},
{
"code": null,
"e": 3142,
"s": 3033,
"text": "In the past, there was a dedicated sns.tsplot function, however, it was deprecated in favor of the lineplot."
},
{
"code": null,
"e": 3452,
"s": 3142,
"text": "A seasonal plot is very similar to the time plot, with the exception that the data is plotted against the individual seasons. Choosing the definition of the season is up to the analyst and in our particular case, the season is simply the month. We can generate the seasonal plot by running the following code."
},
{
"code": null,
"e": 3603,
"s": 3452,
"text": "We can see that instead of plotting all 11 years as a one long series, we plot the same data per month. By doing so, we can clearly see the following:"
},
{
"code": null,
"e": 3680,
"s": 3603,
"text": "the previously mentioned seasonal patterns with the spikes in summer months,"
},
{
"code": null,
"e": 3741,
"s": 3680,
"text": "the trend, as the number of passengers is increasing yearly."
},
{
"code": null,
"e": 3848,
"s": 3741,
"text": "Additionally, a seasonal plot is especially useful for identifying the years in which the patterns change."
},
{
"code": null,
"e": 3944,
"s": 3848,
"text": "Alternatively, we can use a handy function from the statsmodels library to create a month_plot."
},
{
"code": null,
"e": 4146,
"s": 3944,
"text": "The information conveyed on this plot is very similar to the previous one, just the grouping is different. Aside from patterns over the years, we can also conveniently see the average values per month."
},
{
"code": null,
"e": 4330,
"s": 4146,
"text": "Lastly, we can also come up with a very similar plot, but this time per quarter. We only need to resample the data to quarterly frequency first and then use the quarter_plot function."
},
{
"code": null,
"e": 4538,
"s": 4330,
"text": "This is a variation of the seasonal plot, with the difference that it uses polar coordinates. Personally, I prefer the traditional seasonal plot, however, I am sure it is also useful for some specific cases."
},
{
"code": null,
"e": 4902,
"s": 4538,
"text": "The very same plot could have been generated using matplotlib + seaborn, however, I try to follow the pragmatist approach. If it is possible to generate the plot much faster with a dedicated and well-established library such as plotly (or plotly_express), then I am strongly in favor of such a solution. And as an extra bonus we do get the interactivity for free!"
},
{
"code": null,
"e": 5250,
"s": 4902,
"text": "Before actually showing the plot, I believe it makes sense to give a brief introduction to time series decomposition. In general, it provides a useful model for thinking about time series and facilitates a better understanding of the data. Decomposition assumes that a time series can be broken down into a combination of the following components:"
},
{
"code": null,
"e": 5291,
"s": 5250,
"text": "level — the average value of the series,"
},
{
"code": null,
"e": 5347,
"s": 5291,
"text": "trend — an increasing/decreasing pattern in the series,"
},
{
"code": null,
"e": 5405,
"s": 5347,
"text": "seasonality — a repeating short-term cycle in the series,"
},
{
"code": null,
"e": 5450,
"s": 5405,
"text": "noise — the random, unexplainable variation."
},
{
"code": null,
"e": 5555,
"s": 5450,
"text": "Where all time series have the level and noise components, while the trend and seasonality are optional."
},
{
"code": null,
"e": 5633,
"s": 5555,
"text": "What is left to add is that there are two main types of decomposition models:"
},
{
"code": null,
"e": 5765,
"s": 5633,
"text": "additive — it assumes that the components above are added together (linear model). The changes over time are more or less constant."
},
{
"code": null,
"e": 5986,
"s": 5765,
"text": "multiplicative — it assumes that the components are multiplied by each other. Hence, the changes over time are non-linear and not constant, so they can increase/decrease with time. An example could be exponential growth."
},
{
"code": null,
"e": 6438,
"s": 5986,
"text": "With that much introduction, we can try an automatic decomposition approach. To do so, we use the seasonal_decompose function from the statsmodels library. For our case, when looking at the time plot we can see that there is monthly seasonality (12 periods, but that can be determined automatically given there is a timestamp index in the DataFrame) and the changes over time are not constant (increasing), so we will go with the multiplicative model."
},
{
"code": null,
"e": 6716,
"s": 6438,
"text": "In the plot we see the actual series in the first part, then the trend component, the seasonal one, and lastly the residuals (error term). The residuals close to 1 in the multiplicative model suggest a good fit. Bear in mind that they should be close to 0 for the additive one."
},
{
"code": null,
"e": 6933,
"s": 6716,
"text": "As always with automatic approaches, we should do a simple sanity check and do not trust the results blindly. For this simple example, we can see the confirmation of what we initially suspected about the time series."
},
{
"code": null,
"e": 7136,
"s": 6933,
"text": "When measuring the correlation between the time series and its lagged values (from previous points in time) we are talking about autocorrelation. There are two types of autocorrelation plots we can use."
},
{
"code": null,
"e": 7451,
"s": 7136,
"text": "The autocorrelation function (ACF) shows the value of the correlation coefficient between the series and its lagged values. The ACF considers all of the components of the time series (mentioned in the decomposition part) while finding the correlations. That is why it’s known as the complete auto-correlation plot."
},
{
"code": null,
"e": 7955,
"s": 7451,
"text": "In contrast, the partial autocorrelation function (PACF) looks at the correlation between the residuals (the remainder after removing the effects explained by the previous lags) and the following lag value. This way, we effectively remove the already found variations before we find the next correlation. In practice, a high partial correlation indicates that there is some information in the residual that can be modeled by the next lag. So we might consider keeping that lag as a feature in our model."
},
{
"code": null,
"e": 8010,
"s": 7955,
"text": "We plot both ACF and PACF using the following snippet."
},
{
"code": null,
"e": 8238,
"s": 8010,
"text": "In the ACF plot, we can see that there are significant autocorrelations (above the 95% confidence interval, corresponding to the default 5% significance level). There are also some significant autocorrelations in the PACF plot."
},
{
"code": null,
"e": 8443,
"s": 8238,
"text": "Normally, the autocorrelations plots are often used for determining the stationarity of the time series or choosing the hyperparameters of the ARIMA class models, but these are topics for another article."
},
{
"code": null,
"e": 8778,
"s": 8443,
"text": "In this article, I showed 5 types of plots that will most likely come in handy while working with time series. The list is by no means exhaustive and often the choice of plots depends on the problem we are working on. For example, for stock price data we might want to visualize the candlestick chart instead of the regular time plot."
},
{
"code": null,
"e": 8940,
"s": 8778,
"text": "You can find the code used for this article on my GitHub. As always, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments."
},
{
"code": null,
"e": 9174,
"s": 8940,
"text": "In early 2020 I published a book on using Python for solving practical tasks in the financial domain. If you are interested, I posted an article introducing the contents of the book. You can get the book on Amazon or Packt’s website."
}
] |
12 Tips to Write Efficient SQL Queries - GeeksforGeeks
|
29 Jun, 2021
We all know the importance of a database in any application. This is the place where a users’ information gets stored and retrieved as per the requirements. SQL is the most popular query language which allows you to store and retrieve data from the database and perform operations. The performance of the database matters a lot when it comes to choose a database and write the queries for a specific task/operation.
In development, writing the queries is not just important. It is also important to write efficient SQL queries. Efficient queries give faster results. When the SQL queries are optimized your application’s faster performance saves a lot of time. It becomes convenient for both database administrators and for SQL developers as well. You should have a fast SQL server to achieve fast, efficient, and credible database queries.
In this blog, we are going to discuss some rules that will help you to make your SQL faster and efficient.
1. Create Small Batches of Data for Deletion and Updation
Instead of deleting and updating data in bulk create small batches of them. In case if there will be a rollback, you will avoid losing or killing your data. It also enhances concurrency, because the data you except the part you’re deleting or updating continue doing other work.
2. Use CASE instead of UPDATE
While writing SQL queries UPDATE statement writes longer to a table in comparison to the CASE statement, because of its logging. Inline CASE statement chooses what is preferred before writing it on the table, which eventually increases the speed.
3. Use Temp Tables
Temporary tables are used in many situations, such as joining a small table to a larger one. You can improve data performance by extracting data from the large table, and then transferring it to a temp table then join with that. This reduces the power required in processing.
4. Avoid Using Another Developer’s Code
When you use someone else code, there will be a high chance of pulling more data than you need. Cutting down this data may be hard for you but if you trim this code as per your need, you won’t end up with huge data clusters.
5. Avoid Negative Searches
Negative searches slow down your DB performance a lot. To avoid this, you can re-write the queries with better indexes, especially when you’re dealing with large amounts of data.
6. Use The Exact Number of Columns
While writing the select statement, make sure that you’re writing the correct number of columns against as many rows as you want. This will make your query faster, and you will speed your processes.
7. No Need to Count Everything in the Table
To check the existence of some data, you need to carry out an action. People often try this:
SET @CT = (SELECT COUNT (*) FROM dbo.T1);If @CT > 0BEGIN <Do something>END
Writing the above statement is unnecessary and it just wastes a lot of time. Instead of the above statement, you can write the statement given below...
If EXISTS (SELECT 1 FROM dbo.T1)BEGIN<Do something>END
From the above method, you can avoid counting every item on the table. When you use EXIST, the SQL server recognizes it and gives faster results.
8. Avoid Using Globally Unique Identifiers
For ordering the table data, avoid using GUIDs as much as you can. GUID’s can easily fast break off your table. You can use IDENTITY or DATE for dramatic breakoff that takes only a couple of minutes.
9. Avoid Using Triggers
Triggers are not important to use in SQL queries. Whatever you plan to do with your data, go through the same transactions as the previous operations. Using triggers results in lock many tables until the trigger completes the cycle. You can split the data into several transactions to lock up certain resources. This will help you in making your transaction faster.
10. Avoid Using ORM
Using ORM (Object Relational Mapper) will give you the worst code in the world of technology. You will come across a bad performance in your daily encounters. If you are unable to avoid them completely, minimize them by writing stored procedures, that are completely your own, and have ORM use yours instead of those it creates.
11. Avoid Using Distinct Keyword
You should always try to avoid using the DISTINCT keyword. Using this keyword requires an extra operation. This will slow down all the queries and makes it almost impossible to get what you need.
12. Use Fewer Cursors
Cursors generate many problems, especially on speed. Also, they are the reasons for blockages as well. One operation can block the other operations. This may affect your system concurrency, slowing everything down.
Conclusion
We have discussed mainly twelve tips for writing efficient SQL queries. It’s not limited here. You can use stored procedures for better efficiency. Also, you can separate large and small transactions. Count your rows using the system table and reduce the nested views to reduce lags. These tips are quite helpful in improving the performance of your SQL server.
As you will progress in writing more database queries, you will learn how things or queries can be optimized more. Seeing the other developers’ code also helps in writing efficient queries. Hope all these tips are helpful in writing better SQL queries.
GBlog
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Roadmap to Become a Web Developer in 2022
DSA Sheet by Love Babbar
Top 10 Angular Libraries For Web Developers
A Freshers Guide To Programming
ML | Underfitting and Overfitting
SQL | DDL, DQL, DML, DCL and TCL Commands
SQL | Join (Inner, Left, Right and Full Joins)
How to find Nth highest salary from a table
SQL | WITH clause
SQL | ALTER (RENAME)
|
[
{
"code": null,
"e": 24930,
"s": 24902,
"text": "\n29 Jun, 2021"
},
{
"code": null,
"e": 25347,
"s": 24930,
"text": "We all know the importance of a database in any application. This is the place where a users’ information gets stored and retrieved as per the requirements. SQL is the most popular query language which allows you to store and retrieve data from the database and perform operations. The performance of the database matters a lot when it comes to choose a database and write the queries for a specific task/operation. "
},
{
"code": null,
"e": 25773,
"s": 25347,
"text": "In development, writing the queries is not just important. It is also important to write efficient SQL queries. Efficient queries give faster results. When the SQL queries are optimized your application’s faster performance saves a lot of time. It becomes convenient for both database administrators and for SQL developers as well. You should have a fast SQL server to achieve fast, efficient, and credible database queries. "
},
{
"code": null,
"e": 25881,
"s": 25773,
"text": "In this blog, we are going to discuss some rules that will help you to make your SQL faster and efficient. "
},
{
"code": null,
"e": 25939,
"s": 25881,
"text": "1. Create Small Batches of Data for Deletion and Updation"
},
{
"code": null,
"e": 26219,
"s": 25939,
"text": "Instead of deleting and updating data in bulk create small batches of them. In case if there will be a rollback, you will avoid losing or killing your data. It also enhances concurrency, because the data you except the part you’re deleting or updating continue doing other work. "
},
{
"code": null,
"e": 26249,
"s": 26219,
"text": "2. Use CASE instead of UPDATE"
},
{
"code": null,
"e": 26497,
"s": 26249,
"text": "While writing SQL queries UPDATE statement writes longer to a table in comparison to the CASE statement, because of its logging. Inline CASE statement chooses what is preferred before writing it on the table, which eventually increases the speed. "
},
{
"code": null,
"e": 26516,
"s": 26497,
"text": "3. Use Temp Tables"
},
{
"code": null,
"e": 26793,
"s": 26516,
"text": "Temporary tables are used in many situations, such as joining a small table to a larger one. You can improve data performance by extracting data from the large table, and then transferring it to a temp table then join with that. This reduces the power required in processing. "
},
{
"code": null,
"e": 26833,
"s": 26793,
"text": "4. Avoid Using Another Developer’s Code"
},
{
"code": null,
"e": 27059,
"s": 26833,
"text": "When you use someone else code, there will be a high chance of pulling more data than you need. Cutting down this data may be hard for you but if you trim this code as per your need, you won’t end up with huge data clusters. "
},
{
"code": null,
"e": 27086,
"s": 27059,
"text": "5. Avoid Negative Searches"
},
{
"code": null,
"e": 27265,
"s": 27086,
"text": "Negative searches slow down your DB performance a lot. To avoid this, you can re-write the queries with better indexes, especially when you’re dealing with large amounts of data."
},
{
"code": null,
"e": 27300,
"s": 27265,
"text": "6. Use The Exact Number of Columns"
},
{
"code": null,
"e": 27500,
"s": 27300,
"text": "While writing the select statement, make sure that you’re writing the correct number of columns against as many rows as you want. This will make your query faster, and you will speed your processes. "
},
{
"code": null,
"e": 27544,
"s": 27500,
"text": "7. No Need to Count Everything in the Table"
},
{
"code": null,
"e": 27637,
"s": 27544,
"text": "To check the existence of some data, you need to carry out an action. People often try this:"
},
{
"code": null,
"e": 27712,
"s": 27637,
"text": "SET @CT = (SELECT COUNT (*) FROM dbo.T1);If @CT > 0BEGIN <Do something>END"
},
{
"code": null,
"e": 27864,
"s": 27712,
"text": "Writing the above statement is unnecessary and it just wastes a lot of time. Instead of the above statement, you can write the statement given below..."
},
{
"code": null,
"e": 27919,
"s": 27864,
"text": "If EXISTS (SELECT 1 FROM dbo.T1)BEGIN<Do something>END"
},
{
"code": null,
"e": 28066,
"s": 27919,
"text": "From the above method, you can avoid counting every item on the table. When you use EXIST, the SQL server recognizes it and gives faster results. "
},
{
"code": null,
"e": 28109,
"s": 28066,
"text": "8. Avoid Using Globally Unique Identifiers"
},
{
"code": null,
"e": 28309,
"s": 28109,
"text": "For ordering the table data, avoid using GUIDs as much as you can. GUID’s can easily fast break off your table. You can use IDENTITY or DATE for dramatic breakoff that takes only a couple of minutes."
},
{
"code": null,
"e": 28333,
"s": 28309,
"text": "9. Avoid Using Triggers"
},
{
"code": null,
"e": 28700,
"s": 28333,
"text": "Triggers are not important to use in SQL queries. Whatever you plan to do with your data, go through the same transactions as the previous operations. Using triggers results in lock many tables until the trigger completes the cycle. You can split the data into several transactions to lock up certain resources. This will help you in making your transaction faster. "
},
{
"code": null,
"e": 28720,
"s": 28700,
"text": "10. Avoid Using ORM"
},
{
"code": null,
"e": 29051,
"s": 28720,
"text": "Using ORM (Object Relational Mapper) will give you the worst code in the world of technology. You will come across a bad performance in your daily encounters. If you are unable to avoid them completely, minimize them by writing stored procedures, that are completely your own, and have ORM use yours instead of those it creates. "
},
{
"code": null,
"e": 29084,
"s": 29051,
"text": "11. Avoid Using Distinct Keyword"
},
{
"code": null,
"e": 29281,
"s": 29084,
"text": "You should always try to avoid using the DISTINCT keyword. Using this keyword requires an extra operation. This will slow down all the queries and makes it almost impossible to get what you need. "
},
{
"code": null,
"e": 29303,
"s": 29281,
"text": "12. Use Fewer Cursors"
},
{
"code": null,
"e": 29519,
"s": 29303,
"text": "Cursors generate many problems, especially on speed. Also, they are the reasons for blockages as well. One operation can block the other operations. This may affect your system concurrency, slowing everything down. "
},
{
"code": null,
"e": 29530,
"s": 29519,
"text": "Conclusion"
},
{
"code": null,
"e": 29893,
"s": 29530,
"text": "We have discussed mainly twelve tips for writing efficient SQL queries. It’s not limited here. You can use stored procedures for better efficiency. Also, you can separate large and small transactions. Count your rows using the system table and reduce the nested views to reduce lags. These tips are quite helpful in improving the performance of your SQL server. "
},
{
"code": null,
"e": 30147,
"s": 29893,
"text": "As you will progress in writing more database queries, you will learn how things or queries can be optimized more. Seeing the other developers’ code also helps in writing efficient queries. Hope all these tips are helpful in writing better SQL queries. "
},
{
"code": null,
"e": 30153,
"s": 30147,
"text": "GBlog"
},
{
"code": null,
"e": 30157,
"s": 30153,
"text": "SQL"
},
{
"code": null,
"e": 30161,
"s": 30157,
"text": "SQL"
},
{
"code": null,
"e": 30259,
"s": 30161,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30268,
"s": 30259,
"text": "Comments"
},
{
"code": null,
"e": 30281,
"s": 30268,
"text": "Old Comments"
},
{
"code": null,
"e": 30323,
"s": 30281,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 30348,
"s": 30323,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 30392,
"s": 30348,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 30424,
"s": 30392,
"text": "A Freshers Guide To Programming"
},
{
"code": null,
"e": 30458,
"s": 30424,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 30500,
"s": 30458,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 30547,
"s": 30500,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 30591,
"s": 30547,
"text": "How to find Nth highest salary from a table"
},
{
"code": null,
"e": 30609,
"s": 30591,
"text": "SQL | WITH clause"
}
] |
Random Forests and One-Hot Encoding Introduction | by Ali Fakhry | Towards Data Science
|
Kaggle’s Titanic Machine Learning Dataset––a classic open-source introduction to the realm of machine learning. While this may be a beginner project, there is still a leaderboard (it is captivating to see yourself rank up as you continue to work on your code).
To start, it is required that you download the “train.csv” and “test.csv” files directly from Kaggle. This can be downloaded here: https://www.kaggle.com/c/titanic/data. Make sure to make sure that the files have been placed in a designated spot that can be pulled later.
In this competition, a large train dataset describes various characteristics of those whose lives were cut short due to the Titanic’s fatal crash and how they related to survival. This includes categorical data such as sex, where they embarked, and their respective names. Yet, there is also numerical data such as age and fare. We have to use a one-hot encoding algorithm to make the overall program and prediction more sufficient for categorical data.
The software that I will be using in the project will be Google Colab. However, this does not really matter in this situation. We do not need a GPU. Using Jupyter Notebooks without a GPU will work just fine. The first thing to do in this project, similar to many others in computer science and machine learning, is to program the imports we need to pull.
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier
Pandas will be used to parse files for this task. The second import, “train_test_split,” will be used to split and separate training and testing files. The last import we need will be RandomForestClassifier, the large overarching import required to use Random Forests.
As I have said, I am using Google Colab. So, I need to “mount” the program onto Google Colab to access Google Drive. I will do this with the following code.
from google.colab import drive drive.mount('/content/gdrive')
Now, we have to take in the .csv files appropriately. This can be done with the following code.
train_df = pd.read_csv('/content/gdrive/My Drive/train.csv') test_df = pd.read_csv('/content/gdrive/My Drive/test.csv')
Next, I am going to drop a variety of categorical information. This includes the tickets, cabins, and names. The names have been removed as they generally would not relate to a correlation between survival or not. Yet, if this was going to be an extensively in-depth analysis, some names may have been more “important.” For instance, based on last name or prefix. For the most part, however, it would be too much work for nothing. Additionally, the ticket and cabin information lacked competition, so it was best to disregard these entire datasets.
This can be completed with the following code.
train_df = train_df.drop(['Name'], axis=1) test_df = test_df.drop(['Name'], axis=1) train_df = train_df.drop(['Cabin'], axis=1) test_df = test_df.drop(['Cabin'], axis=1)train_df = train_df.drop(['Ticket'], axis=1) test_df = test_df.drop(['Ticket'], axis=1)
To see how the data looks like now, it may be beneficial to print out the train data collection. To do so, type the following.
train_df
The same can be done for the test data.
test_df
Next, we should consider the “embarked” category in the dataset. Similar to the ticket and cabin dataset, values are missing. However, there are not as many significant gaps. The most common embarked value is “S,” so for the few missing values, those will just be filled in with “S.” This is not precise or perfect, but every value must be filled in.
common_value = 'S' data = [train_df, test_df] for dataset in data: dataset['Embarked'] = dataset['Embarked'].fillna(common_value)
Now, we have to use one-hot encoding to organize the categorical data. This will be applied to the two categorical data sets remaining, which are “sex” and “embark.” This will be applied to both the “train” and “test” datasets.
def clean_sex(train_df): try: return train_df[0] except TypeError: return "None"train_df["Sex"] = train_df.Sex.apply(clean_sex) categorical_variables = ['Sex', 'Embarked'] for variable in categorical_variables: train_df[variable].fillna("Missing", inplace=True) discarded = pd.get_dummies(train_df[variable],prefix = variable) train_df= pd.concat([train_df, discarded], axis = 1) train_df.drop([variable], axis = 1, inplace = True)
The above was applied for the “train” data. Now, we have to do the same for the “test” dataset.
def clean_sex(test_df):try: return test_df[0] except TypeError: return "None"test_df["Sex"] = test_df.Sex.apply(clean_sex) categorical_variables = ['Sex', 'Embarked']for variable in categorical_variables: test_df[variable].fillna("Missing", inplace=True) discarded = pd.get_dummies(test_df[variable], prefix = variable) test_df= pd.concat([test_df, discarded], axis = 1) test_df.drop([variable], axis = 1, inplace = True)
After organizing the categorical data, we should now consider the numerical data. For the “age” and “fare” data, there are spots in which there are missing values that are not being considered. Rather than completely ignoring these datasets, we need to find a way to implement a data value. To do so, we will take the average of “age” and “fare” and use these for values we do not have. We will have to do this for both the “train” and “test” data.
train_df["Age"].fillna (train_df.Age.mean(), inplace = True)test_df["Age"].fillna (test_df.Age.mean(), inplace = True)train_df["Fare"].fillna (train_df.Fare.mean(), inplace = True)test_df["Fare"].fillna (test_df.Fare.mean(), inplace = True)
We should now look at our data again to double-check that all the appropriate applications have been made.
This will print the “train” manipulated data.
train_df
This will print the “test” manipulated data.
test_df
Now, because age is usually represented as an integer, it would be best to convert them into integer-based descriptions. We again need to do this for both the “train” and “test” datasets.
train_df = train_df.round({'Age':0})test_df = test_df.round({'Age':0})
At this point, we have manipulated our data at a “decent level.” While not fully precise, it is at a point in which we can start to use a random forest algorithm to start formulating predictions.
So, for our local estimation, we will drop the “survived” value on the train data for a new variable called “X_train.” Then, for “Y_train,” we will include just “Survived.” Then, we will make the X_test equal to “test_df” directly. Lastly, print out the shape.
X_train = train_df.drop("Survived", axis=1) Y_train = train_df["Survived"] X_test = test_df X_train.shape, Y_train.shape, X_test.shape
To double-check, it may be useful to print out “x_train.” Again, this can be done simply with the following command.
X_train
Next, we should initialize our random forest. We should also use a variety of parameters to better our algorithm.
random_forest = RandomForestClassifier(criterion='gini', n_estimators=700, min_samples_split=10, min_samples_leaf=1, max_features='auto', oob_score=True, random_state=1, n_jobs=-1) random_forest.fit(X_train, Y_train)Y_pred = random_forest.predict(X_test) acc_random_forest = round(random_forest.score(X_train, Y_train) * 100, 2) acc_random_forest
The “n_estimators” value represents the number of estimators used in the random forest (the number of trees in the forest). In this case, 700 was a value that worked well. “Min_samples_split” is the number of samples (minimum) required to separate and split the internal node. “Min_samples_leaf” represents the minimum number of samples required to be a leaf node. “Max_features” is used to describe the size of random subsets of features considered when splitting a node. When set to auto, there is no feature subset. The “oob_score,” when set to true, will attempt to validate the random forest model with an “Out of Bag” score. When “n_jobs” is set to -1, all the processors will be used to run.
The last segment of the code above fits the model and produces a prediction (y_pred) that works alongside the X_test data. The accuracy of the random forest will then be printed out. Locally testing this data produces an accuracy of approximately 90% (91.81%). However, this is just a local prediction based on separating the survival values from the training dataset. For an accurate estimate, we need to submit it directly to Kaggle. To do so, write the following code to get the “submission.csv” file.
submission = pd.DataFrame({ "PassengerId": test_df["PassengerId"], "Survived": Y_pred})submission.to_csv('submission.csv', index=False)
Conclusion:
Kaggle produces an accuracy value of “0.79186” or “79.186%.” When I submitted using this prediction, I was ranked at 1573 out of 19649, which is approximately the top 8%. The difference between the local prediction and the Kaggle prediction is that the “train” data was modified as a “test hybrid” dataset, and Kaggle used the actual “test data.” Yet, in both situations, there was a level of randomization.
Overall, using random forests seemed to produce a decent result. For the most part, the predictions were accurate. Yet, data was thrown out for simplicity, which definitely harmed the overall strength of this prediction. Additionally, while random forests are suitable for low-level estimations, using other algorithms would produce more solidified and accurate results and would typically correlate with a higher training time.
|
[
{
"code": null,
"e": 433,
"s": 172,
"text": "Kaggle’s Titanic Machine Learning Dataset––a classic open-source introduction to the realm of machine learning. While this may be a beginner project, there is still a leaderboard (it is captivating to see yourself rank up as you continue to work on your code)."
},
{
"code": null,
"e": 705,
"s": 433,
"text": "To start, it is required that you download the “train.csv” and “test.csv” files directly from Kaggle. This can be downloaded here: https://www.kaggle.com/c/titanic/data. Make sure to make sure that the files have been placed in a designated spot that can be pulled later."
},
{
"code": null,
"e": 1159,
"s": 705,
"text": "In this competition, a large train dataset describes various characteristics of those whose lives were cut short due to the Titanic’s fatal crash and how they related to survival. This includes categorical data such as sex, where they embarked, and their respective names. Yet, there is also numerical data such as age and fare. We have to use a one-hot encoding algorithm to make the overall program and prediction more sufficient for categorical data."
},
{
"code": null,
"e": 1514,
"s": 1159,
"text": "The software that I will be using in the project will be Google Colab. However, this does not really matter in this situation. We do not need a GPU. Using Jupyter Notebooks without a GPU will work just fine. The first thing to do in this project, similar to many others in computer science and machine learning, is to program the imports we need to pull."
},
{
"code": null,
"e": 1640,
"s": 1514,
"text": "import pandas as pd from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier "
},
{
"code": null,
"e": 1909,
"s": 1640,
"text": "Pandas will be used to parse files for this task. The second import, “train_test_split,” will be used to split and separate training and testing files. The last import we need will be RandomForestClassifier, the large overarching import required to use Random Forests."
},
{
"code": null,
"e": 2066,
"s": 1909,
"text": "As I have said, I am using Google Colab. So, I need to “mount” the program onto Google Colab to access Google Drive. I will do this with the following code."
},
{
"code": null,
"e": 2128,
"s": 2066,
"text": "from google.colab import drive drive.mount('/content/gdrive')"
},
{
"code": null,
"e": 2224,
"s": 2128,
"text": "Now, we have to take in the .csv files appropriately. This can be done with the following code."
},
{
"code": null,
"e": 2345,
"s": 2224,
"text": "train_df = pd.read_csv('/content/gdrive/My Drive/train.csv') test_df = pd.read_csv('/content/gdrive/My Drive/test.csv') "
},
{
"code": null,
"e": 2894,
"s": 2345,
"text": "Next, I am going to drop a variety of categorical information. This includes the tickets, cabins, and names. The names have been removed as they generally would not relate to a correlation between survival or not. Yet, if this was going to be an extensively in-depth analysis, some names may have been more “important.” For instance, based on last name or prefix. For the most part, however, it would be too much work for nothing. Additionally, the ticket and cabin information lacked competition, so it was best to disregard these entire datasets."
},
{
"code": null,
"e": 2941,
"s": 2894,
"text": "This can be completed with the following code."
},
{
"code": null,
"e": 3201,
"s": 2941,
"text": "train_df = train_df.drop(['Name'], axis=1) test_df = test_df.drop(['Name'], axis=1) train_df = train_df.drop(['Cabin'], axis=1) test_df = test_df.drop(['Cabin'], axis=1)train_df = train_df.drop(['Ticket'], axis=1) test_df = test_df.drop(['Ticket'], axis=1)"
},
{
"code": null,
"e": 3328,
"s": 3201,
"text": "To see how the data looks like now, it may be beneficial to print out the train data collection. To do so, type the following."
},
{
"code": null,
"e": 3337,
"s": 3328,
"text": "train_df"
},
{
"code": null,
"e": 3377,
"s": 3337,
"text": "The same can be done for the test data."
},
{
"code": null,
"e": 3385,
"s": 3377,
"text": "test_df"
},
{
"code": null,
"e": 3736,
"s": 3385,
"text": "Next, we should consider the “embarked” category in the dataset. Similar to the ticket and cabin dataset, values are missing. However, there are not as many significant gaps. The most common embarked value is “S,” so for the few missing values, those will just be filled in with “S.” This is not precise or perfect, but every value must be filled in."
},
{
"code": null,
"e": 3873,
"s": 3736,
"text": "common_value = 'S' data = [train_df, test_df] for dataset in data: dataset['Embarked'] = dataset['Embarked'].fillna(common_value) "
},
{
"code": null,
"e": 4101,
"s": 3873,
"text": "Now, we have to use one-hot encoding to organize the categorical data. This will be applied to the two categorical data sets remaining, which are “sex” and “embark.” This will be applied to both the “train” and “test” datasets."
},
{
"code": null,
"e": 4565,
"s": 4101,
"text": "def clean_sex(train_df): try: return train_df[0] except TypeError: return \"None\"train_df[\"Sex\"] = train_df.Sex.apply(clean_sex) categorical_variables = ['Sex', 'Embarked'] for variable in categorical_variables: train_df[variable].fillna(\"Missing\", inplace=True) discarded = pd.get_dummies(train_df[variable],prefix = variable) train_df= pd.concat([train_df, discarded], axis = 1) train_df.drop([variable], axis = 1, inplace = True) "
},
{
"code": null,
"e": 4661,
"s": 4565,
"text": "The above was applied for the “train” data. Now, we have to do the same for the “test” dataset."
},
{
"code": null,
"e": 5096,
"s": 4661,
"text": "def clean_sex(test_df):try: return test_df[0] except TypeError: return \"None\"test_df[\"Sex\"] = test_df.Sex.apply(clean_sex) categorical_variables = ['Sex', 'Embarked']for variable in categorical_variables: test_df[variable].fillna(\"Missing\", inplace=True) discarded = pd.get_dummies(test_df[variable], prefix = variable) test_df= pd.concat([test_df, discarded], axis = 1) test_df.drop([variable], axis = 1, inplace = True) "
},
{
"code": null,
"e": 5545,
"s": 5096,
"text": "After organizing the categorical data, we should now consider the numerical data. For the “age” and “fare” data, there are spots in which there are missing values that are not being considered. Rather than completely ignoring these datasets, we need to find a way to implement a data value. To do so, we will take the average of “age” and “fare” and use these for values we do not have. We will have to do this for both the “train” and “test” data."
},
{
"code": null,
"e": 5786,
"s": 5545,
"text": "train_df[\"Age\"].fillna (train_df.Age.mean(), inplace = True)test_df[\"Age\"].fillna (test_df.Age.mean(), inplace = True)train_df[\"Fare\"].fillna (train_df.Fare.mean(), inplace = True)test_df[\"Fare\"].fillna (test_df.Fare.mean(), inplace = True)"
},
{
"code": null,
"e": 5893,
"s": 5786,
"text": "We should now look at our data again to double-check that all the appropriate applications have been made."
},
{
"code": null,
"e": 5939,
"s": 5893,
"text": "This will print the “train” manipulated data."
},
{
"code": null,
"e": 5948,
"s": 5939,
"text": "train_df"
},
{
"code": null,
"e": 5993,
"s": 5948,
"text": "This will print the “test” manipulated data."
},
{
"code": null,
"e": 6001,
"s": 5993,
"text": "test_df"
},
{
"code": null,
"e": 6189,
"s": 6001,
"text": "Now, because age is usually represented as an integer, it would be best to convert them into integer-based descriptions. We again need to do this for both the “train” and “test” datasets."
},
{
"code": null,
"e": 6260,
"s": 6189,
"text": "train_df = train_df.round({'Age':0})test_df = test_df.round({'Age':0})"
},
{
"code": null,
"e": 6456,
"s": 6260,
"text": "At this point, we have manipulated our data at a “decent level.” While not fully precise, it is at a point in which we can start to use a random forest algorithm to start formulating predictions."
},
{
"code": null,
"e": 6717,
"s": 6456,
"text": "So, for our local estimation, we will drop the “survived” value on the train data for a new variable called “X_train.” Then, for “Y_train,” we will include just “Survived.” Then, we will make the X_test equal to “test_df” directly. Lastly, print out the shape."
},
{
"code": null,
"e": 6853,
"s": 6717,
"text": "X_train = train_df.drop(\"Survived\", axis=1) Y_train = train_df[\"Survived\"] X_test = test_df X_train.shape, Y_train.shape, X_test.shape"
},
{
"code": null,
"e": 6970,
"s": 6853,
"text": "To double-check, it may be useful to print out “x_train.” Again, this can be done simply with the following command."
},
{
"code": null,
"e": 6978,
"s": 6970,
"text": "X_train"
},
{
"code": null,
"e": 7092,
"s": 6978,
"text": "Next, we should initialize our random forest. We should also use a variety of parameters to better our algorithm."
},
{
"code": null,
"e": 7466,
"s": 7092,
"text": "random_forest = RandomForestClassifier(criterion='gini', n_estimators=700, min_samples_split=10, min_samples_leaf=1, max_features='auto', oob_score=True, random_state=1, n_jobs=-1) random_forest.fit(X_train, Y_train)Y_pred = random_forest.predict(X_test) acc_random_forest = round(random_forest.score(X_train, Y_train) * 100, 2) acc_random_forest "
},
{
"code": null,
"e": 8165,
"s": 7466,
"text": "The “n_estimators” value represents the number of estimators used in the random forest (the number of trees in the forest). In this case, 700 was a value that worked well. “Min_samples_split” is the number of samples (minimum) required to separate and split the internal node. “Min_samples_leaf” represents the minimum number of samples required to be a leaf node. “Max_features” is used to describe the size of random subsets of features considered when splitting a node. When set to auto, there is no feature subset. The “oob_score,” when set to true, will attempt to validate the random forest model with an “Out of Bag” score. When “n_jobs” is set to -1, all the processors will be used to run."
},
{
"code": null,
"e": 8670,
"s": 8165,
"text": "The last segment of the code above fits the model and produces a prediction (y_pred) that works alongside the X_test data. The accuracy of the random forest will then be printed out. Locally testing this data produces an accuracy of approximately 90% (91.81%). However, this is just a local prediction based on separating the survival values from the training dataset. For an accurate estimate, we need to submit it directly to Kaggle. To do so, write the following code to get the “submission.csv” file."
},
{
"code": null,
"e": 8812,
"s": 8670,
"text": "submission = pd.DataFrame({ \"PassengerId\": test_df[\"PassengerId\"], \"Survived\": Y_pred})submission.to_csv('submission.csv', index=False)"
},
{
"code": null,
"e": 8824,
"s": 8812,
"text": "Conclusion:"
},
{
"code": null,
"e": 9232,
"s": 8824,
"text": "Kaggle produces an accuracy value of “0.79186” or “79.186%.” When I submitted using this prediction, I was ranked at 1573 out of 19649, which is approximately the top 8%. The difference between the local prediction and the Kaggle prediction is that the “train” data was modified as a “test hybrid” dataset, and Kaggle used the actual “test data.” Yet, in both situations, there was a level of randomization."
}
] |
Angular Material mat-tab-group - GeeksforGeeks
|
16 Feb, 2021
Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it you can enter the below command and can download it. mat-tab-group is used mainly for navbar requirements when we have multiple tabs to display.
Installation:
ng add @angular/material
Approach:
First, install the angular material using the above-mentioned command.
After completing the installation, Import ‘MatTabsModule’ from ‘@angular/material/tabs’ in the app.module.ts file.
Then use the <mat-tab-group> tag to group all the items inside this group tag.
Inside the <mat-tab-group> tag we need to use <mat-tab> tag for every item.
We can also style the tabs basing upon the position like start, center, and end. For this, we need to use a property called mat-align-tabs.
If we want to change the theme then we can change it by using the color property. In angular we have 3 themes, they are primary, accent, and warn.
Once done with the above steps then serve or start the project.
Example:
app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { MatTabsModule } from '@angular/material/tabs'; import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; @NgModule({ imports: [ BrowserModule, FormsModule, MatTabsModule, BrowserAnimationsModule], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }
app.component.html
<p> Implementation of mat-tab-group for center style and for default theme</p> <mat-tab-group mat-align-tabs="center"> <mat-tab label="Home">Home Content</mat-tab> <mat-tab label="Overview">Overview Content</mat-tab></mat-tab-group><br> <p> Implementation of mat-tab-group for center style and for primary theme</p> <mat-tab-group mat-align-tabs="center" backgroundColor="primary"> <mat-tab label="Home">Home Content</mat-tab> <mat-tab label="Overview">Overview Content</mat-tab></mat-tab-group><br> <p> Implementation of mat-tab-group for center style and for accent theme</p> <mat-tab-group mat-align-tabs="center" backgroundColor="accent"> <mat-tab label="Home">Home Content</mat-tab> <mat-tab label="Overview">Overview Content</mat-tab></mat-tab-group>
Output:
Angular-material
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Angular PrimeNG Dropdown Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular 10 (blur) Event
How to create module with Routing in Angular 9 ?
How to setup 404 page in angular routing ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24718,
"s": 24690,
"text": "\n16 Feb, 2021"
},
{
"code": null,
"e": 25103,
"s": 24718,
"text": "Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it you can enter the below command and can download it. mat-tab-group is used mainly for navbar requirements when we have multiple tabs to display."
},
{
"code": null,
"e": 25117,
"s": 25103,
"text": "Installation:"
},
{
"code": null,
"e": 25142,
"s": 25117,
"text": "ng add @angular/material"
},
{
"code": null,
"e": 25152,
"s": 25142,
"text": "Approach:"
},
{
"code": null,
"e": 25223,
"s": 25152,
"text": "First, install the angular material using the above-mentioned command."
},
{
"code": null,
"e": 25338,
"s": 25223,
"text": "After completing the installation, Import ‘MatTabsModule’ from ‘@angular/material/tabs’ in the app.module.ts file."
},
{
"code": null,
"e": 25417,
"s": 25338,
"text": "Then use the <mat-tab-group> tag to group all the items inside this group tag."
},
{
"code": null,
"e": 25493,
"s": 25417,
"text": "Inside the <mat-tab-group> tag we need to use <mat-tab> tag for every item."
},
{
"code": null,
"e": 25633,
"s": 25493,
"text": "We can also style the tabs basing upon the position like start, center, and end. For this, we need to use a property called mat-align-tabs."
},
{
"code": null,
"e": 25780,
"s": 25633,
"text": "If we want to change the theme then we can change it by using the color property. In angular we have 3 themes, they are primary, accent, and warn."
},
{
"code": null,
"e": 25844,
"s": 25780,
"text": "Once done with the above steps then serve or start the project."
},
{
"code": null,
"e": 25853,
"s": 25844,
"text": "Example:"
},
{
"code": null,
"e": 25867,
"s": 25853,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { MatTabsModule } from '@angular/material/tabs'; import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; @NgModule({ imports: [ BrowserModule, FormsModule, MatTabsModule, BrowserAnimationsModule], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }",
"e": 26410,
"s": 25867,
"text": null
},
{
"code": null,
"e": 26429,
"s": 26410,
"text": "app.component.html"
},
{
"code": "<p> Implementation of mat-tab-group for center style and for default theme</p> <mat-tab-group mat-align-tabs=\"center\"> <mat-tab label=\"Home\">Home Content</mat-tab> <mat-tab label=\"Overview\">Overview Content</mat-tab></mat-tab-group><br> <p> Implementation of mat-tab-group for center style and for primary theme</p> <mat-tab-group mat-align-tabs=\"center\" backgroundColor=\"primary\"> <mat-tab label=\"Home\">Home Content</mat-tab> <mat-tab label=\"Overview\">Overview Content</mat-tab></mat-tab-group><br> <p> Implementation of mat-tab-group for center style and for accent theme</p> <mat-tab-group mat-align-tabs=\"center\" backgroundColor=\"accent\"> <mat-tab label=\"Home\">Home Content</mat-tab> <mat-tab label=\"Overview\">Overview Content</mat-tab></mat-tab-group>",
"e": 27212,
"s": 26429,
"text": null
},
{
"code": null,
"e": 27220,
"s": 27212,
"text": "Output:"
},
{
"code": null,
"e": 27237,
"s": 27220,
"text": "Angular-material"
},
{
"code": null,
"e": 27244,
"s": 27237,
"text": "Picked"
},
{
"code": null,
"e": 27254,
"s": 27244,
"text": "AngularJS"
},
{
"code": null,
"e": 27271,
"s": 27254,
"text": "Web Technologies"
},
{
"code": null,
"e": 27369,
"s": 27271,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27378,
"s": 27369,
"text": "Comments"
},
{
"code": null,
"e": 27391,
"s": 27378,
"text": "Old Comments"
},
{
"code": null,
"e": 27426,
"s": 27391,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 27479,
"s": 27426,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 27503,
"s": 27479,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 27552,
"s": 27503,
"text": "How to create module with Routing in Angular 9 ?"
},
{
"code": null,
"e": 27595,
"s": 27552,
"text": "How to setup 404 page in angular routing ?"
},
{
"code": null,
"e": 27651,
"s": 27595,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 27684,
"s": 27651,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27746,
"s": 27684,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27789,
"s": 27746,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Consistently Beautiful Visualizations with Altair Themes | by Sergio Sánchez | Towards Data Science
|
If you are a data visualization fan or practitioner who also uses python you may have heard of Jake Vanderplas and Brian Granger's altair: "a declarative statistical visualization library for Python, based on Vega and Vega-lite".
With Altair, you can spend more time understanding your data and its meaning. Altair’s API is simple, friendly and consistent and built on top of the powerful Vega-Lite visualization grammar. This elegant simplicity produces beautiful and effective visualizations with a minimal amount of code.
In this piece we’ll be digging deeper into one of altair's less known features: themes.
A theme, in altair, is a set of chart configurations applied globally each python session. This means you can produce similar-looking visualizations consistently.
Maybe you are working on developing a personal style for your blog or maybe you are part of a company that already has a style in place or maybe you hate gridlines and are tired of turning them off every single time you create a chart. Having a style guide to follow is always a benefit when you are producing data visualizations.
Rather than explaining the value of style-guides and consistency in your visualizations, in this article we will explore how to implement one in altair by recreating the Urban Institute's Data Visualization Style Guide.
Here’s a simple example from the docs:
import altair as altfrom vega_datasets import data# define the theme by returning the dictionary of configurationsdef black_marks(): return { 'config': { 'view': { 'height': 300, 'width': 400, }, 'mark': { 'color': 'black', 'fill': 'black' } } }# register the custom theme under a chosen namealt.themes.register('black_marks', black_marks)# enable the newly registered themealt.themes.enable('black_marks')# draw the chartcars = data.cars.urlalt.Chart(cars).mark_point().encode( x='Horsepower:Q', y='Miles_per_Gallon:Q')
height and width remained the same as the default theme but we have now included color and fill values to be applied globally (unless otherwise specified) to any charts generated from this point until the end of this python session.
This would be the equivalent of
alt.Chart(cars).mark_point(color = 'black', fill = 'black').encode( x='Horsepower:Q', y='Miles_per_Gallon:Q')
in the black_marks config dictionary returned you can see that we specified the value black for the keys color and fill in mark. This is the format all these specifications follow. For example, if you wanted to configure the left axis' label's font size:
def my_theme(): return { 'config': { 'view': { 'height': 300, 'width': 400, }, 'mark': { 'color': 'black', 'fill': '#000000', }, 'axisLeft': { 'labelFontSize': 30, }, } }# register the custom theme under a chosen namealt.themes.register('my_theme', my_theme)# enable the newly registered themealt.themes.enable('my_theme')
(side note: you can get these specifications (i.e. 'axisLeft') from Vega-Lite's documentation
This can be particularly useful if you or your company have a style guide you have to follow. Even if you don’t have a style guide, you can start building one by saving your configurations on your personal theme rather than in your viz code (it pays off long-term!).
Vega already has some themes on GitHub.
So let’s build a simplified Urban Institute’s altair theme.
All the information for this simplified version of Urban Institute’s style can be found in this graphic from their GitHub page.
The basic anatomy of the theme is as follows:
def theme_name():return { "config": { "TOP_LEVEL_OBJECT": { # i.e. "title", "axisX", "legend", "CONFIGURATION": "VALUE", "ANOTHER_ONE": "ANOTHER_VALUE", "MAYBE_A_SIZE": 14, # values can be a string, boolean, or number, }, "ANOTHER_OBJECT": { "CONFIGURATION": "VALUE", } } }
We will configure the top-level objects “title”, “axisX”, “axisY”, “range”, and “legend”, plus a few other one-liner specifications.
Now, off the bat we saw that Urban uses the “Lato” font on all text, we can save that as a variable so we don’t have to reuse it.
“title”
“title”
Titles at Urban are 18px in size, Lato font, left-aligned, black.
def urban_theme(): font = "Lato"return { "config": { "title": { "fontSize": 18, "font": font, "anchor": "start", # equivalent of left-aligned. "fontColor": "#000000" } } }
At this point you could register and enable this theme and all your altair charts in this python session would have an Urban-Institute-looking title.
# registeralt.themes.register("my_custom_theme", urban_theme)# enablealt.themes.enable("my_custom_theme")
If you do not have “Lato” font installed in your computer you can run this code in a cell to import it to your browser from Google Fonts for the time being.
%%html<style>@import url('https://fonts.googleapis.com/css?family=Lato');</style>
“axisX” and “axisY”
“axisX” and “axisY”
At Urban the X-axis and Y-axis differ slightly. X-axes have what in altair is referred to as domain, the line that runs across the axis. Y-axes do not have this (similar to seaborn's sns.despine()). Y-axes have gridlines, X-axes do not. X-axes have ticks, Y-axes do not. But both have same-size labels and titles.
def urban_theme(): # Typography font = "Lato" # At Urban it's the same font for all text but it's good to keep them separate in case you want to change one later. labelFont = "Lato" sourceFont = "Lato" # Axes axisColor = "#000000" gridColor = "#DEDDDD"return { "config": { "title": { "fontSize": 18, "font": font, "anchor": "start", # equivalent of left-aligned. "fontColor": "#000000" }, "axisX": { "domain": True, "domainColor": axisColor, "domainWidth": 1, "grid": False, "labelFont": labelFont, "labelFontSize": 12, "labelAngle": 0, "tickColor": axisColor, "tickSize": 5, # default, including it just to show you can change it "titleFont": font, "titleFontSize": 12, "titlePadding": 10, # guessing, not specified in styleguide "title": "X Axis Title (units)", }, "axisY": { "domain": False, "grid": True, "gridColor": gridColor, "gridWidth": 1, "labelFont": labelFont, "labelFontSize": 12, "labelAngle": 0, "ticks": False, # even if you don't have a "domain" you need to turn these off. "titleFont": font, "titleFontSize": 12, "titlePadding": 10, # guessing, not specified in styleguide "title": "Y Axis Title (units)", # titles are by default vertical left of axis so we need to hack this "titleAngle": 0, # horizontal "titleY": -10, # move it up "titleX": 18, # move it to the right so it aligns with the labels },} }
If you registered and enabled this theme you’d have something that kinda, sorta, looks like an Urban Institute’s chart. But what lets you know right away that you are looking at an Urban Institute’s data visualization is the colors.
In altair, you have scales with domain and range. These are "functions that transforms values in the data domain (numbers, dates, strings, etc) to visual values (pixels, colors, sizes) of the encoding channels." So if you want to add a default color scheme all you have to do is encode in your theme the values for the top-level object "range".
We’ll save the values as a list main_palette and sequential_palette. The Urban Institute's Data Visualization Style Guide has a lot of color combinations. We will encode these two as defaults but when it comes to colors you will most likely end up modifying your data visualization on the go.
def urban_theme(): # Typography font = "Lato" # At Urban it's the same font for all text but it's good to keep them separate in case you want to change one later. labelFont = "Lato" sourceFont = "Lato" # Axes axisColor = "#000000" gridColor = "#DEDDDD" # Colors main_palette = ["#1696d2", "#d2d2d2", "#000000", "#fdbf11", "#ec008b", "#55b748", "#5c5859", "#db2b27", ] sequential_palette = ["#cfe8f3", "#a2d4ec", "#73bfe2", "#46abdb", "#1696d2", "#12719e", ]return { "config": { "title": { "fontSize": 18, "font": font, "anchor": "start", # equivalent of left-aligned. "fontColor": "#000000" }, "axisX": { "domain": True, "domainColor": axisColor, "domainWidth": 1, "grid": False, "labelFont": labelFont, "labelFontSize": 12, "labelAngle": 0, "tickColor": axisColor, "tickSize": 5, # default, including it just to show you can change it "titleFont": font, "titleFontSize": 12, "titlePadding": 10, # guessing, not specified in styleguide "title": "X Axis Title (units)", }, "axisY": { "domain": False, "grid": True, "gridColor": gridColor, "gridWidth": 1, "labelFont": labelFont, "labelFontSize": 12, "labelAngle": 0, "ticks": False, # even if you don't have a "domain" you need to turn these off. "titleFont": font, "titleFontSize": 12, "titlePadding": 10, # guessing, not specified in styleguide "title": "Y Axis Title (units)", # titles are by default vertical left of axis so we need to hack this "titleAngle": 0, # horizontal "titleY": -10, # move it up "titleX": 18, # move it to the right so it aligns with the labels }, "range": { "category": main_palette, "diverging": sequential_palette, }} }
At this point, your theme will have the Urban Institute’s title, axes, and color configurations by default. Pretty cool but that’s not all you can do.
Let’s add a default legend configuration. This time we’ll stray away from the style guide a little because the position of the legend depends on the chart at hand (and you can’t have a horizontal legend in Vega-lite).
This code also includes “view” and “background” configurations which are easy to follow without much explanation. It also includes the configurations for “area”, “line”, “trail”, “bar”, “point”, and other marks. This is just setting up the colors right for each specific mark.
def urban_theme(): # Typography font = "Lato" # At Urban it's the same font for all text but it's good to keep them separate in case you want to change one later. labelFont = "Lato" sourceFont = "Lato" # Axes axisColor = "#000000" gridColor = "#DEDDDD" # Colors main_palette = ["#1696d2", "#d2d2d2", "#000000", "#fdbf11", "#ec008b", "#55b748", "#5c5859", "#db2b27", ] sequential_palette = ["#cfe8f3", "#a2d4ec", "#73bfe2", "#46abdb", "#1696d2", "#12719e", ]return { # width and height are configured outside the config dict because they are Chart configurations/properties not chart-elements' configurations/properties. "width": 685, # from the guide "height": 380, # not in the guide "config": { "title": { "fontSize": 18, "font": font, "anchor": "start", # equivalent of left-aligned. "fontColor": "#000000" }, "axisX": { "domain": True, "domainColor": axisColor, "domainWidth": 1, "grid": False, "labelFont": labelFont, "labelFontSize": 12, "labelAngle": 0, "tickColor": axisColor, "tickSize": 5, # default, including it just to show you can change it "titleFont": font, "titleFontSize": 12, "titlePadding": 10, # guessing, not specified in styleguide "title": "X Axis Title (units)", }, "axisY": { "domain": False, "grid": True, "gridColor": gridColor, "gridWidth": 1, "labelFont": labelFont, "labelFontSize": 12, "labelAngle": 0, "ticks": False, # even if you don't have a "domain" you need to turn these off. "titleFont": font, "titleFontSize": 12, "titlePadding": 10, # guessing, not specified in styleguide "title": "Y Axis Title (units)", # titles are by default vertical left of axis so we need to hack this "titleAngle": 0, # horizontal "titleY": -10, # move it up "titleX": 18, # move it to the right so it aligns with the labels }, "range": { "category": main_palette, "diverging": sequential_palette, }, "legend": { "labelFont": labelFont, "labelFontSize": 12, "symbolType": "square", # just 'cause "symbolSize": 100, # default "titleFont": font, "titleFontSize": 12, "title": "", # set it to no-title by default "orient": "top-left", # so it's right next to the y-axis "offset": 0, # literally right next to the y-axis. }, "view": { "stroke": "transparent", # altair uses gridlines to box the area where the data is visualized. This takes that off. }, "background": { "color": "#FFFFFF", # white rather than transparent }, ### MARKS CONFIGURATIONS ### "area": { "fill": markColor, }, "line": { "color": markColor, "stroke": markColor, "strokeWidth": 5, }, "trail": { "color": markColor, "stroke": markColor, "strokeWidth": 0, "size": 1, }, "path": { "stroke": markColor, "strokeWidth": 0.5, }, "point": { "filled": True, }, "text": { "font": sourceFont, "color": markColor, "fontSize": 11, "align": "right", "fontWeight": 400, "size": 11, }, "bar": { "size": 40, "binSpacing": 1, "continuousBandSize": 30, "discreteBandSize": 30, "fill": markColor, "stroke": False, },} }
I personally save these themes in a .py script with
import altair as altalt.themes.register("my_custom_theme", urban_theme)alt.themes.enable("my_custom_theme")
at the end and just %run theme.py in my jupyter notebook.
Here are some examples of charts created with that theme.
There are a lot of ways to configure your theme and I would encourage you to try many different things. You can take this theme we just put together and play around with the values. Use a different font, font size, color-scheme. Have gridlines, don’t have gridlines. Have really, really, big labels for your axes. Do whatever you want but save it somewhere so you can build on it and grow your personal style.
While you may want to look up more on this in the altairdocumentation, I find it better to use the Vega-lite documentation. After all, altair is a python-wrapper for Vega-lite.
All images and code can be found in this GitHub repo.
Any comments, questions, tips? I’m on twitter, linkedin and Instagram.
|
[
{
"code": null,
"e": 401,
"s": 171,
"text": "If you are a data visualization fan or practitioner who also uses python you may have heard of Jake Vanderplas and Brian Granger's altair: \"a declarative statistical visualization library for Python, based on Vega and Vega-lite\"."
},
{
"code": null,
"e": 696,
"s": 401,
"text": "With Altair, you can spend more time understanding your data and its meaning. Altair’s API is simple, friendly and consistent and built on top of the powerful Vega-Lite visualization grammar. This elegant simplicity produces beautiful and effective visualizations with a minimal amount of code."
},
{
"code": null,
"e": 784,
"s": 696,
"text": "In this piece we’ll be digging deeper into one of altair's less known features: themes."
},
{
"code": null,
"e": 947,
"s": 784,
"text": "A theme, in altair, is a set of chart configurations applied globally each python session. This means you can produce similar-looking visualizations consistently."
},
{
"code": null,
"e": 1278,
"s": 947,
"text": "Maybe you are working on developing a personal style for your blog or maybe you are part of a company that already has a style in place or maybe you hate gridlines and are tired of turning them off every single time you create a chart. Having a style guide to follow is always a benefit when you are producing data visualizations."
},
{
"code": null,
"e": 1498,
"s": 1278,
"text": "Rather than explaining the value of style-guides and consistency in your visualizations, in this article we will explore how to implement one in altair by recreating the Urban Institute's Data Visualization Style Guide."
},
{
"code": null,
"e": 1537,
"s": 1498,
"text": "Here’s a simple example from the docs:"
},
{
"code": null,
"e": 2188,
"s": 1537,
"text": "import altair as altfrom vega_datasets import data# define the theme by returning the dictionary of configurationsdef black_marks(): return { 'config': { 'view': { 'height': 300, 'width': 400, }, 'mark': { 'color': 'black', 'fill': 'black' } } }# register the custom theme under a chosen namealt.themes.register('black_marks', black_marks)# enable the newly registered themealt.themes.enable('black_marks')# draw the chartcars = data.cars.urlalt.Chart(cars).mark_point().encode( x='Horsepower:Q', y='Miles_per_Gallon:Q')"
},
{
"code": null,
"e": 2421,
"s": 2188,
"text": "height and width remained the same as the default theme but we have now included color and fill values to be applied globally (unless otherwise specified) to any charts generated from this point until the end of this python session."
},
{
"code": null,
"e": 2453,
"s": 2421,
"text": "This would be the equivalent of"
},
{
"code": null,
"e": 2569,
"s": 2453,
"text": "alt.Chart(cars).mark_point(color = 'black', fill = 'black').encode( x='Horsepower:Q', y='Miles_per_Gallon:Q')"
},
{
"code": null,
"e": 2824,
"s": 2569,
"text": "in the black_marks config dictionary returned you can see that we specified the value black for the keys color and fill in mark. This is the format all these specifications follow. For example, if you wanted to configure the left axis' label's font size:"
},
{
"code": null,
"e": 3308,
"s": 2824,
"text": "def my_theme(): return { 'config': { 'view': { 'height': 300, 'width': 400, }, 'mark': { 'color': 'black', 'fill': '#000000', }, 'axisLeft': { 'labelFontSize': 30, }, } }# register the custom theme under a chosen namealt.themes.register('my_theme', my_theme)# enable the newly registered themealt.themes.enable('my_theme')"
},
{
"code": null,
"e": 3402,
"s": 3308,
"text": "(side note: you can get these specifications (i.e. 'axisLeft') from Vega-Lite's documentation"
},
{
"code": null,
"e": 3669,
"s": 3402,
"text": "This can be particularly useful if you or your company have a style guide you have to follow. Even if you don’t have a style guide, you can start building one by saving your configurations on your personal theme rather than in your viz code (it pays off long-term!)."
},
{
"code": null,
"e": 3709,
"s": 3669,
"text": "Vega already has some themes on GitHub."
},
{
"code": null,
"e": 3769,
"s": 3709,
"text": "So let’s build a simplified Urban Institute’s altair theme."
},
{
"code": null,
"e": 3897,
"s": 3769,
"text": "All the information for this simplified version of Urban Institute’s style can be found in this graphic from their GitHub page."
},
{
"code": null,
"e": 3943,
"s": 3897,
"text": "The basic anatomy of the theme is as follows:"
},
{
"code": null,
"e": 4339,
"s": 3943,
"text": "def theme_name():return { \"config\": { \"TOP_LEVEL_OBJECT\": { # i.e. \"title\", \"axisX\", \"legend\", \"CONFIGURATION\": \"VALUE\", \"ANOTHER_ONE\": \"ANOTHER_VALUE\", \"MAYBE_A_SIZE\": 14, # values can be a string, boolean, or number, }, \"ANOTHER_OBJECT\": { \"CONFIGURATION\": \"VALUE\", } } }"
},
{
"code": null,
"e": 4472,
"s": 4339,
"text": "We will configure the top-level objects “title”, “axisX”, “axisY”, “range”, and “legend”, plus a few other one-liner specifications."
},
{
"code": null,
"e": 4602,
"s": 4472,
"text": "Now, off the bat we saw that Urban uses the “Lato” font on all text, we can save that as a variable so we don’t have to reuse it."
},
{
"code": null,
"e": 4610,
"s": 4602,
"text": "“title”"
},
{
"code": null,
"e": 4618,
"s": 4610,
"text": "“title”"
},
{
"code": null,
"e": 4684,
"s": 4618,
"text": "Titles at Urban are 18px in size, Lato font, left-aligned, black."
},
{
"code": null,
"e": 4958,
"s": 4684,
"text": "def urban_theme(): font = \"Lato\"return { \"config\": { \"title\": { \"fontSize\": 18, \"font\": font, \"anchor\": \"start\", # equivalent of left-aligned. \"fontColor\": \"#000000\" } } }"
},
{
"code": null,
"e": 5108,
"s": 4958,
"text": "At this point you could register and enable this theme and all your altair charts in this python session would have an Urban-Institute-looking title."
},
{
"code": null,
"e": 5214,
"s": 5108,
"text": "# registeralt.themes.register(\"my_custom_theme\", urban_theme)# enablealt.themes.enable(\"my_custom_theme\")"
},
{
"code": null,
"e": 5371,
"s": 5214,
"text": "If you do not have “Lato” font installed in your computer you can run this code in a cell to import it to your browser from Google Fonts for the time being."
},
{
"code": null,
"e": 5453,
"s": 5371,
"text": "%%html<style>@import url('https://fonts.googleapis.com/css?family=Lato');</style>"
},
{
"code": null,
"e": 5473,
"s": 5453,
"text": "“axisX” and “axisY”"
},
{
"code": null,
"e": 5493,
"s": 5473,
"text": "“axisX” and “axisY”"
},
{
"code": null,
"e": 5807,
"s": 5493,
"text": "At Urban the X-axis and Y-axis differ slightly. X-axes have what in altair is referred to as domain, the line that runs across the axis. Y-axes do not have this (similar to seaborn's sns.despine()). Y-axes have gridlines, X-axes do not. X-axes have ticks, Y-axes do not. But both have same-size labels and titles."
},
{
"code": null,
"e": 7733,
"s": 5807,
"text": "def urban_theme(): # Typography font = \"Lato\" # At Urban it's the same font for all text but it's good to keep them separate in case you want to change one later. labelFont = \"Lato\" sourceFont = \"Lato\" # Axes axisColor = \"#000000\" gridColor = \"#DEDDDD\"return { \"config\": { \"title\": { \"fontSize\": 18, \"font\": font, \"anchor\": \"start\", # equivalent of left-aligned. \"fontColor\": \"#000000\" }, \"axisX\": { \"domain\": True, \"domainColor\": axisColor, \"domainWidth\": 1, \"grid\": False, \"labelFont\": labelFont, \"labelFontSize\": 12, \"labelAngle\": 0, \"tickColor\": axisColor, \"tickSize\": 5, # default, including it just to show you can change it \"titleFont\": font, \"titleFontSize\": 12, \"titlePadding\": 10, # guessing, not specified in styleguide \"title\": \"X Axis Title (units)\", }, \"axisY\": { \"domain\": False, \"grid\": True, \"gridColor\": gridColor, \"gridWidth\": 1, \"labelFont\": labelFont, \"labelFontSize\": 12, \"labelAngle\": 0, \"ticks\": False, # even if you don't have a \"domain\" you need to turn these off. \"titleFont\": font, \"titleFontSize\": 12, \"titlePadding\": 10, # guessing, not specified in styleguide \"title\": \"Y Axis Title (units)\", # titles are by default vertical left of axis so we need to hack this \"titleAngle\": 0, # horizontal \"titleY\": -10, # move it up \"titleX\": 18, # move it to the right so it aligns with the labels },} }"
},
{
"code": null,
"e": 7966,
"s": 7733,
"text": "If you registered and enabled this theme you’d have something that kinda, sorta, looks like an Urban Institute’s chart. But what lets you know right away that you are looking at an Urban Institute’s data visualization is the colors."
},
{
"code": null,
"e": 8311,
"s": 7966,
"text": "In altair, you have scales with domain and range. These are \"functions that transforms values in the data domain (numbers, dates, strings, etc) to visual values (pixels, colors, sizes) of the encoding channels.\" So if you want to add a default color scheme all you have to do is encode in your theme the values for the top-level object \"range\"."
},
{
"code": null,
"e": 8604,
"s": 8311,
"text": "We’ll save the values as a list main_palette and sequential_palette. The Urban Institute's Data Visualization Style Guide has a lot of color combinations. We will encode these two as defaults but when it comes to colors you will most likely end up modifying your data visualization on the go."
},
{
"code": null,
"e": 11181,
"s": 8604,
"text": "def urban_theme(): # Typography font = \"Lato\" # At Urban it's the same font for all text but it's good to keep them separate in case you want to change one later. labelFont = \"Lato\" sourceFont = \"Lato\" # Axes axisColor = \"#000000\" gridColor = \"#DEDDDD\" # Colors main_palette = [\"#1696d2\", \"#d2d2d2\", \"#000000\", \"#fdbf11\", \"#ec008b\", \"#55b748\", \"#5c5859\", \"#db2b27\", ] sequential_palette = [\"#cfe8f3\", \"#a2d4ec\", \"#73bfe2\", \"#46abdb\", \"#1696d2\", \"#12719e\", ]return { \"config\": { \"title\": { \"fontSize\": 18, \"font\": font, \"anchor\": \"start\", # equivalent of left-aligned. \"fontColor\": \"#000000\" }, \"axisX\": { \"domain\": True, \"domainColor\": axisColor, \"domainWidth\": 1, \"grid\": False, \"labelFont\": labelFont, \"labelFontSize\": 12, \"labelAngle\": 0, \"tickColor\": axisColor, \"tickSize\": 5, # default, including it just to show you can change it \"titleFont\": font, \"titleFontSize\": 12, \"titlePadding\": 10, # guessing, not specified in styleguide \"title\": \"X Axis Title (units)\", }, \"axisY\": { \"domain\": False, \"grid\": True, \"gridColor\": gridColor, \"gridWidth\": 1, \"labelFont\": labelFont, \"labelFontSize\": 12, \"labelAngle\": 0, \"ticks\": False, # even if you don't have a \"domain\" you need to turn these off. \"titleFont\": font, \"titleFontSize\": 12, \"titlePadding\": 10, # guessing, not specified in styleguide \"title\": \"Y Axis Title (units)\", # titles are by default vertical left of axis so we need to hack this \"titleAngle\": 0, # horizontal \"titleY\": -10, # move it up \"titleX\": 18, # move it to the right so it aligns with the labels }, \"range\": { \"category\": main_palette, \"diverging\": sequential_palette, }} }"
},
{
"code": null,
"e": 11332,
"s": 11181,
"text": "At this point, your theme will have the Urban Institute’s title, axes, and color configurations by default. Pretty cool but that’s not all you can do."
},
{
"code": null,
"e": 11550,
"s": 11332,
"text": "Let’s add a default legend configuration. This time we’ll stray away from the style guide a little because the position of the legend depends on the chart at hand (and you can’t have a horizontal legend in Vega-lite)."
},
{
"code": null,
"e": 11827,
"s": 11550,
"text": "This code also includes “view” and “background” configurations which are easy to follow without much explanation. It also includes the configurations for “area”, “line”, “trail”, “bar”, “point”, and other marks. This is just setting up the colors right for each specific mark."
},
{
"code": null,
"e": 16424,
"s": 11827,
"text": "def urban_theme(): # Typography font = \"Lato\" # At Urban it's the same font for all text but it's good to keep them separate in case you want to change one later. labelFont = \"Lato\" sourceFont = \"Lato\" # Axes axisColor = \"#000000\" gridColor = \"#DEDDDD\" # Colors main_palette = [\"#1696d2\", \"#d2d2d2\", \"#000000\", \"#fdbf11\", \"#ec008b\", \"#55b748\", \"#5c5859\", \"#db2b27\", ] sequential_palette = [\"#cfe8f3\", \"#a2d4ec\", \"#73bfe2\", \"#46abdb\", \"#1696d2\", \"#12719e\", ]return { # width and height are configured outside the config dict because they are Chart configurations/properties not chart-elements' configurations/properties. \"width\": 685, # from the guide \"height\": 380, # not in the guide \"config\": { \"title\": { \"fontSize\": 18, \"font\": font, \"anchor\": \"start\", # equivalent of left-aligned. \"fontColor\": \"#000000\" }, \"axisX\": { \"domain\": True, \"domainColor\": axisColor, \"domainWidth\": 1, \"grid\": False, \"labelFont\": labelFont, \"labelFontSize\": 12, \"labelAngle\": 0, \"tickColor\": axisColor, \"tickSize\": 5, # default, including it just to show you can change it \"titleFont\": font, \"titleFontSize\": 12, \"titlePadding\": 10, # guessing, not specified in styleguide \"title\": \"X Axis Title (units)\", }, \"axisY\": { \"domain\": False, \"grid\": True, \"gridColor\": gridColor, \"gridWidth\": 1, \"labelFont\": labelFont, \"labelFontSize\": 12, \"labelAngle\": 0, \"ticks\": False, # even if you don't have a \"domain\" you need to turn these off. \"titleFont\": font, \"titleFontSize\": 12, \"titlePadding\": 10, # guessing, not specified in styleguide \"title\": \"Y Axis Title (units)\", # titles are by default vertical left of axis so we need to hack this \"titleAngle\": 0, # horizontal \"titleY\": -10, # move it up \"titleX\": 18, # move it to the right so it aligns with the labels }, \"range\": { \"category\": main_palette, \"diverging\": sequential_palette, }, \"legend\": { \"labelFont\": labelFont, \"labelFontSize\": 12, \"symbolType\": \"square\", # just 'cause \"symbolSize\": 100, # default \"titleFont\": font, \"titleFontSize\": 12, \"title\": \"\", # set it to no-title by default \"orient\": \"top-left\", # so it's right next to the y-axis \"offset\": 0, # literally right next to the y-axis. }, \"view\": { \"stroke\": \"transparent\", # altair uses gridlines to box the area where the data is visualized. This takes that off. }, \"background\": { \"color\": \"#FFFFFF\", # white rather than transparent }, ### MARKS CONFIGURATIONS ### \"area\": { \"fill\": markColor, }, \"line\": { \"color\": markColor, \"stroke\": markColor, \"strokeWidth\": 5, }, \"trail\": { \"color\": markColor, \"stroke\": markColor, \"strokeWidth\": 0, \"size\": 1, }, \"path\": { \"stroke\": markColor, \"strokeWidth\": 0.5, }, \"point\": { \"filled\": True, }, \"text\": { \"font\": sourceFont, \"color\": markColor, \"fontSize\": 11, \"align\": \"right\", \"fontWeight\": 400, \"size\": 11, }, \"bar\": { \"size\": 40, \"binSpacing\": 1, \"continuousBandSize\": 30, \"discreteBandSize\": 30, \"fill\": markColor, \"stroke\": False, },} }"
},
{
"code": null,
"e": 16476,
"s": 16424,
"text": "I personally save these themes in a .py script with"
},
{
"code": null,
"e": 16584,
"s": 16476,
"text": "import altair as altalt.themes.register(\"my_custom_theme\", urban_theme)alt.themes.enable(\"my_custom_theme\")"
},
{
"code": null,
"e": 16642,
"s": 16584,
"text": "at the end and just %run theme.py in my jupyter notebook."
},
{
"code": null,
"e": 16700,
"s": 16642,
"text": "Here are some examples of charts created with that theme."
},
{
"code": null,
"e": 17110,
"s": 16700,
"text": "There are a lot of ways to configure your theme and I would encourage you to try many different things. You can take this theme we just put together and play around with the values. Use a different font, font size, color-scheme. Have gridlines, don’t have gridlines. Have really, really, big labels for your axes. Do whatever you want but save it somewhere so you can build on it and grow your personal style."
},
{
"code": null,
"e": 17287,
"s": 17110,
"text": "While you may want to look up more on this in the altairdocumentation, I find it better to use the Vega-lite documentation. After all, altair is a python-wrapper for Vega-lite."
},
{
"code": null,
"e": 17341,
"s": 17287,
"text": "All images and code can be found in this GitHub repo."
}
] |
C++ For Loop
|
When you know exactly how many times you want to loop through a block of
code, use the for loop instead of a while loop:
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
The example below will print the numbers 0 to 4:
Statement 1 sets a variable before the loop starts (int i = 0).
Statement 2 defines the condition for the loop to run (i must be less than
5). If the condition is true, the loop will start over again, if it is false,
the loop will end.
Statement 3 increases a value (i++) each time the code block in the loop has
been executed.
This example will only print even values between 0 and 10:
Use a for loop to print "Yes" 5 times:
(int i = 0; i < 5; ) {
cout << << "\n";
}
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": 122,
"s": 0,
"text": "When you know exactly how many times you want to loop through a block of \ncode, use the for loop instead of a while loop:"
},
{
"code": null,
"e": 197,
"s": 122,
"text": "Statement 1 is executed (one time) before the execution of the code block."
},
{
"code": null,
"e": 261,
"s": 197,
"text": "Statement 2 defines the condition for executing the code block."
},
{
"code": null,
"e": 338,
"s": 261,
"text": "Statement 3 is executed (every time) after the code block has been executed."
},
{
"code": null,
"e": 387,
"s": 338,
"text": "The example below will print the numbers 0 to 4:"
},
{
"code": null,
"e": 451,
"s": 387,
"text": "Statement 1 sets a variable before the loop starts (int i = 0)."
},
{
"code": null,
"e": 625,
"s": 451,
"text": "Statement 2 defines the condition for the loop to run (i must be less than \n5). If the condition is true, the loop will start over again, if it is false, \nthe loop will end."
},
{
"code": null,
"e": 718,
"s": 625,
"text": "Statement 3 increases a value (i++) each time the code block in the loop has \nbeen executed."
},
{
"code": null,
"e": 777,
"s": 718,
"text": "This example will only print even values between 0 and 10:"
},
{
"code": null,
"e": 816,
"s": 777,
"text": "Use a for loop to print \"Yes\" 5 times:"
},
{
"code": null,
"e": 863,
"s": 816,
"text": " (int i = 0; i < 5; ) {\n cout << << \"\\n\";\n}\n"
},
{
"code": null,
"e": 882,
"s": 863,
"text": "Start the Exercise"
},
{
"code": null,
"e": 915,
"s": 882,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 957,
"s": 915,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1064,
"s": 957,
"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": 1083,
"s": 1064,
"text": "[email protected]"
}
] |
Extract punctuation from the specified column of Dataframe using Regex - GeeksforGeeks
|
29 Dec, 2020
Prerequisite: Regular Expression in Python
In this article, we will see how to extract punctuation used in the specified column of the Dataframe using Regex.
Firstly, we are making regular expression that contains all the punctuation: [!”\$%&\'()*+,\-.\/:;=#@?\[\\\]^_`{|}~]* Then we are passing each row of specific column to re.findall() function for extracting the punctuation and then assigning that extracted punctuation to a new column in a Dataframe.
re.findall() function is used to extract 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.
Syntax: re.findall(regex, string)
Return: All non-overlapping matches of pattern in string, as a list of strings.
Now, Let’s create a Dataframe:
Python3
# import required librariesimport pandas as pdimport re # creating Dataframe with# name and their commentsdf = pd.DataFrame({ 'Name' : ['Akash', 'Ashish', 'Ayush', 'Diksha' , 'Radhika'], 'Comments': ['Hey! Akash how r u' , 'Why are you asking this to me?' , 'Today, what we are going to do.' , 'No plans for today why?' , 'Wedding plans, what are you saying?']}, columns = ['Name', 'Comments'] ) # show the Dataframedf
Output:
Now, Extracting the punctuation from the column comment:
Python3
# define a function for extracting# the punctuationsdef check_find_punctuations(text): # regular expression containing # all punctuation result = re.findall(r'[!"\$%&\'()*+,\-.\/:;=#@?\[\\\]^_`{|}~]*', text) # form a string string = "".join(result) # list of strings return return list(string) # creating new column name# as a punctuation_used and # applying user defined function# on each rows of Comments columndf['punctuation_used'] = df['Comments'].apply( lambda x : check_find_punctuations(x) ) # show the Dataframedf
Output:
Python pandas-dataFrame
Python Pandas-exercise
Python Regex-programs
Python-pandas
python-regex
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python
|
[
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 24255,
"s": 24212,
"text": "Prerequisite: Regular Expression in Python"
},
{
"code": null,
"e": 24370,
"s": 24255,
"text": "In this article, we will see how to extract punctuation used in the specified column of the Dataframe using Regex."
},
{
"code": null,
"e": 24670,
"s": 24370,
"text": "Firstly, we are making regular expression that contains all the punctuation: [!”\\$%&\\'()*+,\\-.\\/:;=#@?\\[\\\\\\]^_`{|}~]* Then we are passing each row of specific column to re.findall() function for extracting the punctuation and then assigning that extracted punctuation to a new column in a Dataframe."
},
{
"code": null,
"e": 24865,
"s": 24670,
"text": "re.findall() function is used to extract 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."
},
{
"code": null,
"e": 24900,
"s": 24865,
"text": "Syntax: re.findall(regex, string) "
},
{
"code": null,
"e": 24980,
"s": 24900,
"text": "Return: All non-overlapping matches of pattern in string, as a list of strings."
},
{
"code": null,
"e": 25011,
"s": 24980,
"text": "Now, Let’s create a Dataframe:"
},
{
"code": null,
"e": 25019,
"s": 25011,
"text": "Python3"
},
{
"code": "# import required librariesimport pandas as pdimport re # creating Dataframe with# name and their commentsdf = pd.DataFrame({ 'Name' : ['Akash', 'Ashish', 'Ayush', 'Diksha' , 'Radhika'], 'Comments': ['Hey! Akash how r u' , 'Why are you asking this to me?' , 'Today, what we are going to do.' , 'No plans for today why?' , 'Wedding plans, what are you saying?']}, columns = ['Name', 'Comments'] ) # show the Dataframedf",
"e": 25538,
"s": 25019,
"text": null
},
{
"code": null,
"e": 25546,
"s": 25538,
"text": "Output:"
},
{
"code": null,
"e": 25603,
"s": 25546,
"text": "Now, Extracting the punctuation from the column comment:"
},
{
"code": null,
"e": 25611,
"s": 25603,
"text": "Python3"
},
{
"code": "# define a function for extracting# the punctuationsdef check_find_punctuations(text): # regular expression containing # all punctuation result = re.findall(r'[!\"\\$%&\\'()*+,\\-.\\/:;=#@?\\[\\\\\\]^_`{|}~]*', text) # form a string string = \"\".join(result) # list of strings return return list(string) # creating new column name# as a punctuation_used and # applying user defined function# on each rows of Comments columndf['punctuation_used'] = df['Comments'].apply( lambda x : check_find_punctuations(x) ) # show the Dataframedf",
"e": 26247,
"s": 25611,
"text": null
},
{
"code": null,
"e": 26255,
"s": 26247,
"text": "Output:"
},
{
"code": null,
"e": 26279,
"s": 26255,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 26302,
"s": 26279,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 26324,
"s": 26302,
"text": "Python Regex-programs"
},
{
"code": null,
"e": 26338,
"s": 26324,
"text": "Python-pandas"
},
{
"code": null,
"e": 26351,
"s": 26338,
"text": "python-regex"
},
{
"code": null,
"e": 26358,
"s": 26351,
"text": "Python"
},
{
"code": null,
"e": 26456,
"s": 26358,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26465,
"s": 26456,
"text": "Comments"
},
{
"code": null,
"e": 26478,
"s": 26465,
"text": "Old Comments"
},
{
"code": null,
"e": 26499,
"s": 26478,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 26531,
"s": 26499,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26554,
"s": 26531,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 26576,
"s": 26554,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26603,
"s": 26576,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26619,
"s": 26603,
"text": "Deque in Python"
},
{
"code": null,
"e": 26661,
"s": 26619,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26717,
"s": 26661,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26762,
"s": 26717,
"text": "Python - Ways to remove duplicates from list"
}
] |
How to use JavaScript to load a webpage after 5 seconds?
|
Use the setTimeout() function in JavaScript to load a webpage after some interval. This function waits for some seconds and then loads the web page.
You can try to run the following code to learn how to load a webpage after 5 seconds −
Live Demo
<!DOCTYPE html>
<html>
<body>
<script>
setTimeout(myURL, 5000);
function myURL(){
window.open('http://qries.com');
}
</script>
<p>Web page loads after 5 seconds.</p>
</body>
</html>
|
[
{
"code": null,
"e": 1211,
"s": 1062,
"text": "Use the setTimeout() function in JavaScript to load a webpage after some interval. This function waits for some seconds and then loads the web page."
},
{
"code": null,
"e": 1298,
"s": 1211,
"text": "You can try to run the following code to learn how to load a webpage after 5 seconds −"
},
{
"code": null,
"e": 1308,
"s": 1298,
"text": "Live Demo"
},
{
"code": null,
"e": 1553,
"s": 1308,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <script>\n setTimeout(myURL, 5000);\n function myURL(){\n window.open('http://qries.com');\n }\n </script>\n <p>Web page loads after 5 seconds.</p>\n </body>\n</html>"
}
] |
Build your own Whatsapp Chat Analyzer | by Samir Sheriff | Towards Data Science
|
Recently, after working on a number of projects from Udacity’s courses, I was on the look out for new, familiar data to analyze and what better place to start than one’s own phone.
Whatsapp claims that nearly 55 billion messages are sent each day. The average user spends 195 minutes per week on Whatsapp, and is a member of plenty of groups.
With this treasure house of data right under our very noses, it is but imperative that we embark on a mission to gain insights on the messages our phones are forced to bear witness to. This article aims to serve as a step-by-step guide to build your own whatsapp conversation analyzer, and is divided into the following 3 main topics:
Data Collection
Data Preparation
Data Exploration
Before you can get started, ensure that the following packages are installed in your Python environment (I recommend using Jupyter since you can see intermediate outputs easily while following the steps in this tutorial):
Pandas
Seaborn
Matplotlib
Jupyter (Optional but useful since you can see intermediate outputs easily while following the steps in this tutorial) OR if you are lazy like me and don’t feel like installing any of these packages, just head over to Google Colaboratory (https://colab.research.google.com) which is a free Jupyter notebook environment that comes with everything pre-installed, and get started in a jiffy!
First off, we require a whatsapp conversation to analyze. Open a whatsapp conversation you wish to analyze (preferably a group chat since they tend to be larger) and use the “Export Chat” functionality to send the entire conversation in text format to your email ID.
Important Note: When prompted by whatsapp, ensure that you do not export any media otherwise it might take ages to export.
Download the exported chat from your email inbox. It should resemble the following:
18/06/17, 22:45 - Messages to this group are now secured with end-to-end encryption. Tap for more info.25/09/16, 21:50 - Nick Fury created group "Avengers"18/06/17, 22:45 - Nick Fury added you18/06/17, 22:45 - Nick Fury added Hulk18/06/17, 22:45 - Nick Fury added Thor18/06/17, 22:45 - Nick Fury added Tony Stark18/06/17, 22:29 - Tony Stark: Here are the details for tomorrow's picnic:The park is located at 123 Main Street. Bring your own snacks, we will also be grilling. It is going to be very warm so dress appropriately. We should be getting there at noon. See you then and don't forget the sunscreen.18/06/17, 22:46 - Hulk: HULK NO CARE18/06/17, 22:46 - Hulk: HULK NO FRIEND HERE18/06/17, 22:46 - Hulk: HULK HATE LOKI18/06/17, 22:46 - Hulk: GFCHGK18/06/17, 22:47 - Thor: Stop pressing every button in there18/06/17, 22:47 - Loki: Why do you have 2 numbers, Banner?18/06/17, 22:48 - Hulk: HULK FIRST SMASH YOU THEN TELL YOU
Just like raw vegetables have to be cooked and garnished with a variety of spices to make them palatable to humans, so also this plain text file will have to be parsed and tokenized in a meaningful manner in order to be served (stored) in a Pandas dataframe:
Let us consider just a single line from the text (which we will call “raw text”) and see how we can extract relevant columns from it:
18/06/17, 22:47 - Loki: Why do you have 2 numbers, Banner?
Hereafter, whenever I wish to draw your attention to different tokens in a string s, I will present to you 2 lines.
The first line will indicate the token names enclosed within {curly braces} and their relative positions within s.
The second line will be the string s modified to indicate the actual values corresponding to each token, enclosed within curly braces.
For instance , if the string s is “Word 1, random word Word 2 :” , then I will provide the following definition:
{Token 1}, random word {Token 2} {Token 3}{Word 1}, random word {Word 2} {:)}
From this, you will be able to infer that the value of Token 1 is “Word 1”, that of Token 2 is “Word 2” and Token 3 is “:)”.
In our sample line of text, our main objective is to automatically break down the raw message into 4 tokens, and we will see how to go about this task in the next section:
{Date}, {Time} - {Author}: {Message}{18/06/17}, {22:47} - {Loki}: {Why do you have 2 numbers, Banner?}
First, in order to detect if a line of text is a new message or belongs to a multi-line message, we will have to check if that line begins with a Date and Time, for which we will need a little bit of regular expression (regex) matching (Don’t worry — it isn’t that mind boggling once you break it down, especially with some nifty tools that I’ll show you in a minute). Let us define a new method called startsWithDateTime :
The following diagram shows how regex matching detects the date and time in our message:
The following diagram gives a brief overview of all the messages detected in the sample text file:
I won’t dive into the details of how regular expressions actually work, but if you are interested, you can find more explanations about how this matching is done by visiting https://regex101.com/ and https://medium.com/tech-tajawal/regular-expressions-the-last-guide-6800283ac034 .
Coming back to our sample line, Before we ran the startsWithDateTime method, no tokens were detected in our raw sample message:
{Raw Message}{18/06/17, 22:47 - Loki: Why do you have 2 numbers, Banner?}
After we run the startsWithDateTime method, 2 tokens were detected in our processed sample message:
{Date}, {Time} -Message{18/06/17}, {22:47} - Loki: Why do you have 2 numbers, Banner?
Now that we have identified lines that contain new messages with Date and Time components, let us move to the next part of the message (everything after the hypen):
Loki: Why do you have 2 numbers, Banner?
Once again, we will require some more regular expression matching. Our objective is to detect the author of this message. While there could be a variety of patterns depending on how you have saved your friends’ names in your phone contacts app, the most commonly used patterns I have identified are as follows (Feel free to add or remove any rules as you deem fit):
Keeping these rules in mind, let us now define a method called startsWithAuthor which finds strings that match at least one of the aforementioned rules:
The following diagram shows how regex matching detects the author in our message:
The following diagram gives a brief overview of all the authors detected in the sample text file:
You can find more explanations about how this matching is done by visiting https://regex101.com/
Before we ran the startsWithAuthor method, 2 tokens had been detected in our processed sample message:
{Date}, {Time} -Message{18/06/17}, {22:47} - {Loki: Why do you have 2 numbers, Banner?}
After we run the startsWithAuthor method, 4 tokens are detected in our processed sample message.
{Date}, {Time} - {Author}: {Message}{18/06/17}, {22:47} - {Loki}: {Why do you have 2 numbers, Banner?}
Note: You might be wondering how the Message token appeared out of thin air. Well, once we have detected the Date, Time and Author tokens, what we are left with is the remaining portion of the string which is the de facto Message token
Now that we have been able to identify the Date, Time, Author and Message tokens in a single message, it is time to split each line based on the separator tokens like commas (,), hyphens(-), colons(:) and spaces( ), so that the required tokens can be extracted and saved in a dataframe. This time, let me invert things by highlighting the separator tokens instead of the Date, Time, Author and Message tokens:
Date{Comma }Time{ Hyphen }Author{Colon }Message18/06/17{, }22:47{ - }Loki{: }Why do you have 2 numbers, Banner?
Let us define a new method called getDataPoint for the task of splitting string based on the separator tokens to extract the tokens of interest:
Sample output values are shown in comments (#) beside each line.
Note: Figuring out when the value of Author token can be None is left as an exercise to the reader.
We have come to the last stage of data parsing, for which we will have to read the entire whatsapp text file, identify and extract tokens from each line and capture all data in tabular format within a list:
Initialize a pandas dataframe using the following code:
You will find all your data tabulated as shown below (Looks neat, doesn’t it?):
Finally, we have reached one of the most exciting parts of our journey — Data Exploration. It is time for us to unearth the interesting stories that all this data is trying to tell us.
Firstly, let us take a look at what pandas has to say about our data frame (df):
This command shows the number of entries (count), unique entries, most frequently occurring entries (top) and frequency of the most frequently occurring entries (freq) for each column in the data frame.
The output might look like this:
Who are the most garrulous members? Let’s take a look at the number of messages sent by the top 10 Authors in the group.
Remember how, a few sections earlier, I had given you an exercise to figure out that the author of certain messages can be None? Well, if you haven’t figured it out yet, you needn’t worry because the results of this section might give you a clue.
Let us find all those messages which have no authors, using the following code:
Do you see any pattern in the messages here?
While glancing through the original text file or the entire data frame, you might have noticed messages containing the string: “<Media omitted>”. These messages represent any pictures, videos or audio messages.
Let us find all media messages and analyze the number of media messages sent by the top 10 authors who send media messages in the group, using the following code:
Do you spot any differences between the authors who send the most messages overall, and the authors who send the most media messages?
Since we are just restricting ourselves just to the analysis of text-only messages sent by our friends in the group, let us create a new data frame (messages_df) by dropping all those messages that are either media messages or do not have an author, using the data frames obtained in the previous 2 sections:
This step could be categorized as data cleaning. Feel free to skip this step if you want to gain insights on the entire non-text data as well.
It might be interesting to count the number of letters and words used by each author in each message. So, let us add 2 new columns to the data frame called “Letter_Count” and “Word_Count”, using the following code:
This step could be categorized as data augmentation.
Now, let us describe the cleaned and augmented data frame. One important point to note here is the distinction made between columns containing continuous values vs. those containing discrete values:
Try running the describe command on the entire data frame without specifying any columns. What do you observe?
Let us take a step back and look at the overall picture. How many words and letters have been sent since the beginning of time (which in this case, happens to be since the moment the group was conceived)?
Running this code revealed that a whopping 1,029,606 letters and 183,485 words were used in the the Avengers’ group.
How many words have been sent in total by each author, since the beginning of time?
Looks like most messages contain only 1 word. I wonder what that word is!
Does it make sense to count the total number of letters sent by each author since the beginning of time as well? Well, since we already have a “Letter Count” column, I don’t see any harm in doing so. So, here goes:
Looks like most messages contain only 1 or 2 letters. Hmmm! Very interesting! Are these letters from the English language or some other symbols?
Do you know the date on which the most number of messages were sent in the history of your group? Well, fear no more, for you will find out in just a second:
22/09/17 was the most active date. Was this the date when Thanos struck, rendering everyone panic-stricken and bursting with questions? What date did you get? Do you remember anything significant happening on this date?
Do you lie awake at night wondering at what time of the day your group is most active? The truth will be revealed:
Looks like the group is mostly active at around 8:15 PM at night. Be sure to message at this time to get a quicker response.
What is the most suitable hour of the day at which to message to increase your chances of getting a response from someone?
In order to answer this question, we will have to augment the data frame to include a new column for the hour (extracted from the “Time” column), as follows:
Now, you just have to run code similar to the ones for obtaining the top dates and times:
Looks like messaging between 6 PM and 7 PM has the highest chances of eliciting responses from group members.
Congratulations! You are more knowledgeable about your whatsapp conversations now! Those were quite a lot of insights, weren’t they? What insights did you gain about your conversations? Did you find any of them useful? Did you find any other useful insights that hasn’t been covered here? Feel free to add your thoughts in the comments section so that I can improve this guide.
This analysis isn’t the be all and end all of exploration and analysis. I haven’t taken into account stuff like emojis, which are used quite a lot in conversations. Or are they? Should I discard punctuations? Why do most messages contain only 1 word?
It seems like our analysis, while answering a lot of questions, has also opened up a Pandora’s box of new questions. Well, this ain’t the end. Stay tuned for an article in the not too distant future, where I will try to dig deeper into some of these questions.
Until then, Adios Amigos and Happy Exploring! Greeting from Me...yeah ME!
|
[
{
"code": null,
"e": 353,
"s": 172,
"text": "Recently, after working on a number of projects from Udacity’s courses, I was on the look out for new, familiar data to analyze and what better place to start than one’s own phone."
},
{
"code": null,
"e": 515,
"s": 353,
"text": "Whatsapp claims that nearly 55 billion messages are sent each day. The average user spends 195 minutes per week on Whatsapp, and is a member of plenty of groups."
},
{
"code": null,
"e": 850,
"s": 515,
"text": "With this treasure house of data right under our very noses, it is but imperative that we embark on a mission to gain insights on the messages our phones are forced to bear witness to. This article aims to serve as a step-by-step guide to build your own whatsapp conversation analyzer, and is divided into the following 3 main topics:"
},
{
"code": null,
"e": 866,
"s": 850,
"text": "Data Collection"
},
{
"code": null,
"e": 883,
"s": 866,
"text": "Data Preparation"
},
{
"code": null,
"e": 900,
"s": 883,
"text": "Data Exploration"
},
{
"code": null,
"e": 1122,
"s": 900,
"text": "Before you can get started, ensure that the following packages are installed in your Python environment (I recommend using Jupyter since you can see intermediate outputs easily while following the steps in this tutorial):"
},
{
"code": null,
"e": 1129,
"s": 1122,
"text": "Pandas"
},
{
"code": null,
"e": 1137,
"s": 1129,
"text": "Seaborn"
},
{
"code": null,
"e": 1148,
"s": 1137,
"text": "Matplotlib"
},
{
"code": null,
"e": 1537,
"s": 1148,
"text": "Jupyter (Optional but useful since you can see intermediate outputs easily while following the steps in this tutorial) OR if you are lazy like me and don’t feel like installing any of these packages, just head over to Google Colaboratory (https://colab.research.google.com) which is a free Jupyter notebook environment that comes with everything pre-installed, and get started in a jiffy!"
},
{
"code": null,
"e": 1804,
"s": 1537,
"text": "First off, we require a whatsapp conversation to analyze. Open a whatsapp conversation you wish to analyze (preferably a group chat since they tend to be larger) and use the “Export Chat” functionality to send the entire conversation in text format to your email ID."
},
{
"code": null,
"e": 1927,
"s": 1804,
"text": "Important Note: When prompted by whatsapp, ensure that you do not export any media otherwise it might take ages to export."
},
{
"code": null,
"e": 2011,
"s": 1927,
"text": "Download the exported chat from your email inbox. It should resemble the following:"
},
{
"code": null,
"e": 2940,
"s": 2011,
"text": "18/06/17, 22:45 - Messages to this group are now secured with end-to-end encryption. Tap for more info.25/09/16, 21:50 - Nick Fury created group \"Avengers\"18/06/17, 22:45 - Nick Fury added you18/06/17, 22:45 - Nick Fury added Hulk18/06/17, 22:45 - Nick Fury added Thor18/06/17, 22:45 - Nick Fury added Tony Stark18/06/17, 22:29 - Tony Stark: Here are the details for tomorrow's picnic:The park is located at 123 Main Street. Bring your own snacks, we will also be grilling. It is going to be very warm so dress appropriately. We should be getting there at noon. See you then and don't forget the sunscreen.18/06/17, 22:46 - Hulk: HULK NO CARE18/06/17, 22:46 - Hulk: HULK NO FRIEND HERE18/06/17, 22:46 - Hulk: HULK HATE LOKI18/06/17, 22:46 - Hulk: GFCHGK18/06/17, 22:47 - Thor: Stop pressing every button in there18/06/17, 22:47 - Loki: Why do you have 2 numbers, Banner?18/06/17, 22:48 - Hulk: HULK FIRST SMASH YOU THEN TELL YOU"
},
{
"code": null,
"e": 3199,
"s": 2940,
"text": "Just like raw vegetables have to be cooked and garnished with a variety of spices to make them palatable to humans, so also this plain text file will have to be parsed and tokenized in a meaningful manner in order to be served (stored) in a Pandas dataframe:"
},
{
"code": null,
"e": 3333,
"s": 3199,
"text": "Let us consider just a single line from the text (which we will call “raw text”) and see how we can extract relevant columns from it:"
},
{
"code": null,
"e": 3392,
"s": 3333,
"text": "18/06/17, 22:47 - Loki: Why do you have 2 numbers, Banner?"
},
{
"code": null,
"e": 3508,
"s": 3392,
"text": "Hereafter, whenever I wish to draw your attention to different tokens in a string s, I will present to you 2 lines."
},
{
"code": null,
"e": 3623,
"s": 3508,
"text": "The first line will indicate the token names enclosed within {curly braces} and their relative positions within s."
},
{
"code": null,
"e": 3758,
"s": 3623,
"text": "The second line will be the string s modified to indicate the actual values corresponding to each token, enclosed within curly braces."
},
{
"code": null,
"e": 3871,
"s": 3758,
"text": "For instance , if the string s is “Word 1, random word Word 2 :” , then I will provide the following definition:"
},
{
"code": null,
"e": 3949,
"s": 3871,
"text": "{Token 1}, random word {Token 2} {Token 3}{Word 1}, random word {Word 2} {:)}"
},
{
"code": null,
"e": 4074,
"s": 3949,
"text": "From this, you will be able to infer that the value of Token 1 is “Word 1”, that of Token 2 is “Word 2” and Token 3 is “:)”."
},
{
"code": null,
"e": 4246,
"s": 4074,
"text": "In our sample line of text, our main objective is to automatically break down the raw message into 4 tokens, and we will see how to go about this task in the next section:"
},
{
"code": null,
"e": 4349,
"s": 4246,
"text": "{Date}, {Time} - {Author}: {Message}{18/06/17}, {22:47} - {Loki}: {Why do you have 2 numbers, Banner?}"
},
{
"code": null,
"e": 4773,
"s": 4349,
"text": "First, in order to detect if a line of text is a new message or belongs to a multi-line message, we will have to check if that line begins with a Date and Time, for which we will need a little bit of regular expression (regex) matching (Don’t worry — it isn’t that mind boggling once you break it down, especially with some nifty tools that I’ll show you in a minute). Let us define a new method called startsWithDateTime :"
},
{
"code": null,
"e": 4862,
"s": 4773,
"text": "The following diagram shows how regex matching detects the date and time in our message:"
},
{
"code": null,
"e": 4961,
"s": 4862,
"text": "The following diagram gives a brief overview of all the messages detected in the sample text file:"
},
{
"code": null,
"e": 5243,
"s": 4961,
"text": "I won’t dive into the details of how regular expressions actually work, but if you are interested, you can find more explanations about how this matching is done by visiting https://regex101.com/ and https://medium.com/tech-tajawal/regular-expressions-the-last-guide-6800283ac034 ."
},
{
"code": null,
"e": 5371,
"s": 5243,
"text": "Coming back to our sample line, Before we ran the startsWithDateTime method, no tokens were detected in our raw sample message:"
},
{
"code": null,
"e": 5445,
"s": 5371,
"text": "{Raw Message}{18/06/17, 22:47 - Loki: Why do you have 2 numbers, Banner?}"
},
{
"code": null,
"e": 5545,
"s": 5445,
"text": "After we run the startsWithDateTime method, 2 tokens were detected in our processed sample message:"
},
{
"code": null,
"e": 5631,
"s": 5545,
"text": "{Date}, {Time} -Message{18/06/17}, {22:47} - Loki: Why do you have 2 numbers, Banner?"
},
{
"code": null,
"e": 5796,
"s": 5631,
"text": "Now that we have identified lines that contain new messages with Date and Time components, let us move to the next part of the message (everything after the hypen):"
},
{
"code": null,
"e": 5837,
"s": 5796,
"text": "Loki: Why do you have 2 numbers, Banner?"
},
{
"code": null,
"e": 6203,
"s": 5837,
"text": "Once again, we will require some more regular expression matching. Our objective is to detect the author of this message. While there could be a variety of patterns depending on how you have saved your friends’ names in your phone contacts app, the most commonly used patterns I have identified are as follows (Feel free to add or remove any rules as you deem fit):"
},
{
"code": null,
"e": 6356,
"s": 6203,
"text": "Keeping these rules in mind, let us now define a method called startsWithAuthor which finds strings that match at least one of the aforementioned rules:"
},
{
"code": null,
"e": 6438,
"s": 6356,
"text": "The following diagram shows how regex matching detects the author in our message:"
},
{
"code": null,
"e": 6536,
"s": 6438,
"text": "The following diagram gives a brief overview of all the authors detected in the sample text file:"
},
{
"code": null,
"e": 6633,
"s": 6536,
"text": "You can find more explanations about how this matching is done by visiting https://regex101.com/"
},
{
"code": null,
"e": 6736,
"s": 6633,
"text": "Before we ran the startsWithAuthor method, 2 tokens had been detected in our processed sample message:"
},
{
"code": null,
"e": 6824,
"s": 6736,
"text": "{Date}, {Time} -Message{18/06/17}, {22:47} - {Loki: Why do you have 2 numbers, Banner?}"
},
{
"code": null,
"e": 6921,
"s": 6824,
"text": "After we run the startsWithAuthor method, 4 tokens are detected in our processed sample message."
},
{
"code": null,
"e": 7024,
"s": 6921,
"text": "{Date}, {Time} - {Author}: {Message}{18/06/17}, {22:47} - {Loki}: {Why do you have 2 numbers, Banner?}"
},
{
"code": null,
"e": 7260,
"s": 7024,
"text": "Note: You might be wondering how the Message token appeared out of thin air. Well, once we have detected the Date, Time and Author tokens, what we are left with is the remaining portion of the string which is the de facto Message token"
},
{
"code": null,
"e": 7670,
"s": 7260,
"text": "Now that we have been able to identify the Date, Time, Author and Message tokens in a single message, it is time to split each line based on the separator tokens like commas (,), hyphens(-), colons(:) and spaces( ), so that the required tokens can be extracted and saved in a dataframe. This time, let me invert things by highlighting the separator tokens instead of the Date, Time, Author and Message tokens:"
},
{
"code": null,
"e": 7782,
"s": 7670,
"text": "Date{Comma }Time{ Hyphen }Author{Colon }Message18/06/17{, }22:47{ - }Loki{: }Why do you have 2 numbers, Banner?"
},
{
"code": null,
"e": 7927,
"s": 7782,
"text": "Let us define a new method called getDataPoint for the task of splitting string based on the separator tokens to extract the tokens of interest:"
},
{
"code": null,
"e": 7992,
"s": 7927,
"text": "Sample output values are shown in comments (#) beside each line."
},
{
"code": null,
"e": 8092,
"s": 7992,
"text": "Note: Figuring out when the value of Author token can be None is left as an exercise to the reader."
},
{
"code": null,
"e": 8299,
"s": 8092,
"text": "We have come to the last stage of data parsing, for which we will have to read the entire whatsapp text file, identify and extract tokens from each line and capture all data in tabular format within a list:"
},
{
"code": null,
"e": 8355,
"s": 8299,
"text": "Initialize a pandas dataframe using the following code:"
},
{
"code": null,
"e": 8435,
"s": 8355,
"text": "You will find all your data tabulated as shown below (Looks neat, doesn’t it?):"
},
{
"code": null,
"e": 8620,
"s": 8435,
"text": "Finally, we have reached one of the most exciting parts of our journey — Data Exploration. It is time for us to unearth the interesting stories that all this data is trying to tell us."
},
{
"code": null,
"e": 8701,
"s": 8620,
"text": "Firstly, let us take a look at what pandas has to say about our data frame (df):"
},
{
"code": null,
"e": 8904,
"s": 8701,
"text": "This command shows the number of entries (count), unique entries, most frequently occurring entries (top) and frequency of the most frequently occurring entries (freq) for each column in the data frame."
},
{
"code": null,
"e": 8937,
"s": 8904,
"text": "The output might look like this:"
},
{
"code": null,
"e": 9058,
"s": 8937,
"text": "Who are the most garrulous members? Let’s take a look at the number of messages sent by the top 10 Authors in the group."
},
{
"code": null,
"e": 9305,
"s": 9058,
"text": "Remember how, a few sections earlier, I had given you an exercise to figure out that the author of certain messages can be None? Well, if you haven’t figured it out yet, you needn’t worry because the results of this section might give you a clue."
},
{
"code": null,
"e": 9385,
"s": 9305,
"text": "Let us find all those messages which have no authors, using the following code:"
},
{
"code": null,
"e": 9430,
"s": 9385,
"text": "Do you see any pattern in the messages here?"
},
{
"code": null,
"e": 9641,
"s": 9430,
"text": "While glancing through the original text file or the entire data frame, you might have noticed messages containing the string: “<Media omitted>”. These messages represent any pictures, videos or audio messages."
},
{
"code": null,
"e": 9804,
"s": 9641,
"text": "Let us find all media messages and analyze the number of media messages sent by the top 10 authors who send media messages in the group, using the following code:"
},
{
"code": null,
"e": 9938,
"s": 9804,
"text": "Do you spot any differences between the authors who send the most messages overall, and the authors who send the most media messages?"
},
{
"code": null,
"e": 10247,
"s": 9938,
"text": "Since we are just restricting ourselves just to the analysis of text-only messages sent by our friends in the group, let us create a new data frame (messages_df) by dropping all those messages that are either media messages or do not have an author, using the data frames obtained in the previous 2 sections:"
},
{
"code": null,
"e": 10390,
"s": 10247,
"text": "This step could be categorized as data cleaning. Feel free to skip this step if you want to gain insights on the entire non-text data as well."
},
{
"code": null,
"e": 10605,
"s": 10390,
"text": "It might be interesting to count the number of letters and words used by each author in each message. So, let us add 2 new columns to the data frame called “Letter_Count” and “Word_Count”, using the following code:"
},
{
"code": null,
"e": 10658,
"s": 10605,
"text": "This step could be categorized as data augmentation."
},
{
"code": null,
"e": 10857,
"s": 10658,
"text": "Now, let us describe the cleaned and augmented data frame. One important point to note here is the distinction made between columns containing continuous values vs. those containing discrete values:"
},
{
"code": null,
"e": 10968,
"s": 10857,
"text": "Try running the describe command on the entire data frame without specifying any columns. What do you observe?"
},
{
"code": null,
"e": 11173,
"s": 10968,
"text": "Let us take a step back and look at the overall picture. How many words and letters have been sent since the beginning of time (which in this case, happens to be since the moment the group was conceived)?"
},
{
"code": null,
"e": 11290,
"s": 11173,
"text": "Running this code revealed that a whopping 1,029,606 letters and 183,485 words were used in the the Avengers’ group."
},
{
"code": null,
"e": 11374,
"s": 11290,
"text": "How many words have been sent in total by each author, since the beginning of time?"
},
{
"code": null,
"e": 11448,
"s": 11374,
"text": "Looks like most messages contain only 1 word. I wonder what that word is!"
},
{
"code": null,
"e": 11663,
"s": 11448,
"text": "Does it make sense to count the total number of letters sent by each author since the beginning of time as well? Well, since we already have a “Letter Count” column, I don’t see any harm in doing so. So, here goes:"
},
{
"code": null,
"e": 11808,
"s": 11663,
"text": "Looks like most messages contain only 1 or 2 letters. Hmmm! Very interesting! Are these letters from the English language or some other symbols?"
},
{
"code": null,
"e": 11966,
"s": 11808,
"text": "Do you know the date on which the most number of messages were sent in the history of your group? Well, fear no more, for you will find out in just a second:"
},
{
"code": null,
"e": 12186,
"s": 11966,
"text": "22/09/17 was the most active date. Was this the date when Thanos struck, rendering everyone panic-stricken and bursting with questions? What date did you get? Do you remember anything significant happening on this date?"
},
{
"code": null,
"e": 12301,
"s": 12186,
"text": "Do you lie awake at night wondering at what time of the day your group is most active? The truth will be revealed:"
},
{
"code": null,
"e": 12426,
"s": 12301,
"text": "Looks like the group is mostly active at around 8:15 PM at night. Be sure to message at this time to get a quicker response."
},
{
"code": null,
"e": 12549,
"s": 12426,
"text": "What is the most suitable hour of the day at which to message to increase your chances of getting a response from someone?"
},
{
"code": null,
"e": 12707,
"s": 12549,
"text": "In order to answer this question, we will have to augment the data frame to include a new column for the hour (extracted from the “Time” column), as follows:"
},
{
"code": null,
"e": 12797,
"s": 12707,
"text": "Now, you just have to run code similar to the ones for obtaining the top dates and times:"
},
{
"code": null,
"e": 12907,
"s": 12797,
"text": "Looks like messaging between 6 PM and 7 PM has the highest chances of eliciting responses from group members."
},
{
"code": null,
"e": 13285,
"s": 12907,
"text": "Congratulations! You are more knowledgeable about your whatsapp conversations now! Those were quite a lot of insights, weren’t they? What insights did you gain about your conversations? Did you find any of them useful? Did you find any other useful insights that hasn’t been covered here? Feel free to add your thoughts in the comments section so that I can improve this guide."
},
{
"code": null,
"e": 13536,
"s": 13285,
"text": "This analysis isn’t the be all and end all of exploration and analysis. I haven’t taken into account stuff like emojis, which are used quite a lot in conversations. Or are they? Should I discard punctuations? Why do most messages contain only 1 word?"
},
{
"code": null,
"e": 13797,
"s": 13536,
"text": "It seems like our analysis, while answering a lot of questions, has also opened up a Pandora’s box of new questions. Well, this ain’t the end. Stay tuned for an article in the not too distant future, where I will try to dig deeper into some of these questions."
}
] |
400x times faster Pandas Data Frame Iteration | by Satyam Kumar | Towards Data Science
|
Data processing is and data wrangling is important components of a data science model development pipeline. A data scientist spends 80% of their time preparing the dataset to make it fit for modeling. Sometimes performing data wrangling and explorations for a large-sized dataset becomes a tedious task, and one is only left to either wait quite long till the computations are completed or shift to some parallel processing.
Pandas is one of the famous Python libraries that has a vast list of API, but when it comes to scalability, it fails miserably. For large-size datasets, it takes a lot of time sometimes even hours just to iterate over the loops, and even for small-size datasets, iterating over the data frame using standard loops is quite time-consuming,
In this article, we will discuss techniques or hacks to speed the iteration process over large size datasets.
iterrows() is a built-in Pandas library function, that returns a series of each instance or row. It iterates over the data frame as a pair of indexes and column features as Series.
To compare the benchmark time constraints, I am using a dataset having 10 million records and 5 columns. We have a feature‘name’ in the dataset with the string type, that has needs to be strip to remove the spaces.
temp=[]for i,row in df.iterrows():name_new = row['name'].strip()temp.append(name_new)
The code snippet took nearly 1967 seconds to execute, which includes hovering over the data frame and performing a strip function of ‘name’ values.
It is not recommended to use iterrows, not only because of time performance issues but also iterrows() function does not preserve dtypes across the rows. You can use itertuples() function that preserves the types.
Now let’s find out the other techniques to iterate over the data frame and compare its time complexity.
Dataframes are Pandas-object with rows and columns. The rows and columns of the data frame are indexed, and one can loop over the indexes to iterate through the rows.
temp=[]for idx in range(0,df.shape[0],1):name_new = df['name'].iloc[idx].strip()temp.append(name_new)
It took nearly 223 seconds (approx 9x times faster than iterrows function) to iterate over the data frame and perform the strip operation.
You can iterate over the data frame and perform your operations with lightning-fast speed by just converting your Pandas data frame into a dictionary. You can use .to_dict() function in Pandas to convert the data frame to a dictionary. Now iterating over a dictionary is comparatively very fast compared to iterrows() function.
df_dict = df.to_dict('records')temp=[]for row in df_dict:name_new = row['name'].strip()temp.append(name_new)
Iterating over a dictionary format of the dataset takes about 25 records that is 77x times faster than the iterrows() function.
apply() is a built-in Pandas function that allows to pass a function and apply it on each value of the Pandas series. apply() function is not faster in itself but it has a huge improvement for the Pandas library as this function helps to segregate data according to the required conditions.
temp = df['name'].apply(lambda x: x.strip())
apply() the function takes 4.60 seconds to execute which is 427x times faster than the iterrows() function.
From the above-mentioned image (starting of this article), you can compare the benchmark time numbers calculated on a system having 8 cores and 32GB of RAM.
In this article, we have discussed several techniques to iterate over the Pandas data frame and compared their time complexity. It is recommended to use the iterrows() function in very specific cases. One can easily shift from using iterrows() or indexing approach to the dictionary-based iteration technique which speeds up the workflow by 77x times.
Apply function is around 400x times faster, but it has limited use, and one needs to make a lot of changes in the code to shift to this approach. I personally convert my data frame to a dictionary and then proceed with the iteration.
[1] Pandas Documentation: https://pandas.pydata.org/docs/index.html
Loved the article? Become a Medium member to continue learning without limits. I’ll receive a small portion of your membership fee if you use the following link, with no extra cost to you.
satyam-kumar.medium.com
Thank You for Reading
|
[
{
"code": null,
"e": 597,
"s": 172,
"text": "Data processing is and data wrangling is important components of a data science model development pipeline. A data scientist spends 80% of their time preparing the dataset to make it fit for modeling. Sometimes performing data wrangling and explorations for a large-sized dataset becomes a tedious task, and one is only left to either wait quite long till the computations are completed or shift to some parallel processing."
},
{
"code": null,
"e": 936,
"s": 597,
"text": "Pandas is one of the famous Python libraries that has a vast list of API, but when it comes to scalability, it fails miserably. For large-size datasets, it takes a lot of time sometimes even hours just to iterate over the loops, and even for small-size datasets, iterating over the data frame using standard loops is quite time-consuming,"
},
{
"code": null,
"e": 1046,
"s": 936,
"text": "In this article, we will discuss techniques or hacks to speed the iteration process over large size datasets."
},
{
"code": null,
"e": 1227,
"s": 1046,
"text": "iterrows() is a built-in Pandas library function, that returns a series of each instance or row. It iterates over the data frame as a pair of indexes and column features as Series."
},
{
"code": null,
"e": 1442,
"s": 1227,
"text": "To compare the benchmark time constraints, I am using a dataset having 10 million records and 5 columns. We have a feature‘name’ in the dataset with the string type, that has needs to be strip to remove the spaces."
},
{
"code": null,
"e": 1528,
"s": 1442,
"text": "temp=[]for i,row in df.iterrows():name_new = row['name'].strip()temp.append(name_new)"
},
{
"code": null,
"e": 1676,
"s": 1528,
"text": "The code snippet took nearly 1967 seconds to execute, which includes hovering over the data frame and performing a strip function of ‘name’ values."
},
{
"code": null,
"e": 1890,
"s": 1676,
"text": "It is not recommended to use iterrows, not only because of time performance issues but also iterrows() function does not preserve dtypes across the rows. You can use itertuples() function that preserves the types."
},
{
"code": null,
"e": 1994,
"s": 1890,
"text": "Now let’s find out the other techniques to iterate over the data frame and compare its time complexity."
},
{
"code": null,
"e": 2161,
"s": 1994,
"text": "Dataframes are Pandas-object with rows and columns. The rows and columns of the data frame are indexed, and one can loop over the indexes to iterate through the rows."
},
{
"code": null,
"e": 2263,
"s": 2161,
"text": "temp=[]for idx in range(0,df.shape[0],1):name_new = df['name'].iloc[idx].strip()temp.append(name_new)"
},
{
"code": null,
"e": 2402,
"s": 2263,
"text": "It took nearly 223 seconds (approx 9x times faster than iterrows function) to iterate over the data frame and perform the strip operation."
},
{
"code": null,
"e": 2730,
"s": 2402,
"text": "You can iterate over the data frame and perform your operations with lightning-fast speed by just converting your Pandas data frame into a dictionary. You can use .to_dict() function in Pandas to convert the data frame to a dictionary. Now iterating over a dictionary is comparatively very fast compared to iterrows() function."
},
{
"code": null,
"e": 2839,
"s": 2730,
"text": "df_dict = df.to_dict('records')temp=[]for row in df_dict:name_new = row['name'].strip()temp.append(name_new)"
},
{
"code": null,
"e": 2967,
"s": 2839,
"text": "Iterating over a dictionary format of the dataset takes about 25 records that is 77x times faster than the iterrows() function."
},
{
"code": null,
"e": 3258,
"s": 2967,
"text": "apply() is a built-in Pandas function that allows to pass a function and apply it on each value of the Pandas series. apply() function is not faster in itself but it has a huge improvement for the Pandas library as this function helps to segregate data according to the required conditions."
},
{
"code": null,
"e": 3303,
"s": 3258,
"text": "temp = df['name'].apply(lambda x: x.strip())"
},
{
"code": null,
"e": 3411,
"s": 3303,
"text": "apply() the function takes 4.60 seconds to execute which is 427x times faster than the iterrows() function."
},
{
"code": null,
"e": 3568,
"s": 3411,
"text": "From the above-mentioned image (starting of this article), you can compare the benchmark time numbers calculated on a system having 8 cores and 32GB of RAM."
},
{
"code": null,
"e": 3920,
"s": 3568,
"text": "In this article, we have discussed several techniques to iterate over the Pandas data frame and compared their time complexity. It is recommended to use the iterrows() function in very specific cases. One can easily shift from using iterrows() or indexing approach to the dictionary-based iteration technique which speeds up the workflow by 77x times."
},
{
"code": null,
"e": 4154,
"s": 3920,
"text": "Apply function is around 400x times faster, but it has limited use, and one needs to make a lot of changes in the code to shift to this approach. I personally convert my data frame to a dictionary and then proceed with the iteration."
},
{
"code": null,
"e": 4222,
"s": 4154,
"text": "[1] Pandas Documentation: https://pandas.pydata.org/docs/index.html"
},
{
"code": null,
"e": 4411,
"s": 4222,
"text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a small portion of your membership fee if you use the following link, with no extra cost to you."
},
{
"code": null,
"e": 4435,
"s": 4411,
"text": "satyam-kumar.medium.com"
}
] |
Counting Boolean function with some variables - GeeksforGeeks
|
28 Jun, 2019
Prerequisite – Canonical and Standard FormIn the below articles, we will see some varieties of problems with three variables.
Statement-1:Counting the number of Boolean functions possible with two variables such that there are exactly two min terms.Explanation:As we already know that from two variables (a and b) four numbers (0, 1, 2, 3) can be formed i.e, in binary digits 00, 01, 10, 11 and possible Min terms are a’b’, a’b, ab’, ab respectively which gives ‘1’ as the output for respective binary digits as input.Thus the number of possible function with two variables as input such that there are exactly two min terms are, Where ‘4’ is the possible number from two variables and ‘2’ is the desired number of min terms for which the number of the function needs to be calculated.
Explanation:As we already know that from two variables (a and b) four numbers (0, 1, 2, 3) can be formed i.e, in binary digits 00, 01, 10, 11 and possible Min terms are a’b’, a’b, ab’, ab respectively which gives ‘1’ as the output for respective binary digits as input.
Thus the number of possible function with two variables as input such that there are exactly two min terms are,
Where ‘4’ is the possible number from two variables and ‘2’ is the desired number of min terms for which the number of the function needs to be calculated.
Statement-2:Counting the number of Boolean functions possible with three variables such that there are exactly three min terms.Explanation:As we already know that from three variables (a, b and c), 8 numbers (0, 1, 2, 3, 4, 5, 6, 7) can be formed i.e, in binary digits 000, 001, 010, 011, 100, 101, 110, 111 and possible Min terms are a’b’c’, a’b’c, a’bc’, a’bc, ab’c, abc’, abc respectively which gives ‘1’ as the output for respective binary digits as input.Thus the number of possible function with three variables as input such that there are exactly three min terms are, Where ‘8’ is the possible number from three variables and ‘3’ is the desired number of min terms for which the number of the function need to be calculated.
Explanation:As we already know that from three variables (a, b and c), 8 numbers (0, 1, 2, 3, 4, 5, 6, 7) can be formed i.e, in binary digits 000, 001, 010, 011, 100, 101, 110, 111 and possible Min terms are a’b’c’, a’b’c, a’bc’, a’bc, ab’c, abc’, abc respectively which gives ‘1’ as the output for respective binary digits as input.
Thus the number of possible function with three variables as input such that there are exactly three min terms are,
Where ‘8’ is the possible number from three variables and ‘3’ is the desired number of min terms for which the number of the function need to be calculated.
Statement-3:Counting the number of boolean functions possible with three variables such that there are atmost 4 min terms.Explanation:As we already know that from three variables (a, b and c), 8 numbers (0, 1, 2, 3, 4, 5, 6, 7) can be formed, i.e., in binary digits 000, 001, 010, 011, 100, 101, 110, 111 and possible Min terms are a’b’c’, a’b’c, a’bc’, a’bc, ab’c, abc’, abc respectively which gives ‘1’ as the output for respective binary digits as input.Thus the number of possible function with three variables as input such that there are at most 4 min terms are, Where ‘8’ is the possible number from three variables and 0, 1, 2, 3, 4 are the desired number of min terms for which the number of the function need to be calculated.
Explanation:As we already know that from three variables (a, b and c), 8 numbers (0, 1, 2, 3, 4, 5, 6, 7) can be formed, i.e., in binary digits 000, 001, 010, 011, 100, 101, 110, 111 and possible Min terms are a’b’c’, a’b’c, a’bc’, a’bc, ab’c, abc’, abc respectively which gives ‘1’ as the output for respective binary digits as input.Thus the number of possible function with three variables as input such that there are at most 4 min terms are,
Where ‘8’ is the possible number from three variables and 0, 1, 2, 3, 4 are the desired number of min terms for which the number of the function need to be calculated.
Statement-4:Counting the number of Boolean functions possible with three variables such that there are minimum 4 min terms.Explanation:As we already know that from three variables (a, b and c), 8 numbers (0, 1, 2, 3, 4, 5, 6, 7) can be formed i.e, in binary digits 000, 001, 010, 011, 100, 101, 110, 111 and possible Min terms are a’b’c’, a’b’c, a’bc’, a’bc, ab’c, abc’, abc respectively which gives ‘1’ as the output for respective binary digits as input.Thus the number of possible function with three variables as input such that there are minimum 4 min terms are, Where ‘8’ is the possible number from three variables and 4, 5, 6, 7 are the desired number of min terms for which the number of the function need to be calculated.
Explanation:As we already know that from three variables (a, b and c), 8 numbers (0, 1, 2, 3, 4, 5, 6, 7) can be formed i.e, in binary digits 000, 001, 010, 011, 100, 101, 110, 111 and possible Min terms are a’b’c’, a’b’c, a’bc’, a’bc, ab’c, abc’, abc respectively which gives ‘1’ as the output for respective binary digits as input.Thus the number of possible function with three variables as input such that there are minimum 4 min terms are,
Where ‘8’ is the possible number from three variables and 4, 5, 6, 7 are the desired number of min terms for which the number of the function need to be calculated.
Statement-5:Counting the number of Boolean functions possible with ‘k’ variables such that there are ‘m’ min terms.Explanation:As we already know that from ‘k’ variables, numbers can be formed.Thus the number of possible function with ‘k’ variables as input such that there are ‘m’ min terms are, Where is the possible number from ‘k’ variables and ‘m’ are the desired number of min terms for which the number of the function need to be calculated.
Explanation:As we already know that from ‘k’ variables, numbers can be formed.Thus the number of possible function with ‘k’ variables as input such that there are ‘m’ min terms are,
Where is the possible number from ‘k’ variables and ‘m’ are the desired number of min terms for which the number of the function need to be calculated.
Statement-6:Counting the number of Boolean functions possible in neutral function of ‘3’ variables where there is equal number of min and max terms.Explanation:As we already know that from three variables (a, b and c), 8 numbers (0, 1, 2, 3, 4, 5, 6, 7) can be formed i.e, in binary digits 000, 001, 010, 011, 100, 101, 110, 111 and there are equal number of max and min terms which gives ‘1’ as the output for min terms and ‘0’ as the output for max terms for respective binary digits as input.For example, suppose 000 is the binary digits then min terms will be a’b’c’ and max terms will be abc.Thus the number of possible Boolean function with three variables in the neutral function are, Where ‘8’ is the possible number from three variables and 4 are the desired number of min terms or max terms for which the number of the function needs to be calculated.
Explanation:As we already know that from three variables (a, b and c), 8 numbers (0, 1, 2, 3, 4, 5, 6, 7) can be formed i.e, in binary digits 000, 001, 010, 011, 100, 101, 110, 111 and there are equal number of max and min terms which gives ‘1’ as the output for min terms and ‘0’ as the output for max terms for respective binary digits as input.
For example, suppose 000 is the binary digits then min terms will be a’b’c’ and max terms will be abc.Thus the number of possible Boolean function with three variables in the neutral function are,
Where ‘8’ is the possible number from three variables and 4 are the desired number of min terms or max terms for which the number of the function needs to be calculated.
Statement-7:Counting the number of Boolean functions possible in neutral function of ‘k’ variables where there is an equal number of min and max terms.Explanation:As we already know that from ‘k’ variables, numbers can be formed.Thus the number of possible Boolean function with ‘k’ variables as input where an equal number of min and max terms are, Where is the possible number from ‘k’ variables and are the desired number of either min or max terms for which the number of the function needs to be calculated.
Explanation:As we already know that from ‘k’ variables, numbers can be formed.Thus the number of possible Boolean function with ‘k’ variables as input where an equal number of min and max terms are,
Where is the possible number from ‘k’ variables and are the desired number of either min or max terms for which the number of the function needs to be calculated.
Digital Electronics & Logic Design
Engineering Mathematics
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Shift Micro-Operations in Computer Architecture
Analog to Digital Conversion
Transmission Impairment in Data Communication
Ring Counter in Digital Logic
Latches in Digital Logic
Relationship between number of nodes and height of binary tree
Inequalities in LaTeX
Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph
Arrow Symbols in LaTeX
Newton's Divided Difference Interpolation Formula
|
[
{
"code": null,
"e": 24436,
"s": 24408,
"text": "\n28 Jun, 2019"
},
{
"code": null,
"e": 24562,
"s": 24436,
"text": "Prerequisite – Canonical and Standard FormIn the below articles, we will see some varieties of problems with three variables."
},
{
"code": null,
"e": 25223,
"s": 24562,
"text": "Statement-1:Counting the number of Boolean functions possible with two variables such that there are exactly two min terms.Explanation:As we already know that from two variables (a and b) four numbers (0, 1, 2, 3) can be formed i.e, in binary digits 00, 01, 10, 11 and possible Min terms are a’b’, a’b, ab’, ab respectively which gives ‘1’ as the output for respective binary digits as input.Thus the number of possible function with two variables as input such that there are exactly two min terms are, Where ‘4’ is the possible number from two variables and ‘2’ is the desired number of min terms for which the number of the function needs to be calculated."
},
{
"code": null,
"e": 25494,
"s": 25223,
"text": "Explanation:As we already know that from two variables (a and b) four numbers (0, 1, 2, 3) can be formed i.e, in binary digits 00, 01, 10, 11 and possible Min terms are a’b’, a’b, ab’, ab respectively which gives ‘1’ as the output for respective binary digits as input."
},
{
"code": null,
"e": 25606,
"s": 25494,
"text": "Thus the number of possible function with two variables as input such that there are exactly two min terms are,"
},
{
"code": null,
"e": 25764,
"s": 25608,
"text": "Where ‘4’ is the possible number from two variables and ‘2’ is the desired number of min terms for which the number of the function needs to be calculated."
},
{
"code": null,
"e": 26498,
"s": 25764,
"text": "Statement-2:Counting the number of Boolean functions possible with three variables such that there are exactly three min terms.Explanation:As we already know that from three variables (a, b and c), 8 numbers (0, 1, 2, 3, 4, 5, 6, 7) can be formed i.e, in binary digits 000, 001, 010, 011, 100, 101, 110, 111 and possible Min terms are a’b’c’, a’b’c, a’bc’, a’bc, ab’c, abc’, abc respectively which gives ‘1’ as the output for respective binary digits as input.Thus the number of possible function with three variables as input such that there are exactly three min terms are, Where ‘8’ is the possible number from three variables and ‘3’ is the desired number of min terms for which the number of the function need to be calculated."
},
{
"code": null,
"e": 26833,
"s": 26498,
"text": "Explanation:As we already know that from three variables (a, b and c), 8 numbers (0, 1, 2, 3, 4, 5, 6, 7) can be formed i.e, in binary digits 000, 001, 010, 011, 100, 101, 110, 111 and possible Min terms are a’b’c’, a’b’c, a’bc’, a’bc, ab’c, abc’, abc respectively which gives ‘1’ as the output for respective binary digits as input."
},
{
"code": null,
"e": 26949,
"s": 26833,
"text": "Thus the number of possible function with three variables as input such that there are exactly three min terms are,"
},
{
"code": null,
"e": 27108,
"s": 26951,
"text": "Where ‘8’ is the possible number from three variables and ‘3’ is the desired number of min terms for which the number of the function need to be calculated."
},
{
"code": null,
"e": 27846,
"s": 27108,
"text": "Statement-3:Counting the number of boolean functions possible with three variables such that there are atmost 4 min terms.Explanation:As we already know that from three variables (a, b and c), 8 numbers (0, 1, 2, 3, 4, 5, 6, 7) can be formed, i.e., in binary digits 000, 001, 010, 011, 100, 101, 110, 111 and possible Min terms are a’b’c’, a’b’c, a’bc’, a’bc, ab’c, abc’, abc respectively which gives ‘1’ as the output for respective binary digits as input.Thus the number of possible function with three variables as input such that there are at most 4 min terms are, Where ‘8’ is the possible number from three variables and 0, 1, 2, 3, 4 are the desired number of min terms for which the number of the function need to be calculated."
},
{
"code": null,
"e": 28294,
"s": 27846,
"text": "Explanation:As we already know that from three variables (a, b and c), 8 numbers (0, 1, 2, 3, 4, 5, 6, 7) can be formed, i.e., in binary digits 000, 001, 010, 011, 100, 101, 110, 111 and possible Min terms are a’b’c’, a’b’c, a’bc’, a’bc, ab’c, abc’, abc respectively which gives ‘1’ as the output for respective binary digits as input.Thus the number of possible function with three variables as input such that there are at most 4 min terms are,"
},
{
"code": null,
"e": 28464,
"s": 28296,
"text": "Where ‘8’ is the possible number from three variables and 0, 1, 2, 3, 4 are the desired number of min terms for which the number of the function need to be calculated."
},
{
"code": null,
"e": 29198,
"s": 28464,
"text": "Statement-4:Counting the number of Boolean functions possible with three variables such that there are minimum 4 min terms.Explanation:As we already know that from three variables (a, b and c), 8 numbers (0, 1, 2, 3, 4, 5, 6, 7) can be formed i.e, in binary digits 000, 001, 010, 011, 100, 101, 110, 111 and possible Min terms are a’b’c’, a’b’c, a’bc’, a’bc, ab’c, abc’, abc respectively which gives ‘1’ as the output for respective binary digits as input.Thus the number of possible function with three variables as input such that there are minimum 4 min terms are, Where ‘8’ is the possible number from three variables and 4, 5, 6, 7 are the desired number of min terms for which the number of the function need to be calculated."
},
{
"code": null,
"e": 29644,
"s": 29198,
"text": "Explanation:As we already know that from three variables (a, b and c), 8 numbers (0, 1, 2, 3, 4, 5, 6, 7) can be formed i.e, in binary digits 000, 001, 010, 011, 100, 101, 110, 111 and possible Min terms are a’b’c’, a’b’c, a’bc’, a’bc, ab’c, abc’, abc respectively which gives ‘1’ as the output for respective binary digits as input.Thus the number of possible function with three variables as input such that there are minimum 4 min terms are,"
},
{
"code": null,
"e": 29811,
"s": 29646,
"text": "Where ‘8’ is the possible number from three variables and 4, 5, 6, 7 are the desired number of min terms for which the number of the function need to be calculated."
},
{
"code": null,
"e": 30262,
"s": 29811,
"text": "Statement-5:Counting the number of Boolean functions possible with ‘k’ variables such that there are ‘m’ min terms.Explanation:As we already know that from ‘k’ variables, numbers can be formed.Thus the number of possible function with ‘k’ variables as input such that there are ‘m’ min terms are, Where is the possible number from ‘k’ variables and ‘m’ are the desired number of min terms for which the number of the function need to be calculated."
},
{
"code": null,
"e": 30445,
"s": 30262,
"text": "Explanation:As we already know that from ‘k’ variables, numbers can be formed.Thus the number of possible function with ‘k’ variables as input such that there are ‘m’ min terms are,"
},
{
"code": null,
"e": 30600,
"s": 30447,
"text": "Where is the possible number from ‘k’ variables and ‘m’ are the desired number of min terms for which the number of the function need to be calculated."
},
{
"code": null,
"e": 31463,
"s": 30600,
"text": "Statement-6:Counting the number of Boolean functions possible in neutral function of ‘3’ variables where there is equal number of min and max terms.Explanation:As we already know that from three variables (a, b and c), 8 numbers (0, 1, 2, 3, 4, 5, 6, 7) can be formed i.e, in binary digits 000, 001, 010, 011, 100, 101, 110, 111 and there are equal number of max and min terms which gives ‘1’ as the output for min terms and ‘0’ as the output for max terms for respective binary digits as input.For example, suppose 000 is the binary digits then min terms will be a’b’c’ and max terms will be abc.Thus the number of possible Boolean function with three variables in the neutral function are, Where ‘8’ is the possible number from three variables and 4 are the desired number of min terms or max terms for which the number of the function needs to be calculated."
},
{
"code": null,
"e": 31812,
"s": 31463,
"text": "Explanation:As we already know that from three variables (a, b and c), 8 numbers (0, 1, 2, 3, 4, 5, 6, 7) can be formed i.e, in binary digits 000, 001, 010, 011, 100, 101, 110, 111 and there are equal number of max and min terms which gives ‘1’ as the output for min terms and ‘0’ as the output for max terms for respective binary digits as input."
},
{
"code": null,
"e": 32009,
"s": 31812,
"text": "For example, suppose 000 is the binary digits then min terms will be a’b’c’ and max terms will be abc.Thus the number of possible Boolean function with three variables in the neutral function are,"
},
{
"code": null,
"e": 32181,
"s": 32011,
"text": "Where ‘8’ is the possible number from three variables and 4 are the desired number of min terms or max terms for which the number of the function needs to be calculated."
},
{
"code": null,
"e": 32697,
"s": 32181,
"text": "Statement-7:Counting the number of Boolean functions possible in neutral function of ‘k’ variables where there is an equal number of min and max terms.Explanation:As we already know that from ‘k’ variables, numbers can be formed.Thus the number of possible Boolean function with ‘k’ variables as input where an equal number of min and max terms are, Where is the possible number from ‘k’ variables and are the desired number of either min or max terms for which the number of the function needs to be calculated."
},
{
"code": null,
"e": 32897,
"s": 32697,
"text": "Explanation:As we already know that from ‘k’ variables, numbers can be formed.Thus the number of possible Boolean function with ‘k’ variables as input where an equal number of min and max terms are,"
},
{
"code": null,
"e": 33064,
"s": 32899,
"text": "Where is the possible number from ‘k’ variables and are the desired number of either min or max terms for which the number of the function needs to be calculated."
},
{
"code": null,
"e": 33099,
"s": 33064,
"text": "Digital Electronics & Logic Design"
},
{
"code": null,
"e": 33123,
"s": 33099,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 33131,
"s": 33123,
"text": "GATE CS"
},
{
"code": null,
"e": 33229,
"s": 33131,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33277,
"s": 33229,
"text": "Shift Micro-Operations in Computer Architecture"
},
{
"code": null,
"e": 33306,
"s": 33277,
"text": "Analog to Digital Conversion"
},
{
"code": null,
"e": 33352,
"s": 33306,
"text": "Transmission Impairment in Data Communication"
},
{
"code": null,
"e": 33382,
"s": 33352,
"text": "Ring Counter in Digital Logic"
},
{
"code": null,
"e": 33407,
"s": 33382,
"text": "Latches in Digital Logic"
},
{
"code": null,
"e": 33470,
"s": 33407,
"text": "Relationship between number of nodes and height of binary tree"
},
{
"code": null,
"e": 33492,
"s": 33470,
"text": "Inequalities in LaTeX"
},
{
"code": null,
"e": 33557,
"s": 33492,
"text": "Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph"
},
{
"code": null,
"e": 33580,
"s": 33557,
"text": "Arrow Symbols in LaTeX"
}
] |
What is PreparedStatement in JDBC?
|
The PreparedStatement interface extends the Statement interface it represents a precompiled SQL statement which can be executed multiple times. This accepts parameterized SQL quires and you can pass 0 or more parameters to this query.
Initially this statement uses place holders “?” instead of parameters, later on you can pass arguments to these dynamically using the setXXX() methods of the PreparedStatement interface.
You can create an object of the PreparedStatement (interface) using the prepareStatement() method of the Connection interface. This method accepts a query (parameterized) and returns a PreparedStatement object.
When you invoke this method the Connection object sends the given query to the database to compile and save it. If the query got compiled successfully then only it returns the object.
To compile a query, database doesn’t require any values so you can use (zero or more) placeholders (Question marks ” ?”) in the place of values in the query.
For example, if you have a table named Employee in the database, created using the following query.
CREATE TABLE Employee(Name VARCHAR(255), Salary INT NOT NULL, Location VARCHAR(255));
Then the you should can use a Prepared Statement to insert values in to it as shown below.
//Creating a Prepared Statement
String query="INSERT INTO Employee(Name, Salary, Location)VALUES(?, ?, ?)";
Statement pstmt = con.prepareStatement(query);
The PreparedStatement interface provides several setter methods such as setInt(), setFloat(), setArray(), setDate(), setDouble() etc.. to set values to the place holders of the prepared statement.
These methods accept two arguments, one is an integer value representing the placement index of the place folder and, the other is an int or, String or, float etc... representing the value you need to insert at that particular position.
You can set values to the place holders of the above created statement using the setter methods as shown below:
pstmt.setString(1, "Amit");
pstmt.setInt(2, 3000);
pstmt.setString(3, "Hyderabad");
pstmt.setString(1, "Kalyan");
pstmt.setInt(2, 4000);
pstmt.setString(3, "Vishakhapatnam");
pstmt.setString(1, "Renuka");
pstmt.setInt(2, 5000);
pstmt.setString(3, "Delhi");
pstmt.setString(1, "Archana");
pstmt.setInt(2, 15000);
pstmt.setString(3, "Mumbai");
Once you have created the PreparedStatement object you can execute it using one of the execute() methods of the PreparedStatement interface namely, execute(), executeUpdate() and, executeQuery().
execute(): This method executes normal static SQL statements in the current prepared statement object and returns a boolean value.
execute(): This method executes normal static SQL statements in the current prepared statement object and returns a boolean value.
executeQuery(): This method executes the current prepared statement and returns a ResultSet object.
executeQuery(): This method executes the current prepared statement and returns a ResultSet object.
executeUpdate(): This method executes SQL DML statements such as insert update or delete in the current Prepared statement. It returns an integer value representing the number of rows affected.
executeUpdate(): This method executes SQL DML statements such as insert update or delete in the current Prepared statement. It returns an integer value representing the number of rows affected.
You can execute the above created prepared statement as shown below:
In this example we are trying to insert values into a table named Employees using a prepared statement.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class PreparedStatementExample {
public static void main(String args[]) throws SQLException {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/testdb";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Creating a Prepared Statement
String query = "INSERT INTO Employees(Name, Salary, Location) VALUES (?, ?, ?)";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, "Amit");
pstmt.setInt(2, 3000);
pstmt.setString(3, "Hyderabad");
pstmt.setString(1, "Kalyan");
pstmt.setInt(2, 4000);
pstmt.setString(3, "Vishakhapatnam");
pstmt.setString(1, "Renuka");
pstmt.setInt(2, 5000);
pstmt.setString(3, "Delhi");
pstmt.setString(1, "Archana");
pstmt.setInt(2, 15000);
pstmt.setString(3, "Mumbai");
int num = pstmt.executeUpdate();
System.out.println("Rows inserted ....");
}
}
Connection established......
Number of rows inserted: 1
If you verify the database, you can observe the inserted values in the table as:
+---------+--------+----------------+
| Name | Salary | Location |
+---------+--------+----------------+
| Amit | 30000 | Hyderabad |
| Kalyan | 40000 | Vishakhapatnam |
| Renuka | 50000 | Delhi |
| Archana | 15000 | Mumbai |
+---------+--------+----------------+
5 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1297,
"s": 1062,
"text": "The PreparedStatement interface extends the Statement interface it represents a precompiled SQL statement which can be executed multiple times. This accepts parameterized SQL quires and you can pass 0 or more parameters to this query."
},
{
"code": null,
"e": 1484,
"s": 1297,
"text": "Initially this statement uses place holders “?” instead of parameters, later on you can pass arguments to these dynamically using the setXXX() methods of the PreparedStatement interface."
},
{
"code": null,
"e": 1695,
"s": 1484,
"text": "You can create an object of the PreparedStatement (interface) using the prepareStatement() method of the Connection interface. This method accepts a query (parameterized) and returns a PreparedStatement object."
},
{
"code": null,
"e": 1879,
"s": 1695,
"text": "When you invoke this method the Connection object sends the given query to the database to compile and save it. If the query got compiled successfully then only it returns the object."
},
{
"code": null,
"e": 2037,
"s": 1879,
"text": "To compile a query, database doesn’t require any values so you can use (zero or more) placeholders (Question marks ” ?”) in the place of values in the query."
},
{
"code": null,
"e": 2137,
"s": 2037,
"text": "For example, if you have a table named Employee in the database, created using the following query."
},
{
"code": null,
"e": 2223,
"s": 2137,
"text": "CREATE TABLE Employee(Name VARCHAR(255), Salary INT NOT NULL, Location VARCHAR(255));"
},
{
"code": null,
"e": 2314,
"s": 2223,
"text": "Then the you should can use a Prepared Statement to insert values in to it as shown below."
},
{
"code": null,
"e": 2469,
"s": 2314,
"text": "//Creating a Prepared Statement\nString query=\"INSERT INTO Employee(Name, Salary, Location)VALUES(?, ?, ?)\";\nStatement pstmt = con.prepareStatement(query);"
},
{
"code": null,
"e": 2666,
"s": 2469,
"text": "The PreparedStatement interface provides several setter methods such as setInt(), setFloat(), setArray(), setDate(), setDouble() etc.. to set values to the place holders of the prepared statement."
},
{
"code": null,
"e": 2903,
"s": 2666,
"text": "These methods accept two arguments, one is an integer value representing the placement index of the place folder and, the other is an int or, String or, float etc... representing the value you need to insert at that particular position."
},
{
"code": null,
"e": 3015,
"s": 2903,
"text": "You can set values to the place holders of the above created statement using the setter methods as shown below:"
},
{
"code": null,
"e": 3360,
"s": 3015,
"text": "pstmt.setString(1, \"Amit\");\npstmt.setInt(2, 3000);\npstmt.setString(3, \"Hyderabad\");\n\npstmt.setString(1, \"Kalyan\");\npstmt.setInt(2, 4000);\npstmt.setString(3, \"Vishakhapatnam\");\n\npstmt.setString(1, \"Renuka\");\npstmt.setInt(2, 5000);\npstmt.setString(3, \"Delhi\");\n\npstmt.setString(1, \"Archana\");\npstmt.setInt(2, 15000);\npstmt.setString(3, \"Mumbai\");"
},
{
"code": null,
"e": 3556,
"s": 3360,
"text": "Once you have created the PreparedStatement object you can execute it using one of the execute() methods of the PreparedStatement interface namely, execute(), executeUpdate() and, executeQuery()."
},
{
"code": null,
"e": 3687,
"s": 3556,
"text": "execute(): This method executes normal static SQL statements in the current prepared statement object and returns a boolean value."
},
{
"code": null,
"e": 3818,
"s": 3687,
"text": "execute(): This method executes normal static SQL statements in the current prepared statement object and returns a boolean value."
},
{
"code": null,
"e": 3918,
"s": 3818,
"text": "executeQuery(): This method executes the current prepared statement and returns a ResultSet object."
},
{
"code": null,
"e": 4018,
"s": 3918,
"text": "executeQuery(): This method executes the current prepared statement and returns a ResultSet object."
},
{
"code": null,
"e": 4212,
"s": 4018,
"text": "executeUpdate(): This method executes SQL DML statements such as insert update or delete in the current Prepared statement. It returns an integer value representing the number of rows affected."
},
{
"code": null,
"e": 4406,
"s": 4212,
"text": "executeUpdate(): This method executes SQL DML statements such as insert update or delete in the current Prepared statement. It returns an integer value representing the number of rows affected."
},
{
"code": null,
"e": 4475,
"s": 4406,
"text": "You can execute the above created prepared statement as shown below:"
},
{
"code": null,
"e": 4579,
"s": 4475,
"text": "In this example we are trying to insert values into a table named Employees using a prepared statement."
},
{
"code": null,
"e": 5832,
"s": 4579,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.SQLException;\npublic class PreparedStatementExample {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/testdb\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n\n //Creating a Prepared Statement\n String query = \"INSERT INTO Employees(Name, Salary, Location) VALUES (?, ?, ?)\";\n PreparedStatement pstmt = con.prepareStatement(query);\n\n pstmt.setString(1, \"Amit\");\n pstmt.setInt(2, 3000);\n pstmt.setString(3, \"Hyderabad\");\n\n pstmt.setString(1, \"Kalyan\");\n pstmt.setInt(2, 4000);\n pstmt.setString(3, \"Vishakhapatnam\");\n\n pstmt.setString(1, \"Renuka\");\n pstmt.setInt(2, 5000);\n pstmt.setString(3, \"Delhi\");\n\n pstmt.setString(1, \"Archana\");\n pstmt.setInt(2, 15000);\n pstmt.setString(3, \"Mumbai\");\n\n int num = pstmt.executeUpdate();\n System.out.println(\"Rows inserted ....\");\n }\n}"
},
{
"code": null,
"e": 5888,
"s": 5832,
"text": "Connection established......\nNumber of rows inserted: 1"
},
{
"code": null,
"e": 5969,
"s": 5888,
"text": "If you verify the database, you can observe the inserted values in the table as:"
},
{
"code": null,
"e": 6298,
"s": 5969,
"text": "+---------+--------+----------------+\n| Name | Salary | Location |\n+---------+--------+----------------+\n| Amit | 30000 | Hyderabad |\n| Kalyan | 40000 | Vishakhapatnam |\n| Renuka | 50000 | Delhi |\n| Archana | 15000 | Mumbai |\n+---------+--------+----------------+\n5 rows in set (0.00 sec)"
}
] |
Converting Strings to Numbers in C/C++ - GeeksforGeeks
|
11 May, 2021
There are two common methods to convert strings to numbers:
Using stringstream class or sscanf() stringstream() : This is an easy way to convert strings of digits into ints, floats or doubles. Following is a sample program using a stringstream to convert string to int.
CPP
// A program to demonstrate the use of stringstream#include <iostream>#include <sstream>using namespace std; int main(){ string s = "12345"; // object from the class stringstream stringstream geek(s); // The object has the value 12345 and stream // it to the integer x int x = 0; geek >> x; // Now the variable x holds the value 12345 cout << "Value of x : " << x; return 0;}
Output:
Value of x : 12345
// A stringstream is similar to input/output
// file stream. We need to declare a stringstream
// just like an fstream, for example:
stringstream ss;
// and, like an fstream or cout,
// we can write to it:
ss << myString; or
ss << myCstring; or
ss << myInt;, or float, or double, etc.
// and we can read from it:
ss >> myChar; or
ss >> myCstring; or
ss >> myInt;
To summarize, stringstream is a convenient way to manipulate strings.sscanf() is a C style function similar to scanf(). It reads input from a string rather that standard input.
CPP
#include<stdio.h>int main(){ const char *str = "12345"; int x; sscanf(str, "%d", &x); printf("\nThe value of x : %d", x); return 0;}
Output:
Value of x : 12345
Similarly we can read float and double using %f and %lf respectively.
String conversion using stoi() or atoi() stoi() : The stoi() function takes a string as an argument and returns its value. Following is a simple implementation:
CPP
// C++ program to demonstrate working of stoi()// Work only if compiler supports C++11 or above.#include <iostream>#include <string>using namespace std; int main(){ string str1 = "45"; string str2 = "3.14159"; string str3 = "31337 geek"; int myint1 = stoi(str1); int myint2 = stoi(str2); int myint3 = stoi(str3); cout << "stoi(\"" << str1 << "\") is " << myint1 << '\n'; cout << "stoi(\"" << str2 << "\") is " << myint2 << '\n'; cout << "stoi(\"" << str3 << "\") is " << myint3 << '\n'; return 0;}
Output:
stoi("45") is 45
stoi("3.14159") is 3
stoi("31337 geek") is 31337
atoi() : The atoi() function takes a character array or string literal as an argument and returns its value. Following is a simple implementation:
CPP
C
// For C++11 above#include <cstdlib>#include <iostream>using namespace std; int main(){ const char* str1 = "42"; const char* str2 = "3.14159"; const char* str3 = "31337 geek"; int num1 = atoi(str1); int num2 = atoi(str2); int num3 = atoi(str3); cout << "atoi(\"" << str1 << "\") is " << num1 << '\n'; cout << "atoi(\"" << str2 << "\") is " << num2 << '\n'; cout << "atoi(\"" << str3 << "\") is " << num3 << '\n'; return 0; }
#include <stdio.h>#include <stdlib.h>int main(){ char* str1 = "42"; char* str2 = "3.14159"; char* str3 = "31337 geek"; int myint1 = atoi(str1); int myint2 = atoi(str2); int myint3 = atoi(str3); printf("stoi(%s) is %d \n", str1, myint1); printf("stoi(%s) is %d \n", str2, myint2); printf("stoi(%s) is %d \n", str3, myint3); // This Code is Contributed by Harshit Srivastava return 0;}
Output:
atoi("42") is 42
atoi("3.14159") is 3
atoi("31337 geek") is 31337
stoi() vs atoi()
atoi() is a legacy C-style function. stoi() is added in C++ 11.
atoi() works only for C-style strings (character array and string literal), stoi() works for both C++ strings and C style strings
atoi() takes only one parameter and returns integer value.
int atoi (const char * str);
stoi() can take upto three parameters, the second parameter is for starting index and third parameter is for base of input number.
int stoi (const string& str, size_t* index = 0, int base = 10);
Exercise Write your own atof() that takes a string (which represents a floating-point value) as an argument and returns its value as double.Reference: http://www.cplusplus.com/reference/string/stoi/ http://www.cplusplus.com/reference/sstream/stringstream/ http://www.cplusplus.com/reference/cstdlib/atoi/This article is contributed by Siffi Singh. 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.
milindbajaj
srivastavaharshit848
CPP-Library
cpp-string
cpp-stringstream
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Core Dump (Segmentation fault) in C/C++
Command line arguments in C/C++
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
Inheritance in C++
C++ Classes and Objects
|
[
{
"code": null,
"e": 24199,
"s": 24171,
"text": "\n11 May, 2021"
},
{
"code": null,
"e": 24261,
"s": 24199,
"text": "There are two common methods to convert strings to numbers: "
},
{
"code": null,
"e": 24472,
"s": 24261,
"text": "Using stringstream class or sscanf() stringstream() : This is an easy way to convert strings of digits into ints, floats or doubles. Following is a sample program using a stringstream to convert string to int. "
},
{
"code": null,
"e": 24476,
"s": 24472,
"text": "CPP"
},
{
"code": "// A program to demonstrate the use of stringstream#include <iostream>#include <sstream>using namespace std; int main(){ string s = \"12345\"; // object from the class stringstream stringstream geek(s); // The object has the value 12345 and stream // it to the integer x int x = 0; geek >> x; // Now the variable x holds the value 12345 cout << \"Value of x : \" << x; return 0;}",
"e": 24886,
"s": 24476,
"text": null
},
{
"code": null,
"e": 24894,
"s": 24886,
"text": "Output:"
},
{
"code": null,
"e": 24913,
"s": 24894,
"text": "Value of x : 12345"
},
{
"code": null,
"e": 25283,
"s": 24913,
"text": "// A stringstream is similar to input/output\n// file stream. We need to declare a stringstream\n// just like an fstream, for example: \nstringstream ss;\n\n// and, like an fstream or cout, \n// we can write to it:\nss << myString; or \nss << myCstring; or\nss << myInt;, or float, or double, etc.\n\n// and we can read from it:\nss >> myChar; or\nss >> myCstring; or\nss >> myInt; "
},
{
"code": null,
"e": 25462,
"s": 25283,
"text": "To summarize, stringstream is a convenient way to manipulate strings.sscanf() is a C style function similar to scanf(). It reads input from a string rather that standard input. "
},
{
"code": null,
"e": 25466,
"s": 25462,
"text": "CPP"
},
{
"code": "#include<stdio.h>int main(){ const char *str = \"12345\"; int x; sscanf(str, \"%d\", &x); printf(\"\\nThe value of x : %d\", x); return 0;}",
"e": 25614,
"s": 25466,
"text": null
},
{
"code": null,
"e": 25622,
"s": 25614,
"text": "Output:"
},
{
"code": null,
"e": 25641,
"s": 25622,
"text": "Value of x : 12345"
},
{
"code": null,
"e": 25711,
"s": 25641,
"text": "Similarly we can read float and double using %f and %lf respectively."
},
{
"code": null,
"e": 25873,
"s": 25711,
"text": "String conversion using stoi() or atoi() stoi() : The stoi() function takes a string as an argument and returns its value. Following is a simple implementation: "
},
{
"code": null,
"e": 25877,
"s": 25873,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate working of stoi()// Work only if compiler supports C++11 or above.#include <iostream>#include <string>using namespace std; int main(){ string str1 = \"45\"; string str2 = \"3.14159\"; string str3 = \"31337 geek\"; int myint1 = stoi(str1); int myint2 = stoi(str2); int myint3 = stoi(str3); cout << \"stoi(\\\"\" << str1 << \"\\\") is \" << myint1 << '\\n'; cout << \"stoi(\\\"\" << str2 << \"\\\") is \" << myint2 << '\\n'; cout << \"stoi(\\\"\" << str3 << \"\\\") is \" << myint3 << '\\n'; return 0;}",
"e": 26432,
"s": 25877,
"text": null
},
{
"code": null,
"e": 26440,
"s": 26432,
"text": "Output:"
},
{
"code": null,
"e": 26507,
"s": 26440,
"text": "stoi(\"45\") is 45\nstoi(\"3.14159\") is 3\nstoi(\"31337 geek\") is 31337 "
},
{
"code": null,
"e": 26655,
"s": 26507,
"text": "atoi() : The atoi() function takes a character array or string literal as an argument and returns its value. Following is a simple implementation: "
},
{
"code": null,
"e": 26659,
"s": 26655,
"text": "CPP"
},
{
"code": null,
"e": 26661,
"s": 26659,
"text": "C"
},
{
"code": "// For C++11 above#include <cstdlib>#include <iostream>using namespace std; int main(){ const char* str1 = \"42\"; const char* str2 = \"3.14159\"; const char* str3 = \"31337 geek\"; int num1 = atoi(str1); int num2 = atoi(str2); int num3 = atoi(str3); cout << \"atoi(\\\"\" << str1 << \"\\\") is \" << num1 << '\\n'; cout << \"atoi(\\\"\" << str2 << \"\\\") is \" << num2 << '\\n'; cout << \"atoi(\\\"\" << str3 << \"\\\") is \" << num3 << '\\n'; return 0; }",
"e": 27123,
"s": 26661,
"text": null
},
{
"code": "#include <stdio.h>#include <stdlib.h>int main(){ char* str1 = \"42\"; char* str2 = \"3.14159\"; char* str3 = \"31337 geek\"; int myint1 = atoi(str1); int myint2 = atoi(str2); int myint3 = atoi(str3); printf(\"stoi(%s) is %d \\n\", str1, myint1); printf(\"stoi(%s) is %d \\n\", str2, myint2); printf(\"stoi(%s) is %d \\n\", str3, myint3); // This Code is Contributed by Harshit Srivastava return 0;}",
"e": 27544,
"s": 27123,
"text": null
},
{
"code": null,
"e": 27552,
"s": 27544,
"text": "Output:"
},
{
"code": null,
"e": 27619,
"s": 27552,
"text": "atoi(\"42\") is 42\natoi(\"3.14159\") is 3\natoi(\"31337 geek\") is 31337 "
},
{
"code": null,
"e": 27636,
"s": 27619,
"text": "stoi() vs atoi()"
},
{
"code": null,
"e": 27702,
"s": 27636,
"text": "atoi() is a legacy C-style function. stoi() is added in C++ 11. "
},
{
"code": null,
"e": 27832,
"s": 27702,
"text": "atoi() works only for C-style strings (character array and string literal), stoi() works for both C++ strings and C style strings"
},
{
"code": null,
"e": 27891,
"s": 27832,
"text": "atoi() takes only one parameter and returns integer value."
},
{
"code": null,
"e": 27921,
"s": 27891,
"text": "int atoi (const char * str); "
},
{
"code": null,
"e": 28052,
"s": 27921,
"text": "stoi() can take upto three parameters, the second parameter is for starting index and third parameter is for base of input number."
},
{
"code": null,
"e": 28118,
"s": 28052,
"text": "int stoi (const string& str, size_t* index = 0, int base = 10); "
},
{
"code": null,
"e": 28814,
"s": 28120,
"text": "Exercise Write your own atof() that takes a string (which represents a floating-point value) as an argument and returns its value as double.Reference: http://www.cplusplus.com/reference/string/stoi/ http://www.cplusplus.com/reference/sstream/stringstream/ http://www.cplusplus.com/reference/cstdlib/atoi/This article is contributed by Siffi Singh. 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": 28826,
"s": 28814,
"text": "milindbajaj"
},
{
"code": null,
"e": 28847,
"s": 28826,
"text": "srivastavaharshit848"
},
{
"code": null,
"e": 28859,
"s": 28847,
"text": "CPP-Library"
},
{
"code": null,
"e": 28870,
"s": 28859,
"text": "cpp-string"
},
{
"code": null,
"e": 28887,
"s": 28870,
"text": "cpp-stringstream"
},
{
"code": null,
"e": 28898,
"s": 28887,
"text": "C Language"
},
{
"code": null,
"e": 28902,
"s": 28898,
"text": "C++"
},
{
"code": null,
"e": 28906,
"s": 28902,
"text": "CPP"
},
{
"code": null,
"e": 29004,
"s": 28906,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29013,
"s": 29004,
"text": "Comments"
},
{
"code": null,
"e": 29026,
"s": 29013,
"text": "Old Comments"
},
{
"code": null,
"e": 29054,
"s": 29026,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 29100,
"s": 29054,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 29112,
"s": 29100,
"text": "fork() in C"
},
{
"code": null,
"e": 29152,
"s": 29112,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 29184,
"s": 29152,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 29202,
"s": 29184,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 29248,
"s": 29202,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 29291,
"s": 29248,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 29310,
"s": 29291,
"text": "Inheritance in C++"
}
] |
How to Block or Disable Normal User Logins in Linux? - GeeksforGeeks
|
22 Mar, 2021
Here we will see how to block or disable normal user logins in Linux. This is a good idea to prevent Normal users from connecting to your system. We will see how to block Normal user logins using /etc/nologin file. We are going to tell the users that what is actually happening by showing them a message.
The main function of /etc/nologin file is to show a message to the users which are attempting to log on to a system during the process of the shutdown.
Once the message is shown to the user the login procedure terminates which stops the user from logging onto the system and apart from this you can also add your own message which you want to display, you can open the file in vi, nano text editor, and type it.
The /etc/nologin file can be created manually as shown below which is used to block the users’ login:
sudo touch /etc/nologin
And the below message will be shown to the user who is attempting to log on to the system.
echo "System down for maintenance, try again later" | sudo tee /etc/nologin
Now you can see from the screenshot below that a Normal user is not able to login.
To allow logins again you have to delete the /etc/nologin file.
The below command will help you in deleting /etc/nologin file.
sudo rm /etc/nologin
You can use the nologin shell to block some specific users. The nologin shell is located in /usr/sbin/nologin
This command will help you in finding the location of nologin shell:
$ which nologin
/usr/sbin/nologin
Now to set the user’s shell to nologin you can use the usermod command, Here we are going to set “priyanshu” users shell to nologin.
usermod -s /usr/sbin/nologin priyanshu
Now to re-enable some specific users to login again simply set their shell back to bash.
To set the “priyanshu” users shell back to bash use the below command:
usermod -s /bin/bash priyanshu
Picked
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Create and Setup Spring Boot Project in Eclipse IDE?
Sed Command in Linux/Unix with examples
grep command in Unix/Linux
TCP Server-Client implementation in C
AWK command in Unix/Linux with examples
cp command in Linux with examples
|
[
{
"code": null,
"e": 24561,
"s": 24533,
"text": "\n22 Mar, 2021"
},
{
"code": null,
"e": 24866,
"s": 24561,
"text": "Here we will see how to block or disable normal user logins in Linux. This is a good idea to prevent Normal users from connecting to your system. We will see how to block Normal user logins using /etc/nologin file. We are going to tell the users that what is actually happening by showing them a message."
},
{
"code": null,
"e": 25018,
"s": 24866,
"text": "The main function of /etc/nologin file is to show a message to the users which are attempting to log on to a system during the process of the shutdown."
},
{
"code": null,
"e": 25278,
"s": 25018,
"text": "Once the message is shown to the user the login procedure terminates which stops the user from logging onto the system and apart from this you can also add your own message which you want to display, you can open the file in vi, nano text editor, and type it."
},
{
"code": null,
"e": 25380,
"s": 25278,
"text": "The /etc/nologin file can be created manually as shown below which is used to block the users’ login:"
},
{
"code": null,
"e": 25404,
"s": 25380,
"text": "sudo touch /etc/nologin"
},
{
"code": null,
"e": 25495,
"s": 25404,
"text": "And the below message will be shown to the user who is attempting to log on to the system."
},
{
"code": null,
"e": 25571,
"s": 25495,
"text": "echo \"System down for maintenance, try again later\" | sudo tee /etc/nologin"
},
{
"code": null,
"e": 25654,
"s": 25571,
"text": "Now you can see from the screenshot below that a Normal user is not able to login."
},
{
"code": null,
"e": 25718,
"s": 25654,
"text": "To allow logins again you have to delete the /etc/nologin file."
},
{
"code": null,
"e": 25781,
"s": 25718,
"text": "The below command will help you in deleting /etc/nologin file."
},
{
"code": null,
"e": 25802,
"s": 25781,
"text": "sudo rm /etc/nologin"
},
{
"code": null,
"e": 25912,
"s": 25802,
"text": "You can use the nologin shell to block some specific users. The nologin shell is located in /usr/sbin/nologin"
},
{
"code": null,
"e": 25981,
"s": 25912,
"text": "This command will help you in finding the location of nologin shell:"
},
{
"code": null,
"e": 26015,
"s": 25981,
"text": "$ which nologin\n/usr/sbin/nologin"
},
{
"code": null,
"e": 26148,
"s": 26015,
"text": "Now to set the user’s shell to nologin you can use the usermod command, Here we are going to set “priyanshu” users shell to nologin."
},
{
"code": null,
"e": 26187,
"s": 26148,
"text": "usermod -s /usr/sbin/nologin priyanshu"
},
{
"code": null,
"e": 26276,
"s": 26187,
"text": "Now to re-enable some specific users to login again simply set their shell back to bash."
},
{
"code": null,
"e": 26347,
"s": 26276,
"text": "To set the “priyanshu” users shell back to bash use the below command:"
},
{
"code": null,
"e": 26378,
"s": 26347,
"text": "usermod -s /bin/bash priyanshu"
},
{
"code": null,
"e": 26385,
"s": 26378,
"text": "Picked"
},
{
"code": null,
"e": 26392,
"s": 26385,
"text": "How To"
},
{
"code": null,
"e": 26403,
"s": 26392,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26501,
"s": 26403,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26510,
"s": 26501,
"text": "Comments"
},
{
"code": null,
"e": 26523,
"s": 26510,
"text": "Old Comments"
},
{
"code": null,
"e": 26557,
"s": 26523,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 26606,
"s": 26557,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 26648,
"s": 26606,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 26706,
"s": 26648,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 26766,
"s": 26706,
"text": "How to Create and Setup Spring Boot Project in Eclipse IDE?"
},
{
"code": null,
"e": 26806,
"s": 26766,
"text": "Sed Command in Linux/Unix with examples"
},
{
"code": null,
"e": 26833,
"s": 26806,
"text": "grep command in Unix/Linux"
},
{
"code": null,
"e": 26871,
"s": 26833,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 26911,
"s": 26871,
"text": "AWK command in Unix/Linux with examples"
}
] |
How to ensure that child class overrides a super class method in java?
|
A method which does not have body is known as abstract method. It contains only method signature with a semi colon and, an abstract keyword before it.
public abstract myMethod();
To use an abstract method, you need to inherit it by extending its class and provide implementation (body) to it. If a class contains at least one abstract method, you must declare it abstract.
In other words, if you extend an abstract class it is mandatory to implement (override) all the abstract methods in it or, declare it abstract else a compile time error will be generated for each abstract method (that you don’t override) saying “subclass_name is not abstract and does not override abstract method abstractmethod_name in classname”.
Following Java example contains two abstract classes: One is an abstract class (MyClass) that contains 3 abstract methods and the other is a class with name AbstractClassExample that extends the earlier one.
In the subclass we are overriding only one abstract method (display()).
import java.io.IOException;
abstract class MyClass {
public abstract void display();
public abstract void setName(String name);
public abstract void setAge(int age);
}
public class AbstractClassExample extends MyClass{
public void display(){
System.out.println("subclass implementation of the display method ");
}
public static void main(String args[]) {
new AbstractClassExample().display();
}
}
On compiling, the above method generates the following compile time error.
AbstractClassExample.java:9: error: AbstractClassExample is not abstract and does not override abstract method setAge(int) in MyClass
public class AbstractClassExample extends MyClass{
^
1 error
Therefore, if you need to make sure that the sub class overrides a particular method of the super class method, you just need to declare the required method abstract.
To make the above program work you need to implement all the abstract methods as −
abstract class MyClass {
public abstract void display();
public abstract void setName(String name);
public abstract void setAge(int age);
}
public class AbstractClassExample extends MyClass{
public void display(){
System.out.println("subclass implementation of the display method ");
}
public void setName(String name){
System.out.println("Name: "+name);
}
public void setAge(int age){
System.out.println("Age: "+age);
}
public static void main(String args[]) {
AbstractClassExample obj = new AbstractClassExample();
obj.display();
obj.setName("Krishna");
obj.setAge(20);
}
}
subclass implementation of the display method
Name: Krishna
Age: 20
|
[
{
"code": null,
"e": 1213,
"s": 1062,
"text": "A method which does not have body is known as abstract method. It contains only method signature with a semi colon and, an abstract keyword before it."
},
{
"code": null,
"e": 1241,
"s": 1213,
"text": "public abstract myMethod();"
},
{
"code": null,
"e": 1435,
"s": 1241,
"text": "To use an abstract method, you need to inherit it by extending its class and provide implementation (body) to it. If a class contains at least one abstract method, you must declare it abstract."
},
{
"code": null,
"e": 1784,
"s": 1435,
"text": "In other words, if you extend an abstract class it is mandatory to implement (override) all the abstract methods in it or, declare it abstract else a compile time error will be generated for each abstract method (that you don’t override) saying “subclass_name is not abstract and does not override abstract method abstractmethod_name in classname”."
},
{
"code": null,
"e": 1992,
"s": 1784,
"text": "Following Java example contains two abstract classes: One is an abstract class (MyClass) that contains 3 abstract methods and the other is a class with name AbstractClassExample that extends the earlier one."
},
{
"code": null,
"e": 2064,
"s": 1992,
"text": "In the subclass we are overriding only one abstract method (display())."
},
{
"code": null,
"e": 2494,
"s": 2064,
"text": "import java.io.IOException;\nabstract class MyClass {\n public abstract void display();\n public abstract void setName(String name);\n public abstract void setAge(int age);\n}\npublic class AbstractClassExample extends MyClass{\n public void display(){\n System.out.println(\"subclass implementation of the display method \");\n }\n public static void main(String args[]) {\n new AbstractClassExample().display();\n }\n}"
},
{
"code": null,
"e": 2569,
"s": 2494,
"text": "On compiling, the above method generates the following compile time error."
},
{
"code": null,
"e": 2764,
"s": 2569,
"text": "AbstractClassExample.java:9: error: AbstractClassExample is not abstract and does not override abstract method setAge(int) in MyClass\npublic class AbstractClassExample extends MyClass{\n^\n1 error"
},
{
"code": null,
"e": 2931,
"s": 2764,
"text": "Therefore, if you need to make sure that the sub class overrides a particular method of the super class method, you just need to declare the required method abstract."
},
{
"code": null,
"e": 3014,
"s": 2931,
"text": "To make the above program work you need to implement all the abstract methods as −"
},
{
"code": null,
"e": 3665,
"s": 3014,
"text": "abstract class MyClass {\n public abstract void display();\n public abstract void setName(String name);\n public abstract void setAge(int age);\n}\npublic class AbstractClassExample extends MyClass{\n public void display(){\n System.out.println(\"subclass implementation of the display method \");\n }\n public void setName(String name){\n System.out.println(\"Name: \"+name);\n }\n public void setAge(int age){\n System.out.println(\"Age: \"+age);\n }\n public static void main(String args[]) {\n AbstractClassExample obj = new AbstractClassExample();\n obj.display();\n obj.setName(\"Krishna\");\n obj.setAge(20);\n }\n}"
},
{
"code": null,
"e": 3733,
"s": 3665,
"text": "subclass implementation of the display method\nName: Krishna\nAge: 20"
}
] |
GATE | GATE-CS-2004 | Question 49 - GeeksforGeeks
|
14 Feb, 2018
A Unix-style i-node has 10 direct pointers and one single, one double and one triple indirect pointers. Disk block size is 1 Kbyte, disk block address is 32 bits, and 48-bit integers are used. What is the maximum possible file size ?(A) 224 bytes(B) 232 bytes(C) 234 bytes(D) 248 bytesAnswer: (C)Explanation: Image Source: Wiki
Size of Disk Block = 1Kbyte
Disk Blocks address = 32bits,
but 48 bit integers are used for address
Therefore address size = 6 bytes
No of addresses per block = 1024/6 = 170.66
Therefore 170 ≈ 2^8 addresses per block can be stored
Maximum File Size = 10 Direct + 1 Single Indirect +
1 Double Indirect + 1 Triple Indirect
= 10 + 28 + 28*28 + 28*28*28
≈ 224 Blocks
Since each block is of size 210
Maximum files size = 224 * 210
= 234
Quiz of this Question
GATE-CS-2004
GATE-GATE-CS-2004
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 7
GATE | GATE-IT-2004 | Question 71
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2019 | Question 27
GATE | GATE-CS-2006 | Question 49
GATE | GATE CS 2011 | Question 65
|
[
{
"code": null,
"e": 24192,
"s": 24164,
"text": "\n14 Feb, 2018"
},
{
"code": null,
"e": 24520,
"s": 24192,
"text": "A Unix-style i-node has 10 direct pointers and one single, one double and one triple indirect pointers. Disk block size is 1 Kbyte, disk block address is 32 bits, and 48-bit integers are used. What is the maximum possible file size ?(A) 224 bytes(B) 232 bytes(C) 234 bytes(D) 248 bytesAnswer: (C)Explanation: Image Source: Wiki"
},
{
"code": null,
"e": 25080,
"s": 24520,
"text": "Size of Disk Block = 1Kbyte\n\nDisk Blocks address = 32bits, \nbut 48 bit integers are used for address\nTherefore address size = 6 bytes\n \n\nNo of addresses per block = 1024/6 = 170.66 \nTherefore 170 ≈ 2^8 addresses per block can be stored\n\nMaximum File Size = 10 Direct + 1 Single Indirect + \n 1 Double Indirect + 1 Triple Indirect\n = 10 + 28 + 28*28 + 28*28*28\n ≈ 224 Blocks\n\nSince each block is of size 210 \n\nMaximum files size = 224 * 210 \n = 234 "
},
{
"code": null,
"e": 25102,
"s": 25080,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 25115,
"s": 25102,
"text": "GATE-CS-2004"
},
{
"code": null,
"e": 25133,
"s": 25115,
"text": "GATE-GATE-CS-2004"
},
{
"code": null,
"e": 25138,
"s": 25133,
"text": "GATE"
},
{
"code": null,
"e": 25236,
"s": 25138,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25270,
"s": 25236,
"text": "GATE | GATE-IT-2004 | Question 66"
},
{
"code": null,
"e": 25312,
"s": 25270,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 25354,
"s": 25312,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 25388,
"s": 25354,
"text": "GATE | GATE CS 2010 | Question 24"
},
{
"code": null,
"e": 25421,
"s": 25388,
"text": "GATE | GATE CS 2011 | Question 7"
},
{
"code": null,
"e": 25455,
"s": 25421,
"text": "GATE | GATE-IT-2004 | Question 71"
},
{
"code": null,
"e": 25488,
"s": 25455,
"text": "GATE | GATE-CS-2004 | Question 3"
},
{
"code": null,
"e": 25522,
"s": 25488,
"text": "GATE | GATE CS 2019 | Question 27"
},
{
"code": null,
"e": 25556,
"s": 25522,
"text": "GATE | GATE-CS-2006 | Question 49"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.