title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Newman-Conway Sequence - GeeksforGeeks
|
16 Apr, 2021
Newman-Conway Sequence is the one which generates the following integer sequence. 1 1 2 2 3 4 4 4 5 6 7 7...In mathematical terms, the sequence P(n) of Newman-Conway numbers is defined by recurrence relation
P(n) = P(P(n - 1)) + P(n - P(n - 1))
with seed values P(1) = 1 and P(2) = 1Given a number n, print n-th number in Newman-Conway Sequence.
Examples :
Input : n = 2
Output : 1
Input : n = 10
Output : 6
Method 1 (Use Recursion) :
A simple approach is direct recursive implementation of above recurrence relation.
C++
Java
Python
C#
PHP
Javascript
// C++ program for n-th// element of Newman-Conway Sequence#include <bits/stdc++.h>using namespace std; // Recursive Function to find the n-th elementint sequence(int n){ if (n == 1 || n == 2) return 1; else return sequence(sequence(n - 1)) + sequence(n - sequence(n - 1));} // Driver Programint main(){ int n = 10; cout << sequence(n); return 0;}
// Java program to find nth// element of Newman-Conway Sequenceimport java.io.*; class GFG { // Recursion to find // n-th element static int sequence(int n) { if (n == 1 || n == 2) return 1; else return sequence(sequence(n - 1)) + sequence(n - sequence(n - 1)); } // Driver Program public static void main(String args[]) { int n = 10; System.out.println(sequence(n)); }} /*This code is contributed by Nikita Tiwari.*/
# Recursive function to find the n-th# element of sequencedef sequence(n): if n == 1 or n == 2: return 1 else: return sequence(sequence(n-1)) + sequence(n-sequence(n-1)); # Driver codedef main(): n = 10 print sequence(n) if __name__ == '__main__': main()
// C# program to find nth element// of Newman-Conway Sequenceusing System; class GFG { // Recursion to find // n-th element static int sequence(int n) { if (n == 1 || n == 2) return 1; else return sequence(sequence(n - 1)) + sequence (n - sequence(n - 1)); } // Driver code public static void Main() { int n = 10; Console.Write(sequence(n)); }} // This code is contributed by Nitin Mittal.
<?php// PHP program for n-th element// of Newman-Conway Sequence // Recursive Function to// find the n-th elementfunction sequence($n){ if ($n == 1 || $n == 2) return 1; else return sequence(sequence($n - 1))+ sequence($n - sequence($n - 1));} // Driver Code$n = 10;echo(sequence($n)); // This code is contributed by Ajit.?>
<script> // JavaScript program to find nth// element of Newman-Conway Sequence // Recursion to find// n-th elementfunction sequence(n){ if (n == 1 || n == 2) return 1; else return sequence(sequence(n - 1)) + sequence(n - sequence(n - 1));} // Driver codelet n = 10;document.write(sequence(n)); // This code is contributed by souravghosh0416 </script>
Output :
6
Method 2 (Use Dynamic Programming) : We can avoid repeated work done in method 1 by storing the values in the sequence in an array.
C++
Java
Python
C#
PHP
Javascript
// C++ program to find the n-th element of// Newman-Conway Sequence#include <bits/stdc++.h>using namespace std; // Function to find the n-th elementint sequence(int n){ // Declare array to store sequence int f[n + 1]; int i; f[0] = 0; f[1] = 1; f[2] = 1; for (i = 3; i <= n; i++) f[i] = f[f[i - 1]] + f[i - f[i - 1]]; return f[n];} // Driver Programint main(){ int n = 10; cout << sequence(n); return 0;}
// JAVA Code for Newman-Conway Sequenceimport java.util.*; class GFG { // Function to find the n-th element static int sequence(int n) { // Declare array to store sequence int f[] = new int[n + 1]; f[0] = 0; f[1] = 1; f[2] = 1; int i; for (i = 3; i <= n; i++) f[i] = f[f[i - 1]] + f[i - f[i - 1]]; return f[n]; } /* Driver program to test above function */ public static void main(String[] args) { int n = 10; System.out.println(sequence(n)); }} // This code is contributed by Arnav Kr. Mandal.
''' Python program to find the n-th element of Newman-Conway Sequence''' # To declare array import module arrayimport arraydef sequence(n): f = array.array('i', [0, 1, 1]) # To store values of sequence in array for i in range(3, n + 1): r = f[f[i-1]]+f[i-f[i-1]] f.append(r); return r # Driver codedef main(): n = 10 print sequence(n) if __name__ == '__main__': main()
// C# Code for Newman-Conway Sequenceusing System; class GFG { // Function to find the n-th element static int sequence(int n) { // Declare array to store sequence int []f = new int[n + 1]; f[0] = 0; f[1] = 1; f[2] = 1; int i; for (i = 3; i <= n; i++) f[i] = f[f[i - 1]] + f[i - f[i - 1]]; return f[n]; } // Driver Code public static void Main() { int n = 10; Console.Write(sequence(n)); }} // This code is contributed by Nitin Mittal.
<?php// PHP program to find the n-th element // of Newman-Conway Sequence // Function to find// the n-th elementfunction sequence($n){ // Declare array to // store sequence $i; $f[0] = 0; $f[1] = 1; $f[2] = 1; for ($i = 3; $i <= $n; $i++) $f[$i] = $f[$f[$i - 1]] + $f[$i - $f[$i - 1]]; return $f[$n];} // Driver Code$n = 10;echo(sequence($n)); // This code is contributed by Ajit.?>
<script>// Javascript program to find the n-th element// of Newman-Conway Sequence // Function to find// the n-th elementfunction sequence(n){ // Declare array to // store sequence let i; let f = []; f[0] = 0; f[1] = 1; f[2] = 1; for (let i = 3; i <= n; i++) f[i] = f[f[i - 1]] + f[i - f[i - 1]]; return f[n];} // Driver Codelet n = 10;document.write(sequence(n)); // This code is contributed by gfgking.</script>
Output :
6
Time Complexity : O(n)References : https://archive.lib.msu.edu/crcmath/math/math/n/n078.htm
nitin mittal
jit_t
souravghosh0416
gfgking
series
Dynamic Programming
Mathematical
Dynamic Programming
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
BellmanβFord Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Subset Sum Problem | DP-25
Matrix Chain Multiplication | DP-8
Coin Change | DP-7
C++ Data Types
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
Coin Change | DP-7
Merge two sorted arrays
|
[
{
"code": null,
"e": 24966,
"s": 24938,
"text": "\n16 Apr, 2021"
},
{
"code": null,
"e": 25175,
"s": 24966,
"text": "Newman-Conway Sequence is the one which generates the following integer sequence. 1 1 2 2 3 4 4 4 5 6 7 7...In mathematical terms, the sequence P(n) of Newman-Conway numbers is defined by recurrence relation "
},
{
"code": null,
"e": 25213,
"s": 25175,
"text": "P(n) = P(P(n - 1)) + P(n - P(n - 1)) "
},
{
"code": null,
"e": 25314,
"s": 25213,
"text": "with seed values P(1) = 1 and P(2) = 1Given a number n, print n-th number in Newman-Conway Sequence."
},
{
"code": null,
"e": 25327,
"s": 25314,
"text": "Examples : "
},
{
"code": null,
"e": 25379,
"s": 25327,
"text": "Input : n = 2\nOutput : 1\n\nInput : n = 10\nOutput : 6"
},
{
"code": null,
"e": 25407,
"s": 25379,
"text": "Method 1 (Use Recursion) : "
},
{
"code": null,
"e": 25492,
"s": 25407,
"text": "A simple approach is direct recursive implementation of above recurrence relation. "
},
{
"code": null,
"e": 25496,
"s": 25492,
"text": "C++"
},
{
"code": null,
"e": 25501,
"s": 25496,
"text": "Java"
},
{
"code": null,
"e": 25508,
"s": 25501,
"text": "Python"
},
{
"code": null,
"e": 25511,
"s": 25508,
"text": "C#"
},
{
"code": null,
"e": 25515,
"s": 25511,
"text": "PHP"
},
{
"code": null,
"e": 25526,
"s": 25515,
"text": "Javascript"
},
{
"code": "// C++ program for n-th// element of Newman-Conway Sequence#include <bits/stdc++.h>using namespace std; // Recursive Function to find the n-th elementint sequence(int n){ if (n == 1 || n == 2) return 1; else return sequence(sequence(n - 1)) + sequence(n - sequence(n - 1));} // Driver Programint main(){ int n = 10; cout << sequence(n); return 0;}",
"e": 25918,
"s": 25526,
"text": null
},
{
"code": "// Java program to find nth// element of Newman-Conway Sequenceimport java.io.*; class GFG { // Recursion to find // n-th element static int sequence(int n) { if (n == 1 || n == 2) return 1; else return sequence(sequence(n - 1)) + sequence(n - sequence(n - 1)); } // Driver Program public static void main(String args[]) { int n = 10; System.out.println(sequence(n)); }} /*This code is contributed by Nikita Tiwari.*/",
"e": 26441,
"s": 25918,
"text": null
},
{
"code": "# Recursive function to find the n-th# element of sequencedef sequence(n): if n == 1 or n == 2: return 1 else: return sequence(sequence(n-1)) + sequence(n-sequence(n-1)); # Driver codedef main(): n = 10 print sequence(n) if __name__ == '__main__': main()",
"e": 26737,
"s": 26441,
"text": null
},
{
"code": "// C# program to find nth element// of Newman-Conway Sequenceusing System; class GFG { // Recursion to find // n-th element static int sequence(int n) { if (n == 1 || n == 2) return 1; else return sequence(sequence(n - 1)) + sequence (n - sequence(n - 1)); } // Driver code public static void Main() { int n = 10; Console.Write(sequence(n)); }} // This code is contributed by Nitin Mittal.",
"e": 27240,
"s": 26737,
"text": null
},
{
"code": "<?php// PHP program for n-th element// of Newman-Conway Sequence // Recursive Function to// find the n-th elementfunction sequence($n){ if ($n == 1 || $n == 2) return 1; else return sequence(sequence($n - 1))+ sequence($n - sequence($n - 1));} // Driver Code$n = 10;echo(sequence($n)); // This code is contributed by Ajit.?>",
"e": 27599,
"s": 27240,
"text": null
},
{
"code": "<script> // JavaScript program to find nth// element of Newman-Conway Sequence // Recursion to find// n-th elementfunction sequence(n){ if (n == 1 || n == 2) return 1; else return sequence(sequence(n - 1)) + sequence(n - sequence(n - 1));} // Driver codelet n = 10;document.write(sequence(n)); // This code is contributed by souravghosh0416 </script>",
"e": 27982,
"s": 27599,
"text": null
},
{
"code": null,
"e": 27992,
"s": 27982,
"text": "Output : "
},
{
"code": null,
"e": 27994,
"s": 27992,
"text": "6"
},
{
"code": null,
"e": 28127,
"s": 27994,
"text": "Method 2 (Use Dynamic Programming) : We can avoid repeated work done in method 1 by storing the values in the sequence in an array. "
},
{
"code": null,
"e": 28131,
"s": 28127,
"text": "C++"
},
{
"code": null,
"e": 28136,
"s": 28131,
"text": "Java"
},
{
"code": null,
"e": 28143,
"s": 28136,
"text": "Python"
},
{
"code": null,
"e": 28146,
"s": 28143,
"text": "C#"
},
{
"code": null,
"e": 28150,
"s": 28146,
"text": "PHP"
},
{
"code": null,
"e": 28161,
"s": 28150,
"text": "Javascript"
},
{
"code": "// C++ program to find the n-th element of// Newman-Conway Sequence#include <bits/stdc++.h>using namespace std; // Function to find the n-th elementint sequence(int n){ // Declare array to store sequence int f[n + 1]; int i; f[0] = 0; f[1] = 1; f[2] = 1; for (i = 3; i <= n; i++) f[i] = f[f[i - 1]] + f[i - f[i - 1]]; return f[n];} // Driver Programint main(){ int n = 10; cout << sequence(n); return 0;}",
"e": 28611,
"s": 28161,
"text": null
},
{
"code": "// JAVA Code for Newman-Conway Sequenceimport java.util.*; class GFG { // Function to find the n-th element static int sequence(int n) { // Declare array to store sequence int f[] = new int[n + 1]; f[0] = 0; f[1] = 1; f[2] = 1; int i; for (i = 3; i <= n; i++) f[i] = f[f[i - 1]] + f[i - f[i - 1]]; return f[n]; } /* Driver program to test above function */ public static void main(String[] args) { int n = 10; System.out.println(sequence(n)); }} // This code is contributed by Arnav Kr. Mandal.",
"e": 29263,
"s": 28611,
"text": null
},
{
"code": "''' Python program to find the n-th element of Newman-Conway Sequence''' # To declare array import module arrayimport arraydef sequence(n): f = array.array('i', [0, 1, 1]) # To store values of sequence in array for i in range(3, n + 1): r = f[f[i-1]]+f[i-f[i-1]] f.append(r); return r # Driver codedef main(): n = 10 print sequence(n) if __name__ == '__main__': main()",
"e": 29676,
"s": 29263,
"text": null
},
{
"code": "// C# Code for Newman-Conway Sequenceusing System; class GFG { // Function to find the n-th element static int sequence(int n) { // Declare array to store sequence int []f = new int[n + 1]; f[0] = 0; f[1] = 1; f[2] = 1; int i; for (i = 3; i <= n; i++) f[i] = f[f[i - 1]] + f[i - f[i - 1]]; return f[n]; } // Driver Code public static void Main() { int n = 10; Console.Write(sequence(n)); }} // This code is contributed by Nitin Mittal.",
"e": 30257,
"s": 29676,
"text": null
},
{
"code": "<?php// PHP program to find the n-th element // of Newman-Conway Sequence // Function to find// the n-th elementfunction sequence($n){ // Declare array to // store sequence $i; $f[0] = 0; $f[1] = 1; $f[2] = 1; for ($i = 3; $i <= $n; $i++) $f[$i] = $f[$f[$i - 1]] + $f[$i - $f[$i - 1]]; return $f[$n];} // Driver Code$n = 10;echo(sequence($n)); // This code is contributed by Ajit.?>",
"e": 30694,
"s": 30257,
"text": null
},
{
"code": "<script>// Javascript program to find the n-th element// of Newman-Conway Sequence // Function to find// the n-th elementfunction sequence(n){ // Declare array to // store sequence let i; let f = []; f[0] = 0; f[1] = 1; f[2] = 1; for (let i = 3; i <= n; i++) f[i] = f[f[i - 1]] + f[i - f[i - 1]]; return f[n];} // Driver Codelet n = 10;document.write(sequence(n)); // This code is contributed by gfgking.</script>",
"e": 31164,
"s": 30694,
"text": null
},
{
"code": null,
"e": 31174,
"s": 31164,
"text": "Output : "
},
{
"code": null,
"e": 31176,
"s": 31174,
"text": "6"
},
{
"code": null,
"e": 31269,
"s": 31176,
"text": "Time Complexity : O(n)References : https://archive.lib.msu.edu/crcmath/math/math/n/n078.htm "
},
{
"code": null,
"e": 31282,
"s": 31269,
"text": "nitin mittal"
},
{
"code": null,
"e": 31288,
"s": 31282,
"text": "jit_t"
},
{
"code": null,
"e": 31304,
"s": 31288,
"text": "souravghosh0416"
},
{
"code": null,
"e": 31312,
"s": 31304,
"text": "gfgking"
},
{
"code": null,
"e": 31319,
"s": 31312,
"text": "series"
},
{
"code": null,
"e": 31339,
"s": 31319,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 31352,
"s": 31339,
"text": "Mathematical"
},
{
"code": null,
"e": 31372,
"s": 31352,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 31385,
"s": 31372,
"text": "Mathematical"
},
{
"code": null,
"e": 31392,
"s": 31385,
"text": "series"
},
{
"code": null,
"e": 31490,
"s": 31392,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31521,
"s": 31490,
"text": "BellmanβFord Algorithm | DP-23"
},
{
"code": null,
"e": 31554,
"s": 31521,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 31581,
"s": 31554,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 31616,
"s": 31581,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 31635,
"s": 31616,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 31650,
"s": 31635,
"text": "C++ Data Types"
},
{
"code": null,
"e": 31693,
"s": 31650,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 31753,
"s": 31693,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 31772,
"s": 31753,
"text": "Coin Change | DP-7"
}
] |
Passing By Pointer Vs Passing By Reference in C++ - GeeksforGeeks
|
13 Jan, 2022
In C++, we can pass parameters to a function either by pointers or by reference. In both cases, we get the same result. So, what is the difference between Passing by Pointer and Passing by Reference in C++?
Lets first understand what Passing by Pointer and Passing by Reference in C++ mean:1) Passing by Pointer: Here, the memory location of the variables is passed to the parameters in the function, and then the operations are performed.
CPP
// C++ program to swap two numbers using// pass by pointer#include <iostream>using namespace std; void swap(int *x, int *y){ int z = *x; *x = *y; *y = z;} // Driver Codeint main(){ int a = 45, b = 35; cout << "Before Swap\n"; cout << "a = " << a << " b = " << b << "\n"; swap(&a, &b); cout << "After Swap with pass by pointer\n"; cout << "a = " << a << " b = " << b << "\n";}
Before Swap
a = 45 b = 35
After Swap with pass by pointer
a = 35 b = 45
2) Passing by Reference: It allows a function to modify a variable without having to create a copy of it. We have to declare reference variables. The memory location of the passed variable and parameter is the same and therefore, any change to the parameter reflects in the variable as well.
CPP
// C++ program to swap two numbers using// pass by reference #include <iostream>using namespace std;void swap(int& x, int& y){ int z = x; x = y; y = z;} int main(){ int a = 45, b = 35; cout << "Before Swap\n"; cout << "a = " << a << " b = " << b << "\n"; swap(a, b); cout << "After Swap with pass by reference\n"; cout << "a = " << a << " b = " << b << "\n";}
Before Swap
a = 45 b = 35
After Swap with pass by reference
a = 35 b = 45
Difference Between Reference Variable and Pointer Variable: A reference is the same object, just with a different name and a reference must refer to an object. Since references canβt be NULL, they are safer to use.
A pointer can be re-assigned while a reference cannot, and must be assigned at initialization only.The pointer can be assigned NULL directly, whereas the reference cannot.Pointers can iterate over an array, we can use increment/decrement operators to go to the next/previous item that a pointer is pointing to.A pointer is a variable that holds a memory address. A reference has the same memory address as the item it references.A pointer to a class/struct uses β->β (arrow operator) to access its members whereas a reference uses a β.β (dot operator)A pointer needs to be dereferenced with * to access the memory location it points to, whereas a reference can be used directly.
A pointer can be re-assigned while a reference cannot, and must be assigned at initialization only.
The pointer can be assigned NULL directly, whereas the reference cannot.
Pointers can iterate over an array, we can use increment/decrement operators to go to the next/previous item that a pointer is pointing to.
A pointer is a variable that holds a memory address. A reference has the same memory address as the item it references.
A pointer to a class/struct uses β->β (arrow operator) to access its members whereas a reference uses a β.β (dot operator)
A pointer needs to be dereferenced with * to access the memory location it points to, whereas a reference can be used directly.
The following example demonstrates the differences:
CPP
// C++ program to demonstrate differences// between pointer and reference#include <iostream>using namespace std; struct demo { int a;}; int main(){ int x = 5; int y = 6; demo d; int* p; p = &x; p = &y; // 1. Pointer reintialization allowed int& r = x; // &r = y; // 1. Compile Error r = y; // 1. x value becomes 6 p = NULL; // &r = NULL; // 2. Compile Error // 3. Points to next memory location p++; // 3. x values becomes 7 r++; cout << &p << " " << &x << '\n'; // 4. Different address cout << &r << " " << &x << '\n'; // 4. Same address demo* q = &d; demo& qq = d; q->a = 8; // q.a = 8; // 5. Compile Error qq.a = 8; // qq->a = 8; // 5. Compile Error // 6. Prints the address cout << p << '\n'; // 6. Print the value of x cout << r << '\n'; return 0;}
0x7ffc7ed95828 0x7ffc7ed95820
0x7ffc7ed95820 0x7ffc7ed95820
0x4
7
Which is preferred in Passing by Pointer Vs Passing by Reference in C++?
References are usually preferred over pointers whenever we donβt need βreseatingβ.
Overall, Use references when you can, and pointers when you have to. But if we want to write C code that compiles with both C and a C++ compiler, youβll have to restrict yourself to using pointers.
This article is contributed by Rohit Kasle. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
jpd20
anshikajain26
kziemianfvt
cpp-parameter-passing
cpp-references
pointer
C Language
C++
CPP
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++
Command line arguments in C/C++
Core Dump (Segmentation fault) in C/C++
Left Shift and Right Shift Operators in C/C++
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
Multidimensional Arrays in C / C++
Socket Programming in C/C++
|
[
{
"code": null,
"e": 24308,
"s": 24280,
"text": "\n13 Jan, 2022"
},
{
"code": null,
"e": 24515,
"s": 24308,
"text": "In C++, we can pass parameters to a function either by pointers or by reference. In both cases, we get the same result. So, what is the difference between Passing by Pointer and Passing by Reference in C++?"
},
{
"code": null,
"e": 24748,
"s": 24515,
"text": "Lets first understand what Passing by Pointer and Passing by Reference in C++ mean:1) Passing by Pointer: Here, the memory location of the variables is passed to the parameters in the function, and then the operations are performed."
},
{
"code": null,
"e": 24752,
"s": 24748,
"text": "CPP"
},
{
"code": "// C++ program to swap two numbers using// pass by pointer#include <iostream>using namespace std; void swap(int *x, int *y){ int z = *x; *x = *y; *y = z;} // Driver Codeint main(){ int a = 45, b = 35; cout << \"Before Swap\\n\"; cout << \"a = \" << a << \" b = \" << b << \"\\n\"; swap(&a, &b); cout << \"After Swap with pass by pointer\\n\"; cout << \"a = \" << a << \" b = \" << b << \"\\n\";}",
"e": 25157,
"s": 24752,
"text": null
},
{
"code": null,
"e": 25229,
"s": 25157,
"text": "Before Swap\na = 45 b = 35\nAfter Swap with pass by pointer\na = 35 b = 45"
},
{
"code": null,
"e": 25521,
"s": 25229,
"text": "2) Passing by Reference: It allows a function to modify a variable without having to create a copy of it. We have to declare reference variables. The memory location of the passed variable and parameter is the same and therefore, any change to the parameter reflects in the variable as well."
},
{
"code": null,
"e": 25525,
"s": 25521,
"text": "CPP"
},
{
"code": "// C++ program to swap two numbers using// pass by reference #include <iostream>using namespace std;void swap(int& x, int& y){ int z = x; x = y; y = z;} int main(){ int a = 45, b = 35; cout << \"Before Swap\\n\"; cout << \"a = \" << a << \" b = \" << b << \"\\n\"; swap(a, b); cout << \"After Swap with pass by reference\\n\"; cout << \"a = \" << a << \" b = \" << b << \"\\n\";}",
"e": 25914,
"s": 25525,
"text": null
},
{
"code": null,
"e": 25988,
"s": 25914,
"text": "Before Swap\na = 45 b = 35\nAfter Swap with pass by reference\na = 35 b = 45"
},
{
"code": null,
"e": 26204,
"s": 25988,
"text": "Difference Between Reference Variable and Pointer Variable: A reference is the same object, just with a different name and a reference must refer to an object. Since references canβt be NULL, they are safer to use. "
},
{
"code": null,
"e": 26883,
"s": 26204,
"text": "A pointer can be re-assigned while a reference cannot, and must be assigned at initialization only.The pointer can be assigned NULL directly, whereas the reference cannot.Pointers can iterate over an array, we can use increment/decrement operators to go to the next/previous item that a pointer is pointing to.A pointer is a variable that holds a memory address. A reference has the same memory address as the item it references.A pointer to a class/struct uses β->β (arrow operator) to access its members whereas a reference uses a β.β (dot operator)A pointer needs to be dereferenced with * to access the memory location it points to, whereas a reference can be used directly."
},
{
"code": null,
"e": 26983,
"s": 26883,
"text": "A pointer can be re-assigned while a reference cannot, and must be assigned at initialization only."
},
{
"code": null,
"e": 27056,
"s": 26983,
"text": "The pointer can be assigned NULL directly, whereas the reference cannot."
},
{
"code": null,
"e": 27196,
"s": 27056,
"text": "Pointers can iterate over an array, we can use increment/decrement operators to go to the next/previous item that a pointer is pointing to."
},
{
"code": null,
"e": 27316,
"s": 27196,
"text": "A pointer is a variable that holds a memory address. A reference has the same memory address as the item it references."
},
{
"code": null,
"e": 27439,
"s": 27316,
"text": "A pointer to a class/struct uses β->β (arrow operator) to access its members whereas a reference uses a β.β (dot operator)"
},
{
"code": null,
"e": 27567,
"s": 27439,
"text": "A pointer needs to be dereferenced with * to access the memory location it points to, whereas a reference can be used directly."
},
{
"code": null,
"e": 27619,
"s": 27567,
"text": "The following example demonstrates the differences:"
},
{
"code": null,
"e": 27623,
"s": 27619,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate differences// between pointer and reference#include <iostream>using namespace std; struct demo { int a;}; int main(){ int x = 5; int y = 6; demo d; int* p; p = &x; p = &y; // 1. Pointer reintialization allowed int& r = x; // &r = y; // 1. Compile Error r = y; // 1. x value becomes 6 p = NULL; // &r = NULL; // 2. Compile Error // 3. Points to next memory location p++; // 3. x values becomes 7 r++; cout << &p << \" \" << &x << '\\n'; // 4. Different address cout << &r << \" \" << &x << '\\n'; // 4. Same address demo* q = &d; demo& qq = d; q->a = 8; // q.a = 8; // 5. Compile Error qq.a = 8; // qq->a = 8; // 5. Compile Error // 6. Prints the address cout << p << '\\n'; // 6. Print the value of x cout << r << '\\n'; return 0;}",
"e": 28532,
"s": 27623,
"text": null
},
{
"code": null,
"e": 28598,
"s": 28532,
"text": "0x7ffc7ed95828 0x7ffc7ed95820\n0x7ffc7ed95820 0x7ffc7ed95820\n0x4\n7"
},
{
"code": null,
"e": 28672,
"s": 28598,
"text": "Which is preferred in Passing by Pointer Vs Passing by Reference in C++? "
},
{
"code": null,
"e": 28755,
"s": 28672,
"text": "References are usually preferred over pointers whenever we donβt need βreseatingβ."
},
{
"code": null,
"e": 28953,
"s": 28755,
"text": "Overall, Use references when you can, and pointers when you have to. But if we want to write C code that compiles with both C and a C++ compiler, youβll have to restrict yourself to using pointers."
},
{
"code": null,
"e": 29123,
"s": 28953,
"text": "This article is contributed by Rohit Kasle. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 29129,
"s": 29123,
"text": "jpd20"
},
{
"code": null,
"e": 29143,
"s": 29129,
"text": "anshikajain26"
},
{
"code": null,
"e": 29155,
"s": 29143,
"text": "kziemianfvt"
},
{
"code": null,
"e": 29177,
"s": 29155,
"text": "cpp-parameter-passing"
},
{
"code": null,
"e": 29192,
"s": 29177,
"text": "cpp-references"
},
{
"code": null,
"e": 29200,
"s": 29192,
"text": "pointer"
},
{
"code": null,
"e": 29211,
"s": 29200,
"text": "C Language"
},
{
"code": null,
"e": 29215,
"s": 29211,
"text": "C++"
},
{
"code": null,
"e": 29219,
"s": 29215,
"text": "CPP"
},
{
"code": null,
"e": 29317,
"s": 29219,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29326,
"s": 29317,
"text": "Comments"
},
{
"code": null,
"e": 29339,
"s": 29326,
"text": "Old Comments"
},
{
"code": null,
"e": 29374,
"s": 29339,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 29402,
"s": 29374,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 29434,
"s": 29402,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 29474,
"s": 29434,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 29520,
"s": 29474,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 29538,
"s": 29520,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 29584,
"s": 29538,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 29627,
"s": 29584,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 29662,
"s": 29627,
"text": "Multidimensional Arrays in C / C++"
}
] |
C# | String class - GeeksforGeeks
|
23 Jan, 2019
In C#, a string is a sequence of Unicode characters or array of characters.
The range of Unicode characters will be U+0000 to U+FFFF. The array of characters is also termed as the text. So the string is the representation of the text. A string is represented by a class System.String.The String class is defined in the .NET base class library. In other words, a String object is a sequential collection of System.Char objects which represent a string. The maximum size of the String object in memory can be 2GB or about 1 billion characters.
Characteristics of String Class:
The System.String class is immutable, i.e once created its state cannot be altered.
With the help of length property, it provides the total number of characters present in the given string.
String objects can include a null character which counts as the part of the stringβs length.
It provides the position of the characters in the given string.
It allows empty strings. Empty strings are the valid instance of String objects that contain zero characters.
A string that has been declared but has not been assigned a value is null. Attempting to call methods on that string throws a NullReferenceException.
It also supports searching strings, comparison of string, testing of equality, modifying the string, normalization of string, copying of strings, etc.
It also provides several ways to create strings like using a constructor, using concatenation, etc.
Example:
// C# program to demonstrate the creation// of string using the constructorusing System;class Geeks { // Main Method public static void Main() { char[] chars = { 'G', 'E', 'E', 'K', 'S' }; // Create a string from a character array. string str1 = new string(chars); Console.WriteLine(str1); // Create a string that consists of // a character repeated 5 times. string str2 = new string('E', 5); Console.WriteLine(str2); }}
GEEKS
EEEEE
Example:
// C# program to demonstrate the// String Class Propertiesusing System; class Geeks { // Main Method public static void Main() { string str = "GeeksforGeeks"; // using Chars[Int32] & Length property for (int i = 0; i <= str.Length - 1; i++) Console.Write("{0} ", str[i]); }}
G e e k s f o r G e e k s
Example:
// C# program to illustrate// String class methodsusing System; class GFG { static void copymethod() { string str1 = "GeeksforGeeks"; string str2 = "geeks"; Console.WriteLine("Original Strings: str1 = " + "'{0}' and str2 ='{1}'", str1, str2); Console.WriteLine(""); Console.WriteLine("After Copy method"); Console.WriteLine(""); // using the Copy method // to copy the value of str1 // into str2 str2 = String.Copy(str1); Console.WriteLine("Strings are str1 = " + "'{0}' and str2='{1}'", str1, str2); } // Main method static public void Main() { // variables string str1 = "geeksforgeeks"; string str2 = "geeksforgeeks"; bool result; // Compare(string, string) method return true // because the given strings are equal result = String.Compare(str1, str2) == 0; Console.WriteLine("Result of Compare Method: " +result); // calling method copymethod(); }}
Result of Compare Method: True
Original Strings: str1 = 'GeeksforGeeks' and str2 ='geeks'
After Copy method
Strings are str1 = 'GeeksforGeeks' and str2='GeeksforGeeks'
Example:
// C# program to illustrate the// Equality and Inequality operatorusing System; class GFG { // Main Method public static void Main(string[] args) { string s1 = "WelcomeToGeeks"; string s2 = "WelcomeToGeeks"; bool result1, result2; // Equality operator return true // as both string are equal result1 = s1 == s2; // Inequality operator return false // as both string are equal result2 = s1 != s2; Console.WriteLine(result1); Console.WriteLine(result2); }}
True
False
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.string?view=netframework-4.7.2#definition
CSharp-string
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Abstract Class and Interface in C#
String.Split() Method in C# with Examples
C# | How to check whether a List contains a specified element
C# | IsNullOrEmpty() Method
C# | Arrays of Strings
C# | Delegates
C# | Abstract Classes
C# | Replace() Method
Extension Method in C#
C# | String.IndexOf( ) Method | Set - 1
|
[
{
"code": null,
"e": 25378,
"s": 25350,
"text": "\n23 Jan, 2019"
},
{
"code": null,
"e": 25454,
"s": 25378,
"text": "In C#, a string is a sequence of Unicode characters or array of characters."
},
{
"code": null,
"e": 25920,
"s": 25454,
"text": "The range of Unicode characters will be U+0000 to U+FFFF. The array of characters is also termed as the text. So the string is the representation of the text. A string is represented by a class System.String.The String class is defined in the .NET base class library. In other words, a String object is a sequential collection of System.Char objects which represent a string. The maximum size of the String object in memory can be 2GB or about 1 billion characters."
},
{
"code": null,
"e": 25953,
"s": 25920,
"text": "Characteristics of String Class:"
},
{
"code": null,
"e": 26037,
"s": 25953,
"text": "The System.String class is immutable, i.e once created its state cannot be altered."
},
{
"code": null,
"e": 26143,
"s": 26037,
"text": "With the help of length property, it provides the total number of characters present in the given string."
},
{
"code": null,
"e": 26236,
"s": 26143,
"text": "String objects can include a null character which counts as the part of the stringβs length."
},
{
"code": null,
"e": 26300,
"s": 26236,
"text": "It provides the position of the characters in the given string."
},
{
"code": null,
"e": 26410,
"s": 26300,
"text": "It allows empty strings. Empty strings are the valid instance of String objects that contain zero characters."
},
{
"code": null,
"e": 26560,
"s": 26410,
"text": "A string that has been declared but has not been assigned a value is null. Attempting to call methods on that string throws a NullReferenceException."
},
{
"code": null,
"e": 26711,
"s": 26560,
"text": "It also supports searching strings, comparison of string, testing of equality, modifying the string, normalization of string, copying of strings, etc."
},
{
"code": null,
"e": 26811,
"s": 26711,
"text": "It also provides several ways to create strings like using a constructor, using concatenation, etc."
},
{
"code": null,
"e": 26820,
"s": 26811,
"text": "Example:"
},
{
"code": "// C# program to demonstrate the creation// of string using the constructorusing System;class Geeks { // Main Method public static void Main() { char[] chars = { 'G', 'E', 'E', 'K', 'S' }; // Create a string from a character array. string str1 = new string(chars); Console.WriteLine(str1); // Create a string that consists of // a character repeated 5 times. string str2 = new string('E', 5); Console.WriteLine(str2); }}",
"e": 27315,
"s": 26820,
"text": null
},
{
"code": null,
"e": 27328,
"s": 27315,
"text": "GEEKS\nEEEEE\n"
},
{
"code": null,
"e": 27337,
"s": 27328,
"text": "Example:"
},
{
"code": "// C# program to demonstrate the// String Class Propertiesusing System; class Geeks { // Main Method public static void Main() { string str = \"GeeksforGeeks\"; // using Chars[Int32] & Length property for (int i = 0; i <= str.Length - 1; i++) Console.Write(\"{0} \", str[i]); }}",
"e": 27670,
"s": 27337,
"text": null
},
{
"code": null,
"e": 27697,
"s": 27670,
"text": "G e e k s f o r G e e k s\n"
},
{
"code": null,
"e": 27706,
"s": 27697,
"text": "Example:"
},
{
"code": "// C# program to illustrate// String class methodsusing System; class GFG { static void copymethod() { string str1 = \"GeeksforGeeks\"; string str2 = \"geeks\"; Console.WriteLine(\"Original Strings: str1 = \" + \"'{0}' and str2 ='{1}'\", str1, str2); Console.WriteLine(\"\"); Console.WriteLine(\"After Copy method\"); Console.WriteLine(\"\"); // using the Copy method // to copy the value of str1 // into str2 str2 = String.Copy(str1); Console.WriteLine(\"Strings are str1 = \" + \"'{0}' and str2='{1}'\", str1, str2); } // Main method static public void Main() { // variables string str1 = \"geeksforgeeks\"; string str2 = \"geeksforgeeks\"; bool result; // Compare(string, string) method return true // because the given strings are equal result = String.Compare(str1, str2) == 0; Console.WriteLine(\"Result of Compare Method: \" +result); // calling method copymethod(); }}",
"e": 28886,
"s": 27706,
"text": null
},
{
"code": null,
"e": 29057,
"s": 28886,
"text": "Result of Compare Method: True\nOriginal Strings: str1 = 'GeeksforGeeks' and str2 ='geeks'\n\nAfter Copy method\n\nStrings are str1 = 'GeeksforGeeks' and str2='GeeksforGeeks'\n"
},
{
"code": null,
"e": 29066,
"s": 29057,
"text": "Example:"
},
{
"code": "// C# program to illustrate the// Equality and Inequality operatorusing System; class GFG { // Main Method public static void Main(string[] args) { string s1 = \"WelcomeToGeeks\"; string s2 = \"WelcomeToGeeks\"; bool result1, result2; // Equality operator return true // as both string are equal result1 = s1 == s2; // Inequality operator return false // as both string are equal result2 = s1 != s2; Console.WriteLine(result1); Console.WriteLine(result2); }}",
"e": 29619,
"s": 29066,
"text": null
},
{
"code": null,
"e": 29631,
"s": 29619,
"text": "True\nFalse\n"
},
{
"code": null,
"e": 29642,
"s": 29631,
"text": "Reference:"
},
{
"code": null,
"e": 29735,
"s": 29642,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.string?view=netframework-4.7.2#definition"
},
{
"code": null,
"e": 29749,
"s": 29735,
"text": "CSharp-string"
},
{
"code": null,
"e": 29752,
"s": 29749,
"text": "C#"
},
{
"code": null,
"e": 29850,
"s": 29752,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29904,
"s": 29850,
"text": "Difference between Abstract Class and Interface in C#"
},
{
"code": null,
"e": 29946,
"s": 29904,
"text": "String.Split() Method in C# with Examples"
},
{
"code": null,
"e": 30008,
"s": 29946,
"text": "C# | How to check whether a List contains a specified element"
},
{
"code": null,
"e": 30036,
"s": 30008,
"text": "C# | IsNullOrEmpty() Method"
},
{
"code": null,
"e": 30059,
"s": 30036,
"text": "C# | Arrays of Strings"
},
{
"code": null,
"e": 30074,
"s": 30059,
"text": "C# | Delegates"
},
{
"code": null,
"e": 30096,
"s": 30074,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 30118,
"s": 30096,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 30141,
"s": 30118,
"text": "Extension Method in C#"
}
] |
How to call a method of a class in C#
|
To call a method, use the name of the method after the object name, for example, β
obj1. Display();
Letβs say the class name is ApplicationOne, so to call the method β
ApplicationOne one = new ApplicationOne();
//calling the displayMax method
ret = one.displayMax(a, b);
The following is the example showing how to call a method in C# β
Live Demo
using System;
namespace Demp {
class ApplicationOne {
public int displayMax(int num1, int num2) {
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
static void Main(string[] args) {
/* local variable definition */
int a = 700;
int b = 400;
int ret;
ApplicationOne one = new ApplicationOne();
ret = one.displayMax(a, b);
Console.WriteLine("Max value is : {0}", ret );
Console.ReadLine();
}
}
}
Max value is : 700
|
[
{
"code": null,
"e": 1145,
"s": 1062,
"text": "To call a method, use the name of the method after the object name, for example, β"
},
{
"code": null,
"e": 1162,
"s": 1145,
"text": "obj1. Display();"
},
{
"code": null,
"e": 1230,
"s": 1162,
"text": "Letβs say the class name is ApplicationOne, so to call the method β"
},
{
"code": null,
"e": 1334,
"s": 1230,
"text": "ApplicationOne one = new ApplicationOne();\n\n//calling the displayMax method\nret = one.displayMax(a, b);"
},
{
"code": null,
"e": 1400,
"s": 1334,
"text": "The following is the example showing how to call a method in C# β"
},
{
"code": null,
"e": 1411,
"s": 1400,
"text": " Live Demo"
},
{
"code": null,
"e": 2037,
"s": 1411,
"text": "using System;\n\nnamespace Demp {\n class ApplicationOne {\n public int displayMax(int num1, int num2) {\n /* local variable declaration */\n int result;\n\n if (num1 > num2)\n result = num1;\n else\n result = num2;\n return result;\n }\n\n static void Main(string[] args) {\n /* local variable definition */\n int a = 700;\n int b = 400;\n int ret;\n ApplicationOne one = new ApplicationOne();\n\n ret = one.displayMax(a, b);\n Console.WriteLine(\"Max value is : {0}\", ret );\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 2056,
"s": 2037,
"text": "Max value is : 700"
}
] |
Angular ng Bootstrap Alert Component - GeeksforGeeks
|
06 Jul, 2021
Angular ng bootstrap is a bootstrap framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites.
In this article, we will see how to use Alert in angular ng bootstrap. Alert is used to provide contextual feedback messages for typical user actions with the handful of available.
Installation syntax:
ng add @ng-bootstrap/ng-bootstrap
Approach:
First, install the angular ng bootstrap using the above-mentioned command.
Import ng bootstrap module in module.tsimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';
imports: [
NgbModule
]
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
imports: [
NgbModule
]
In app.component.html make an alert component.
Serve the app using ng serve.
Example 1:
app.component.html
<p> <ngb-alert [dismissible]="false" type='success'> <strong>GeeksforGeeks</strong> </ngb-alert></p>
app.module.ts
import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule }from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { }
Output:
Example 2:
app.component.html
<p> <ngb-alert [dismissible]="true" type='success'> <strong>GeeksforGeeks</strong> </ngb-alert></p>
app.module.ts
import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule }from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { }
Output:
Reference: https://ng-bootstrap.github.io/#/components/alert/examples
Angular-ng-bootstrap
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Angular PrimeNG Calendar Component
Angular 10 (blur) Event
Angular PrimeNG Messages Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
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": 26354,
"s": 26326,
"text": "\n06 Jul, 2021"
},
{
"code": null,
"e": 26538,
"s": 26354,
"text": "Angular ng bootstrap is a bootstrap framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites."
},
{
"code": null,
"e": 26719,
"s": 26538,
"text": "In this article, we will see how to use Alert in angular ng bootstrap. Alert is used to provide contextual feedback messages for typical user actions with the handful of available."
},
{
"code": null,
"e": 26740,
"s": 26719,
"text": "Installation syntax:"
},
{
"code": null,
"e": 26774,
"s": 26740,
"text": "ng add @ng-bootstrap/ng-bootstrap"
},
{
"code": null,
"e": 26784,
"s": 26774,
"text": "Approach:"
},
{
"code": null,
"e": 26859,
"s": 26784,
"text": "First, install the angular ng bootstrap using the above-mentioned command."
},
{
"code": null,
"e": 26981,
"s": 26859,
"text": "Import ng bootstrap module in module.tsimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';\n\nimports: [\n NgbModule\n]\n"
},
{
"code": null,
"e": 27064,
"s": 26981,
"text": "import { NgbModule } from '@ng-bootstrap/ng-bootstrap';\n\nimports: [\n NgbModule\n]\n"
},
{
"code": null,
"e": 27111,
"s": 27064,
"text": "In app.component.html make an alert component."
},
{
"code": null,
"e": 27141,
"s": 27111,
"text": "Serve the app using ng serve."
},
{
"code": null,
"e": 27154,
"s": 27143,
"text": "Example 1:"
},
{
"code": null,
"e": 27173,
"s": 27154,
"text": "app.component.html"
},
{
"code": "<p> <ngb-alert [dismissible]=\"false\" type='success'> <strong>GeeksforGeeks</strong> </ngb-alert></p>",
"e": 27292,
"s": 27173,
"text": null
},
{
"code": null,
"e": 27306,
"s": 27292,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule }from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { }",
"e": 27911,
"s": 27306,
"text": null
},
{
"code": null,
"e": 27919,
"s": 27911,
"text": "Output:"
},
{
"code": null,
"e": 27930,
"s": 27919,
"text": "Example 2:"
},
{
"code": null,
"e": 27949,
"s": 27930,
"text": "app.component.html"
},
{
"code": "<p> <ngb-alert [dismissible]=\"true\" type='success'> <strong>GeeksforGeeks</strong> </ngb-alert></p>",
"e": 28066,
"s": 27949,
"text": null
},
{
"code": null,
"e": 28080,
"s": 28066,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule }from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { }",
"e": 28686,
"s": 28080,
"text": null
},
{
"code": null,
"e": 28694,
"s": 28686,
"text": "Output:"
},
{
"code": null,
"e": 28764,
"s": 28694,
"text": "Reference: https://ng-bootstrap.github.io/#/components/alert/examples"
},
{
"code": null,
"e": 28785,
"s": 28764,
"text": "Angular-ng-bootstrap"
},
{
"code": null,
"e": 28795,
"s": 28785,
"text": "AngularJS"
},
{
"code": null,
"e": 28812,
"s": 28795,
"text": "Web Technologies"
},
{
"code": null,
"e": 28910,
"s": 28812,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28945,
"s": 28910,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 28980,
"s": 28945,
"text": "Angular PrimeNG Calendar Component"
},
{
"code": null,
"e": 29004,
"s": 28980,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 29039,
"s": 29004,
"text": "Angular PrimeNG Messages Component"
},
{
"code": null,
"e": 29092,
"s": 29039,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 29132,
"s": 29092,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29165,
"s": 29132,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29210,
"s": 29165,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29253,
"s": 29210,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Count ways to reach the n'th stair | Practice | GeeksforGeeks
|
There are n stairs, a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Count the number of ways, the person can reach the top (order does matter).
Example 1:
Input:
n = 4
Output: 5
Explanation:
You can reach 4th stair in 5 ways.
Way 1: Climb 2 stairs at a time.
Way 2: Climb 1 stair at a time.
Way 3: Climb 2 stairs, then 1 stair
and then 1 stair.
Way 4: Climb 1 stair, then 2 stairs
then 1 stair.
Way 5: Climb 1 stair, then 1 stair and
then 2 stairs.
Example 2:
Input:
n = 10
Output: 89
Explanation:
There are 89 ways to reach the 10th stair.
Your Task:
Complete the function countWays() which takes the top stair number m as input parameters and returns the answer % 10^9+7.
Expected Time Complexity : O(n)
Expected Auxiliary Space: O(1)
Constraints:
1 β€ n β€ 104
0
fpouuc6g15gpbb5he4q9k3uvb20hihh1bxzvc7jn3 weeks ago
C++ Solution:
int countWays(int n){
int prev1 = 1,prev2 = 1,MOD = 1e9 + 7;
for(int i = 2; i<=n; i++){
long long curr = 1LL*prev1 + prev2;
prev2 = prev1;
prev1 = curr%MOD;
}
return prev1;
}
+1
danishsharma4963 weeks ago
NO BAKWAS SIMPLE CPP SOLN USING RECURSION AND MEMOIZATION
long long int memo[100000]; int pow = 1000000007; long long int countWays(int n) { if(n ==0 ) return 1 ; if(n < 0 ) return 0 ; if(memo[n]!= 0 ) return memo[n]; memo[n] = (countWays(n-1) + countWays(n-2) ) %pow; return memo[n]; }
0
devashishbakare1 month ago
JAVA : Using DP(Tabulation)
public static int solve(int n, int tab[])
{
tab[0] = 1;
int pow = 1000000007;
for(int i = 1 ; i <= n ; i++)
{
if(i == 1)
tab[i] = tab[i-1];
else{
tab[i] = (tab[i-1] + tab[i-2])%pow;
}
}
return tab[n];
}
0
sudhanshujha9611 month ago
Dp + Space Optimisation
int countWays(int n)
{
// your code here
int prev = 1 , prev2 = 1;
for(int i = 2; i<=n; i++){
int curr = (prev + prev2)%1000000007;
prev2 = prev;
prev = curr;
}
return prev;
}
0
dronzerdracel1 month ago
Recursion+Memoization
int fib(int n,int *dp){
if(n<0)
return dp[n]=0;
if(n==0)
return dp[n]=1;
if(dp[n]!=-1)
return dp[n];
dp[n]=(fib(n-1,dp)+fib(n-2,dp))%1000000007;
return dp[n];
}
int countWays(int n)
{
// your code here
int dp[n+1];
memset(dp,-1,sizeof(dp));
fib(n,dp);
return dp[n];
}
+1
ashayvsant1 month ago
Simple Recursive solution in Java -
class Solution
{
static int dp[];
//Function to count number of ways to reach the nth stair.
int countWays(int n)
{
// your code here
dp = new int[n];
for(int i=0; i<n; i++) dp[i] = -1;
return solve(n, 1);
}
int solve(int n, int currentStair) {
if(currentStair >= n) return 1;
if(dp[currentStair] != -1)
return dp[currentStair];
dp[currentStair] = (solve(n, currentStair+1) + solve(n, currentStair+2))%(1000000007);
return dp[currentStair];
}
}
0
harshsinghreal2 months ago
VERY SIMPLE C++ SOLUTION-β
Hope you like it (kindly up vote it π).
int countWays(int n)
{
int a = 1, b = 1,j;
for (int i = 1;i < n;i++) {
j=b;
b=(b+a)%1000000007;
a = j;
}
return b;
}
+2
sdmrf2 months ago
Python Soln:
def countWays(self,n,memo={}):
mod=10**9+7
if n in memo:
return memo[n]%mod
elif n==0 or n==1:
return 1
elif n==2:
return 2
else:
memo[n]= self.countWays(n-1,memo)%mod + self.countWays(n-2,memo)%mod
return memo[n]%mod
+1
kashyapjhon2 months ago
C++ Solution Using DP Time=(0.0/1.1):
long long int mod= 1000000007; int help(vector<int> &dp,int sum,int n){ if(sum==0 || sum==1){ return 1; } if(dp[sum]!=-1){ return dp[sum]; } if(sum>=2){ return dp[sum]=(help(dp,sum-2,n)+help(dp,sum-1,n))%mod; } } int countWays(int n) { // your code here int count=0; vector<int> dp(n+1,-1); int sum=n; return help(dp,sum,n); }
0
kuldeepy104592 months ago
int mod =1e9+7; int countWays(int n) { // your code here vector<int>output(n+1); output[0]=1; output[1]=1; for(int i=2;i<=n;i++){ output[i]=(output[i-1]+output[i-2])%mod; } return output[n]%mod; }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 449,
"s": 238,
"text": "There are n stairs, a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Count the number of ways, the person can reach the top (order does matter)."
},
{
"code": null,
"e": 460,
"s": 449,
"text": "Example 1:"
},
{
"code": null,
"e": 757,
"s": 460,
"text": "Input:\nn = 4\nOutput: 5\nExplanation:\nYou can reach 4th stair in 5 ways. \nWay 1: Climb 2 stairs at a time. \nWay 2: Climb 1 stair at a time.\nWay 3: Climb 2 stairs, then 1 stair\nand then 1 stair.\nWay 4: Climb 1 stair, then 2 stairs\nthen 1 stair.\nWay 5: Climb 1 stair, then 1 stair and\nthen 2 stairs.\n"
},
{
"code": null,
"e": 768,
"s": 757,
"text": "Example 2:"
},
{
"code": null,
"e": 852,
"s": 768,
"text": "Input:\nn = 10\nOutput: 89 \nExplanation: \nThere are 89 ways to reach the 10th stair.\n"
},
{
"code": null,
"e": 985,
"s": 852,
"text": "Your Task:\nComplete the function countWays() which takes the top stair number m as input parameters and returns the answer % 10^9+7."
},
{
"code": null,
"e": 1048,
"s": 985,
"text": "Expected Time Complexity : O(n)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1073,
"s": 1048,
"text": "Constraints:\n1 β€ n β€ 104"
},
{
"code": null,
"e": 1075,
"s": 1073,
"text": "0"
},
{
"code": null,
"e": 1127,
"s": 1075,
"text": "fpouuc6g15gpbb5he4q9k3uvb20hihh1bxzvc7jn3 weeks ago"
},
{
"code": null,
"e": 1141,
"s": 1127,
"text": "C++ Solution:"
},
{
"code": null,
"e": 1388,
"s": 1141,
"text": "int countWays(int n){\n int prev1 = 1,prev2 = 1,MOD = 1e9 + 7;\n for(int i = 2; i<=n; i++){\n long long curr = 1LL*prev1 + prev2;\n prev2 = prev1;\n prev1 = curr%MOD;\n }\n return prev1;\n }"
},
{
"code": null,
"e": 1391,
"s": 1388,
"text": "+1"
},
{
"code": null,
"e": 1418,
"s": 1391,
"text": "danishsharma4963 weeks ago"
},
{
"code": null,
"e": 1476,
"s": 1418,
"text": "NO BAKWAS SIMPLE CPP SOLN USING RECURSION AND MEMOIZATION"
},
{
"code": null,
"e": 1777,
"s": 1478,
"text": " long long int memo[100000]; int pow = 1000000007; long long int countWays(int n) { if(n ==0 ) return 1 ; if(n < 0 ) return 0 ; if(memo[n]!= 0 ) return memo[n]; memo[n] = (countWays(n-1) + countWays(n-2) ) %pow; return memo[n]; }"
},
{
"code": null,
"e": 1779,
"s": 1777,
"text": "0"
},
{
"code": null,
"e": 1806,
"s": 1779,
"text": "devashishbakare1 month ago"
},
{
"code": null,
"e": 1834,
"s": 1806,
"text": "JAVA : Using DP(Tabulation)"
},
{
"code": null,
"e": 2176,
"s": 1834,
"text": " public static int solve(int n, int tab[])\n {\n tab[0] = 1;\n int pow = 1000000007;\n \n for(int i = 1 ; i <= n ; i++)\n {\n if(i == 1)\n tab[i] = tab[i-1];\n else{\n tab[i] = (tab[i-1] + tab[i-2])%pow;\n }\n }\n return tab[n];\n \n }"
},
{
"code": null,
"e": 2178,
"s": 2176,
"text": "0"
},
{
"code": null,
"e": 2205,
"s": 2178,
"text": "sudhanshujha9611 month ago"
},
{
"code": null,
"e": 2229,
"s": 2205,
"text": "Dp + Space Optimisation"
},
{
"code": null,
"e": 2487,
"s": 2229,
"text": " int countWays(int n)\n {\n // your code here\n int prev = 1 , prev2 = 1;\n for(int i = 2; i<=n; i++){\n int curr = (prev + prev2)%1000000007;\n prev2 = prev;\n prev = curr;\n }\n return prev;\n }"
},
{
"code": null,
"e": 2489,
"s": 2487,
"text": "0"
},
{
"code": null,
"e": 2514,
"s": 2489,
"text": "dronzerdracel1 month ago"
},
{
"code": null,
"e": 2536,
"s": 2514,
"text": "Recursion+Memoization"
},
{
"code": null,
"e": 2928,
"s": 2536,
"text": "int fib(int n,int *dp){\n if(n<0)\n return dp[n]=0;\n if(n==0)\n return dp[n]=1;\n if(dp[n]!=-1)\n return dp[n];\n dp[n]=(fib(n-1,dp)+fib(n-2,dp))%1000000007;\n return dp[n];\n }\n int countWays(int n)\n {\n // your code here\n int dp[n+1];\n memset(dp,-1,sizeof(dp));\n fib(n,dp);\n return dp[n];\n }"
},
{
"code": null,
"e": 2931,
"s": 2928,
"text": "+1"
},
{
"code": null,
"e": 2953,
"s": 2931,
"text": "ashayvsant1 month ago"
},
{
"code": null,
"e": 2989,
"s": 2953,
"text": "Simple Recursive solution in Java -"
},
{
"code": null,
"e": 3561,
"s": 2989,
"text": "class Solution\n{\n static int dp[];\n //Function to count number of ways to reach the nth stair.\n int countWays(int n)\n {\n // your code here\n dp = new int[n];\n for(int i=0; i<n; i++) dp[i] = -1;\n return solve(n, 1);\n }\n \n int solve(int n, int currentStair) {\n if(currentStair >= n) return 1;\n \n if(dp[currentStair] != -1)\n return dp[currentStair];\n \n dp[currentStair] = (solve(n, currentStair+1) + solve(n, currentStair+2))%(1000000007);\n return dp[currentStair];\n }\n}"
},
{
"code": null,
"e": 3563,
"s": 3561,
"text": "0"
},
{
"code": null,
"e": 3590,
"s": 3563,
"text": "harshsinghreal2 months ago"
},
{
"code": null,
"e": 3617,
"s": 3590,
"text": "VERY SIMPLE C++ SOLUTION-β"
},
{
"code": null,
"e": 3658,
"s": 3617,
"text": "Hope you like it (kindly up vote it π)."
},
{
"code": null,
"e": 3839,
"s": 3658,
"text": "int countWays(int n)\n {\n \n int a = 1, b = 1,j;\n for (int i = 1;i < n;i++) {\n j=b;\n b=(b+a)%1000000007;\n a = j;\n }\n return b;\n }"
},
{
"code": null,
"e": 3842,
"s": 3839,
"text": "+2"
},
{
"code": null,
"e": 3860,
"s": 3842,
"text": "sdmrf2 months ago"
},
{
"code": null,
"e": 3873,
"s": 3860,
"text": "Python Soln:"
},
{
"code": null,
"e": 4185,
"s": 3873,
"text": " def countWays(self,n,memo={}):\n mod=10**9+7\n if n in memo:\n return memo[n]%mod\n elif n==0 or n==1:\n return 1\n elif n==2:\n return 2\n else:\n memo[n]= self.countWays(n-1,memo)%mod + self.countWays(n-2,memo)%mod\n return memo[n]%mod"
},
{
"code": null,
"e": 4188,
"s": 4185,
"text": "+1"
},
{
"code": null,
"e": 4212,
"s": 4188,
"text": "kashyapjhon2 months ago"
},
{
"code": null,
"e": 4250,
"s": 4212,
"text": "C++ Solution Using DP Time=(0.0/1.1):"
},
{
"code": null,
"e": 4693,
"s": 4250,
"text": "long long int mod= 1000000007; int help(vector<int> &dp,int sum,int n){ if(sum==0 || sum==1){ return 1; } if(dp[sum]!=-1){ return dp[sum]; } if(sum>=2){ return dp[sum]=(help(dp,sum-2,n)+help(dp,sum-1,n))%mod; } } int countWays(int n) { // your code here int count=0; vector<int> dp(n+1,-1); int sum=n; return help(dp,sum,n); }"
},
{
"code": null,
"e": 4695,
"s": 4693,
"text": "0"
},
{
"code": null,
"e": 4721,
"s": 4695,
"text": "kuldeepy104592 months ago"
},
{
"code": null,
"e": 4977,
"s": 4721,
"text": " int mod =1e9+7; int countWays(int n) { // your code here vector<int>output(n+1); output[0]=1; output[1]=1; for(int i=2;i<=n;i++){ output[i]=(output[i-1]+output[i-2])%mod; } return output[n]%mod; }"
},
{
"code": null,
"e": 5123,
"s": 4977,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 5159,
"s": 5123,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5169,
"s": 5159,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5179,
"s": 5169,
"text": "\nContest\n"
},
{
"code": null,
"e": 5242,
"s": 5179,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5390,
"s": 5242,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 5598,
"s": 5390,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 5704,
"s": 5598,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Java Program to evaluate mathematical expressions in String
|
To evaluate mathematical expression in String, use Nashorn JavaScript in Java i.e. scripting. Nashorn invoke dynamics feature, introduced in Java 7 to improve performance.
For scripting, use the ScriptEngineManager class for the engine β
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript");
Now for JavaScript code from string, use eval i.e. execute the script. Here, we are evaluating mathematical expressions in a string β
Object ob = scriptEngine.eval("9 + 15 + 30");
System.out.println("Result of evaluating mathematical expressions in String = "+ob);
Live Demo
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class Main {
public static void main(String[] args) throws Exception {
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript");
// JavaScript code from String
Object ob = scriptEngine.eval("9 + 15 + 30");
System.out.println("Result of evaluating mathematical expressions in String = "+ob);
}
}
Result of evaluating mathematical expressions in String = 54
|
[
{
"code": null,
"e": 1234,
"s": 1062,
"text": "To evaluate mathematical expression in String, use Nashorn JavaScript in Java i.e. scripting. Nashorn invoke dynamics feature, introduced in Java 7 to improve performance."
},
{
"code": null,
"e": 1300,
"s": 1234,
"text": "For scripting, use the ScriptEngineManager class for the engine β"
},
{
"code": null,
"e": 1448,
"s": 1300,
"text": "ScriptEngineManager scriptEngineManager = new ScriptEngineManager();\nScriptEngine scriptEngine = scriptEngineManager.getEngineByName(\"JavaScript\");"
},
{
"code": null,
"e": 1582,
"s": 1448,
"text": "Now for JavaScript code from string, use eval i.e. execute the script. Here, we are evaluating mathematical expressions in a string β"
},
{
"code": null,
"e": 1713,
"s": 1582,
"text": "Object ob = scriptEngine.eval(\"9 + 15 + 30\");\nSystem.out.println(\"Result of evaluating mathematical expressions in String = \"+ob);"
},
{
"code": null,
"e": 1724,
"s": 1713,
"text": " Live Demo"
},
{
"code": null,
"e": 2227,
"s": 1724,
"text": "import javax.script.ScriptEngine;\nimport javax.script.ScriptEngineManager;\npublic class Main {\n public static void main(String[] args) throws Exception {\n ScriptEngineManager scriptEngineManager = new ScriptEngineManager();\n ScriptEngine scriptEngine = scriptEngineManager.getEngineByName(\"JavaScript\");\n // JavaScript code from String\n Object ob = scriptEngine.eval(\"9 + 15 + 30\");\n System.out.println(\"Result of evaluating mathematical expressions in String = \"+ob);\n }\n}"
},
{
"code": null,
"e": 2288,
"s": 2227,
"text": "Result of evaluating mathematical expressions in String = 54"
}
] |
A Quick Introduction to the βPandasβ Python Library | by Adi Bronshtein | Towards Data Science
|
Hello everyone! Today I want to write about the Pandas library (link to the website). Pandas stands for βPython Data Analysis Libraryβ. According to the Wikipedia page on Pandas, βthe name is derived from the term βpanel dataβ, an econometrics term for multidimensional structured data sets.β But I think itβs just a cute name to a super-useful Python library!
Pandas is quite a game changer when it comes to analyzing data with Python and it is one of the most preferred and widely used tools in data munging/wrangling if not THE most used one. Pandas is an open source, free to use (under a BSD license) and it was originally written by Wes McKinney (hereβs a link to his GitHub page).
Whatβs cool about Pandas is that it takes data (like a CSV or TSV file, or a SQL database) and creates a Python object with rows and columns called data frame that looks very similar to table in a statistical software (think Excel or SPSS for example. People who are familiar with R would see similarities to R too). This is so much easier to work with in comparison to working with lists and/or dictionaries through for loops or list comprehension (please feel free to check out one of my previous blog posts about very basic data analysis using Python. It would have been so much easier to do what I did there using Pandas!).
In order to βgetβ Pandas you would need to install it. You would also need to have Python 3.5.3 and above. as a pre-requirement for installation (will work with Python 3.6, 3.7, or 3.8) It is also dependent on other libraries (like NumPy) and has optional dependancies (like Matplotlib for plotting). Therefore, I think that the easiest way to get Pandas set up is to install it through a package like the Anaconda distribution , βa cross platform distribution for data analysis and scientific computing.β There you can download the Windows, OS X and Linux versions. If you want to install in a different way, these are the full installation instructions.
In order to use Pandas in your Python IDE (Integrated Development Environment) like Jupyter Notebook or Spyder (both of them come with Anaconda by default), you need to import the Pandas library first. Importing a library means loading it into the memory and then itβs there for you to work with. In order to import Pandas all you have to do is run the following code:
import pandas as pd import numpy as np
Usually you would add the second part (βas pdβ) so you can access Pandas with βpd.commandβ instead of needing to write βpandas.commandβ every time you need to use it. Also, you would import numpy as well, because it is very useful library for scientific computing with Python. Now Pandas is ready for use! Remember, you would need to do it every time you start a new Jupyter Notebook, Spyder file etc.
When you want to use Pandas for data analysis, youβll usually use it in one of three different ways:
Convert a Pythonβs list, dictionary or Numpy array to a Pandas data frame
Open a local file using Pandas, usually a CSV file, but could also be a delimited text file (like TSV), Excel, etc
Open a remote file or database like a CSV or a JSONon a website through a URL or read from a SQL table/database
There are different commands to each of these options, but when you open a file, they would look like this:
pd.read_filetype()
As I mentioned before, there are different filetypes Pandas can work with, so you would replace βfiletypeβ with the actual, well, filetype (like CSV). You would give the path, filename etc inside the parenthesis. Inside the parenthesis you can also pass different arguments that relate to how to open the file. There are numerous arguments and in order to know all you them, you would have to read the documentation (for example, the documentation for pd.read_csv() would contain all the arguments you can pass in this Pandas command).
In order to convert a certain Python object (dictionary, lists etc) the basic command is:
pd.DataFrame()
Inside the parenthesis you would specify the object(s) youβre creating the data frame from. This command also has different arguments (clickable link).
You can also save a data frame youβre working with/on to different kinds of files (like CSV, Excel, JSON and SQL tables). The general code for that is:
df.to_filetype(filename)
Now that youβve loaded your data, itβs time to take a look. How does the data frame look? Running the name of the data frame would give you the entire table, but you can also get the first n rows with df.head(n) or the last n rows with df.tail(n). df.shape would give you the number of rows and columns. df.info() would give you the index, datatype and memory information. The command s.value_counts(dropna=False) would allow you to view unique values and counts for a series (like a column or a few columns). A very useful command is df.describe() which inputs summary statistics for numerical columns. It is also possible to get statistics on the entire data frame or a series (a column etc):
df.mean()Returns the mean of all columns
df.corr()Returns the correlation between columns in a data frame
df.count()Returns the number of non-null values in each data frame column
df.max()Returns the highest value in each column
df.min()Returns the lowest value in each column
df.median()Returns the median of each column
df.std()Returns the standard deviation of each column
One of the things that is so much easier in Pandas is selecting the data you want in comparison to selecting a value from a list or a dictionary. You can select a column (df[col]) and return column with label col as Series or a few columns (df[[col1, col2]]) and returns columns as a new DataFrame. You can select by position (s.iloc[0]), or by index (s.loc['index_one']) . In order to select the first row you can use df.iloc[0,:] and in order to select the first element of the first column you would run df.iloc[0,0] . These can also be used in different combinations, so I hope it gives you an idea of the different selection and indexing you can perform in Pandas.
You can use different conditions to filter columns. For example, df[df[year] > 1984] would give you only the column year is greater than 1984. You can use & (and) or | (or) to add different conditions to your filtering. This is also called boolean filtering.
It is possible to sort values in a certain column in an ascending order using df.sort_values(col1) ; and also in a descending order using df.sort_values(col2,ascending=False). Furthermore, itβs possible to sort values by col1 in ascending order then col2 in descending order by using df.sort_values([col1,col2],ascending=[True,False]).
The last command in this section is groupby. It involves splitting the data into groups based on some criteria, applying a function to each group independently and combining the results into a data structure. df.groupby(col) returns a groupby object for values from one column while df.groupby([col1,col2]) returns a groupby object for values from multiple columns.
Data cleaning is a very important step in data analysis. For example, we always check for missing values in the data by running pd.isnull() which checks for null Values, and returns a boolean array (an array of true for missing values and false for non-missing values). In order to get a sum of null/missing values, run pd.isnull().sum(). pd.notnull() is the opposite of pd.isnull(). After you get a list of missing values you can get rid of them, or drop them by using df.dropna() to drop the rows or df.dropna(axis=1) to drop the columns. A different approach would be to fill the missing values with other values by using df.fillna(x) which fills the missing values with x (you can put there whatever you want) or s.fillna(s.mean()) to replace all null values with the mean (mean can be replaced with almost any function from the statistics section).
It is sometimes necessary to replace values with different values. For example, s.replace(1,'one') would replace all values equal to 1 with 'one'. Itβs possible to do it for multiple values: s.replace([1,3],['one','three']) would replace all 1 with 'one' and 3 with 'three'. You can also rename specific columns by running: df.rename(columns={'old_name': 'new_ name'}) or use df.set_index('column_one') to change the index of the data frame.
The last set of basic Pandas commands are for joining or combining data frames or rows/columns. The three commands are:
df1.append(df2)β add the rows in df1 to the end of df2 (columns should be identical)
df.concat([df1, df2],axis=1) β add the columns in df1 to the end of df2 (rows should be identical)
df1.join(df2,on=col1,how='inner') β SQL-style join the columns in df1 with the columns on df2 where the rows for colhave identical values. how can be equal to one of: 'left', 'right', 'outer', 'inner'
These are the very basic Pandas commands but I hope you can see how powerful Pandas can be for data analysis. This post is just the tip of the iceberg β after all, entire books can be (and have been) written about data analysis with Pandas. I also hope this post made you feel like taking a dataset and playing around with it using Pandas! :)
As always, if you have any comments, notes, suggestions or questions, please donβt hesitate to write me! Thanks for reading :) I will end, naturally with a picture of cute pandas and with a question β which do you prefer, giant pandas or red pandas???
See you next time!
P.S.
If you liked this tutorial, please check out my quick introduction to NumPy!
|
[
{
"code": null,
"e": 533,
"s": 172,
"text": "Hello everyone! Today I want to write about the Pandas library (link to the website). Pandas stands for βPython Data Analysis Libraryβ. According to the Wikipedia page on Pandas, βthe name is derived from the term βpanel dataβ, an econometrics term for multidimensional structured data sets.β But I think itβs just a cute name to a super-useful Python library!"
},
{
"code": null,
"e": 860,
"s": 533,
"text": "Pandas is quite a game changer when it comes to analyzing data with Python and it is one of the most preferred and widely used tools in data munging/wrangling if not THE most used one. Pandas is an open source, free to use (under a BSD license) and it was originally written by Wes McKinney (hereβs a link to his GitHub page)."
},
{
"code": null,
"e": 1488,
"s": 860,
"text": "Whatβs cool about Pandas is that it takes data (like a CSV or TSV file, or a SQL database) and creates a Python object with rows and columns called data frame that looks very similar to table in a statistical software (think Excel or SPSS for example. People who are familiar with R would see similarities to R too). This is so much easier to work with in comparison to working with lists and/or dictionaries through for loops or list comprehension (please feel free to check out one of my previous blog posts about very basic data analysis using Python. It would have been so much easier to do what I did there using Pandas!)."
},
{
"code": null,
"e": 2144,
"s": 1488,
"text": "In order to βgetβ Pandas you would need to install it. You would also need to have Python 3.5.3 and above. as a pre-requirement for installation (will work with Python 3.6, 3.7, or 3.8) It is also dependent on other libraries (like NumPy) and has optional dependancies (like Matplotlib for plotting). Therefore, I think that the easiest way to get Pandas set up is to install it through a package like the Anaconda distribution , βa cross platform distribution for data analysis and scientific computing.β There you can download the Windows, OS X and Linux versions. If you want to install in a different way, these are the full installation instructions."
},
{
"code": null,
"e": 2513,
"s": 2144,
"text": "In order to use Pandas in your Python IDE (Integrated Development Environment) like Jupyter Notebook or Spyder (both of them come with Anaconda by default), you need to import the Pandas library first. Importing a library means loading it into the memory and then itβs there for you to work with. In order to import Pandas all you have to do is run the following code:"
},
{
"code": null,
"e": 2553,
"s": 2513,
"text": "import pandas as pd import numpy as np "
},
{
"code": null,
"e": 2955,
"s": 2553,
"text": "Usually you would add the second part (βas pdβ) so you can access Pandas with βpd.commandβ instead of needing to write βpandas.commandβ every time you need to use it. Also, you would import numpy as well, because it is very useful library for scientific computing with Python. Now Pandas is ready for use! Remember, you would need to do it every time you start a new Jupyter Notebook, Spyder file etc."
},
{
"code": null,
"e": 3056,
"s": 2955,
"text": "When you want to use Pandas for data analysis, youβll usually use it in one of three different ways:"
},
{
"code": null,
"e": 3130,
"s": 3056,
"text": "Convert a Pythonβs list, dictionary or Numpy array to a Pandas data frame"
},
{
"code": null,
"e": 3245,
"s": 3130,
"text": "Open a local file using Pandas, usually a CSV file, but could also be a delimited text file (like TSV), Excel, etc"
},
{
"code": null,
"e": 3357,
"s": 3245,
"text": "Open a remote file or database like a CSV or a JSONon a website through a URL or read from a SQL table/database"
},
{
"code": null,
"e": 3465,
"s": 3357,
"text": "There are different commands to each of these options, but when you open a file, they would look like this:"
},
{
"code": null,
"e": 3484,
"s": 3465,
"text": "pd.read_filetype()"
},
{
"code": null,
"e": 4020,
"s": 3484,
"text": "As I mentioned before, there are different filetypes Pandas can work with, so you would replace βfiletypeβ with the actual, well, filetype (like CSV). You would give the path, filename etc inside the parenthesis. Inside the parenthesis you can also pass different arguments that relate to how to open the file. There are numerous arguments and in order to know all you them, you would have to read the documentation (for example, the documentation for pd.read_csv() would contain all the arguments you can pass in this Pandas command)."
},
{
"code": null,
"e": 4110,
"s": 4020,
"text": "In order to convert a certain Python object (dictionary, lists etc) the basic command is:"
},
{
"code": null,
"e": 4125,
"s": 4110,
"text": "pd.DataFrame()"
},
{
"code": null,
"e": 4277,
"s": 4125,
"text": "Inside the parenthesis you would specify the object(s) youβre creating the data frame from. This command also has different arguments (clickable link)."
},
{
"code": null,
"e": 4429,
"s": 4277,
"text": "You can also save a data frame youβre working with/on to different kinds of files (like CSV, Excel, JSON and SQL tables). The general code for that is:"
},
{
"code": null,
"e": 4454,
"s": 4429,
"text": "df.to_filetype(filename)"
},
{
"code": null,
"e": 5149,
"s": 4454,
"text": "Now that youβve loaded your data, itβs time to take a look. How does the data frame look? Running the name of the data frame would give you the entire table, but you can also get the first n rows with df.head(n) or the last n rows with df.tail(n). df.shape would give you the number of rows and columns. df.info() would give you the index, datatype and memory information. The command s.value_counts(dropna=False) would allow you to view unique values and counts for a series (like a column or a few columns). A very useful command is df.describe() which inputs summary statistics for numerical columns. It is also possible to get statistics on the entire data frame or a series (a column etc):"
},
{
"code": null,
"e": 5190,
"s": 5149,
"text": "df.mean()Returns the mean of all columns"
},
{
"code": null,
"e": 5255,
"s": 5190,
"text": "df.corr()Returns the correlation between columns in a data frame"
},
{
"code": null,
"e": 5329,
"s": 5255,
"text": "df.count()Returns the number of non-null values in each data frame column"
},
{
"code": null,
"e": 5378,
"s": 5329,
"text": "df.max()Returns the highest value in each column"
},
{
"code": null,
"e": 5426,
"s": 5378,
"text": "df.min()Returns the lowest value in each column"
},
{
"code": null,
"e": 5471,
"s": 5426,
"text": "df.median()Returns the median of each column"
},
{
"code": null,
"e": 5525,
"s": 5471,
"text": "df.std()Returns the standard deviation of each column"
},
{
"code": null,
"e": 6195,
"s": 5525,
"text": "One of the things that is so much easier in Pandas is selecting the data you want in comparison to selecting a value from a list or a dictionary. You can select a column (df[col]) and return column with label col as Series or a few columns (df[[col1, col2]]) and returns columns as a new DataFrame. You can select by position (s.iloc[0]), or by index (s.loc['index_one']) . In order to select the first row you can use df.iloc[0,:] and in order to select the first element of the first column you would run df.iloc[0,0] . These can also be used in different combinations, so I hope it gives you an idea of the different selection and indexing you can perform in Pandas."
},
{
"code": null,
"e": 6454,
"s": 6195,
"text": "You can use different conditions to filter columns. For example, df[df[year] > 1984] would give you only the column year is greater than 1984. You can use & (and) or | (or) to add different conditions to your filtering. This is also called boolean filtering."
},
{
"code": null,
"e": 6790,
"s": 6454,
"text": "It is possible to sort values in a certain column in an ascending order using df.sort_values(col1) ; and also in a descending order using df.sort_values(col2,ascending=False). Furthermore, itβs possible to sort values by col1 in ascending order then col2 in descending order by using df.sort_values([col1,col2],ascending=[True,False])."
},
{
"code": null,
"e": 7156,
"s": 6790,
"text": "The last command in this section is groupby. It involves splitting the data into groups based on some criteria, applying a function to each group independently and combining the results into a data structure. df.groupby(col) returns a groupby object for values from one column while df.groupby([col1,col2]) returns a groupby object for values from multiple columns."
},
{
"code": null,
"e": 8010,
"s": 7156,
"text": "Data cleaning is a very important step in data analysis. For example, we always check for missing values in the data by running pd.isnull() which checks for null Values, and returns a boolean array (an array of true for missing values and false for non-missing values). In order to get a sum of null/missing values, run pd.isnull().sum(). pd.notnull() is the opposite of pd.isnull(). After you get a list of missing values you can get rid of them, or drop them by using df.dropna() to drop the rows or df.dropna(axis=1) to drop the columns. A different approach would be to fill the missing values with other values by using df.fillna(x) which fills the missing values with x (you can put there whatever you want) or s.fillna(s.mean()) to replace all null values with the mean (mean can be replaced with almost any function from the statistics section)."
},
{
"code": null,
"e": 8452,
"s": 8010,
"text": "It is sometimes necessary to replace values with different values. For example, s.replace(1,'one') would replace all values equal to 1 with 'one'. Itβs possible to do it for multiple values: s.replace([1,3],['one','three']) would replace all 1 with 'one' and 3 with 'three'. You can also rename specific columns by running: df.rename(columns={'old_name': 'new_ name'}) or use df.set_index('column_one') to change the index of the data frame."
},
{
"code": null,
"e": 8572,
"s": 8452,
"text": "The last set of basic Pandas commands are for joining or combining data frames or rows/columns. The three commands are:"
},
{
"code": null,
"e": 8657,
"s": 8572,
"text": "df1.append(df2)β add the rows in df1 to the end of df2 (columns should be identical)"
},
{
"code": null,
"e": 8756,
"s": 8657,
"text": "df.concat([df1, df2],axis=1) β add the columns in df1 to the end of df2 (rows should be identical)"
},
{
"code": null,
"e": 8957,
"s": 8756,
"text": "df1.join(df2,on=col1,how='inner') β SQL-style join the columns in df1 with the columns on df2 where the rows for colhave identical values. how can be equal to one of: 'left', 'right', 'outer', 'inner'"
},
{
"code": null,
"e": 9300,
"s": 8957,
"text": "These are the very basic Pandas commands but I hope you can see how powerful Pandas can be for data analysis. This post is just the tip of the iceberg β after all, entire books can be (and have been) written about data analysis with Pandas. I also hope this post made you feel like taking a dataset and playing around with it using Pandas! :)"
},
{
"code": null,
"e": 9552,
"s": 9300,
"text": "As always, if you have any comments, notes, suggestions or questions, please donβt hesitate to write me! Thanks for reading :) I will end, naturally with a picture of cute pandas and with a question β which do you prefer, giant pandas or red pandas???"
},
{
"code": null,
"e": 9571,
"s": 9552,
"text": "See you next time!"
},
{
"code": null,
"e": 9576,
"s": 9571,
"text": "P.S."
}
] |
Logistic Regression Explained from Scratch (Visually, Mathematically and Programmatically) | by Abhibhav Sharma | Towards Data Science
|
A plethora of results appear on a small google search βLogistic Regressionβ. Sometimes it gets very confusing for beginners in data science, to get around the main idea behind logistic regression. And why wouldn't they be confused!!? Every different tutorial, article, or forum has a different narration on Logistic Regression (not including the legit verbose of textbooks because that would kill the entire purpose of these βquick sourcesβ of mastery). Some sources claim it a βClassification algorithmβ and some more sophisticated ones call it a βRegressorβ, however, the idea and utility remain unrevealed. Remember that Logistic regression is the basic building block of artificial neural networks and no/fallacious understanding of it could make it really difficult to understand the advanced formalisms of data science.
Here, I will try to shed some light on and inside the Logistic Regression model and its formalisms in a very basic manner in order to give a sense of understanding to the readers (hopefully without confusing them). Now the simplicity offered here is at a cost of capering the in-depth details of some crucial aspects, and to get into the nitty-gritty of each aspect of Logistic regression would be like diving into the fractal (there will be no end to the discussion). However, for each such concept, I will provide eminent readings/sources that one should refer to.
For there are two major branches in the study of Logistic regression (i) Modelling and (ii) Post Modelling analysis (using the logistic regression results). While the latter is the measure of effect from the fitted coefficients, I believe that the black-box aspect of logistic regression has always been in its Modelling.
My aim here is to:
To elaborate Logistic regression in the most layman way.To discuss the underlying mathematics of two popular optimizers that are employed in Logistic Regression (Gradient Descent and Newton Method).To create a logistic-regression module from scratch in R for each type of optimizer.
To elaborate Logistic regression in the most layman way.
To discuss the underlying mathematics of two popular optimizers that are employed in Logistic Regression (Gradient Descent and Newton Method).
To create a logistic-regression module from scratch in R for each type of optimizer.
One last thing before we proceed, this entire article is designed by keeping the binary classification problem in mind in order to avoid complexity.
Yes, it is not. It is rather a regression model in the core of its heart. I will depict what and why logistic regression while preserving its resonance with a linear regression model. Assuming that my readers are somewhat aware of the basics of linear regression, it is easy to say that the linear regression predicts a βvalueβ of the targeted variable through a linear combination of the given features, while on the other hand, a Logistic regression predicts βprobability valueβ through a linear combination of the given features plugged inside a logistic function (aka inverse-logit) given as eq(1):
Hence the name logistic regression. This logistic function is a simple strategy to map the linear combination βzβ, lying in the (-inf,inf) range to the probability interval of [0,1] (in the context of logistic regression, this z will be called the log(odd) or logit or log(p/1-p)) (see the above plot). Consequently, Logistic regression is a type of regression where the range of mapping is confined to [0,1], unlike simple linear regression models where the domain and range could take any real value.
Consider simple data with one variable and its corresponding binary class either 0 or 1. The scatter plot of this data looks something like (Fig A left). We see that the data points are in the two extreme clusters. Good, now for our prediction modeling, a naive regression line in this scenario will give a nonsense fit (red line in Fig A right) and what we actually require to fit is something like a squiggly line (or a curvy βSβ shaped blue rule in Fig A right) to explain (or to correctly separate) a maximum number of data points.
Logistic regression is a scheme to search this most optimum blue squiggly line. Now first let's understand what each point on this squiggly line represents. given any variable value projected on this line, this squiggly line tells the probability of falling in Class 1 (say βpβ) for that projected variable value. So accordingly the line tells that all the bottom points that lie on this blue line have zero chances (p=0) of being in class 1 and the top points that lie on it have the probability of 1(p=1) for the same. Now, remember that I have mentioned that the logistic (aka inverse-logit) is a strategy to map infinitely stretching space (-inf, inf) to a probability space of [0,1], a logit function could transform the probability space of [0,1] to a space stretching to (-inf, inf) eq(2)&(Fig B).
Keeping this in mind, here comes the mantra of logistic regression modeling:
Logistic Regression starts with first A transforming the space of class probability[0,1] vs variable{R} (as in fig A right) to the space of Logit{R} vs variable{R} where a βregression likeβ fitting is performed by adjusting the coefficient and slope in order to maximize the Likelihood (a very fancy stuff that I will elaborated this part in coming section). B Once tweaking and tuning are done, the Logit{R} vs variable{R} space is remapped to class probability[0,1] vs variable{R} using inverse-Logit (aka Logistic function). Performing this cycle iteratively (A βB βA ) would eventually result in the most optimum squiggly line or the most discriminating rule.
WOW!!!
Well, you may (should) ask (i) Why and how to do this transformation ??, (ii) what the heck is Likelihood?? and (iii) How this scheme would lead to the most optimum squiggle?!!.
So for (i), the idea to the transformation from a confined probability space [0,1] to an infinitely stretching real space (-inf, inf) is because it will make the fitting problem very close to solving a linear regression, for which we have a lot of optimizers and techniques to fit the most optimum line. The latter questions will be answered eventually.
Now coming back to our search for the best classifying blue squiggly line, the idea is to plot an initial linear regression line with the arbitrary coefficient on β οΈlogit vs variable spaceβ οΈ coordinates first and then adjust the coefficients of this fit to maximize the likelihood (relax!! I will explain the βlikelihoodβ when it is needed).
In our one variable case, we can write equation 3:
logit(p) = log(p/1-p) = Ξ²0+ Ξ²1*v .....................................(eq 3)
In Fig C (I), the red line is our arbitrary chosen regression line fitted for the data points, mapped in a different coordinate system with Ξ²0 (intercept) as -20 and Ξ²1(slope) as 3.75.
β οΈ Note that the coordinate space is not class{0,1} vs variable{R} but its the Logit{R} vs variable{R}. Also, notice that the transformation from Fig A(right) to Fig C(I) has no effects on the positional preferences of the points i.e. the extremes as in equation 2 above, the logit(0)=-infinity, and logit(1)=+infinity.
At this point, let me reiterate our objective: We want to fit the straight line for the data points in logit vs variable plot in such a way that it explains (correctly separates) the maximum number of data points when it gets converted to the blue squiggly line through inverse-logit (aka logistic function) eq(1). So to achieve the best regression, a similar strategy of simple linear regression comes into play but despite minimizing the squared residual, the idea is to maximize the likelihood (relax!!). Since the points scattered on the infinity make it difficult to proceed in an orthodox linear regression method, the trick is to project these points on the logit (the initial chosen/fitted line with the arbitrary coefficient) Fig C(II). In this way, each data point projected on the logit corresponds to a logit value. When these logit values are plugged into the logistic function eq(1), we get their probability of falling in class 1 Fig C(III).
Note: This also can be proven mathematically as well that: logit(p)=logisticβ1(p)
This probability can be represented mathematically as equation 4, which is very close to a Bernoulli distribution, isn't it?.
P(Y = y|X = x) = Ο(Ξ²T x)y Β· [1 β Ο(Ξ²Tx)](1βy) ; where y is either 0 or 1..eq(4)
The equation reads that for a given data instance x, the probability of the label Y being y(where y is either 0 or 1) is equal to the logistic of logit when y=1 and is equal to (1-logistic of logit) if y=0. These new probability values are illustrated in our class{0,1} vs variable{R} space as blue dots in Fig C(III). This new probability value for a datapoint is what we call the LIKELIHOOD of that data point. So in simple terms, likelihood is the probability value of the datapoint where the probability value indicates that how LIKELY the point is to be falling in the class 1 category. And the likelihood of the training label for the fitted weight vector Ξ² is nothing but the product of each of these newfound probability values equation 5&6.
L(Ξ²) = nβi=1 P(Y = y(i) | X = x(i) )................................eq(5)
Substituting equation 4 in equation 5 we get,
L(Ξ²) = nβi=1 Ο(Ξ²T x(i))y(i) Β· [1 β Ο(Ξ²Tx(i))](1βy(i)) ..................eq(6)
The idea is to estimate the parameters (Ξ²) such that it maximizes the L(Ξ²). However, due to the mathematical convenience, we maximize the log of L(Ξ²) and call its log-likelihood equation 7.
LL(Ξ²) = nβi=1 y(i)log Ο(Ξ²T x(i)) + (1β y(i)) log[1 β Ο(Ξ²Tx(i))]........eq(7)
So at this point, I hope that our earlier stated objective is much understandable i.e. to find the best fitting parameters Ξ² in logit vs variable space such that LL(Ξ²) in probability vs variable space is maximum. For this, there is no close form and so in the next section, I will touch upon two optimization methods (1) Gradient descent and (2) Newtonβs method to find the optimum parameters.
Our optimization first requires the partial derivative of the log-likelihood function. So let me shamelessly share the snap from a very eminent lecture note that beautifully elucidate the steps to derive the partial derivative of LL(Ξ²). (Note: the calculations shown here use ΞΈ in place of Ξ² to represent the parameters.)
To update the parameter, the steps toward the global maximum is:
so the algorithm is:
Initialize Ξ² and set likelihood=0
While likelihoodβ€max(likelihood){
Calculate logit(p) = xΞ²T
Calculate P=logistic(XΞ²T)= 1/(1+exp(-XΞ²T))
Calculate Likelihood L(Ξ²) = nβi=1ifelse( y(i)=1, p(i), (1-p(i)))
Calculate first_derivative βLL(Ξ²) = XT (Y-P)
Update: Ξ²(new) = Ξ² (old) + Ξ·βLL(Ξ²)
}
Newtonβs Method is another strong candidate among the all available optimizers. We have learned Newtonβs Method as an algorithm to stepwise find the maximum/minimum point on the concave/convex functions in our early lessons:
xn+1=xn + βf(xn). ββfβ1(xn)
In the context of our log-likelihood function, the βf(xn) will be replaced by the gradient of LL(Ξ²) (i.e βLL(Ξ²)) and the ββfβ1(xn) would be the Hessian H i.e. the second-order partial derivative of LL(Ξ²)). Well, I will caper the details here, but your curious brain should refer to this. So, the ultimate expression to update the parameter, in this case, is given by:
Ξ²n+1=Ξ²n+ Hβ1. βLL(Ξ²)
Here in the case of logistic regression, the calculation of H is super easy because:
H= ββLL(Ξ²) = βnβi=1[y β Ο(Ξ²Tx(i))].x(i)
= βnβi=1[y β pi].x(i)
= βnβi=1 x(i)(βpi) = βnβi=1 x(i) pi(1-pi) (x(i))T
thus, H= -XWXT, where W=(P*(1-P))T I
So the algorithms are:
Initialize Ξ² and set likelihood=0
While likelihoodβ€max(likelihood){
Calculate logit(p) = xΞ²T
Calculate P=logistic(XΞ²T)= 1/(1+exp(-XΞ²T))
Calculate Likelihood L(Ξ²) = nβi=1ifelse( y(i)=1, p(i), (1-p(i)))
Calculate first_derivative βLL(Ξ²) = XT (Y-P)
Calculate Second_derivative Hessian H = -XT (P*(1-P))TI X
Ξ²(new) = Ξ² (old) + Hβ1. βLL(Ξ²)
}
The dataset that I am going to use for training and testing my binary classification model can be downloaded from here. Originally this dataset is an Algerian Forest Fires Dataset. You can check out the details of the dataset here.
For the readers who hopped the entire article above to play around with code, I would recommend having a quick eyeballing through the second section as I have given a spet-wise algorithm for both the optimizer and my code will strictly follow that order.
The training Function
setwd("C:/Users/Dell/Desktop")set.seed(111) #to generate the same results as mine#-------------Training Function---------------------------------#logistic.train<- function(train_data, method, lr, verbose){ b0<-rep(1, nrow(train_data)) x<-as.matrix(cbind(b0, train_data[,1:(ncol(train_data)-1)])) y<- train_data[, ncol(train_data)] beta<- as.matrix(rep(0.5,ncol(x))); likelihood<-0; epoch<-0 #initiate beta_all<-NULL beta_at<-c(1,10,50,100,110,150,180,200,300,500,600,800,1000, 1500,2000,4000,5000,6000,10000) #checkpoints (the epochs at which I will record the betas) #-----------------------------Gradient Descent---------------------# if(method=="Gradient"){ while( (likelihood < 0.95) & (epoch<=35000)){ logit<-x%*%beta #Calculate logit(p) = xΞ²T p <- 1/( 1+ exp(-(logit))) #Calculate P=logistic(XΞ²T)= 1/(1+exp(-XΞ²T)) # Likelihood: L(x|beta) = P(Y=1|x,beta)*P(Y=0|x,beta) likelihood<-1 for(i in 1:length(p)){ likelihood <- likelihood*(ifelse( y[i]==1, p[i], (1-p[i]))) #product of all the probability } first_d<- t(x) %*% (y-p)#first derivative of the likelihood function beta <- beta + lr*first_d #updating the parameters for a step toward maximization #to see inside the steps of learning (irrelevant to the main working algo) if(verbose==T){ ifelse(epoch%%200==0, print(paste0(epoch, "th Epoch", "---------Likelihood=", round(likelihood,4), "---------log-likelihood=", round(log(likelihood),4), collapse = "")), NA)} if(epoch %in% beta_at){beta_all<-cbind(beta_all, beta)} epoch<- epoch+1 } } #--------------Newton second order diff method-------------# else if(method=="Newton"){ while((likelihood < 0.95) & (epoch<=35000)){ logit<-x%*%beta #Calculate logit(p) = xΞ²T p <- 1/( 1+ exp(-(logit))) #Calculate P=logistic(XΞ²T)= 1/(1+exp(-XΞ²T)) # Likelihood: L(x|beta) = P(Y=1|x,beta)*P(Y=0|x,beta) likelihood<-1 for(i in 1:length(p)){ likelihood <- likelihood*(ifelse( y[i]==1, p[i], (1-p[i]))) } first_d<- t(x) %*% (y-p)#first derivative of the likelihood function w<-matrix(0, ncol= nrow(x), nrow = nrow(x)) #initializing p(1-p) diagonal matrix diag(w)<-p*(1-p) hessian<- -t(x) %*% w %*% x #hessian matrix hessian<- diag(ncol(x))-hessian #Levenberg-Marquardt method: Add a scaled identity matrix to avoid singularity issues k<- solve(hessian) %*% (t(x) %*% (y-p)) #the gradient for newton method beta <- beta + k #updating the parameters for a step toward maximization if(verbose==T){ ifelse(epoch%%200==0, print(paste0(epoch, "th Epoch", "---------Likelihood=", round(likelihood,4), "---------log-likelihood=", round(log(likelihood),4), collapse = "")), NA)} if(epoch %in% beta_at){beta_all<-cbind(beta_all, beta)} #just to inside the learning epoch<- epoch+1 } } else(break) beta_all<-cbind(beta_all, beta) colnames(beta_all)<-c(beta_at[1:(ncol(beta_all)-1)], epoch-1) mylist<-list(as.matrix(beta), likelihood, beta_all) names(mylist)<- c("Beta", "likelihood", "Beta_all") return(mylist)} # Fitting of logistic model
The Prediction Function
logistic.pred<-function(model, test_data){ test_new<- cbind( rep(1, nrow(test_data)), test_data[,-ncol(test_data)]) #adding 1 to fit the intercept beta<-as.matrix(model$Beta) #extract the best suiting beta (the beta at final epoch) beta_all<-model$Beta_all #extract all the betas at different checkpoints ll<- model$likelihood #extract the highest likelihood obtained log_odd<-cbind(as.matrix(test_new)) %*% beta #logit(p) probability<- 1/(1+ exp(-log_odd)) # p=logistic(logit(p)) predicted_label<- ifelse(probability >= 0.5, 1, 0) #discrimination rule k<-cbind(test_data[,ncol(test_data)], predicted_label) # actual label vs predicted label colnames(k)<- c("Actual", "Predicted") k<- as.data.frame(k) tp<-length(which(k$Actual==1 & k$Predicted==1)) #true positive tn<-length(which(k$Actual==0 & k$Predicted==0)) #true negative fp<-length(which(k$Actual==0 & k$Predicted==1)) #false positive fn<-length(which(k$Actual==1 & k$Predicted==0)) #false negative cf<-matrix(c(tp, fn, fp, tn), 2, 2, byrow = F) #confusion matrix rownames(cf)<- c("1", "0") colnames(cf)<- c("1", "0") p_list<-list(k, cf, beta, ll, beta_all) names(p_list)<- c("predticted", "confusion matrix","beta", "liklihood", "Beta_all") return(p_list) } # to make prediction from the trained model
Data Parsing
#importing datadata<-read.csv("fire.csv", header = T) #importdata$Classes<-as.numeric(ifelse(1:nrow(data)%in%grep("not",data$Classes), 0, 1)) # one hot encoding ; numeric conversion from label to 1 or 0data<-rbind(data[which(data$Classes==0),], data[sample(size=length(which(data$Classes==0)),which(data$Classes==1)),]) #balancing the classesdata<-data[sample(1:nrow(data)),] #shufflingdata<-as.data.frame(data) #data to data framedata<-lapply(data, as.numeric) data<-as.data.frame(data)#missing data handlingif(!is.null(is.na(data))){ data<-data[-unique(which(is.na(data), arr.ind = T)[,1]),]}#test train partitionpartition<-sample(c(0,1), size=nrow(data), prob = c(0.8,0.2), replace = T) train<-data[which(partition==0),]test<-data[which(partition==1),]
Training β Testing β Results
#-------------------------TRAINING---------------------------------#mymodel_newton<- logistic.train(train, "Newton", 0.01, verbose=T) # Fitting the model using Newton methodmymodel_gradient<- logistic.train(train, "Gradient", 0.01, verbose=T) # Fitting the model using Gradient method#------------------------TESTING-------------------------------------#myresult1<-logistic.pred( mymodel_newton, test_data = test) #prediction using Newton trained modelmyresult2<-logistic.pred( mymodel_gradient, test_data = test) #prediction using Gradient trained model#------------------------Results----------------------------------#myresult1$`confusion matrix`myresult2$`confusion matrix`
The Results
The confusion matrix obtained by both methods is the same. The accuracies obtained by both methods on the independent test set are 95.2% (quite good!!).
However, the best fitting coefficients Ξ² obtained by both methods are very different in terms of values. Newtonβs method took 3,566 epochs to obtain a likelihood of 1, while Gradient descent took 3,539 to read the maximum likelihood of 0.999.
In terms of time taken, Newtonβs method took more time to reach the optimum in comparison to the gradient method because, in Newton's method, the solving inverse of Hessian makes it a little computationally extensive and time-consuming algorithm.
As you have noticed that I have captured the betas at various checkpoints during the training. This will allow us to peep into the training process that is carried out while maximizing the likelihood (see β©β©β©β©)
We can also peep into the fitting on the test set by the fully trained model
So at this point, I think I can reiterate to the reader that the fundamental nature of Logistic Regression is not of classification, rather it is of regression. Through substantiating a regression in its core functioning, The Logistic regression gives output as probability attached to a given instance. It is when a rule of >orβ€ 0.5 or something is employed, the assignment of an instance to a particular discrete class is carried out.
If you are here then go get yourself a fine treat, you are a real MVP. I hope my very casual elaboration on logistic regression gave you slightly better insights into the logistic regression. This article encompasses the concept, the underlying mathematics, and the programming of logistic regression. While the ideas here depict the actual scheme, there are some out-of-scope aspects of the optimizers discussed here, in which the optimizing algorithm might fail to achieve an optimum, more details can be found here.
Feel free to download the entire code (Model and plots) from my git.
The Elements of Statistical Learning Data Mining, Inference, and Prediction
thelaziestprogrammer.com
Also, feel free to explore Part I and Part II of the Hands-on Vanilla Modelling series. Cheers :)
|
[
{
"code": null,
"e": 998,
"s": 172,
"text": "A plethora of results appear on a small google search βLogistic Regressionβ. Sometimes it gets very confusing for beginners in data science, to get around the main idea behind logistic regression. And why wouldn't they be confused!!? Every different tutorial, article, or forum has a different narration on Logistic Regression (not including the legit verbose of textbooks because that would kill the entire purpose of these βquick sourcesβ of mastery). Some sources claim it a βClassification algorithmβ and some more sophisticated ones call it a βRegressorβ, however, the idea and utility remain unrevealed. Remember that Logistic regression is the basic building block of artificial neural networks and no/fallacious understanding of it could make it really difficult to understand the advanced formalisms of data science."
},
{
"code": null,
"e": 1565,
"s": 998,
"text": "Here, I will try to shed some light on and inside the Logistic Regression model and its formalisms in a very basic manner in order to give a sense of understanding to the readers (hopefully without confusing them). Now the simplicity offered here is at a cost of capering the in-depth details of some crucial aspects, and to get into the nitty-gritty of each aspect of Logistic regression would be like diving into the fractal (there will be no end to the discussion). However, for each such concept, I will provide eminent readings/sources that one should refer to."
},
{
"code": null,
"e": 1887,
"s": 1565,
"text": "For there are two major branches in the study of Logistic regression (i) Modelling and (ii) Post Modelling analysis (using the logistic regression results). While the latter is the measure of effect from the fitted coefficients, I believe that the black-box aspect of logistic regression has always been in its Modelling."
},
{
"code": null,
"e": 1906,
"s": 1887,
"text": "My aim here is to:"
},
{
"code": null,
"e": 2189,
"s": 1906,
"text": "To elaborate Logistic regression in the most layman way.To discuss the underlying mathematics of two popular optimizers that are employed in Logistic Regression (Gradient Descent and Newton Method).To create a logistic-regression module from scratch in R for each type of optimizer."
},
{
"code": null,
"e": 2246,
"s": 2189,
"text": "To elaborate Logistic regression in the most layman way."
},
{
"code": null,
"e": 2389,
"s": 2246,
"text": "To discuss the underlying mathematics of two popular optimizers that are employed in Logistic Regression (Gradient Descent and Newton Method)."
},
{
"code": null,
"e": 2474,
"s": 2389,
"text": "To create a logistic-regression module from scratch in R for each type of optimizer."
},
{
"code": null,
"e": 2623,
"s": 2474,
"text": "One last thing before we proceed, this entire article is designed by keeping the binary classification problem in mind in order to avoid complexity."
},
{
"code": null,
"e": 3226,
"s": 2623,
"text": "Yes, it is not. It is rather a regression model in the core of its heart. I will depict what and why logistic regression while preserving its resonance with a linear regression model. Assuming that my readers are somewhat aware of the basics of linear regression, it is easy to say that the linear regression predicts a βvalueβ of the targeted variable through a linear combination of the given features, while on the other hand, a Logistic regression predicts βprobability valueβ through a linear combination of the given features plugged inside a logistic function (aka inverse-logit) given as eq(1):"
},
{
"code": null,
"e": 3729,
"s": 3226,
"text": "Hence the name logistic regression. This logistic function is a simple strategy to map the linear combination βzβ, lying in the (-inf,inf) range to the probability interval of [0,1] (in the context of logistic regression, this z will be called the log(odd) or logit or log(p/1-p)) (see the above plot). Consequently, Logistic regression is a type of regression where the range of mapping is confined to [0,1], unlike simple linear regression models where the domain and range could take any real value."
},
{
"code": null,
"e": 4265,
"s": 3729,
"text": "Consider simple data with one variable and its corresponding binary class either 0 or 1. The scatter plot of this data looks something like (Fig A left). We see that the data points are in the two extreme clusters. Good, now for our prediction modeling, a naive regression line in this scenario will give a nonsense fit (red line in Fig A right) and what we actually require to fit is something like a squiggly line (or a curvy βSβ shaped blue rule in Fig A right) to explain (or to correctly separate) a maximum number of data points."
},
{
"code": null,
"e": 5070,
"s": 4265,
"text": "Logistic regression is a scheme to search this most optimum blue squiggly line. Now first let's understand what each point on this squiggly line represents. given any variable value projected on this line, this squiggly line tells the probability of falling in Class 1 (say βpβ) for that projected variable value. So accordingly the line tells that all the bottom points that lie on this blue line have zero chances (p=0) of being in class 1 and the top points that lie on it have the probability of 1(p=1) for the same. Now, remember that I have mentioned that the logistic (aka inverse-logit) is a strategy to map infinitely stretching space (-inf, inf) to a probability space of [0,1], a logit function could transform the probability space of [0,1] to a space stretching to (-inf, inf) eq(2)&(Fig B)."
},
{
"code": null,
"e": 5147,
"s": 5070,
"text": "Keeping this in mind, here comes the mantra of logistic regression modeling:"
},
{
"code": null,
"e": 5811,
"s": 5147,
"text": "Logistic Regression starts with first A transforming the space of class probability[0,1] vs variable{R} (as in fig A right) to the space of Logit{R} vs variable{R} where a βregression likeβ fitting is performed by adjusting the coefficient and slope in order to maximize the Likelihood (a very fancy stuff that I will elaborated this part in coming section). B Once tweaking and tuning are done, the Logit{R} vs variable{R} space is remapped to class probability[0,1] vs variable{R} using inverse-Logit (aka Logistic function). Performing this cycle iteratively (A βB βA ) would eventually result in the most optimum squiggly line or the most discriminating rule."
},
{
"code": null,
"e": 5818,
"s": 5811,
"text": "WOW!!!"
},
{
"code": null,
"e": 5996,
"s": 5818,
"text": "Well, you may (should) ask (i) Why and how to do this transformation ??, (ii) what the heck is Likelihood?? and (iii) How this scheme would lead to the most optimum squiggle?!!."
},
{
"code": null,
"e": 6350,
"s": 5996,
"text": "So for (i), the idea to the transformation from a confined probability space [0,1] to an infinitely stretching real space (-inf, inf) is because it will make the fitting problem very close to solving a linear regression, for which we have a lot of optimizers and techniques to fit the most optimum line. The latter questions will be answered eventually."
},
{
"code": null,
"e": 6692,
"s": 6350,
"text": "Now coming back to our search for the best classifying blue squiggly line, the idea is to plot an initial linear regression line with the arbitrary coefficient on β οΈlogit vs variable spaceβ οΈ coordinates first and then adjust the coefficients of this fit to maximize the likelihood (relax!! I will explain the βlikelihoodβ when it is needed)."
},
{
"code": null,
"e": 6743,
"s": 6692,
"text": "In our one variable case, we can write equation 3:"
},
{
"code": null,
"e": 6820,
"s": 6743,
"text": "logit(p) = log(p/1-p) = Ξ²0+ Ξ²1*v .....................................(eq 3)"
},
{
"code": null,
"e": 7005,
"s": 6820,
"text": "In Fig C (I), the red line is our arbitrary chosen regression line fitted for the data points, mapped in a different coordinate system with Ξ²0 (intercept) as -20 and Ξ²1(slope) as 3.75."
},
{
"code": null,
"e": 7325,
"s": 7005,
"text": "β οΈ Note that the coordinate space is not class{0,1} vs variable{R} but its the Logit{R} vs variable{R}. Also, notice that the transformation from Fig A(right) to Fig C(I) has no effects on the positional preferences of the points i.e. the extremes as in equation 2 above, the logit(0)=-infinity, and logit(1)=+infinity."
},
{
"code": null,
"e": 8282,
"s": 7325,
"text": "At this point, let me reiterate our objective: We want to fit the straight line for the data points in logit vs variable plot in such a way that it explains (correctly separates) the maximum number of data points when it gets converted to the blue squiggly line through inverse-logit (aka logistic function) eq(1). So to achieve the best regression, a similar strategy of simple linear regression comes into play but despite minimizing the squared residual, the idea is to maximize the likelihood (relax!!). Since the points scattered on the infinity make it difficult to proceed in an orthodox linear regression method, the trick is to project these points on the logit (the initial chosen/fitted line with the arbitrary coefficient) Fig C(II). In this way, each data point projected on the logit corresponds to a logit value. When these logit values are plugged into the logistic function eq(1), we get their probability of falling in class 1 Fig C(III)."
},
{
"code": null,
"e": 8364,
"s": 8282,
"text": "Note: This also can be proven mathematically as well that: logit(p)=logisticβ1(p)"
},
{
"code": null,
"e": 8490,
"s": 8364,
"text": "This probability can be represented mathematically as equation 4, which is very close to a Bernoulli distribution, isn't it?."
},
{
"code": null,
"e": 8570,
"s": 8490,
"text": "P(Y = y|X = x) = Ο(Ξ²T x)y Β· [1 β Ο(Ξ²Tx)](1βy) ; where y is either 0 or 1..eq(4)"
},
{
"code": null,
"e": 9320,
"s": 8570,
"text": "The equation reads that for a given data instance x, the probability of the label Y being y(where y is either 0 or 1) is equal to the logistic of logit when y=1 and is equal to (1-logistic of logit) if y=0. These new probability values are illustrated in our class{0,1} vs variable{R} space as blue dots in Fig C(III). This new probability value for a datapoint is what we call the LIKELIHOOD of that data point. So in simple terms, likelihood is the probability value of the datapoint where the probability value indicates that how LIKELY the point is to be falling in the class 1 category. And the likelihood of the training label for the fitted weight vector Ξ² is nothing but the product of each of these newfound probability values equation 5&6."
},
{
"code": null,
"e": 9394,
"s": 9320,
"text": "L(Ξ²) = nβi=1 P(Y = y(i) | X = x(i) )................................eq(5)"
},
{
"code": null,
"e": 9440,
"s": 9394,
"text": "Substituting equation 4 in equation 5 we get,"
},
{
"code": null,
"e": 9518,
"s": 9440,
"text": "L(Ξ²) = nβi=1 Ο(Ξ²T x(i))y(i) Β· [1 β Ο(Ξ²Tx(i))](1βy(i)) ..................eq(6)"
},
{
"code": null,
"e": 9708,
"s": 9518,
"text": "The idea is to estimate the parameters (Ξ²) such that it maximizes the L(Ξ²). However, due to the mathematical convenience, we maximize the log of L(Ξ²) and call its log-likelihood equation 7."
},
{
"code": null,
"e": 9785,
"s": 9708,
"text": "LL(Ξ²) = nβi=1 y(i)log Ο(Ξ²T x(i)) + (1β y(i)) log[1 β Ο(Ξ²Tx(i))]........eq(7)"
},
{
"code": null,
"e": 10179,
"s": 9785,
"text": "So at this point, I hope that our earlier stated objective is much understandable i.e. to find the best fitting parameters Ξ² in logit vs variable space such that LL(Ξ²) in probability vs variable space is maximum. For this, there is no close form and so in the next section, I will touch upon two optimization methods (1) Gradient descent and (2) Newtonβs method to find the optimum parameters."
},
{
"code": null,
"e": 10501,
"s": 10179,
"text": "Our optimization first requires the partial derivative of the log-likelihood function. So let me shamelessly share the snap from a very eminent lecture note that beautifully elucidate the steps to derive the partial derivative of LL(Ξ²). (Note: the calculations shown here use ΞΈ in place of Ξ² to represent the parameters.)"
},
{
"code": null,
"e": 10566,
"s": 10501,
"text": "To update the parameter, the steps toward the global maximum is:"
},
{
"code": null,
"e": 10587,
"s": 10566,
"text": "so the algorithm is:"
},
{
"code": null,
"e": 10621,
"s": 10587,
"text": "Initialize Ξ² and set likelihood=0"
},
{
"code": null,
"e": 10655,
"s": 10621,
"text": "While likelihoodβ€max(likelihood){"
},
{
"code": null,
"e": 10680,
"s": 10655,
"text": "Calculate logit(p) = xΞ²T"
},
{
"code": null,
"e": 10723,
"s": 10680,
"text": "Calculate P=logistic(XΞ²T)= 1/(1+exp(-XΞ²T))"
},
{
"code": null,
"e": 10788,
"s": 10723,
"text": "Calculate Likelihood L(Ξ²) = nβi=1ifelse( y(i)=1, p(i), (1-p(i)))"
},
{
"code": null,
"e": 10833,
"s": 10788,
"text": "Calculate first_derivative βLL(Ξ²) = XT (Y-P)"
},
{
"code": null,
"e": 10868,
"s": 10833,
"text": "Update: Ξ²(new) = Ξ² (old) + Ξ·βLL(Ξ²)"
},
{
"code": null,
"e": 10870,
"s": 10868,
"text": "}"
},
{
"code": null,
"e": 11095,
"s": 10870,
"text": "Newtonβs Method is another strong candidate among the all available optimizers. We have learned Newtonβs Method as an algorithm to stepwise find the maximum/minimum point on the concave/convex functions in our early lessons:"
},
{
"code": null,
"e": 11123,
"s": 11095,
"text": "xn+1=xn + βf(xn). ββfβ1(xn)"
},
{
"code": null,
"e": 11491,
"s": 11123,
"text": "In the context of our log-likelihood function, the βf(xn) will be replaced by the gradient of LL(Ξ²) (i.e βLL(Ξ²)) and the ββfβ1(xn) would be the Hessian H i.e. the second-order partial derivative of LL(Ξ²)). Well, I will caper the details here, but your curious brain should refer to this. So, the ultimate expression to update the parameter, in this case, is given by:"
},
{
"code": null,
"e": 11512,
"s": 11491,
"text": "Ξ²n+1=Ξ²n+ Hβ1. βLL(Ξ²)"
},
{
"code": null,
"e": 11597,
"s": 11512,
"text": "Here in the case of logistic regression, the calculation of H is super easy because:"
},
{
"code": null,
"e": 11637,
"s": 11597,
"text": "H= ββLL(Ξ²) = βnβi=1[y β Ο(Ξ²Tx(i))].x(i)"
},
{
"code": null,
"e": 11659,
"s": 11637,
"text": "= βnβi=1[y β pi].x(i)"
},
{
"code": null,
"e": 11709,
"s": 11659,
"text": "= βnβi=1 x(i)(βpi) = βnβi=1 x(i) pi(1-pi) (x(i))T"
},
{
"code": null,
"e": 11746,
"s": 11709,
"text": "thus, H= -XWXT, where W=(P*(1-P))T I"
},
{
"code": null,
"e": 11769,
"s": 11746,
"text": "So the algorithms are:"
},
{
"code": null,
"e": 11803,
"s": 11769,
"text": "Initialize Ξ² and set likelihood=0"
},
{
"code": null,
"e": 11837,
"s": 11803,
"text": "While likelihoodβ€max(likelihood){"
},
{
"code": null,
"e": 11862,
"s": 11837,
"text": "Calculate logit(p) = xΞ²T"
},
{
"code": null,
"e": 11905,
"s": 11862,
"text": "Calculate P=logistic(XΞ²T)= 1/(1+exp(-XΞ²T))"
},
{
"code": null,
"e": 11970,
"s": 11905,
"text": "Calculate Likelihood L(Ξ²) = nβi=1ifelse( y(i)=1, p(i), (1-p(i)))"
},
{
"code": null,
"e": 12015,
"s": 11970,
"text": "Calculate first_derivative βLL(Ξ²) = XT (Y-P)"
},
{
"code": null,
"e": 12073,
"s": 12015,
"text": "Calculate Second_derivative Hessian H = -XT (P*(1-P))TI X"
},
{
"code": null,
"e": 12104,
"s": 12073,
"text": "Ξ²(new) = Ξ² (old) + Hβ1. βLL(Ξ²)"
},
{
"code": null,
"e": 12106,
"s": 12104,
"text": "}"
},
{
"code": null,
"e": 12338,
"s": 12106,
"text": "The dataset that I am going to use for training and testing my binary classification model can be downloaded from here. Originally this dataset is an Algerian Forest Fires Dataset. You can check out the details of the dataset here."
},
{
"code": null,
"e": 12593,
"s": 12338,
"text": "For the readers who hopped the entire article above to play around with code, I would recommend having a quick eyeballing through the second section as I have given a spet-wise algorithm for both the optimizer and my code will strictly follow that order."
},
{
"code": null,
"e": 12615,
"s": 12593,
"text": "The training Function"
},
{
"code": null,
"e": 16057,
"s": 12615,
"text": "setwd(\"C:/Users/Dell/Desktop\")set.seed(111) #to generate the same results as mine#-------------Training Function---------------------------------#logistic.train<- function(train_data, method, lr, verbose){ b0<-rep(1, nrow(train_data)) x<-as.matrix(cbind(b0, train_data[,1:(ncol(train_data)-1)])) y<- train_data[, ncol(train_data)] beta<- as.matrix(rep(0.5,ncol(x))); likelihood<-0; epoch<-0 #initiate beta_all<-NULL beta_at<-c(1,10,50,100,110,150,180,200,300,500,600,800,1000, 1500,2000,4000,5000,6000,10000) #checkpoints (the epochs at which I will record the betas) #-----------------------------Gradient Descent---------------------# if(method==\"Gradient\"){ while( (likelihood < 0.95) & (epoch<=35000)){ logit<-x%*%beta #Calculate logit(p) = xΞ²T p <- 1/( 1+ exp(-(logit))) #Calculate P=logistic(XΞ²T)= 1/(1+exp(-XΞ²T)) # Likelihood: L(x|beta) = P(Y=1|x,beta)*P(Y=0|x,beta) likelihood<-1 for(i in 1:length(p)){ likelihood <- likelihood*(ifelse( y[i]==1, p[i], (1-p[i]))) #product of all the probability } first_d<- t(x) %*% (y-p)#first derivative of the likelihood function beta <- beta + lr*first_d #updating the parameters for a step toward maximization #to see inside the steps of learning (irrelevant to the main working algo) if(verbose==T){ ifelse(epoch%%200==0, print(paste0(epoch, \"th Epoch\", \"---------Likelihood=\", round(likelihood,4), \"---------log-likelihood=\", round(log(likelihood),4), collapse = \"\")), NA)} if(epoch %in% beta_at){beta_all<-cbind(beta_all, beta)} epoch<- epoch+1 } } #--------------Newton second order diff method-------------# else if(method==\"Newton\"){ while((likelihood < 0.95) & (epoch<=35000)){ logit<-x%*%beta #Calculate logit(p) = xΞ²T p <- 1/( 1+ exp(-(logit))) #Calculate P=logistic(XΞ²T)= 1/(1+exp(-XΞ²T)) # Likelihood: L(x|beta) = P(Y=1|x,beta)*P(Y=0|x,beta) likelihood<-1 for(i in 1:length(p)){ likelihood <- likelihood*(ifelse( y[i]==1, p[i], (1-p[i]))) } first_d<- t(x) %*% (y-p)#first derivative of the likelihood function w<-matrix(0, ncol= nrow(x), nrow = nrow(x)) #initializing p(1-p) diagonal matrix diag(w)<-p*(1-p) hessian<- -t(x) %*% w %*% x #hessian matrix hessian<- diag(ncol(x))-hessian #Levenberg-Marquardt method: Add a scaled identity matrix to avoid singularity issues k<- solve(hessian) %*% (t(x) %*% (y-p)) #the gradient for newton method beta <- beta + k #updating the parameters for a step toward maximization if(verbose==T){ ifelse(epoch%%200==0, print(paste0(epoch, \"th Epoch\", \"---------Likelihood=\", round(likelihood,4), \"---------log-likelihood=\", round(log(likelihood),4), collapse = \"\")), NA)} if(epoch %in% beta_at){beta_all<-cbind(beta_all, beta)} #just to inside the learning epoch<- epoch+1 } } else(break) beta_all<-cbind(beta_all, beta) colnames(beta_all)<-c(beta_at[1:(ncol(beta_all)-1)], epoch-1) mylist<-list(as.matrix(beta), likelihood, beta_all) names(mylist)<- c(\"Beta\", \"likelihood\", \"Beta_all\") return(mylist)} # Fitting of logistic model"
},
{
"code": null,
"e": 16081,
"s": 16057,
"text": "The Prediction Function"
},
{
"code": null,
"e": 17378,
"s": 16081,
"text": "logistic.pred<-function(model, test_data){ test_new<- cbind( rep(1, nrow(test_data)), test_data[,-ncol(test_data)]) #adding 1 to fit the intercept beta<-as.matrix(model$Beta) #extract the best suiting beta (the beta at final epoch) beta_all<-model$Beta_all #extract all the betas at different checkpoints ll<- model$likelihood #extract the highest likelihood obtained log_odd<-cbind(as.matrix(test_new)) %*% beta #logit(p) probability<- 1/(1+ exp(-log_odd)) # p=logistic(logit(p)) predicted_label<- ifelse(probability >= 0.5, 1, 0) #discrimination rule k<-cbind(test_data[,ncol(test_data)], predicted_label) # actual label vs predicted label colnames(k)<- c(\"Actual\", \"Predicted\") k<- as.data.frame(k) tp<-length(which(k$Actual==1 & k$Predicted==1)) #true positive tn<-length(which(k$Actual==0 & k$Predicted==0)) #true negative fp<-length(which(k$Actual==0 & k$Predicted==1)) #false positive fn<-length(which(k$Actual==1 & k$Predicted==0)) #false negative cf<-matrix(c(tp, fn, fp, tn), 2, 2, byrow = F) #confusion matrix rownames(cf)<- c(\"1\", \"0\") colnames(cf)<- c(\"1\", \"0\") p_list<-list(k, cf, beta, ll, beta_all) names(p_list)<- c(\"predticted\", \"confusion matrix\",\"beta\", \"liklihood\", \"Beta_all\") return(p_list) } # to make prediction from the trained model"
},
{
"code": null,
"e": 17391,
"s": 17378,
"text": "Data Parsing"
},
{
"code": null,
"e": 18159,
"s": 17391,
"text": "#importing datadata<-read.csv(\"fire.csv\", header = T) #importdata$Classes<-as.numeric(ifelse(1:nrow(data)%in%grep(\"not\",data$Classes), 0, 1)) # one hot encoding ; numeric conversion from label to 1 or 0data<-rbind(data[which(data$Classes==0),], data[sample(size=length(which(data$Classes==0)),which(data$Classes==1)),]) #balancing the classesdata<-data[sample(1:nrow(data)),] #shufflingdata<-as.data.frame(data) #data to data framedata<-lapply(data, as.numeric) data<-as.data.frame(data)#missing data handlingif(!is.null(is.na(data))){ data<-data[-unique(which(is.na(data), arr.ind = T)[,1]),]}#test train partitionpartition<-sample(c(0,1), size=nrow(data), prob = c(0.8,0.2), replace = T) train<-data[which(partition==0),]test<-data[which(partition==1),]"
},
{
"code": null,
"e": 18188,
"s": 18159,
"text": "Training β Testing β Results"
},
{
"code": null,
"e": 18866,
"s": 18188,
"text": "#-------------------------TRAINING---------------------------------#mymodel_newton<- logistic.train(train, \"Newton\", 0.01, verbose=T) # Fitting the model using Newton methodmymodel_gradient<- logistic.train(train, \"Gradient\", 0.01, verbose=T) # Fitting the model using Gradient method#------------------------TESTING-------------------------------------#myresult1<-logistic.pred( mymodel_newton, test_data = test) #prediction using Newton trained modelmyresult2<-logistic.pred( mymodel_gradient, test_data = test) #prediction using Gradient trained model#------------------------Results----------------------------------#myresult1$`confusion matrix`myresult2$`confusion matrix`"
},
{
"code": null,
"e": 18878,
"s": 18866,
"text": "The Results"
},
{
"code": null,
"e": 19031,
"s": 18878,
"text": "The confusion matrix obtained by both methods is the same. The accuracies obtained by both methods on the independent test set are 95.2% (quite good!!)."
},
{
"code": null,
"e": 19274,
"s": 19031,
"text": "However, the best fitting coefficients Ξ² obtained by both methods are very different in terms of values. Newtonβs method took 3,566 epochs to obtain a likelihood of 1, while Gradient descent took 3,539 to read the maximum likelihood of 0.999."
},
{
"code": null,
"e": 19521,
"s": 19274,
"text": "In terms of time taken, Newtonβs method took more time to reach the optimum in comparison to the gradient method because, in Newton's method, the solving inverse of Hessian makes it a little computationally extensive and time-consuming algorithm."
},
{
"code": null,
"e": 19732,
"s": 19521,
"text": "As you have noticed that I have captured the betas at various checkpoints during the training. This will allow us to peep into the training process that is carried out while maximizing the likelihood (see β©β©β©β©)"
},
{
"code": null,
"e": 19809,
"s": 19732,
"text": "We can also peep into the fitting on the test set by the fully trained model"
},
{
"code": null,
"e": 20246,
"s": 19809,
"text": "So at this point, I think I can reiterate to the reader that the fundamental nature of Logistic Regression is not of classification, rather it is of regression. Through substantiating a regression in its core functioning, The Logistic regression gives output as probability attached to a given instance. It is when a rule of >orβ€ 0.5 or something is employed, the assignment of an instance to a particular discrete class is carried out."
},
{
"code": null,
"e": 20765,
"s": 20246,
"text": "If you are here then go get yourself a fine treat, you are a real MVP. I hope my very casual elaboration on logistic regression gave you slightly better insights into the logistic regression. This article encompasses the concept, the underlying mathematics, and the programming of logistic regression. While the ideas here depict the actual scheme, there are some out-of-scope aspects of the optimizers discussed here, in which the optimizing algorithm might fail to achieve an optimum, more details can be found here."
},
{
"code": null,
"e": 20834,
"s": 20765,
"text": "Feel free to download the entire code (Model and plots) from my git."
},
{
"code": null,
"e": 20910,
"s": 20834,
"text": "The Elements of Statistical Learning Data Mining, Inference, and Prediction"
},
{
"code": null,
"e": 20935,
"s": 20910,
"text": "thelaziestprogrammer.com"
}
] |
Analysis of Algorithms | Set 2 (Worst, Average and Best Cases) - GeeksforGeeks
|
26 Jan, 2022
In the previous post, we discussed how Asymptotic analysis overcomes the problems of the naive way of analyzing algorithms. In this post, we will take an example of Linear Search and analyze it using Asymptotic analysis.We can have three cases to analyze an algorithm: 1) The Worst Case 2) Average Case 3) Best CaseLet us consider the following implementation of Linear Search.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Linearly search x in arr[].// If x is present then return the index,// otherwise return -1int search(int arr[], int n, int x){ int i; for (i = 0; i < n; i++) { if (arr[i] == x) return i; } return -1;} // Driver Codeint main(){ int arr[] = { 1, 10, 30, 15 }; int x = 30; int n = sizeof(arr) / sizeof(arr[0]); cout << x << " is present at index " << search(arr, n, x); getchar(); return 0;} // This code is contributed// by Akanksha Rai
// C implementation of the approach#include <stdio.h> // Linearly search x in arr[].// If x is present then return the index,// otherwise return -1int search(int arr[], int n, int x){ int i; for (i = 0; i < n; i++) { if (arr[i] == x) return i; } return -1;} /* Driver program to test above functions*/int main(){ int arr[] = { 1, 10, 30, 15 }; int x = 30; int n = sizeof(arr) / sizeof(arr[0]); printf("%d is present at index %d", x, search(arr, n, x)); getchar(); return 0;}
// Java implementation of the approach public class GFG { // Linearly search x in arr[]. If x is present then // return the index, otherwise return -1 static int search(int arr[], int n, int x) { int i; for (i = 0; i < n; i++) { if (arr[i] == x) { return i; } } return -1; } /* Driver program to test above functions*/ public static void main(String[] args) { int arr[] = { 1, 10, 30, 15 }; int x = 30; int n = arr.length; System.out.printf("%d is present at index %d", x, search(arr, n, x)); }} /*This code is contributed by PrinciRaj1992*/
# Python 3 implementation of the approach # Linearly search x in arr[]. If x is present# then return the index, otherwise return -1 def search(arr, x): for index, value in enumerate(arr): if value == x: return index return -1 # Driver Codearr = [1, 10, 30, 15]x = 30print(x, "is present at index", search(arr, x)) # This code is contributed# by PrinciRaj1992
// C# implementation of the approachusing System;public class GFG { // Linearly search x in arr[]. If x is present then // return the index, otherwise return -1 static int search(int[] arr, int n, int x) { int i; for (i = 0; i < n; i++) { if (arr[i] == x) { return i; } } return -1; } /* Driver program to test above functions*/ public static void Main() { int[] arr = { 1, 10, 30, 15 }; int x = 30; int n = arr.Length; Console.WriteLine(x + " is present at index " + search(arr, n, x)); }} /*This code is contributed by PrinciRaj1992*/
<?php// PHP implementation of the approach // Linearly search x in arr[]. If x// is present then return the index,// otherwise return -1function search($arr, $n, $x){ for ($i = 0; $i < $n; $i++) { if ($arr[$i] == $x) return $i; } return -1;} // Driver Code$arr = array(1, 10, 30, 15);$x = 30;$n = sizeof($arr);echo $x . " is present at index ". search($arr, $n, $x); // This code is contributed// by Akanksha Rai
<script>// javascript implementation of the approach // Linearly search x in arr. If x is present then // return the index, otherwise return -1 function search(arr , n , x) { var i; for (i = 0; i < n; i++) { if (arr[i] == x) { return i; } } return -1; } /* Driver program to test above functions */ var arr = [ 1, 10, 30, 15 ]; var x = 30; var n = arr.length; document.write(x+" is present at index "+ search(arr, n, x)); // This code is contributed by gauravrajput1</script>
Output:
30 is present at index 2
Worst Case Analysis (Usually Done) In the worst-case analysis, we calculate the upper bound on the running time of an algorithm. We must know the case that causes a maximum number of operations to be executed. For Linear Search, the worst case happens when the element to be searched (x in the above code) is not present in the array. When x is not present, the search() function compares it with all the elements of arr[] one by one. Therefore, the worst-case time complexity of linear search would be Ξ(n).
Average Case Analysis (Sometimes done) In average case analysis, we take all possible inputs and calculate computing time for all of the inputs. Sum all the calculated values and divide the sum by the total number of inputs. We must know (or predict) the distribution of cases. For the linear search problem, let us assume that all cases are uniformly distributed (including the case of x not being present in the array). So we sum all the cases and divide the sum by (n+1). Following is the value of average-case time complexity.
Average Case Time =
=
= Ξ(n)
Best Case Analysis (Bogus) In the best case analysis, we calculate the lower bound on the running time of an algorithm. We must know the case that causes a minimum number of operations to be executed. In the linear search problem, the best case occurs when x is present at the first location. The number of operations in the best case is constant (not dependent on n). So time complexity in the best case would be Ξ(1) Most of the times, we do worst-case analysis to analyze algorithms. In the worst analysis, we guarantee an upper bound on the running time of an algorithm which is good information. The average case analysis is not easy to do in most practical cases and it is rarely done. In the average case analysis, we must know (or predict) the mathematical distribution of all possible inputs. The Best Case analysis is bogus. Guaranteeing a lower bound on an algorithm doesnβt provide any information as in the worst case, an algorithm may take years to run.For some algorithms, all the cases are asymptotically the same, i.e., there are no worst and best cases. For example, Merge Sort. Merge Sort does Ξ(nlogn) operations in all cases. Most of the other sorting algorithms have worst and best cases. For example, in the typical implementation of Quick Sort (where pivot is chosen as a corner element), the worst occurs when the input array is already sorted and the best occurs when the pivot elements always divide the array into two halves. For insertion sort, the worst case occurs when the array is reverse sorted and the best case occurs when the array is sorted in the same order as output.
https://youtu.be/rlZpZ8es_6k
princiraj1992
Akanksha_Rai
AnkurChattopadhyay
GauriShankarBadola
urvishmahajan
GauravRajput1
tanvibugdani
Analysis
Articles
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Practice Questions on Time Complexity Analysis
Understanding Time Complexity with Simple Examples
Time Complexity and Space Complexity
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Time Complexity of building a heap
Tree Traversals (Inorder, Preorder and Postorder)
SQL | Join (Inner, Left, Right and Full Joins)
find command in Linux with examples
Mutex vs Semaphore
Understanding "extern" keyword in C
|
[
{
"code": null,
"e": 34514,
"s": 34486,
"text": "\n26 Jan, 2022"
},
{
"code": null,
"e": 34894,
"s": 34514,
"text": "In the previous post, we discussed how Asymptotic analysis overcomes the problems of the naive way of analyzing algorithms. In this post, we will take an example of Linear Search and analyze it using Asymptotic analysis.We can have three cases to analyze an algorithm: 1) The Worst Case 2) Average Case 3) Best CaseLet us consider the following implementation of Linear Search. "
},
{
"code": null,
"e": 34898,
"s": 34894,
"text": "C++"
},
{
"code": null,
"e": 34900,
"s": 34898,
"text": "C"
},
{
"code": null,
"e": 34905,
"s": 34900,
"text": "Java"
},
{
"code": null,
"e": 34913,
"s": 34905,
"text": "Python3"
},
{
"code": null,
"e": 34916,
"s": 34913,
"text": "C#"
},
{
"code": null,
"e": 34920,
"s": 34916,
"text": "PHP"
},
{
"code": null,
"e": 34931,
"s": 34920,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Linearly search x in arr[].// If x is present then return the index,// otherwise return -1int search(int arr[], int n, int x){ int i; for (i = 0; i < n; i++) { if (arr[i] == x) return i; } return -1;} // Driver Codeint main(){ int arr[] = { 1, 10, 30, 15 }; int x = 30; int n = sizeof(arr) / sizeof(arr[0]); cout << x << \" is present at index \" << search(arr, n, x); getchar(); return 0;} // This code is contributed// by Akanksha Rai",
"e": 35508,
"s": 34931,
"text": null
},
{
"code": "// C implementation of the approach#include <stdio.h> // Linearly search x in arr[].// If x is present then return the index,// otherwise return -1int search(int arr[], int n, int x){ int i; for (i = 0; i < n; i++) { if (arr[i] == x) return i; } return -1;} /* Driver program to test above functions*/int main(){ int arr[] = { 1, 10, 30, 15 }; int x = 30; int n = sizeof(arr) / sizeof(arr[0]); printf(\"%d is present at index %d\", x, search(arr, n, x)); getchar(); return 0;}",
"e": 36042,
"s": 35508,
"text": null
},
{
"code": "// Java implementation of the approach public class GFG { // Linearly search x in arr[]. If x is present then // return the index, otherwise return -1 static int search(int arr[], int n, int x) { int i; for (i = 0; i < n; i++) { if (arr[i] == x) { return i; } } return -1; } /* Driver program to test above functions*/ public static void main(String[] args) { int arr[] = { 1, 10, 30, 15 }; int x = 30; int n = arr.length; System.out.printf(\"%d is present at index %d\", x, search(arr, n, x)); }} /*This code is contributed by PrinciRaj1992*/",
"e": 36732,
"s": 36042,
"text": null
},
{
"code": "# Python 3 implementation of the approach # Linearly search x in arr[]. If x is present# then return the index, otherwise return -1 def search(arr, x): for index, value in enumerate(arr): if value == x: return index return -1 # Driver Codearr = [1, 10, 30, 15]x = 30print(x, \"is present at index\", search(arr, x)) # This code is contributed# by PrinciRaj1992",
"e": 37122,
"s": 36732,
"text": null
},
{
"code": "// C# implementation of the approachusing System;public class GFG { // Linearly search x in arr[]. If x is present then // return the index, otherwise return -1 static int search(int[] arr, int n, int x) { int i; for (i = 0; i < n; i++) { if (arr[i] == x) { return i; } } return -1; } /* Driver program to test above functions*/ public static void Main() { int[] arr = { 1, 10, 30, 15 }; int x = 30; int n = arr.Length; Console.WriteLine(x + \" is present at index \" + search(arr, n, x)); }} /*This code is contributed by PrinciRaj1992*/",
"e": 37807,
"s": 37122,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Linearly search x in arr[]. If x// is present then return the index,// otherwise return -1function search($arr, $n, $x){ for ($i = 0; $i < $n; $i++) { if ($arr[$i] == $x) return $i; } return -1;} // Driver Code$arr = array(1, 10, 30, 15);$x = 30;$n = sizeof($arr);echo $x . \" is present at index \". search($arr, $n, $x); // This code is contributed// by Akanksha Rai",
"e": 38254,
"s": 37807,
"text": null
},
{
"code": "<script>// javascript implementation of the approach // Linearly search x in arr. If x is present then // return the index, otherwise return -1 function search(arr , n , x) { var i; for (i = 0; i < n; i++) { if (arr[i] == x) { return i; } } return -1; } /* Driver program to test above functions */ var arr = [ 1, 10, 30, 15 ]; var x = 30; var n = arr.length; document.write(x+\" is present at index \"+ search(arr, n, x)); // This code is contributed by gauravrajput1</script>",
"e": 38846,
"s": 38254,
"text": null
},
{
"code": null,
"e": 38855,
"s": 38846,
"text": "Output: "
},
{
"code": null,
"e": 38880,
"s": 38855,
"text": "30 is present at index 2"
},
{
"code": null,
"e": 39389,
"s": 38880,
"text": "Worst Case Analysis (Usually Done) In the worst-case analysis, we calculate the upper bound on the running time of an algorithm. We must know the case that causes a maximum number of operations to be executed. For Linear Search, the worst case happens when the element to be searched (x in the above code) is not present in the array. When x is not present, the search() function compares it with all the elements of arr[] one by one. Therefore, the worst-case time complexity of linear search would be Ξ(n)."
},
{
"code": null,
"e": 39922,
"s": 39389,
"text": "Average Case Analysis (Sometimes done) In average case analysis, we take all possible inputs and calculate computing time for all of the inputs. Sum all the calculated values and divide the sum by the total number of inputs. We must know (or predict) the distribution of cases. For the linear search problem, let us assume that all cases are uniformly distributed (including the case of x not being present in the array). So we sum all the cases and divide the sum by (n+1). Following is the value of average-case time complexity. "
},
{
"code": null,
"e": 39944,
"s": 39922,
"text": "Average Case Time = "
},
{
"code": null,
"e": 39947,
"s": 39944,
"text": "= "
},
{
"code": null,
"e": 39955,
"s": 39947,
"text": "= Ξ(n) "
},
{
"code": null,
"e": 41564,
"s": 39955,
"text": "Best Case Analysis (Bogus) In the best case analysis, we calculate the lower bound on the running time of an algorithm. We must know the case that causes a minimum number of operations to be executed. In the linear search problem, the best case occurs when x is present at the first location. The number of operations in the best case is constant (not dependent on n). So time complexity in the best case would be Ξ(1) Most of the times, we do worst-case analysis to analyze algorithms. In the worst analysis, we guarantee an upper bound on the running time of an algorithm which is good information. The average case analysis is not easy to do in most practical cases and it is rarely done. In the average case analysis, we must know (or predict) the mathematical distribution of all possible inputs. The Best Case analysis is bogus. Guaranteeing a lower bound on an algorithm doesnβt provide any information as in the worst case, an algorithm may take years to run.For some algorithms, all the cases are asymptotically the same, i.e., there are no worst and best cases. For example, Merge Sort. Merge Sort does Ξ(nlogn) operations in all cases. Most of the other sorting algorithms have worst and best cases. For example, in the typical implementation of Quick Sort (where pivot is chosen as a corner element), the worst occurs when the input array is already sorted and the best occurs when the pivot elements always divide the array into two halves. For insertion sort, the worst case occurs when the array is reverse sorted and the best case occurs when the array is sorted in the same order as output. "
},
{
"code": null,
"e": 41593,
"s": 41564,
"text": "https://youtu.be/rlZpZ8es_6k"
},
{
"code": null,
"e": 41607,
"s": 41593,
"text": "princiraj1992"
},
{
"code": null,
"e": 41620,
"s": 41607,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 41639,
"s": 41620,
"text": "AnkurChattopadhyay"
},
{
"code": null,
"e": 41658,
"s": 41639,
"text": "GauriShankarBadola"
},
{
"code": null,
"e": 41672,
"s": 41658,
"text": "urvishmahajan"
},
{
"code": null,
"e": 41686,
"s": 41672,
"text": "GauravRajput1"
},
{
"code": null,
"e": 41699,
"s": 41686,
"text": "tanvibugdani"
},
{
"code": null,
"e": 41708,
"s": 41699,
"text": "Analysis"
},
{
"code": null,
"e": 41717,
"s": 41708,
"text": "Articles"
},
{
"code": null,
"e": 41815,
"s": 41717,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41824,
"s": 41815,
"text": "Comments"
},
{
"code": null,
"e": 41837,
"s": 41824,
"text": "Old Comments"
},
{
"code": null,
"e": 41884,
"s": 41837,
"text": "Practice Questions on Time Complexity Analysis"
},
{
"code": null,
"e": 41935,
"s": 41884,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 41972,
"s": 41935,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 42055,
"s": 41972,
"text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree"
},
{
"code": null,
"e": 42090,
"s": 42055,
"text": "Time Complexity of building a heap"
},
{
"code": null,
"e": 42140,
"s": 42090,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 42187,
"s": 42140,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 42223,
"s": 42187,
"text": "find command in Linux with examples"
},
{
"code": null,
"e": 42242,
"s": 42223,
"text": "Mutex vs Semaphore"
}
] |
Minimum Remove to Make Valid Parentheses in C++
|
Suppose we have a string s of '(' , ')' and lowercase English characters. We have to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parenthese string is valid and return any valid string. A parentheses string is valid when all of these criteria are fulfilled β
It is the empty string, contains lowercase characters only, or
It is the empty string, contains lowercase characters only, or
It can be written as the form of AB (A concatenated with B), where A and B are valid strings, or
It can be written as the form of AB (A concatenated with B), where A and B are valid strings, or
It can be written as the form of (A), where A is a valid string.
It can be written as the form of (A), where A is a valid string.
So if the input is like βa)b(c)dβ, then the output will be βab(c)dβ
To solve this, we will follow these steps β
Define a stack st
Define a stack st
for i in range 0 to size of sif s[i] = β(β, then insert i into stotherwise when s[i] is β)β, thenif stack is not empty, then pop from stack, otherwise s[i] = β*β
for i in range 0 to size of s
if s[i] = β(β, then insert i into st
if s[i] = β(β, then insert i into st
otherwise when s[i] is β)β, thenif stack is not empty, then pop from stack, otherwise s[i] = β*β
otherwise when s[i] is β)β, then
if stack is not empty, then pop from stack, otherwise s[i] = β*β
if stack is not empty, then pop from stack, otherwise s[i] = β*β
while st is not empty,s[top element of stack] = β*βpop from stack
while st is not empty,
s[top element of stack] = β*β
s[top element of stack] = β*β
pop from stack
pop from stack
ans := empty string
ans := empty string
for i in range 0 to size of s β 1if s[i] is not β*β, then ans := ans + s[i]
for i in range 0 to size of s β 1
if s[i] is not β*β, then ans := ans + s[i]
if s[i] is not β*β, then ans := ans + s[i]
return ans
return ans
Let us see the following implementation to get better understanding β
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string minRemoveToMakeValid(string s) {
stack <int> st;
for(int i = 0; i < s.size(); i++){
if(s[i] == '(')st.push(i);
else if(s[i] == ')'){
if(!st.empty())st.pop();
else s[i] = '*';
}
}
while(!st.empty()){
s[st.top()] = '*';
st.pop();
}
string ans = "";
for(int i = 0; i < s.size(); i++){
if(s[i] != '*')ans += s[i];
}
return ans;
}
};
main(){
Solution ob;
cout << (ob.minRemoveToMakeValid("a)b(c)d"));
}
"a)b(c)d"
ab(c)d
|
[
{
"code": null,
"e": 1372,
"s": 1062,
"text": "Suppose we have a string s of '(' , ')' and lowercase English characters. We have to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parenthese string is valid and return any valid string. A parentheses string is valid when all of these criteria are fulfilled β"
},
{
"code": null,
"e": 1435,
"s": 1372,
"text": "It is the empty string, contains lowercase characters only, or"
},
{
"code": null,
"e": 1498,
"s": 1435,
"text": "It is the empty string, contains lowercase characters only, or"
},
{
"code": null,
"e": 1595,
"s": 1498,
"text": "It can be written as the form of AB (A concatenated with B), where A and B are valid strings, or"
},
{
"code": null,
"e": 1692,
"s": 1595,
"text": "It can be written as the form of AB (A concatenated with B), where A and B are valid strings, or"
},
{
"code": null,
"e": 1757,
"s": 1692,
"text": "It can be written as the form of (A), where A is a valid string."
},
{
"code": null,
"e": 1822,
"s": 1757,
"text": "It can be written as the form of (A), where A is a valid string."
},
{
"code": null,
"e": 1890,
"s": 1822,
"text": "So if the input is like βa)b(c)dβ, then the output will be βab(c)dβ"
},
{
"code": null,
"e": 1934,
"s": 1890,
"text": "To solve this, we will follow these steps β"
},
{
"code": null,
"e": 1952,
"s": 1934,
"text": "Define a stack st"
},
{
"code": null,
"e": 1970,
"s": 1952,
"text": "Define a stack st"
},
{
"code": null,
"e": 2132,
"s": 1970,
"text": "for i in range 0 to size of sif s[i] = β(β, then insert i into stotherwise when s[i] is β)β, thenif stack is not empty, then pop from stack, otherwise s[i] = β*β"
},
{
"code": null,
"e": 2162,
"s": 2132,
"text": "for i in range 0 to size of s"
},
{
"code": null,
"e": 2199,
"s": 2162,
"text": "if s[i] = β(β, then insert i into st"
},
{
"code": null,
"e": 2236,
"s": 2199,
"text": "if s[i] = β(β, then insert i into st"
},
{
"code": null,
"e": 2333,
"s": 2236,
"text": "otherwise when s[i] is β)β, thenif stack is not empty, then pop from stack, otherwise s[i] = β*β"
},
{
"code": null,
"e": 2366,
"s": 2333,
"text": "otherwise when s[i] is β)β, then"
},
{
"code": null,
"e": 2431,
"s": 2366,
"text": "if stack is not empty, then pop from stack, otherwise s[i] = β*β"
},
{
"code": null,
"e": 2496,
"s": 2431,
"text": "if stack is not empty, then pop from stack, otherwise s[i] = β*β"
},
{
"code": null,
"e": 2562,
"s": 2496,
"text": "while st is not empty,s[top element of stack] = β*βpop from stack"
},
{
"code": null,
"e": 2585,
"s": 2562,
"text": "while st is not empty,"
},
{
"code": null,
"e": 2615,
"s": 2585,
"text": "s[top element of stack] = β*β"
},
{
"code": null,
"e": 2645,
"s": 2615,
"text": "s[top element of stack] = β*β"
},
{
"code": null,
"e": 2660,
"s": 2645,
"text": "pop from stack"
},
{
"code": null,
"e": 2675,
"s": 2660,
"text": "pop from stack"
},
{
"code": null,
"e": 2695,
"s": 2675,
"text": "ans := empty string"
},
{
"code": null,
"e": 2715,
"s": 2695,
"text": "ans := empty string"
},
{
"code": null,
"e": 2791,
"s": 2715,
"text": "for i in range 0 to size of s β 1if s[i] is not β*β, then ans := ans + s[i]"
},
{
"code": null,
"e": 2825,
"s": 2791,
"text": "for i in range 0 to size of s β 1"
},
{
"code": null,
"e": 2868,
"s": 2825,
"text": "if s[i] is not β*β, then ans := ans + s[i]"
},
{
"code": null,
"e": 2911,
"s": 2868,
"text": "if s[i] is not β*β, then ans := ans + s[i]"
},
{
"code": null,
"e": 2922,
"s": 2911,
"text": "return ans"
},
{
"code": null,
"e": 2933,
"s": 2922,
"text": "return ans"
},
{
"code": null,
"e": 3003,
"s": 2933,
"text": "Let us see the following implementation to get better understanding β"
},
{
"code": null,
"e": 3014,
"s": 3003,
"text": " Live Demo"
},
{
"code": null,
"e": 3635,
"s": 3014,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n string minRemoveToMakeValid(string s) {\n stack <int> st;\n for(int i = 0; i < s.size(); i++){\n if(s[i] == '(')st.push(i);\n else if(s[i] == ')'){\n if(!st.empty())st.pop();\n else s[i] = '*';\n }\n }\n while(!st.empty()){\n s[st.top()] = '*';\n st.pop();\n }\n string ans = \"\";\n for(int i = 0; i < s.size(); i++){\n if(s[i] != '*')ans += s[i];\n }\n return ans;\n }\n};\nmain(){\n Solution ob;\n cout << (ob.minRemoveToMakeValid(\"a)b(c)d\"));\n}"
},
{
"code": null,
"e": 3645,
"s": 3635,
"text": "\"a)b(c)d\""
},
{
"code": null,
"e": 3652,
"s": 3645,
"text": "ab(c)d"
}
] |
Minimum Depth of a Binary Tree | Practice | GeeksforGeeks
|
Given a binary tree, find its minimum depth.
Example 1:
Input:
1
/ \
3 2
/
4
Output: 2
Explanation:
Minimum depth is between nodes 1 and 2 since
minimum depth is defined as the number of
nodes along the shortest path from the root
node down to the nearest leaf node.
Example 2:
Input:
10
/ \
20 30
\ \
40 60
/
2
Output: 3
Explanation:
Minimum depth is between nodes 10,20 and 40.
Your Task:
You don't need to read input or print anything. Complete the function minDepth() which takes the root node as an input parameter and returns the minimum depth.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(height of the tree)
Constraints:
1 β€ N β€ 10^5
0
devashishbakare1 month ago
JAVA SOLUTION WITH EXPLANATION
while trying to do a normal Min(left call + right call + 1) then we have very less count because a root have null to left or right then we consider only null element due than required answer change
While solving this problem we have some cases as discuss below int minDepth(Node root){ if(root == null) return 0; //if we reach out to null node then we have to return null //no need to count coz it leaf node
if(root.left==null && root.right== null) return 1; //left is not null and right is null Math.min will not work it update less count hence final count is reduced
else if(root.left!=null && root.right== null) return minDepth(root.left)+1; //right is not null and left is null Math.min will not work it update less count hence final count is reduced
else if(root.left==null && root.right!= null) return minDepth(root.right)+1; //if both not null means there is proper subtree from left side and right side and we have required minimum so used basic formula and consider root itself hence +1 else return Math.min(minDepth(root.left), minDepth(root.right)) + 1; }
0
detroix071 month ago
class Solution { public: /*You are required to complete this method*/
void dfs(Node* root , int level, int &d) { // base case if(root==NULL) return; // when encounter with leaf node , it can be one of my answer if(!root->left && !root->right) { if(level < d) { d=level; } } dfs(root->left,level+1,d); dfs(root->right,level+1,d); } int minDepth(Node *root) { int d = INT_MAX; dfs(root,0,d); return d+1; }};
0
manudatta4u1 month ago
Python3 solution:
Time taken: 0.6/2.2
class Solution:
def minDepth(self, root):
if root is None:
return 0
left = self.minDepth(root.left)
right = self.minDepth(root.right)
if(root.left and root.right):
return 1 + min(left, right)
elif(root.left):
return 1+ left
else:
return 1 + right
0
redeagle172 months ago
class Solution{ public: /*You are required to complete this method*/ int minDepth(Node *root) { // Your code here if(root==NULL){ return 0; } int l=minDepth(root->left); int r=minDepth(root->right); if(l==0 || r==0){ return 1+max(l,r); } return 1+min(l,r); }};
0
imaniket2 months ago
int minDepth(Node *root) {
if(root->left==NULL && root->right==NULL) return 1;
int left = root->left ? 1+minDepth(root->left): INT_MAX;
int right = root->right ? 1+minDepth(root->right): INT_MAX;
return min(left, right);
}
+1
amanpandey30072 months ago
int solve(Node*root) { if(!root) return 0; int l=solve(root->left); int r=solve(root->right); if(l==0 and r==0) return 1; if(l==0) return r+1; if(r==0) return l+1; return min(l,r)+1; } int minDepth(Node *root) { return solve(root); }
0
dronzerdracel2 months ago
My simple solution using helper function
class Solution{
public:
/*You are required to complete this method*/
void min(Node* root,int level,int &minm){
if(!root)
return;
if(!root->left&&!root->right){
if(level<minm)
minm=level;
}
min(root->left,level+1,minm);
min(root->right,level+1,minm);
}
int minDepth(Node *root) {
// Your code here
if(!root)
return 0;
int minm=INT_MAX;
min(root,0,minm);
return 1+minm;
}
};
0
tanujrajput00002 months ago
int minDepth(Node *root) {
// Your code here
if(!root) return 0;
int left = minDepth(root->left);
int right = minDepth(root->right);
if(root->left and root->right) return 1 + min(left,right);
else if(root->left) return 1 + left;
else return 1 + right;
}
+1
ashiqhussainkumar1433 months ago
int minDepth(Node *root) { // Your code here if(!root) return 0; int left=minDepth(root->left); int right=minDepth(root->right); if(root->left and root->right) return 1+min(left , right); else if(root->left) return 1+left; else return 1+right; }
0
namanshah22753 months ago
cpp solution time O(N) 0.2 sec space O(h)
public: /*You are required to complete this method*/ int minDepth(Node *root) { if(root == NULL) return 0; int l = minDepth(root->left); int r = minDepth(root->right); if(root->left == NULL || root->right == NULL) return 1+max(l,r); return 1+min(l,r); }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 283,
"s": 238,
"text": "Given a binary tree, find its minimum depth."
},
{
"code": null,
"e": 294,
"s": 283,
"text": "Example 1:"
},
{
"code": null,
"e": 573,
"s": 294,
"text": "Input:\n 1\n / \\\n 3 2\n /\n 4 \n\nOutput: 2\n\nExplanation:\nMinimum depth is between nodes 1 and 2 since\nminimum depth is defined as the number of \nnodes along the shortest path from the root \nnode down to the nearest leaf node."
},
{
"code": null,
"e": 585,
"s": 573,
"text": "\nExample 2:"
},
{
"code": null,
"e": 806,
"s": 585,
"text": "Input:\n 10\n / \\\n 20 30\n \\ \\ \n 40 60 \n /\n 2 \n\nOutput: 3\n\nExplanation:\nMinimum depth is between nodes 10,20 and 40."
},
{
"code": null,
"e": 982,
"s": 806,
"text": "\nYour Task: \nYou don't need to read input or print anything. Complete the function minDepth() which takes the root node as an input parameter and returns the minimum depth.\n "
},
{
"code": null,
"e": 1063,
"s": 982,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(height of the tree)\n "
},
{
"code": null,
"e": 1089,
"s": 1063,
"text": "Constraints:\n1 β€ N β€ 10^5"
},
{
"code": null,
"e": 1091,
"s": 1089,
"text": "0"
},
{
"code": null,
"e": 1118,
"s": 1091,
"text": "devashishbakare1 month ago"
},
{
"code": null,
"e": 1149,
"s": 1118,
"text": "JAVA SOLUTION WITH EXPLANATION"
},
{
"code": null,
"e": 1352,
"s": 1151,
"text": "while trying to do a normal Min(left call + right call + 1) then we have very less count because a root have null to left or right then we consider only null element due than required answer change "
},
{
"code": null,
"e": 1578,
"s": 1352,
"text": "While solving this problem we have some cases as discuss below int minDepth(Node root){ if(root == null) return 0; //if we reach out to null node then we have to return null //no need to count coz it leaf node"
},
{
"code": null,
"e": 1757,
"s": 1578,
"text": " if(root.left==null && root.right== null) return 1; //left is not null and right is null Math.min will not work it update less count hence final count is reduced"
},
{
"code": null,
"e": 1961,
"s": 1757,
"text": " else if(root.left!=null && root.right== null) return minDepth(root.left)+1; //right is not null and left is null Math.min will not work it update less count hence final count is reduced "
},
{
"code": null,
"e": 2301,
"s": 1961,
"text": " else if(root.left==null && root.right!= null) return minDepth(root.right)+1; //if both not null means there is proper subtree from left side and right side and we have required minimum so used basic formula and consider root itself hence +1 else return Math.min(minDepth(root.left), minDepth(root.right)) + 1; }"
},
{
"code": null,
"e": 2307,
"s": 2305,
"text": "0"
},
{
"code": null,
"e": 2328,
"s": 2307,
"text": "detroix071 month ago"
},
{
"code": null,
"e": 2400,
"s": 2328,
"text": "class Solution { public: /*You are required to complete this method*/"
},
{
"code": null,
"e": 2829,
"s": 2400,
"text": " void dfs(Node* root , int level, int &d) { // base case if(root==NULL) return; // when encounter with leaf node , it can be one of my answer if(!root->left && !root->right) { if(level < d) { d=level; } } dfs(root->left,level+1,d); dfs(root->right,level+1,d); } int minDepth(Node *root) { int d = INT_MAX; dfs(root,0,d); return d+1; }};"
},
{
"code": null,
"e": 2831,
"s": 2829,
"text": "0"
},
{
"code": null,
"e": 2854,
"s": 2831,
"text": "manudatta4u1 month ago"
},
{
"code": null,
"e": 2872,
"s": 2854,
"text": "Python3 solution:"
},
{
"code": null,
"e": 2892,
"s": 2872,
"text": "Time taken: 0.6/2.2"
},
{
"code": null,
"e": 3263,
"s": 2894,
"text": "class Solution:\n def minDepth(self, root):\n if root is None:\n return 0\n \n left = self.minDepth(root.left)\n right = self.minDepth(root.right)\n \n if(root.left and root.right):\n return 1 + min(left, right)\n elif(root.left):\n return 1+ left\n else:\n return 1 + right"
},
{
"code": null,
"e": 3265,
"s": 3263,
"text": "0"
},
{
"code": null,
"e": 3288,
"s": 3265,
"text": "redeagle172 months ago"
},
{
"code": null,
"e": 3623,
"s": 3288,
"text": "class Solution{ public: /*You are required to complete this method*/ int minDepth(Node *root) { // Your code here if(root==NULL){ return 0; } int l=minDepth(root->left); int r=minDepth(root->right); if(l==0 || r==0){ return 1+max(l,r); } return 1+min(l,r); }};"
},
{
"code": null,
"e": 3625,
"s": 3623,
"text": "0"
},
{
"code": null,
"e": 3646,
"s": 3625,
"text": "imaniket2 months ago"
},
{
"code": null,
"e": 3901,
"s": 3646,
"text": "int minDepth(Node *root) {\n if(root->left==NULL && root->right==NULL) return 1;\n int left = root->left ? 1+minDepth(root->left): INT_MAX;\n int right = root->right ? 1+minDepth(root->right): INT_MAX;\n return min(left, right);\n }"
},
{
"code": null,
"e": 3904,
"s": 3901,
"text": "+1"
},
{
"code": null,
"e": 3931,
"s": 3904,
"text": "amanpandey30072 months ago"
},
{
"code": null,
"e": 4305,
"s": 3931,
"text": "int solve(Node*root) { if(!root) return 0; int l=solve(root->left); int r=solve(root->right); if(l==0 and r==0) return 1; if(l==0) return r+1; if(r==0) return l+1; return min(l,r)+1; } int minDepth(Node *root) { return solve(root); } "
},
{
"code": null,
"e": 4307,
"s": 4305,
"text": "0"
},
{
"code": null,
"e": 4333,
"s": 4307,
"text": "dronzerdracel2 months ago"
},
{
"code": null,
"e": 4374,
"s": 4333,
"text": "My simple solution using helper function"
},
{
"code": null,
"e": 4893,
"s": 4374,
"text": "class Solution{\n public:\n /*You are required to complete this method*/\n void min(Node* root,int level,int &minm){\n if(!root)\n return;\n if(!root->left&&!root->right){\n if(level<minm)\n minm=level;\n } \n min(root->left,level+1,minm);\n min(root->right,level+1,minm);\n }\n int minDepth(Node *root) {\n // Your code here\n if(!root)\n return 0;\n int minm=INT_MAX;\n min(root,0,minm);\n return 1+minm;\n }\n};"
},
{
"code": null,
"e": 4895,
"s": 4893,
"text": "0"
},
{
"code": null,
"e": 4923,
"s": 4895,
"text": "tanujrajput00002 months ago"
},
{
"code": null,
"e": 5238,
"s": 4923,
"text": " int minDepth(Node *root) {\n // Your code here\n if(!root) return 0;\n int left = minDepth(root->left);\n int right = minDepth(root->right);\n if(root->left and root->right) return 1 + min(left,right);\n else if(root->left) return 1 + left;\n else return 1 + right;\n }"
},
{
"code": null,
"e": 5241,
"s": 5238,
"text": "+1"
},
{
"code": null,
"e": 5274,
"s": 5241,
"text": "ashiqhussainkumar1433 months ago"
},
{
"code": null,
"e": 5568,
"s": 5274,
"text": " int minDepth(Node *root) { // Your code here if(!root) return 0; int left=minDepth(root->left); int right=minDepth(root->right); if(root->left and root->right) return 1+min(left , right); else if(root->left) return 1+left; else return 1+right; }"
},
{
"code": null,
"e": 5570,
"s": 5568,
"text": "0"
},
{
"code": null,
"e": 5596,
"s": 5570,
"text": "namanshah22753 months ago"
},
{
"code": null,
"e": 5638,
"s": 5596,
"text": "cpp solution time O(N) 0.2 sec space O(h)"
},
{
"code": null,
"e": 5972,
"s": 5640,
"text": "public: /*You are required to complete this method*/ int minDepth(Node *root) { if(root == NULL) return 0; int l = minDepth(root->left); int r = minDepth(root->right); if(root->left == NULL || root->right == NULL) return 1+max(l,r); return 1+min(l,r); }"
},
{
"code": null,
"e": 6120,
"s": 5974,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 6156,
"s": 6120,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6166,
"s": 6156,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6176,
"s": 6166,
"text": "\nContest\n"
},
{
"code": null,
"e": 6239,
"s": 6176,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6387,
"s": 6239,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 6595,
"s": 6387,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 6701,
"s": 6595,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Draw Dot Patterns Using Turtle in Python - GeeksforGeeks
|
10 Jul, 2020
Prerequisite: Turtle Programming Basics
Turtle is an inbuilt module in Python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle (pen). To move turtle, there are some functions i.e forward(), backward(), etc.
Following steps are used :
Import turtle
Make turtle
Define a function to draw a square with dots
Call that function
Hide the turtle.
Below is the implementation :
Python3
# import package and making objectimport turtle pen = turtle.Turtle() # method to draw square with dots# space --> distance between dots# x --> side of squaredef draw(space,x): for i in range(x): for j in range(x): # dot pen.dot() # distance for another dot pen.forward(space) pen.backward(space*x) # direction pen.right(90) pen.forward(space) pen.left(90) # Main Sectionpen.penup()draw(10,8) # hide the turtlepen.hideturtle()
Output :
Following steps are used :
Import turtle
Make turtle
Define a function to draw a rectangle with dots
Call that function
Hide the turtle.
Below is the implementation :
Python3
# import package and making objectimport turtle pen = turtle.Turtle() # method to draw rectangle with dots# space --> distance between dots# x --> height of rectangle# y --> width of rectangledef draw(space,x,y): for i in range(x): for j in range(y): # dot pen.dot() # distance for another dot pen.forward(space) pen.backward(space*y) # direction pen.right(90) pen.forward(space) pen.left(90) # Main Sectionpen.penup()draw(10,5,12) # hide the turtlepen.hideturtle()
Output :
Following steps are used :
Import turtle
Make turtle
Define a function to draw a diamond with dots
Call that function
Hide the turtle.
Below is the implementation :
Python3
# import package and making objectimport turtle pen = turtle.Turtle() # method to draw diamond with dots# space --> distance between dots# x --> side of diamonddef draw(space,x): for i in range(x): for j in range(x): # dot pen.dot() # distance for another dot pen.forward(space) pen.backward(space*x) # direction pen.right(90) pen.forward(space) pen.left(90) # Main Sectionpen.penup() # direction to form diamondpen.left(45)draw(10,8) # hide the turtlepen.hideturtle()
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 23941,
"s": 23901,
"text": "Prerequisite: Turtle Programming Basics"
},
{
"code": null,
"e": 24185,
"s": 23941,
"text": "Turtle is an inbuilt module in Python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle (pen). To move turtle, there are some functions i.e forward(), backward(), etc."
},
{
"code": null,
"e": 24212,
"s": 24185,
"text": "Following steps are used :"
},
{
"code": null,
"e": 24226,
"s": 24212,
"text": "Import turtle"
},
{
"code": null,
"e": 24238,
"s": 24226,
"text": "Make turtle"
},
{
"code": null,
"e": 24283,
"s": 24238,
"text": "Define a function to draw a square with dots"
},
{
"code": null,
"e": 24302,
"s": 24283,
"text": "Call that function"
},
{
"code": null,
"e": 24319,
"s": 24302,
"text": "Hide the turtle."
},
{
"code": null,
"e": 24349,
"s": 24319,
"text": "Below is the implementation :"
},
{
"code": null,
"e": 24357,
"s": 24349,
"text": "Python3"
},
{
"code": "# import package and making objectimport turtle pen = turtle.Turtle() # method to draw square with dots# space --> distance between dots# x --> side of squaredef draw(space,x): for i in range(x): for j in range(x): # dot pen.dot() # distance for another dot pen.forward(space) pen.backward(space*x) # direction pen.right(90) pen.forward(space) pen.left(90) # Main Sectionpen.penup()draw(10,8) # hide the turtlepen.hideturtle()",
"e": 24866,
"s": 24357,
"text": null
},
{
"code": null,
"e": 24875,
"s": 24866,
"text": "Output :"
},
{
"code": null,
"e": 24902,
"s": 24875,
"text": "Following steps are used :"
},
{
"code": null,
"e": 24916,
"s": 24902,
"text": "Import turtle"
},
{
"code": null,
"e": 24928,
"s": 24916,
"text": "Make turtle"
},
{
"code": null,
"e": 24976,
"s": 24928,
"text": "Define a function to draw a rectangle with dots"
},
{
"code": null,
"e": 24995,
"s": 24976,
"text": "Call that function"
},
{
"code": null,
"e": 25012,
"s": 24995,
"text": "Hide the turtle."
},
{
"code": null,
"e": 25042,
"s": 25012,
"text": "Below is the implementation :"
},
{
"code": null,
"e": 25050,
"s": 25042,
"text": "Python3"
},
{
"code": "# import package and making objectimport turtle pen = turtle.Turtle() # method to draw rectangle with dots# space --> distance between dots# x --> height of rectangle# y --> width of rectangledef draw(space,x,y): for i in range(x): for j in range(y): # dot pen.dot() # distance for another dot pen.forward(space) pen.backward(space*y) # direction pen.right(90) pen.forward(space) pen.left(90) # Main Sectionpen.penup()draw(10,5,12) # hide the turtlepen.hideturtle()",
"e": 25602,
"s": 25050,
"text": null
},
{
"code": null,
"e": 25611,
"s": 25602,
"text": "Output :"
},
{
"code": null,
"e": 25638,
"s": 25611,
"text": "Following steps are used :"
},
{
"code": null,
"e": 25652,
"s": 25638,
"text": "Import turtle"
},
{
"code": null,
"e": 25664,
"s": 25652,
"text": "Make turtle"
},
{
"code": null,
"e": 25710,
"s": 25664,
"text": "Define a function to draw a diamond with dots"
},
{
"code": null,
"e": 25729,
"s": 25710,
"text": "Call that function"
},
{
"code": null,
"e": 25746,
"s": 25729,
"text": "Hide the turtle."
},
{
"code": null,
"e": 25776,
"s": 25746,
"text": "Below is the implementation :"
},
{
"code": null,
"e": 25784,
"s": 25776,
"text": "Python3"
},
{
"code": "# import package and making objectimport turtle pen = turtle.Turtle() # method to draw diamond with dots# space --> distance between dots# x --> side of diamonddef draw(space,x): for i in range(x): for j in range(x): # dot pen.dot() # distance for another dot pen.forward(space) pen.backward(space*x) # direction pen.right(90) pen.forward(space) pen.left(90) # Main Sectionpen.penup() # direction to form diamondpen.left(45)draw(10,8) # hide the turtlepen.hideturtle()",
"e": 26338,
"s": 25784,
"text": null
},
{
"code": null,
"e": 26347,
"s": 26338,
"text": "Output :"
},
{
"code": null,
"e": 26361,
"s": 26347,
"text": "Python-turtle"
},
{
"code": null,
"e": 26368,
"s": 26361,
"text": "Python"
},
{
"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": 26475,
"s": 26466,
"text": "Comments"
},
{
"code": null,
"e": 26488,
"s": 26475,
"text": "Old Comments"
},
{
"code": null,
"e": 26520,
"s": 26488,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26576,
"s": 26520,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26618,
"s": 26576,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26660,
"s": 26618,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26696,
"s": 26660,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 26735,
"s": 26696,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26757,
"s": 26735,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26788,
"s": 26757,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26815,
"s": 26788,
"text": "Python Classes and Objects"
}
] |
Building a Sentiment Classifier using Scikit-Learn | by Dorian Lazar | Towards Data Science
|
Sentiment analysis, an important area in Natural Language Processing, is the process of automatically detecting affective states of text. Sentiment analysis is widely applied to voice-of-customer materials such as product reviews in online shopping websites like Amazon, movie reviews or social media. It can be just a basic task of classifying the polarity of a text as being positive/negative or it can go beyond polarity, looking at emotional states such as βhappyβ, βangryβ, etc.
Here we will build a classifier that is able to distinguish movie reviews as being either positive or negative. For that, we will use Large Movie Review Dataset v1.0[2] of IMDB movie reviews. This dataset contains 50,000 movie reviews divided evenly into 25k train and 25k test. The labels are balanced between the two classes (positive and negative). Reviews with a score <= 4 out of 10 are labeled negative and those with score >= 7 out of 10 are labeled positive. Neutral reviews are not included in the labeled data. This dataset also contains unlabeled reviews for unsupervised learning; we will not use them here. There are no more than 30 reviews for a particular movie because the ratings of the same movie tend to be correlated. All reviews for a given movie are either in train or test set but not in both, in order to avoid test accuracy gain by memorizing movie-specific terms.
After the dataset has been downloaded and extracted from archive we have to transform it into a more suitable form for feeding it into a machine learning model for training. We will start by combining all review data into 2 pandas Data Frames representing the train and test datasets, and then saving them as csv files: imdb_train.csv and imdb_test.csv.
The Data Frames will have the following form:
where:
review1, review2, ... = the actual text of movie review
0 = negative review
1 = positive review
But machine learning algorithms work only with numerical values. We canβt just input the text itself into a machine learning model and have it learn from that. We have to, somehow, represent the text by numbers or vectors of numbers. One way of doing this is by using the Bag-of-words model[3], in which a piece of text(often called a document) is represented by a vector of the counts of words from a vocabulary in that document. This model doesnβt take into account grammar rules or word ordering; all it considers is the frequency of words. If we use the counts of each word independently we name this representation a unigram. In general, in a n-gram we take into account the counts of each combination of n words from the vocabulary that appears in a given document.
For example, consider these two documents:
The vocabulary of all words encountered in these two sentences is:
The unigram representations of d1 and d2:
And, the bigrams of d1 and d2 are:
Often, we can achieve slightly better results if instead of counts of words we use something called term frequency times inverse document frequency (or tf-idf). Maybe it sounds complicated, but it is not. Bear with me, I will explain this. The intuition behind this is the following. So, whatβs the problem of using just the frequency of terms inside a document? Although some terms may have a high frequency inside documents they may not be so relevant for describing a given document in which they appear. Thatβs because those terms may also have a high frequency across the collection of all documents. For example, a collection of movie reviews may have terms specific to movies/cinematography that are present in almost all documents(they have a high document frequency). So, when we encounter those terms in a document this doesnβt tell much about whether it is a positive or negative review. We need a way of relating term frequency (how frequent a term is inside a document) to document frequency (how frequent a term is across the whole collection of documents). That is:
Now, there are more ways used to describe both term frequency and inverse document frequency. But the most common way is by putting them on a logarithmic scale:
where:
We added 1 in the first logarithm to avoid getting -β when the count is 0. In the second logarithm we added one fake document to avoid division by zero.
Before we transform our data into vectors of counts or tf-idf values we should remove English stopwords[6][7]. Stopwords are words that are very common in a language and are usually removed in the preprocessing stage of natural text-related tasks like sentiment analysis or search.
Note that we should construct our vocabulary only based on the training set. When we will process the test data in order to make predictions we should use only the vocabulary constructed in the training phase, the rest of the words will be ignored.
Now, letβs create the data frames and save them as csv files:
Fortunately, for the text vectorization part all the hard work is already done in the Scikit-Learn classes CountVectorizer[8] and TfidfTransformer[5]. We will use these classes to transform our csv files into unigram and bigram matrices(using both counts and tf-idf values). (It turns out that if we only use a n-gram for a large n we don't get a good accuracy, we usually use all n-grams up to some n. So, when we say here bigrams we actually refer to uni+bigrams and when we say unigrams it's just unigrams.) Each row in those matrices will represent a document (review) in our dataset, and each column will represent values associated with each word in the vocabulary (in the case of unigrams) or values associated with each combination of maximum 2 words in the vocabulary (bigrams).
CountVectorizer has a parameter ngram_range which expects a tuple of size 2 that controls what n-grams to include. After we constructed a CountVectorizer object we should call .fit() method with the actual text as a parameter, in order for it to learn the required statistics of our collection of documents. Then, by calling .transform() method with our collection of documents it returns the matrix for the n-gram range specified. As the class name suggests, this matrix will contain just the counts. To obtain the tf-idf values, the class TfidfTransformer should be used. It has the .fit() and .transform() methods that are used in a similar way with those of CountVectorizer, but they take as input the counts matrix obtained in the previous step and .transform() will return a matrix with tf-idf values. We should use .fit() only on training data and then store these objects. When we want to evaluate the test score or whenever we want to make a prediction we should use these objects to transform the data before feeding it into our classifier.
Note that the matrices generated for our train or test data will be huge, and if we store them as normal numpy arrays they will not even fit into RAM. But most of the entries in these matrices will be zero. So, these Scikit-Learn classes are using Scipy sparse matrices[9] (csr_matrix[10] to be more exactly), which store just the non-zero entries and save a LOT of space.
We will use a linear classifier with stochastic gradient descent, sklearn.linear_model.SGDClassifier[11], as our model. First we will generate and save our data in 4 forms: unigram and bigram matrix (with both counts and tf-idf values for each). Then we will train and evaluate our model for each these 4 data representations using SGDClassifier with the default parameters. After that, we choose the data representation which led to the best score and we will tune the hyper-parameters of our model with this data form using cross-validation in order to obtain the best results.
Now, for each data form we split it into train & validation sets, train a SGDClassifier and output the score.
This is what we get:
Unigram CountsTrain score: 0.99 ; Validation score: 0.87Unigram Tf-IdfTrain score: 0.95 ; Validation score: 0.89Bigram CountsTrain score: 1.0 ; Validation score: 0.89Bigram Tf-IdfTrain score: 0.98 ; Validation score: 0.9
The best data form seems to be bigram with tf-idf as it gets the highest validation accuracy: 0.9; we will use it next for hyper-parameter tuning.
For this part we will use RandomizedSearchCV[12] which chooses the parameters randomly from the list that we give, or according to the distribution that we specify from scipy.stats (e.g. uniform); then is estimates the test error by doing cross-validation and after all iterations we can find the best estimator, the best parameters and the best score in the variables best_estimator_, best_params_ and best_score_.
Because the search space for the parameters that we want to test is very big and it may need a huge number of iterations until it finds the best combination, we will split the set of parameters in 2 and do the hyper-parameter tuning process in two phases. First we will find the optimal combination of loss, learning_rate and eta0 (i.e. initial learning rate); and then for penalty and alpha.
The output that we get is:
Best params: {'eta0': 0.008970361272584921, 'learning_rate': 'optimal', 'loss': 'squared_hinge'}Best score: 0.90564
Because we got βlearning_rate = optimalβ to be the best, then we will ignore the eta0 (initial learning rate) as it isnβt used when learning_rate=βoptimalβ; we got this value of eta0 just because of the randomness involved in the process.
Best params: {'alpha': 1.2101013664295101e-05, 'penalty': 'l2'}Best score: 0.90852
So, the best parameters that I got are:
loss: squared_hingelearning_rate: optimalpenalty: l2alpha: 1.2101013664295101e-05
And we got 90.18% test accuracy. Thatβs not bad for our simple linear model. There are more advanced methods that give better results. The current state-of-the-art on this dataset is 97.42% [13]
[1] Sentiment Analysis β Wikipedia[2] Learning Word Vectors for Sentiment Analysis[3] Bag-of-words model β Wikipedia[4] Tf-idf β Wikipedia[5] TfidfTransformer β Scikit-learn documentation[6] Stop words β Wikipedia[7] A list of English stopwords[8] CountVectorizer β Scikit-learn documentation[9] Scipy sparse matrices[10] Compressed Sparse Row matrix[11] SGDClassifier β Scikit-learn documentation[12] RandomizedSearchCV β Scikit-learn documentation[13] Sentiment Classification using Document Embeddings trained with Cosine Similarity
The Jupyter notebook can be found here.
I hope you found this information useful and thanks for reading!
This article is also posted on my own website here. Feel free to have a look!
|
[
{
"code": null,
"e": 655,
"s": 171,
"text": "Sentiment analysis, an important area in Natural Language Processing, is the process of automatically detecting affective states of text. Sentiment analysis is widely applied to voice-of-customer materials such as product reviews in online shopping websites like Amazon, movie reviews or social media. It can be just a basic task of classifying the polarity of a text as being positive/negative or it can go beyond polarity, looking at emotional states such as βhappyβ, βangryβ, etc."
},
{
"code": null,
"e": 1545,
"s": 655,
"text": "Here we will build a classifier that is able to distinguish movie reviews as being either positive or negative. For that, we will use Large Movie Review Dataset v1.0[2] of IMDB movie reviews. This dataset contains 50,000 movie reviews divided evenly into 25k train and 25k test. The labels are balanced between the two classes (positive and negative). Reviews with a score <= 4 out of 10 are labeled negative and those with score >= 7 out of 10 are labeled positive. Neutral reviews are not included in the labeled data. This dataset also contains unlabeled reviews for unsupervised learning; we will not use them here. There are no more than 30 reviews for a particular movie because the ratings of the same movie tend to be correlated. All reviews for a given movie are either in train or test set but not in both, in order to avoid test accuracy gain by memorizing movie-specific terms."
},
{
"code": null,
"e": 1899,
"s": 1545,
"text": "After the dataset has been downloaded and extracted from archive we have to transform it into a more suitable form for feeding it into a machine learning model for training. We will start by combining all review data into 2 pandas Data Frames representing the train and test datasets, and then saving them as csv files: imdb_train.csv and imdb_test.csv."
},
{
"code": null,
"e": 1945,
"s": 1899,
"text": "The Data Frames will have the following form:"
},
{
"code": null,
"e": 1952,
"s": 1945,
"text": "where:"
},
{
"code": null,
"e": 2008,
"s": 1952,
"text": "review1, review2, ... = the actual text of movie review"
},
{
"code": null,
"e": 2028,
"s": 2008,
"text": "0 = negative review"
},
{
"code": null,
"e": 2048,
"s": 2028,
"text": "1 = positive review"
},
{
"code": null,
"e": 2820,
"s": 2048,
"text": "But machine learning algorithms work only with numerical values. We canβt just input the text itself into a machine learning model and have it learn from that. We have to, somehow, represent the text by numbers or vectors of numbers. One way of doing this is by using the Bag-of-words model[3], in which a piece of text(often called a document) is represented by a vector of the counts of words from a vocabulary in that document. This model doesnβt take into account grammar rules or word ordering; all it considers is the frequency of words. If we use the counts of each word independently we name this representation a unigram. In general, in a n-gram we take into account the counts of each combination of n words from the vocabulary that appears in a given document."
},
{
"code": null,
"e": 2863,
"s": 2820,
"text": "For example, consider these two documents:"
},
{
"code": null,
"e": 2930,
"s": 2863,
"text": "The vocabulary of all words encountered in these two sentences is:"
},
{
"code": null,
"e": 2972,
"s": 2930,
"text": "The unigram representations of d1 and d2:"
},
{
"code": null,
"e": 3007,
"s": 2972,
"text": "And, the bigrams of d1 and d2 are:"
},
{
"code": null,
"e": 4088,
"s": 3007,
"text": "Often, we can achieve slightly better results if instead of counts of words we use something called term frequency times inverse document frequency (or tf-idf). Maybe it sounds complicated, but it is not. Bear with me, I will explain this. The intuition behind this is the following. So, whatβs the problem of using just the frequency of terms inside a document? Although some terms may have a high frequency inside documents they may not be so relevant for describing a given document in which they appear. Thatβs because those terms may also have a high frequency across the collection of all documents. For example, a collection of movie reviews may have terms specific to movies/cinematography that are present in almost all documents(they have a high document frequency). So, when we encounter those terms in a document this doesnβt tell much about whether it is a positive or negative review. We need a way of relating term frequency (how frequent a term is inside a document) to document frequency (how frequent a term is across the whole collection of documents). That is:"
},
{
"code": null,
"e": 4249,
"s": 4088,
"text": "Now, there are more ways used to describe both term frequency and inverse document frequency. But the most common way is by putting them on a logarithmic scale:"
},
{
"code": null,
"e": 4256,
"s": 4249,
"text": "where:"
},
{
"code": null,
"e": 4409,
"s": 4256,
"text": "We added 1 in the first logarithm to avoid getting -β when the count is 0. In the second logarithm we added one fake document to avoid division by zero."
},
{
"code": null,
"e": 4691,
"s": 4409,
"text": "Before we transform our data into vectors of counts or tf-idf values we should remove English stopwords[6][7]. Stopwords are words that are very common in a language and are usually removed in the preprocessing stage of natural text-related tasks like sentiment analysis or search."
},
{
"code": null,
"e": 4940,
"s": 4691,
"text": "Note that we should construct our vocabulary only based on the training set. When we will process the test data in order to make predictions we should use only the vocabulary constructed in the training phase, the rest of the words will be ignored."
},
{
"code": null,
"e": 5002,
"s": 4940,
"text": "Now, letβs create the data frames and save them as csv files:"
},
{
"code": null,
"e": 5790,
"s": 5002,
"text": "Fortunately, for the text vectorization part all the hard work is already done in the Scikit-Learn classes CountVectorizer[8] and TfidfTransformer[5]. We will use these classes to transform our csv files into unigram and bigram matrices(using both counts and tf-idf values). (It turns out that if we only use a n-gram for a large n we don't get a good accuracy, we usually use all n-grams up to some n. So, when we say here bigrams we actually refer to uni+bigrams and when we say unigrams it's just unigrams.) Each row in those matrices will represent a document (review) in our dataset, and each column will represent values associated with each word in the vocabulary (in the case of unigrams) or values associated with each combination of maximum 2 words in the vocabulary (bigrams)."
},
{
"code": null,
"e": 6841,
"s": 5790,
"text": "CountVectorizer has a parameter ngram_range which expects a tuple of size 2 that controls what n-grams to include. After we constructed a CountVectorizer object we should call .fit() method with the actual text as a parameter, in order for it to learn the required statistics of our collection of documents. Then, by calling .transform() method with our collection of documents it returns the matrix for the n-gram range specified. As the class name suggests, this matrix will contain just the counts. To obtain the tf-idf values, the class TfidfTransformer should be used. It has the .fit() and .transform() methods that are used in a similar way with those of CountVectorizer, but they take as input the counts matrix obtained in the previous step and .transform() will return a matrix with tf-idf values. We should use .fit() only on training data and then store these objects. When we want to evaluate the test score or whenever we want to make a prediction we should use these objects to transform the data before feeding it into our classifier."
},
{
"code": null,
"e": 7214,
"s": 6841,
"text": "Note that the matrices generated for our train or test data will be huge, and if we store them as normal numpy arrays they will not even fit into RAM. But most of the entries in these matrices will be zero. So, these Scikit-Learn classes are using Scipy sparse matrices[9] (csr_matrix[10] to be more exactly), which store just the non-zero entries and save a LOT of space."
},
{
"code": null,
"e": 7794,
"s": 7214,
"text": "We will use a linear classifier with stochastic gradient descent, sklearn.linear_model.SGDClassifier[11], as our model. First we will generate and save our data in 4 forms: unigram and bigram matrix (with both counts and tf-idf values for each). Then we will train and evaluate our model for each these 4 data representations using SGDClassifier with the default parameters. After that, we choose the data representation which led to the best score and we will tune the hyper-parameters of our model with this data form using cross-validation in order to obtain the best results."
},
{
"code": null,
"e": 7904,
"s": 7794,
"text": "Now, for each data form we split it into train & validation sets, train a SGDClassifier and output the score."
},
{
"code": null,
"e": 7925,
"s": 7904,
"text": "This is what we get:"
},
{
"code": null,
"e": 8146,
"s": 7925,
"text": "Unigram CountsTrain score: 0.99 ; Validation score: 0.87Unigram Tf-IdfTrain score: 0.95 ; Validation score: 0.89Bigram CountsTrain score: 1.0 ; Validation score: 0.89Bigram Tf-IdfTrain score: 0.98 ; Validation score: 0.9"
},
{
"code": null,
"e": 8293,
"s": 8146,
"text": "The best data form seems to be bigram with tf-idf as it gets the highest validation accuracy: 0.9; we will use it next for hyper-parameter tuning."
},
{
"code": null,
"e": 8709,
"s": 8293,
"text": "For this part we will use RandomizedSearchCV[12] which chooses the parameters randomly from the list that we give, or according to the distribution that we specify from scipy.stats (e.g. uniform); then is estimates the test error by doing cross-validation and after all iterations we can find the best estimator, the best parameters and the best score in the variables best_estimator_, best_params_ and best_score_."
},
{
"code": null,
"e": 9102,
"s": 8709,
"text": "Because the search space for the parameters that we want to test is very big and it may need a huge number of iterations until it finds the best combination, we will split the set of parameters in 2 and do the hyper-parameter tuning process in two phases. First we will find the optimal combination of loss, learning_rate and eta0 (i.e. initial learning rate); and then for penalty and alpha."
},
{
"code": null,
"e": 9129,
"s": 9102,
"text": "The output that we get is:"
},
{
"code": null,
"e": 9245,
"s": 9129,
"text": "Best params: {'eta0': 0.008970361272584921, 'learning_rate': 'optimal', 'loss': 'squared_hinge'}Best score: 0.90564"
},
{
"code": null,
"e": 9484,
"s": 9245,
"text": "Because we got βlearning_rate = optimalβ to be the best, then we will ignore the eta0 (initial learning rate) as it isnβt used when learning_rate=βoptimalβ; we got this value of eta0 just because of the randomness involved in the process."
},
{
"code": null,
"e": 9567,
"s": 9484,
"text": "Best params: {'alpha': 1.2101013664295101e-05, 'penalty': 'l2'}Best score: 0.90852"
},
{
"code": null,
"e": 9607,
"s": 9567,
"text": "So, the best parameters that I got are:"
},
{
"code": null,
"e": 9689,
"s": 9607,
"text": "loss: squared_hingelearning_rate: optimalpenalty: l2alpha: 1.2101013664295101e-05"
},
{
"code": null,
"e": 9884,
"s": 9689,
"text": "And we got 90.18% test accuracy. Thatβs not bad for our simple linear model. There are more advanced methods that give better results. The current state-of-the-art on this dataset is 97.42% [13]"
},
{
"code": null,
"e": 10420,
"s": 9884,
"text": "[1] Sentiment Analysis β Wikipedia[2] Learning Word Vectors for Sentiment Analysis[3] Bag-of-words model β Wikipedia[4] Tf-idf β Wikipedia[5] TfidfTransformer β Scikit-learn documentation[6] Stop words β Wikipedia[7] A list of English stopwords[8] CountVectorizer β Scikit-learn documentation[9] Scipy sparse matrices[10] Compressed Sparse Row matrix[11] SGDClassifier β Scikit-learn documentation[12] RandomizedSearchCV β Scikit-learn documentation[13] Sentiment Classification using Document Embeddings trained with Cosine Similarity"
},
{
"code": null,
"e": 10460,
"s": 10420,
"text": "The Jupyter notebook can be found here."
},
{
"code": null,
"e": 10525,
"s": 10460,
"text": "I hope you found this information useful and thanks for reading!"
}
] |
Python 3 - dictionary copy() Method
|
The method copy() returns a shallow copy of the dictionary.
Following is the syntax for copy() method β
dict.copy()
NA
This method returns a shallow copy of the dictionary.
The following example shows the usage of copy() method.
#!/usr/bin/python3
dict1 = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
dict2 = dict1.copy()
print ("New Dictionary : ",dict2)
When we run above program, it produces the following result β
New dictionary : {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
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": 2400,
"s": 2340,
"text": "The method copy() returns a shallow copy of the dictionary."
},
{
"code": null,
"e": 2444,
"s": 2400,
"text": "Following is the syntax for copy() method β"
},
{
"code": null,
"e": 2457,
"s": 2444,
"text": "dict.copy()\n"
},
{
"code": null,
"e": 2460,
"s": 2457,
"text": "NA"
},
{
"code": null,
"e": 2514,
"s": 2460,
"text": "This method returns a shallow copy of the dictionary."
},
{
"code": null,
"e": 2570,
"s": 2514,
"text": "The following example shows the usage of copy() method."
},
{
"code": null,
"e": 2699,
"s": 2570,
"text": "#!/usr/bin/python3\n\ndict1 = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}\ndict2 = dict1.copy()\nprint (\"New Dictionary : \",dict2)"
},
{
"code": null,
"e": 2761,
"s": 2699,
"text": "When we run above program, it produces the following result β"
},
{
"code": null,
"e": 2826,
"s": 2761,
"text": "New dictionary : {'Name': 'Manni', 'Age': 7, 'Class': 'First'}\n"
},
{
"code": null,
"e": 2863,
"s": 2826,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 2879,
"s": 2863,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 2912,
"s": 2879,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2931,
"s": 2912,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 2966,
"s": 2931,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 2988,
"s": 2966,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3022,
"s": 2988,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3050,
"s": 3022,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3085,
"s": 3050,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3099,
"s": 3085,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3132,
"s": 3099,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3149,
"s": 3132,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3156,
"s": 3149,
"text": " Print"
},
{
"code": null,
"e": 3167,
"s": 3156,
"text": " Add Notes"
}
] |
Deriving a Class in Java
|
A class can be derived from the base class in Java by using the extends keyword. This keyword is basically used to indicate that a new class is derived from the base class using inheritance. It can also be said that it is used to extend the functionality of the class.
A program that demonstrates this is given as follows:
Live Demo
class A {
void funcA() {
System.out.println("This is class A");
}
}
class B extends A {
void funcB() {
System.out.println("This is class B");
}
}
public class Demo {
public static void main(String args[]) {
B obj = new B();
obj.funcA();
obj.funcB();
}
}
This is class A
This is class B
Now let us understand the above program.
The class A contains a member function funcA(). The class B uses the extends keyword to derive from class A. It also contains a member function funcB(). A code snippet which demonstrates this is as follows:
class A {
void funcA() {
System.out.println("This is class A");
}
}
class B extends A {
void funcB() {
System.out.println("This is class B");
}
}
In the main() method in class Demo, an object obj of class B is created. Then the functions funcA() and funcB() are called. A code snippet which demonstrates this is as follows:
public class Demo {
public static void main(String args[]) {
B obj = new B();
obj.funcA();
obj.funcB();
}
}
|
[
{
"code": null,
"e": 1331,
"s": 1062,
"text": "A class can be derived from the base class in Java by using the extends keyword. This keyword is basically used to indicate that a new class is derived from the base class using inheritance. It can also be said that it is used to extend the functionality of the class."
},
{
"code": null,
"e": 1385,
"s": 1331,
"text": "A program that demonstrates this is given as follows:"
},
{
"code": null,
"e": 1396,
"s": 1385,
"text": " Live Demo"
},
{
"code": null,
"e": 1698,
"s": 1396,
"text": "class A {\n void funcA() {\n System.out.println(\"This is class A\");\n }\n}\nclass B extends A {\n void funcB() {\n System.out.println(\"This is class B\");\n }\n}\npublic class Demo {\n public static void main(String args[]) {\n B obj = new B();\n obj.funcA();\n obj.funcB();\n }\n}"
},
{
"code": null,
"e": 1730,
"s": 1698,
"text": "This is class A\nThis is class B"
},
{
"code": null,
"e": 1771,
"s": 1730,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 1978,
"s": 1771,
"text": "The class A contains a member function funcA(). The class B uses the extends keyword to derive from class A. It also contains a member function funcB(). A code snippet which demonstrates this is as follows:"
},
{
"code": null,
"e": 2148,
"s": 1978,
"text": "class A {\n void funcA() {\n System.out.println(\"This is class A\");\n }\n}\nclass B extends A {\n void funcB() {\n System.out.println(\"This is class B\");\n }\n}"
},
{
"code": null,
"e": 2326,
"s": 2148,
"text": "In the main() method in class Demo, an object obj of class B is created. Then the functions funcA() and funcB() are called. A code snippet which demonstrates this is as follows:"
},
{
"code": null,
"e": 2458,
"s": 2326,
"text": "public class Demo {\n public static void main(String args[]) {\n B obj = new B();\n obj.funcA();\n obj.funcB();\n }\n}"
}
] |
String format for Double in C#
|
Use the static method String.Format for form double string format in C#.
For three decimal places β
String.Format("{0:0.000}", 987.383);
String.Format("{0:0.000}", 987.38);
String.Format("{0:0.000}", 987.7899);
For thousands separator β
String.Format("{0:0,0.0}", 54567.46);
String.Format("{0:0,0}", 54567.46);
To format string β
using System;
class Demo {
public static void Main(String[] args) {
Console.WriteLine("Three decimal places...");
Console.WriteLine( String.Format("{0:0.000}", 987.383));
Console.WriteLine( String.Format("{0:0.000}", 987.38));
Console.WriteLine(String.Format("{0:0.000}", 987.7899));
Console.WriteLine("Thousands Separator...");
Console.WriteLine(String.Format("{0:0,0.0}", 54567.46));
Console.WriteLine(String.Format("{0:0,0}", 54567.46));
}
}
|
[
{
"code": null,
"e": 1135,
"s": 1062,
"text": "Use the static method String.Format for form double string format in C#."
},
{
"code": null,
"e": 1162,
"s": 1135,
"text": "For three decimal places β"
},
{
"code": null,
"e": 1273,
"s": 1162,
"text": "String.Format(\"{0:0.000}\", 987.383);\nString.Format(\"{0:0.000}\", 987.38);\nString.Format(\"{0:0.000}\", 987.7899);"
},
{
"code": null,
"e": 1299,
"s": 1273,
"text": "For thousands separator β"
},
{
"code": null,
"e": 1373,
"s": 1299,
"text": "String.Format(\"{0:0,0.0}\", 54567.46);\nString.Format(\"{0:0,0}\", 54567.46);"
},
{
"code": null,
"e": 1392,
"s": 1373,
"text": "To format string β"
},
{
"code": null,
"e": 1895,
"s": 1392,
"text": "using System;\n\nclass Demo {\n\n public static void Main(String[] args) {\n Console.WriteLine(\"Three decimal places...\");\n \n Console.WriteLine( String.Format(\"{0:0.000}\", 987.383));\n Console.WriteLine( String.Format(\"{0:0.000}\", 987.38));\n Console.WriteLine(String.Format(\"{0:0.000}\", 987.7899));\n \n Console.WriteLine(\"Thousands Separator...\");\n Console.WriteLine(String.Format(\"{0:0,0.0}\", 54567.46));\n Console.WriteLine(String.Format(\"{0:0,0}\", 54567.46));\n }\n}"
}
] |
Lodash _.dictionary() Method - GeeksforGeeks
|
30 Sep, 2020
The Lodash _.dictionary() method returns a function that will attempt to look up a field that it is given.
Syntax:
funct = _.dictionary( object );
Parameters: This method accepts single parameter as mentioned above and described below:
object: This method takes the object from which the field is to be searched.
Return Value: This method returns a function that will attempt to look up a field that is given.
Note: This will not work in normal JavaScript because it requires the lodash.js contrib library to be installed. Lodash.js contrib library can be installed using npm install lodash-contrib.
Example 1:
Javascript
// Defining underscore lodash variable
var _ = require('lodash-contrib');
var ob = { gfg : "GeeksforGeeks" }
var gfgg = _.dictionary( ob );
console.log(gfgg("gfg"));
Output:
GeeksforGeeks
Example 2:
Javascript
// Defining underscore lodash variable
var _ = require('lodash-contrib');
var ob = { gfg : "GeeksforGeeks" }
var gfgg = _.dictionary( ob );
console.log(gfgg("geek"));
Output:
undefined
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to detect browser or tab closing in JavaScript ?
How to get selected value in dropdown list using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25372,
"s": 25341,
"text": " \n30 Sep, 2020\n"
},
{
"code": null,
"e": 25479,
"s": 25372,
"text": "The Lodash _.dictionary() method returns a function that will attempt to look up a field that it is given."
},
{
"code": null,
"e": 25487,
"s": 25479,
"text": "Syntax:"
},
{
"code": null,
"e": 25520,
"s": 25487,
"text": "funct = _.dictionary( object );\n"
},
{
"code": null,
"e": 25609,
"s": 25520,
"text": "Parameters: This method accepts single parameter as mentioned above and described below:"
},
{
"code": null,
"e": 25686,
"s": 25609,
"text": "object: This method takes the object from which the field is to be searched."
},
{
"code": null,
"e": 25783,
"s": 25686,
"text": "Return Value: This method returns a function that will attempt to look up a field that is given."
},
{
"code": null,
"e": 25973,
"s": 25783,
"text": "Note: This will not work in normal JavaScript because it requires the lodash.js contrib library to be installed. Lodash.js contrib library can be installed using npm install lodash-contrib."
},
{
"code": null,
"e": 25984,
"s": 25973,
"text": "Example 1:"
},
{
"code": null,
"e": 25995,
"s": 25984,
"text": "Javascript"
},
{
"code": "\n\n\n\n\n\n\n// Defining underscore lodash variable \nvar _ = require('lodash-contrib'); \n \nvar ob = { gfg : \"GeeksforGeeks\" } \nvar gfgg = _.dictionary( ob ); \n \nconsole.log(gfgg(\"gfg\"));\n\n\n\n\n\n",
"e": 26200,
"s": 26005,
"text": null
},
{
"code": null,
"e": 26208,
"s": 26200,
"text": "Output:"
},
{
"code": null,
"e": 26223,
"s": 26208,
"text": "GeeksforGeeks\n"
},
{
"code": null,
"e": 26234,
"s": 26223,
"text": "Example 2:"
},
{
"code": null,
"e": 26245,
"s": 26234,
"text": "Javascript"
},
{
"code": "\n\n\n\n\n\n\n// Defining underscore lodash variable \nvar _ = require('lodash-contrib'); \n \nvar ob = { gfg : \"GeeksforGeeks\" } \nvar gfgg = _.dictionary( ob ); \n \nconsole.log(gfgg(\"geek\"));\n\n\n\n\n\n",
"e": 26451,
"s": 26255,
"text": null
},
{
"code": null,
"e": 26459,
"s": 26451,
"text": "Output:"
},
{
"code": null,
"e": 26470,
"s": 26459,
"text": "undefined\n"
},
{
"code": null,
"e": 26490,
"s": 26470,
"text": "\nJavaScript-Lodash\n"
},
{
"code": null,
"e": 26503,
"s": 26490,
"text": "\nJavaScript\n"
},
{
"code": null,
"e": 26522,
"s": 26503,
"text": "\nWeb Technologies\n"
},
{
"code": null,
"e": 26727,
"s": 26522,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 26788,
"s": 26727,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26829,
"s": 26788,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 26883,
"s": 26829,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 26936,
"s": 26883,
"text": "How to detect browser or tab closing in JavaScript ?"
},
{
"code": null,
"e": 26998,
"s": 26936,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 27040,
"s": 26998,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27073,
"s": 27040,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27135,
"s": 27073,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27178,
"s": 27135,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
BigInt (BIG INTEGERS) in C++ with Example - GeeksforGeeks
|
17 Feb, 2022
In C/C++ the number of digits a long long int can have is a maximum of 20. And the question is to store the 22 digit number which is not easy to store in any kind of primitive type. So to deal with this type of problem letβs design a new data type which is going to be called BigInt In this article, a few basic operations are being implemented on the new data type.
Add two big integers.Subtract two big integersMultiply two big integers.Divide two big integers.Modulo two big integersRaise a big integer to a powerThe square root of a big integerComparison between two big integers to check which is greater and which is smaller.Find the number of digits in the big integer.Print the big integer.Convert an integer to a big integer.
Add two big integers.
Subtract two big integers
Multiply two big integers.
Divide two big integers.
Modulo two big integers
Raise a big integer to a power
The square root of a big integer
Comparison between two big integers to check which is greater and which is smaller.
Find the number of digits in the big integer.
Print the big integer.
Convert an integer to a big integer.
Applications Of BigInt:Below are some basic applications of the new data type, BigInt:
Calculating the Fibonacci number of a large number.Calculating the Catalan number of a large numberCalculating the Factorial of a big integer.
Calculating the Fibonacci number of a large number.
Calculating the Catalan number of a large number
Calculating the Factorial of a big integer.
Approach:To create a new data type of big integers following concepts are being implemented:
C++ strings in that we can store our numbers in the form of characters (in reverse order for efficiency purposes) such that using strings we can store very big numbers also.For the addition/subtraction operation of two big integers, use the basic math for addition which says that add the corresponding two digits and if some carry is generated add it to the sum of the next digits and repeat this process until all digits are added/subtracted.Similarly, for the multiplication of two numbers, use the basic mathematics approach which states that multiply every digit of one number with the other complete number and at last add all the numbers we get in multiplication.The following operations are being performed on BigInt-Defining some big integers.Checking the number of digits in the big integer.Post/Pre Incrementation or DecrementationAdding two big integers.Subtracting two big integers.Multiplying two big integers.Divide two big integersModulo of two big integersThe square root of a big integer (floor integer value)Raise a big integer to a powerConverting a simple integer to a big integer.Calculating Fibonacci up to 10 000. (even 100000 but slower)Calculating Factorial up to 1 000.Calculating Catalan up to 1 000.Checking which big integer is greater and which is smaller.
C++ strings in that we can store our numbers in the form of characters (in reverse order for efficiency purposes) such that using strings we can store very big numbers also.
For the addition/subtraction operation of two big integers, use the basic math for addition which says that add the corresponding two digits and if some carry is generated add it to the sum of the next digits and repeat this process until all digits are added/subtracted.
Similarly, for the multiplication of two numbers, use the basic mathematics approach which states that multiply every digit of one number with the other complete number and at last add all the numbers we get in multiplication.
The following operations are being performed on BigInt-Defining some big integers.Checking the number of digits in the big integer.Post/Pre Incrementation or DecrementationAdding two big integers.Subtracting two big integers.Multiplying two big integers.Divide two big integersModulo of two big integersThe square root of a big integer (floor integer value)Raise a big integer to a powerConverting a simple integer to a big integer.Calculating Fibonacci up to 10 000. (even 100000 but slower)Calculating Factorial up to 1 000.Calculating Catalan up to 1 000.Checking which big integer is greater and which is smaller.
Defining some big integers.Checking the number of digits in the big integer.Post/Pre Incrementation or DecrementationAdding two big integers.Subtracting two big integers.Multiplying two big integers.Divide two big integersModulo of two big integersThe square root of a big integer (floor integer value)Raise a big integer to a powerConverting a simple integer to a big integer.Calculating Fibonacci up to 10 000. (even 100000 but slower)Calculating Factorial up to 1 000.Calculating Catalan up to 1 000.Checking which big integer is greater and which is smaller.
Defining some big integers.
Checking the number of digits in the big integer.
Post/Pre Incrementation or Decrementation
Adding two big integers.
Subtracting two big integers.
Multiplying two big integers.
Divide two big integers
Modulo of two big integers
The square root of a big integer (floor integer value)
Raise a big integer to a power
Converting a simple integer to a big integer.
Calculating Fibonacci up to 10 000. (even 100000 but slower)
Calculating Factorial up to 1 000.
Calculating Catalan up to 1 000.
Checking which big integer is greater and which is smaller.
Below is the C++ implementation of the above approach:
C++
// C++ program to implement// the above approach#include <bits/stdc++.h> using namespace std; class BigInt{ string digits;public: //Constructors: BigInt(unsigned long long n = 0); BigInt(string &); BigInt(const char *); BigInt(BigInt &); //Helper Functions: friend void divide_by_2(BigInt &a); friend bool Null(const BigInt &); friend int Length(const BigInt &); int operator[](const int)const; /* * * * Operator Overloading * * * */ //Direct assignment BigInt &operator=(const BigInt &); //Post/Pre - Incrementation BigInt &operator++(); BigInt operator++(int temp); BigInt &operator--(); BigInt operator--(int temp); //Addition and Subtraction friend BigInt &operator+=(BigInt &, const BigInt &); friend BigInt operator+(const BigInt &, const BigInt &); friend BigInt operator-(const BigInt &, const BigInt &); friend BigInt &operator-=(BigInt &, const BigInt &); //Comparison operators friend bool operator==(const BigInt &, const BigInt &); friend bool operator!=(const BigInt &, const BigInt &); friend bool operator>(const BigInt &, const BigInt &); friend bool operator>=(const BigInt &, const BigInt &); friend bool operator<(const BigInt &, const BigInt &); friend bool operator<=(const BigInt &, const BigInt &); //Multiplication and Division friend BigInt &operator*=(BigInt &, const BigInt &); friend BigInt operator*(const BigInt &, const BigInt &); friend BigInt &operator/=(BigInt &, const BigInt &); friend BigInt operator/(const BigInt &, const BigInt &); //Modulo friend BigInt operator%(const BigInt &, const BigInt &); friend BigInt &operator%=(BigInt &, const BigInt &); //Power Function friend BigInt &operator^=(BigInt &,const BigInt &); friend BigInt operator^(BigInt &, const BigInt &); //Square Root Function friend BigInt sqrt(BigInt &a); //Read and Write friend ostream &operator<<(ostream &,const BigInt &); friend istream &operator>>(istream &, BigInt &); //Others friend BigInt NthCatalan(int n); friend BigInt NthFibonacci(int n); friend BigInt Factorial(int n);}; BigInt::BigInt(string & s){ digits = ""; int n = s.size(); for (int i = n - 1; i >= 0;i--){ if(!isdigit(s[i])) throw("ERROR"); digits.push_back(s[i] - '0'); }}BigInt::BigInt(unsigned long long nr){ do{ digits.push_back(nr % 10); nr /= 10; } while (nr);}BigInt::BigInt(const char *s){ digits = ""; for (int i = strlen(s) - 1; i >= 0;i--) { if(!isdigit(s[i])) throw("ERROR"); digits.push_back(s[i] - '0'); }}BigInt::BigInt(BigInt & a){ digits = a.digits;} bool Null(const BigInt& a){ if(a.digits.size() == 1 && a.digits[0] == 0) return true; return false;}int Length(const BigInt & a){ return a.digits.size();}int BigInt::operator[](const int index)const{ if(digits.size() <= index || index < 0) throw("ERROR"); return digits[index];}bool operator==(const BigInt &a, const BigInt &b){ return a.digits == b.digits;}bool operator!=(const BigInt & a,const BigInt &b){ return !(a == b);}bool operator<(const BigInt&a,const BigInt&b){ int n = Length(a), m = Length(b); if(n != m) return n < m; while(n--) if(a.digits[n] != b.digits[n]) return a.digits[n] < b.digits[n]; return false;}bool operator>(const BigInt&a,const BigInt&b){ return b < a;}bool operator>=(const BigInt&a,const BigInt&b){ return !(a < b);}bool operator<=(const BigInt&a,const BigInt&b){ return !(a > b);} BigInt &BigInt::operator=(const BigInt &a){ digits = a.digits; return *this;} BigInt &BigInt::operator++(){ int i, n = digits.size(); for (i = 0; i < n && digits[i] == 9;i++) digits[i] = 0; if(i == n) digits.push_back(1); else digits[i]++; return *this;}BigInt BigInt::operator++(int temp){ BigInt aux; aux = *this; ++(*this); return aux;} BigInt &BigInt::operator--(){ if(digits[0] == 0 && digits.size() == 1) throw("UNDERFLOW"); int i, n = digits.size(); for (i = 0; digits[i] == 0 && i < n;i++) digits[i] = 9; digits[i]--; if(n > 1 && digits[n - 1] == 0) digits.pop_back(); return *this;}BigInt BigInt::operator--(int temp){ BigInt aux; aux = *this; --(*this); return aux;} BigInt &operator+=(BigInt &a,const BigInt& b){ int t = 0, s, i; int n = Length(a), m = Length(b); if(m > n) a.digits.append(m - n, 0); n = Length(a); for (i = 0; i < n;i++){ if(i < m) s = (a.digits[i] + b.digits[i]) + t; else s = a.digits[i] + t; t = s / 10; a.digits[i] = (s % 10); } if(t) a.digits.push_back(t); return a;}BigInt operator+(const BigInt &a, const BigInt &b){ BigInt temp; temp = a; temp += b; return temp;} BigInt &operator-=(BigInt&a,const BigInt &b){ if(a < b) throw("UNDERFLOW"); int n = Length(a), m = Length(b); int i, t = 0, s; for (i = 0; i < n;i++){ if(i < m) s = a.digits[i] - b.digits[i]+ t; else s = a.digits[i]+ t; if(s < 0) s += 10, t = -1; else t = 0; a.digits[i] = s; } while(n > 1 && a.digits[n - 1] == 0) a.digits.pop_back(), n--; return a;}BigInt operator-(const BigInt& a,const BigInt&b){ BigInt temp; temp = a; temp -= b; return temp;} BigInt &operator*=(BigInt &a, const BigInt &b){ if(Null(a) || Null(b)){ a = BigInt(); return a; } int n = a.digits.size(), m = b.digits.size(); vector<int> v(n + m, 0); for (int i = 0; i < n;i++) for (int j = 0; j < m;j++){ v[i + j] += (a.digits[i] ) * (b.digits[j]); } n += m; a.digits.resize(v.size()); for (int s, i = 0, t = 0; i < n; i++) { s = t + v[i]; v[i] = s % 10; t = s / 10; a.digits[i] = v[i] ; } for (int i = n - 1; i >= 1 && !v[i];i--) a.digits.pop_back(); return a;}BigInt operator*(const BigInt&a,const BigInt&b){ BigInt temp; temp = a; temp *= b; return temp;} BigInt &operator/=(BigInt& a,const BigInt &b){ if(Null(b)) throw("Arithmetic Error: Division By 0"); if(a < b){ a = BigInt(); return a; } if(a == b){ a = BigInt(1); return a; } int i, lgcat = 0, cc; int n = Length(a), m = Length(b); vector<int> cat(n, 0); BigInt t; for (i = n - 1; t * 10 + a.digits[i] < b;i--){ t *= 10; t += a.digits[i] ; } for (; i >= 0; i--){ t = t * 10 + a.digits[i]; for (cc = 9; cc * b > t;cc--); t -= cc * b; cat[lgcat++] = cc; } a.digits.resize(cat.size()); for (i = 0; i < lgcat;i++) a.digits[i] = cat[lgcat - i - 1]; a.digits.resize(lgcat); return a;}BigInt operator/(const BigInt &a,const BigInt &b){ BigInt temp; temp = a; temp /= b; return temp;} BigInt &operator%=(BigInt& a,const BigInt &b){ if(Null(b)) throw("Arithmetic Error: Division By 0"); if(a < b){ a = BigInt(); return a; } if(a == b){ a = BigInt(1); return a; } int i, lgcat = 0, cc; int n = Length(a), m = Length(b); vector<int> cat(n, 0); BigInt t; for (i = n - 1; t * 10 + a.digits[i] < b;i--){ t *= 10; t += a.digits[i]; } for (; i >= 0; i--){ t = t * 10 + a.digits[i]; for (cc = 9; cc * b > t;cc--); t -= cc * b; cat[lgcat++] = cc; } a = t; return a;}BigInt operator%(const BigInt &a,BigInt &b){ BigInt temp; temp = a; temp %= b; return temp;} BigInt &operator^=(BigInt & a,const BigInt & b){ BigInt Exponent, Base(a); Exponent = b; a = 1; while(!Null(Exponent)){ if(Exponent[0] & 1) a *= Base; Base *= Base; divide_by_2(Exponent); } return a;}BigInt operator^(BigInt & a,BigInt & b){ BigInt temp(a); temp ^= b; return temp;} void divide_by_2(BigInt & a){ int add = 0; for (int i = a.digits.size() - 1; i >= 0;i--){ int digit = (a.digits[i] >> 1) + add; add = ((a.digits[i] & 1) * 5); a.digits[i] = digit; } while(a.digits.size() > 1 && !a.digits.back()) a.digits.pop_back();} BigInt sqrt(BigInt & a){ BigInt left(1), right(a), v(1), mid, prod; divide_by_2(right); while(left <= right){ mid += left; mid += right; divide_by_2(mid); prod = (mid * mid); if(prod <= a){ v = mid; ++mid; left = mid; } else{ --mid; right = mid; } mid = BigInt(); } return v;} BigInt NthCatalan(int n){ BigInt a(1),b; for (int i = 2; i <= n;i++) a *= i; b = a; for (int i = n + 1; i <= 2 * n;i++) b *= i; a *= a; a *= (n + 1); b /= a; return b;} BigInt NthFibonacci(int n){ BigInt a(1), b(1), c; if(!n) return c; n--; while(n--){ c = a + b; b = a; a = c; } return b;} BigInt Factorial(int n){ BigInt f(1); for (int i = 2; i <= n;i++) f *= i; return f;} istream &operator>>(istream &in,BigInt&a){ string s; in >> s; int n = s.size(); for (int i = n - 1; i >= 0;i--){ if(!isdigit(s[i])) throw("INVALID NUMBER"); a.digits[n - i - 1] = s[i]; } return in;} ostream &operator<<(ostream &out,const BigInt &a){ for (int i = a.digits.size() - 1; i >= 0;i--) cout << (short)a.digits[i]; return cout;} //Driver code with some examplesint main(){ BigInt first("12345"); cout << "The number of digits" << " in first big integer = " << Length(first) << '\n'; BigInt second(12345); if (first == second) { cout << "first and second are equal!\n"; } else cout << "Not equal!\n"; BigInt third("10000"); BigInt fourth("100000"); if (third < fourth) { cout << "third is smaller than fourth!\n"; } BigInt fifth("10000000"); if (fifth > fourth) { cout << "fifth is larger than fourth!\n"; } // Printing all the numbers cout << "first = " << first << '\n'; cout << "second = " << second << '\n'; cout << "third = " << third << '\n'; cout << "fourth = " << fourth<< '\n'; cout << "fifth = " << fifth<< '\n'; // Incrementing the value of first first++; cout << "After incrementing the" << " value of first is : "; cout << first << '\n'; BigInt sum; sum = (fourth + fifth); cout << "Sum of fourth and fifth = " << sum << '\n'; BigInt product; product = second * third; cout << "Product of second and third = " << product << '\n'; // Print the fibonaccii number from 1 to 100 cout << "-------------------------Fibonacci" << "------------------------------\n"; for (int i = 0; i <= 100; i++) { BigInt Fib; Fib = NthFibonacci(i); cout << "Fibonacci " << i << " = " << Fib<<'\n'; } cout << "-------------------------Catalan" << "------------------------------\n"; for (int i = 0; i <= 100; i++) { BigInt Cat; Cat = NthCatalan(i); cout << "Catalan " << i << " = " << Cat<<'\n'; } // Calculating factorial of from 1 to 100 cout << "-------------------------Factorial" << "------------------------------\n"; for (int i = 0; i <= 100; i++) { BigInt fact; fact = Factorial(i); cout << "Factorial of " << i << " = "; cout << fact << '\n'; } // This code is contributed // by Gatea David}
The number of digits in first big integer = 5
first and second are equal!
third is smaller than fourth!
fifth is larger than fourth!
first = 12345
second = 12345
third = 10000
fourth = 100000
fifth = 10000000
After incrementing the value of first is : 12346
Sum of fourth and fifth = 10100000
Product of second and third = 123450000
-------------------------Fibonacci------------------------------
Fibonacci 0 = 0
Fibonacci 1 = 1
Fibonacci 2 = 1
Fibonacci 3 = 2
Fibonacci 4 = 3
Fibonacci 5 = 5
Fibonacci 6 = 8
Fibonacci 7 = 13
Fibonacci 8 = 21
Fibonacci 9 = 34
Fibonacci 10 = 55
Fibonacci 11 = 89
Fibonacci 12 = 144
Fibonacci 13 = 233
Fibonacci 14 = 377
Fibonacci 15 = 610
Fibonacci 16 = 987
Fibonacci 17 = 1597
Fibonacci 18 = 2584
Fibonacci 19 = 4181
Fibonacci 20 = 6765
Fibonacci 21 = 10946
Fibonacci 22 = 17711
Fibonacci 23 = 28657
Fibonacci 24 = 46368
Fibonacci 25 = 75025
Fibonacci 26 = 121393
Fibonacci 27 = 196418
Fibonacci 28 = 317811
Fibonacci 29 = 514229
Fibonacci 30 = 832040
Fibonacci 31 = 1346269
Fibonacci 32 = 2178309
Fibonacci 33 = 3524578
Fibonacci 34 = 5702887
Fibonacci 35 = 9227465
Fibonacci 36 = 14930352
Fibonacci 37 = 24157817
Fibonacci 38 = 39088169
Fibonacci 39 = 63245986
Fibonacci 40 = 102334155
Fibonacci 41 = 165580141
Fibonacci 42 = 267914296
Fibonacci 43 = 433494437
Fibonacci 44 = 701408733
Fibonacci 45 = 1134903170
Fibonacci 46 = 1836311903
Fibonacci 47 = 2971215073
Fibonacci 48 = 4807526976
Fibonacci 49 = 7778742049
Fibonacci 50 = 12586269025
Fibonacci 51 = 20365011074
Fibonacci 52 = 32951280099
Fibonacci 53 = 53316291173
Fibonacci 54 = 86267571272
Fibonacci 55 = 139583862445
Fibonacci 56 = 225851433717
Fibonacci 57 = 365435296162
Fibonacci 58 = 591286729879
Fibonacci 59 = 956722026041
Fibonacci 60 = 1548008755920
Fibonacci 61 = 2504730781961
Fibonacci 62 = 4052739537881
Fibonacci 63 = 6557470319842
Fibonacci 64 = 10610209857723
Fibonacci 65 = 17167680177565
Fibonacci 66 = 27777890035288
Fibonacci 67 = 44945570212853
Fibonacci 68 = 72723460248141
Fibonacci 69 = 117669030460994
Fibonacci 70 = 190392490709135
Fibonacci 71 = 308061521170129
Fibonacci 72 = 498454011879264
Fibonacci 73 = 806515533049393
Fibonacci 74 = 1304969544928657
Fibonacci 75 = 2111485077978050
Fibonacci 76 = 3416454622906707
Fibonacci 77 = 5527939700884757
Fibonacci 78 = 8944394323791464
Fibonacci 79 = 14472334024676221
Fibonacci 80 = 23416728348467685
Fibonacci 81 = 37889062373143906
Fibonacci 82 = 61305790721611591
Fibonacci 83 = 99194853094755497
Fibonacci 84 = 160500643816367088
Fibonacci 85 = 259695496911122585
Fibonacci 86 = 420196140727489673
Fibonacci 87 = 679891637638612258
Fibonacci 88 = 1100087778366101931
Fibonacci 89 = 1779979416004714189
Fibonacci 90 = 2880067194370816120
Fibonacci 91 = 4660046610375530309
Fibonacci 92 = 7540113804746346429
Fibonacci 93 = 12200160415121876738
Fibonacci 94 = 19740274219868223167
Fibonacci 95 = 31940434634990099905
Fibonacci 96 = 51680708854858323072
Fibonacci 97 = 83621143489848422977
Fibonacci 98 = 135301852344706746049
Fibonacci 99 = 218922995834555169026
Fibonacci 100 = 354224848179261915075
-------------------------Catalan------------------------------
Catalan 0 = 1
Catalan 1 = 1
Catalan 2 = 2
Catalan 3 = 5
Catalan 4 = 14
Catalan 5 = 42
Catalan 6 = 132
Catalan 7 = 429
Catalan 8 = 1430
Catalan 9 = 4862
Catalan 10 = 16796
Catalan 11 = 58786
Catalan 12 = 208012
Catalan 13 = 742900
Catalan 14 = 2674440
Catalan 15 = 9694845
Catalan 16 = 35357670
Catalan 17 = 129644790
Catalan 18 = 477638700
Catalan 19 = 1767263190
Catalan 20 = 6564120420
Catalan 21 = 24466267020
Catalan 22 = 91482563640
Catalan 23 = 343059613650
Catalan 24 = 1289904147324
Catalan 25 = 4861946401452
Catalan 26 = 18367353072152
Catalan 27 = 69533550916004
Catalan 28 = 263747951750360
Catalan 29 = 1002242216651368
Catalan 30 = 3814986502092304
Catalan 31 = 14544636039226909
Catalan 32 = 55534064877048198
Catalan 33 = 212336130412243110
Catalan 34 = 812944042149730764
Catalan 35 = 3116285494907301262
Catalan 36 = 11959798385860453492
Catalan 37 = 45950804324621742364
Catalan 38 = 176733862787006701400
Catalan 39 = 680425371729975800390
Catalan 40 = 2622127042276492108820
Catalan 41 = 10113918591637898134020
Catalan 42 = 39044429911904443959240
Catalan 43 = 150853479205085351660700
Catalan 44 = 583300119592996693088040
Catalan 45 = 2257117854077248073253720
Catalan 46 = 8740328711533173390046320
Catalan 47 = 33868773757191046886429490
Catalan 48 = 131327898242169365477991900
Catalan 49 = 509552245179617138054608572
Catalan 50 = 1978261657756160653623774456
Catalan 51 = 7684785670514316385230816156
Catalan 52 = 29869166945772625950142417512
Catalan 53 = 116157871455782434250553845880
Catalan 54 = 451959718027953471447609509424
Catalan 55 = 1759414616608818870992479875972
Catalan 56 = 6852456927844873497549658464312
Catalan 57 = 26700952856774851904245220912664
Catalan 58 = 104088460289122304033498318812080
Catalan 59 = 405944995127576985730643443367112
Catalan 60 = 1583850964596120042686772779038896
Catalan 61 = 6182127958584855650487080847216336
Catalan 62 = 24139737743045626825711458546273312
Catalan 63 = 94295850558771979787935384946380125
Catalan 64 = 368479169875816659479009042713546950
Catalan 65 = 1440418573150919668872489894243865350
Catalan 66 = 5632681584560312734993915705849145100
Catalan 67 = 22033725021956517463358552614056949950
Catalan 68 = 86218923998960285726185640663701108500
Catalan 69 = 337485502510215975556783793455058624700
Catalan 70 = 1321422108420282270489942177190229544600
Catalan 71 = 5175569924646105559418940193995065716350
Catalan 72 = 20276890389709399862928998568254641025700
Catalan 73 = 79463489365077377841208237632349268884500
Catalan 74 = 311496878311103321137536291518809134027240
Catalan 75 = 1221395654430378811828760722007962130791020
Catalan 76 = 4790408930363303911328386208394864461024520
Catalan 77 = 18793142726809884575211361279087545193250040
Catalan 78 = 73745243611532458459690151854647329239335600
Catalan 79 = 289450081175264899454283846029490767264392230
Catalan 80 = 1136359577947336271931632877004667456667613940
Catalan 81 = 4462290049988320482463241297506133183499654740
Catalan 82 = 17526585015616776834735140517915655636396234280
Catalan 83 = 68854441132780194707888052034668647142985206100
Catalan 84 = 270557451039395118028642463289168566420671280440
Catalan 85 = 1063353702922273835973036658043476458723103404520
Catalan 86 = 4180080073556524734514695828170907458428751314320
Catalan 87 = 16435314834665426797069144960762886143367590394940
Catalan 88 = 64633260585762914370496637486146181462681535261000
Catalan 89 = 254224158304000796523953440778841647086547372026600
Catalan 90 = 1000134600800354781929399250536541864362461089950800
Catalan 91 = 3935312233584004685417853572763349509774031680023800
Catalan 92 = 15487357822491889407128326963778343232013931127835600
Catalan 93 = 60960876535340415751462563580829648891969728907438000
Catalan 94 = 239993345518077005168915776623476723006280827488229600
Catalan 95 = 944973797977428207852605870454939596837230758234904050
Catalan 96 = 3721443204405954385563870541379246659709506697378694300
Catalan 97 = 14657929356129575437016877846657032761712954950899755100
Catalan 98 = 57743358069601357782187700608042856334020731624756611000
Catalan 99 = 227508830794229349661819540395688853956041682601541047340
Catalan 100 = 896519947090131496687170070074100632420837521538745909320
-------------------------Factorial------------------------------
Factorial of 0 = 1
Factorial of 1 = 1
Factorial of 2 = 2
Factorial of 3 = 6
Factorial of 4 = 24
Factorial of 5 = 120
Factorial of 6 = 720
Factorial of 7 = 5040
Factorial of 8 = 40320
Factorial of 9 = 362880
Factorial of 10 = 3628800
Factorial of 11 = 39916800
Factorial of 12 = 479001600
Factorial of 13 = 6227020800
Factorial of 14 = 87178291200
Factorial of 15 = 1307674368000
Factorial of 16 = 20922789888000
Factorial of 17 = 355687428096000
Factorial of 18 = 6402373705728000
Factorial of 19 = 121645100408832000
Factorial of 20 = 2432902008176640000
Factorial of 21 = 51090942171709440000
Factorial of 22 = 1124000727777607680000
Factorial of 23 = 25852016738884976640000
Factorial of 24 = 620448401733239439360000
Factorial of 25 = 15511210043330985984000000
Factorial of 26 = 403291461126605635584000000
Factorial of 27 = 10888869450418352160768000000
Factorial of 28 = 304888344611713860501504000000
Factorial of 29 = 8841761993739701954543616000000
Factorial of 30 = 265252859812191058636308480000000
Factorial of 31 = 8222838654177922817725562880000000
Factorial of 32 = 263130836933693530167218012160000000
Factorial of 33 = 8683317618811886495518194401280000000
Factorial of 34 = 295232799039604140847618609643520000000
Factorial of 35 = 10333147966386144929666651337523200000000
Factorial of 36 = 371993326789901217467999448150835200000000
Factorial of 37 = 13763753091226345046315979581580902400000000
Factorial of 38 = 523022617466601111760007224100074291200000000
Factorial of 39 = 20397882081197443358640281739902897356800000000
Factorial of 40 = 815915283247897734345611269596115894272000000000
Factorial of 41 = 33452526613163807108170062053440751665152000000000
Factorial of 42 = 1405006117752879898543142606244511569936384000000000
Factorial of 43 = 60415263063373835637355132068513997507264512000000000
Factorial of 44 = 2658271574788448768043625811014615890319638528000000000
Factorial of 45 = 119622220865480194561963161495657715064383733760000000000
Factorial of 46 = 5502622159812088949850305428800254892961651752960000000000
Factorial of 47 = 258623241511168180642964355153611979969197632389120000000000
Factorial of 48 = 12413915592536072670862289047373375038521486354677760000000000
Factorial of 49 = 608281864034267560872252163321295376887552831379210240000000000
Factorial of 50 = 30414093201713378043612608166064768844377641568960512000000000000
Factorial of 51 = 1551118753287382280224243016469303211063259720016986112000000000000
Factorial of 52 = 80658175170943878571660636856403766975289505440883277824000000000000
Factorial of 53 = 4274883284060025564298013753389399649690343788366813724672000000000000
Factorial of 54 = 230843697339241380472092742683027581083278564571807941132288000000000000
Factorial of 55 = 12696403353658275925965100847566516959580321051449436762275840000000000000
Factorial of 56 = 710998587804863451854045647463724949736497978881168458687447040000000000000
Factorial of 57 = 40526919504877216755680601905432322134980384796226602145184481280000000000000
Factorial of 58 = 2350561331282878571829474910515074683828862318181142924420699914240000000000000
Factorial of 59 = 138683118545689835737939019720389406345902876772687432540821294940160000000000000
Factorial of 60 = 8320987112741390144276341183223364380754172606361245952449277696409600000000000000
Factorial of 61 = 507580213877224798800856812176625227226004528988036003099405939480985600000000000000
Factorial of 62 = 31469973260387937525653122354950764088012280797258232192163168247821107200000000000000
Factorial of 63 = 1982608315404440064116146708361898137544773690227268628106279599612729753600000000000000
Factorial of 64 = 126886932185884164103433389335161480802865516174545192198801894375214704230400000000000000
Factorial of 65 = 8247650592082470666723170306785496252186258551345437492922123134388955774976000000000000000
Factorial of 66 = 544344939077443064003729240247842752644293064388798874532860126869671081148416000000000000000
Factorial of 67 = 36471110918188685288249859096605464427167635314049524593701628500267962436943872000000000000000
Factorial of 68 = 2480035542436830599600990418569171581047399201355367672371710738018221445712183296000000000000000
Factorial of 69 = 171122452428141311372468338881272839092270544893520369393648040923257279754140647424000000000000000
Factorial of 70 = 11978571669969891796072783721689098736458938142546425857555362864628009582789845319680000000000000000
Factorial of 71 = 850478588567862317521167644239926010288584608120796235886430763388588680378079017697280000000000000000
Factorial of 72 = 61234458376886086861524070385274672740778091784697328983823014963978384987221689274204160000000000000000
Factorial of 73 = 4470115461512684340891257138125051110076800700282905015819080092370422104067183317016903680000000000000000
Factorial of 74 = 330788544151938641225953028221253782145683251820934971170611926835411235700971565459250872320000000000000000
Factorial of 75 = 24809140811395398091946477116594033660926243886570122837795894512655842677572867409443815424000000000000000000
Factorial of 76 = 1885494701666050254987932260861146558230394535379329335672487982961844043495537923117729972224000000000000000000
Factorial of 77 = 145183092028285869634070784086308284983740379224208358846781574688061991349156420080065207861248000000000000000000
Factorial of 78 = 11324281178206297831457521158732046228731749579488251990048962825668835325234200766245086213177344000000000000000000
Factorial of 79 = 894618213078297528685144171539831652069808216779571907213868063227837990693501860533361810841010176000000000000000000
Factorial of 80 = 71569457046263802294811533723186532165584657342365752577109445058227039255480148842668944867280814080000000000000000000
Factorial of 81 = 5797126020747367985879734231578109105412357244731625958745865049716390179693892056256184534249745940480000000000000000000
Factorial of 82 = 475364333701284174842138206989404946643813294067993328617160934076743994734899148613007131808479167119360000000000000000000
Factorial of 83 = 39455239697206586511897471180120610571436503407643446275224357528369751562996629334879591940103770870906880000000000000000000
Factorial of 84 = 3314240134565353266999387579130131288000666286242049487118846032383059131291716864129885722968716753156177920000000000000000000
Factorial of 85 = 281710411438055027694947944226061159480056634330574206405101912752560026159795933451040286452340924018275123200000000000000000000
Factorial of 86 = 24227095383672732381765523203441259715284870552429381750838764496720162249742450276789464634901319465571660595200000000000000000000
Factorial of 87 = 2107757298379527717213600518699389595229783738061356212322972511214654115727593174080683423236414793504734471782400000000000000000000
Factorial of 88 = 185482642257398439114796845645546284380220968949399346684421580986889562184028199319100141244804501828416633516851200000000000000000000
Factorial of 89 = 16507955160908461081216919262453619309839666236496541854913520707833171034378509739399912570787600662729080382999756800000000000000000000
Factorial of 90 = 1485715964481761497309522733620825737885569961284688766942216863704985393094065876545992131370884059645617234469978112000000000000000000000
Factorial of 91 = 135200152767840296255166568759495142147586866476906677791741734597153670771559994765685283954750449427751168336768008192000000000000000000000
Factorial of 92 = 12438414054641307255475324325873553077577991715875414356840239582938137710983519518443046123837041347353107486982656753664000000000000000000000
Factorial of 93 = 1156772507081641574759205162306240436214753229576413535186142281213246807121467315215203289516844845303838996289387078090752000000000000000000000
Factorial of 94 = 108736615665674308027365285256786601004186803580182872307497374434045199869417927630229109214583415458560865651202385340530688000000000000000000000
Factorial of 95 = 10329978488239059262599702099394727095397746340117372869212250571234293987594703124871765375385424468563282236864226607350415360000000000000000000000
Factorial of 96 = 991677934870949689209571401541893801158183648651267795444376054838492222809091499987689476037000748982075094738965754305639874560000000000000000000000
Factorial of 97 = 96192759682482119853328425949563698712343813919172976158104477319333745612481875498805879175589072651261284189679678167647067832320000000000000000000000
Factorial of 98 = 9426890448883247745626185743057242473809693764078951663494238777294707070023223798882976159207729119823605850588608460429412647567360000000000000000000000
Factorial of 99 = 933262154439441526816992388562667004907159682643816214685929638952175999932299156089414639761565182862536979208272237582511852109168640000000000000000000000
Factorial of 100 = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
erichfrazer
davidgatea21
anikakapoor
sweetyty
rkbhola5
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Array of Strings in C++ (5 Different Ways to Create)
Inline Functions in C++
Convert string to char array in C++
Pair in C++ Standard Template Library (STL)
Destructors in C++
|
[
{
"code": null,
"e": 24220,
"s": 24192,
"text": "\n17 Feb, 2022"
},
{
"code": null,
"e": 24587,
"s": 24220,
"text": "In C/C++ the number of digits a long long int can have is a maximum of 20. And the question is to store the 22 digit number which is not easy to store in any kind of primitive type. So to deal with this type of problem letβs design a new data type which is going to be called BigInt In this article, a few basic operations are being implemented on the new data type."
},
{
"code": null,
"e": 24955,
"s": 24587,
"text": "Add two big integers.Subtract two big integersMultiply two big integers.Divide two big integers.Modulo two big integersRaise a big integer to a powerThe square root of a big integerComparison between two big integers to check which is greater and which is smaller.Find the number of digits in the big integer.Print the big integer.Convert an integer to a big integer."
},
{
"code": null,
"e": 24977,
"s": 24955,
"text": "Add two big integers."
},
{
"code": null,
"e": 25003,
"s": 24977,
"text": "Subtract two big integers"
},
{
"code": null,
"e": 25030,
"s": 25003,
"text": "Multiply two big integers."
},
{
"code": null,
"e": 25055,
"s": 25030,
"text": "Divide two big integers."
},
{
"code": null,
"e": 25079,
"s": 25055,
"text": "Modulo two big integers"
},
{
"code": null,
"e": 25110,
"s": 25079,
"text": "Raise a big integer to a power"
},
{
"code": null,
"e": 25143,
"s": 25110,
"text": "The square root of a big integer"
},
{
"code": null,
"e": 25227,
"s": 25143,
"text": "Comparison between two big integers to check which is greater and which is smaller."
},
{
"code": null,
"e": 25273,
"s": 25227,
"text": "Find the number of digits in the big integer."
},
{
"code": null,
"e": 25296,
"s": 25273,
"text": "Print the big integer."
},
{
"code": null,
"e": 25333,
"s": 25296,
"text": "Convert an integer to a big integer."
},
{
"code": null,
"e": 25420,
"s": 25333,
"text": "Applications Of BigInt:Below are some basic applications of the new data type, BigInt:"
},
{
"code": null,
"e": 25563,
"s": 25420,
"text": "Calculating the Fibonacci number of a large number.Calculating the Catalan number of a large numberCalculating the Factorial of a big integer."
},
{
"code": null,
"e": 25615,
"s": 25563,
"text": "Calculating the Fibonacci number of a large number."
},
{
"code": null,
"e": 25664,
"s": 25615,
"text": "Calculating the Catalan number of a large number"
},
{
"code": null,
"e": 25708,
"s": 25664,
"text": "Calculating the Factorial of a big integer."
},
{
"code": null,
"e": 25801,
"s": 25708,
"text": "Approach:To create a new data type of big integers following concepts are being implemented:"
},
{
"code": null,
"e": 27089,
"s": 25801,
"text": "C++ strings in that we can store our numbers in the form of characters (in reverse order for efficiency purposes) such that using strings we can store very big numbers also.For the addition/subtraction operation of two big integers, use the basic math for addition which says that add the corresponding two digits and if some carry is generated add it to the sum of the next digits and repeat this process until all digits are added/subtracted.Similarly, for the multiplication of two numbers, use the basic mathematics approach which states that multiply every digit of one number with the other complete number and at last add all the numbers we get in multiplication.The following operations are being performed on BigInt-Defining some big integers.Checking the number of digits in the big integer.Post/Pre Incrementation or DecrementationAdding two big integers.Subtracting two big integers.Multiplying two big integers.Divide two big integersModulo of two big integersThe square root of a big integer (floor integer value)Raise a big integer to a powerConverting a simple integer to a big integer.Calculating Fibonacci up to 10 000. (even 100000 but slower)Calculating Factorial up to 1 000.Calculating Catalan up to 1 000.Checking which big integer is greater and which is smaller."
},
{
"code": null,
"e": 27263,
"s": 27089,
"text": "C++ strings in that we can store our numbers in the form of characters (in reverse order for efficiency purposes) such that using strings we can store very big numbers also."
},
{
"code": null,
"e": 27535,
"s": 27263,
"text": "For the addition/subtraction operation of two big integers, use the basic math for addition which says that add the corresponding two digits and if some carry is generated add it to the sum of the next digits and repeat this process until all digits are added/subtracted."
},
{
"code": null,
"e": 27762,
"s": 27535,
"text": "Similarly, for the multiplication of two numbers, use the basic mathematics approach which states that multiply every digit of one number with the other complete number and at last add all the numbers we get in multiplication."
},
{
"code": null,
"e": 28380,
"s": 27762,
"text": "The following operations are being performed on BigInt-Defining some big integers.Checking the number of digits in the big integer.Post/Pre Incrementation or DecrementationAdding two big integers.Subtracting two big integers.Multiplying two big integers.Divide two big integersModulo of two big integersThe square root of a big integer (floor integer value)Raise a big integer to a powerConverting a simple integer to a big integer.Calculating Fibonacci up to 10 000. (even 100000 but slower)Calculating Factorial up to 1 000.Calculating Catalan up to 1 000.Checking which big integer is greater and which is smaller."
},
{
"code": null,
"e": 28943,
"s": 28380,
"text": "Defining some big integers.Checking the number of digits in the big integer.Post/Pre Incrementation or DecrementationAdding two big integers.Subtracting two big integers.Multiplying two big integers.Divide two big integersModulo of two big integersThe square root of a big integer (floor integer value)Raise a big integer to a powerConverting a simple integer to a big integer.Calculating Fibonacci up to 10 000. (even 100000 but slower)Calculating Factorial up to 1 000.Calculating Catalan up to 1 000.Checking which big integer is greater and which is smaller."
},
{
"code": null,
"e": 28971,
"s": 28943,
"text": "Defining some big integers."
},
{
"code": null,
"e": 29021,
"s": 28971,
"text": "Checking the number of digits in the big integer."
},
{
"code": null,
"e": 29063,
"s": 29021,
"text": "Post/Pre Incrementation or Decrementation"
},
{
"code": null,
"e": 29088,
"s": 29063,
"text": "Adding two big integers."
},
{
"code": null,
"e": 29118,
"s": 29088,
"text": "Subtracting two big integers."
},
{
"code": null,
"e": 29148,
"s": 29118,
"text": "Multiplying two big integers."
},
{
"code": null,
"e": 29172,
"s": 29148,
"text": "Divide two big integers"
},
{
"code": null,
"e": 29199,
"s": 29172,
"text": "Modulo of two big integers"
},
{
"code": null,
"e": 29254,
"s": 29199,
"text": "The square root of a big integer (floor integer value)"
},
{
"code": null,
"e": 29285,
"s": 29254,
"text": "Raise a big integer to a power"
},
{
"code": null,
"e": 29331,
"s": 29285,
"text": "Converting a simple integer to a big integer."
},
{
"code": null,
"e": 29392,
"s": 29331,
"text": "Calculating Fibonacci up to 10 000. (even 100000 but slower)"
},
{
"code": null,
"e": 29427,
"s": 29392,
"text": "Calculating Factorial up to 1 000."
},
{
"code": null,
"e": 29460,
"s": 29427,
"text": "Calculating Catalan up to 1 000."
},
{
"code": null,
"e": 29520,
"s": 29460,
"text": "Checking which big integer is greater and which is smaller."
},
{
"code": null,
"e": 29575,
"s": 29520,
"text": "Below is the C++ implementation of the above approach:"
},
{
"code": null,
"e": 29579,
"s": 29575,
"text": "C++"
},
{
"code": "// C++ program to implement// the above approach#include <bits/stdc++.h> using namespace std; class BigInt{ string digits;public: //Constructors: BigInt(unsigned long long n = 0); BigInt(string &); BigInt(const char *); BigInt(BigInt &); //Helper Functions: friend void divide_by_2(BigInt &a); friend bool Null(const BigInt &); friend int Length(const BigInt &); int operator[](const int)const; /* * * * Operator Overloading * * * */ //Direct assignment BigInt &operator=(const BigInt &); //Post/Pre - Incrementation BigInt &operator++(); BigInt operator++(int temp); BigInt &operator--(); BigInt operator--(int temp); //Addition and Subtraction friend BigInt &operator+=(BigInt &, const BigInt &); friend BigInt operator+(const BigInt &, const BigInt &); friend BigInt operator-(const BigInt &, const BigInt &); friend BigInt &operator-=(BigInt &, const BigInt &); //Comparison operators friend bool operator==(const BigInt &, const BigInt &); friend bool operator!=(const BigInt &, const BigInt &); friend bool operator>(const BigInt &, const BigInt &); friend bool operator>=(const BigInt &, const BigInt &); friend bool operator<(const BigInt &, const BigInt &); friend bool operator<=(const BigInt &, const BigInt &); //Multiplication and Division friend BigInt &operator*=(BigInt &, const BigInt &); friend BigInt operator*(const BigInt &, const BigInt &); friend BigInt &operator/=(BigInt &, const BigInt &); friend BigInt operator/(const BigInt &, const BigInt &); //Modulo friend BigInt operator%(const BigInt &, const BigInt &); friend BigInt &operator%=(BigInt &, const BigInt &); //Power Function friend BigInt &operator^=(BigInt &,const BigInt &); friend BigInt operator^(BigInt &, const BigInt &); //Square Root Function friend BigInt sqrt(BigInt &a); //Read and Write friend ostream &operator<<(ostream &,const BigInt &); friend istream &operator>>(istream &, BigInt &); //Others friend BigInt NthCatalan(int n); friend BigInt NthFibonacci(int n); friend BigInt Factorial(int n);}; BigInt::BigInt(string & s){ digits = \"\"; int n = s.size(); for (int i = n - 1; i >= 0;i--){ if(!isdigit(s[i])) throw(\"ERROR\"); digits.push_back(s[i] - '0'); }}BigInt::BigInt(unsigned long long nr){ do{ digits.push_back(nr % 10); nr /= 10; } while (nr);}BigInt::BigInt(const char *s){ digits = \"\"; for (int i = strlen(s) - 1; i >= 0;i--) { if(!isdigit(s[i])) throw(\"ERROR\"); digits.push_back(s[i] - '0'); }}BigInt::BigInt(BigInt & a){ digits = a.digits;} bool Null(const BigInt& a){ if(a.digits.size() == 1 && a.digits[0] == 0) return true; return false;}int Length(const BigInt & a){ return a.digits.size();}int BigInt::operator[](const int index)const{ if(digits.size() <= index || index < 0) throw(\"ERROR\"); return digits[index];}bool operator==(const BigInt &a, const BigInt &b){ return a.digits == b.digits;}bool operator!=(const BigInt & a,const BigInt &b){ return !(a == b);}bool operator<(const BigInt&a,const BigInt&b){ int n = Length(a), m = Length(b); if(n != m) return n < m; while(n--) if(a.digits[n] != b.digits[n]) return a.digits[n] < b.digits[n]; return false;}bool operator>(const BigInt&a,const BigInt&b){ return b < a;}bool operator>=(const BigInt&a,const BigInt&b){ return !(a < b);}bool operator<=(const BigInt&a,const BigInt&b){ return !(a > b);} BigInt &BigInt::operator=(const BigInt &a){ digits = a.digits; return *this;} BigInt &BigInt::operator++(){ int i, n = digits.size(); for (i = 0; i < n && digits[i] == 9;i++) digits[i] = 0; if(i == n) digits.push_back(1); else digits[i]++; return *this;}BigInt BigInt::operator++(int temp){ BigInt aux; aux = *this; ++(*this); return aux;} BigInt &BigInt::operator--(){ if(digits[0] == 0 && digits.size() == 1) throw(\"UNDERFLOW\"); int i, n = digits.size(); for (i = 0; digits[i] == 0 && i < n;i++) digits[i] = 9; digits[i]--; if(n > 1 && digits[n - 1] == 0) digits.pop_back(); return *this;}BigInt BigInt::operator--(int temp){ BigInt aux; aux = *this; --(*this); return aux;} BigInt &operator+=(BigInt &a,const BigInt& b){ int t = 0, s, i; int n = Length(a), m = Length(b); if(m > n) a.digits.append(m - n, 0); n = Length(a); for (i = 0; i < n;i++){ if(i < m) s = (a.digits[i] + b.digits[i]) + t; else s = a.digits[i] + t; t = s / 10; a.digits[i] = (s % 10); } if(t) a.digits.push_back(t); return a;}BigInt operator+(const BigInt &a, const BigInt &b){ BigInt temp; temp = a; temp += b; return temp;} BigInt &operator-=(BigInt&a,const BigInt &b){ if(a < b) throw(\"UNDERFLOW\"); int n = Length(a), m = Length(b); int i, t = 0, s; for (i = 0; i < n;i++){ if(i < m) s = a.digits[i] - b.digits[i]+ t; else s = a.digits[i]+ t; if(s < 0) s += 10, t = -1; else t = 0; a.digits[i] = s; } while(n > 1 && a.digits[n - 1] == 0) a.digits.pop_back(), n--; return a;}BigInt operator-(const BigInt& a,const BigInt&b){ BigInt temp; temp = a; temp -= b; return temp;} BigInt &operator*=(BigInt &a, const BigInt &b){ if(Null(a) || Null(b)){ a = BigInt(); return a; } int n = a.digits.size(), m = b.digits.size(); vector<int> v(n + m, 0); for (int i = 0; i < n;i++) for (int j = 0; j < m;j++){ v[i + j] += (a.digits[i] ) * (b.digits[j]); } n += m; a.digits.resize(v.size()); for (int s, i = 0, t = 0; i < n; i++) { s = t + v[i]; v[i] = s % 10; t = s / 10; a.digits[i] = v[i] ; } for (int i = n - 1; i >= 1 && !v[i];i--) a.digits.pop_back(); return a;}BigInt operator*(const BigInt&a,const BigInt&b){ BigInt temp; temp = a; temp *= b; return temp;} BigInt &operator/=(BigInt& a,const BigInt &b){ if(Null(b)) throw(\"Arithmetic Error: Division By 0\"); if(a < b){ a = BigInt(); return a; } if(a == b){ a = BigInt(1); return a; } int i, lgcat = 0, cc; int n = Length(a), m = Length(b); vector<int> cat(n, 0); BigInt t; for (i = n - 1; t * 10 + a.digits[i] < b;i--){ t *= 10; t += a.digits[i] ; } for (; i >= 0; i--){ t = t * 10 + a.digits[i]; for (cc = 9; cc * b > t;cc--); t -= cc * b; cat[lgcat++] = cc; } a.digits.resize(cat.size()); for (i = 0; i < lgcat;i++) a.digits[i] = cat[lgcat - i - 1]; a.digits.resize(lgcat); return a;}BigInt operator/(const BigInt &a,const BigInt &b){ BigInt temp; temp = a; temp /= b; return temp;} BigInt &operator%=(BigInt& a,const BigInt &b){ if(Null(b)) throw(\"Arithmetic Error: Division By 0\"); if(a < b){ a = BigInt(); return a; } if(a == b){ a = BigInt(1); return a; } int i, lgcat = 0, cc; int n = Length(a), m = Length(b); vector<int> cat(n, 0); BigInt t; for (i = n - 1; t * 10 + a.digits[i] < b;i--){ t *= 10; t += a.digits[i]; } for (; i >= 0; i--){ t = t * 10 + a.digits[i]; for (cc = 9; cc * b > t;cc--); t -= cc * b; cat[lgcat++] = cc; } a = t; return a;}BigInt operator%(const BigInt &a,BigInt &b){ BigInt temp; temp = a; temp %= b; return temp;} BigInt &operator^=(BigInt & a,const BigInt & b){ BigInt Exponent, Base(a); Exponent = b; a = 1; while(!Null(Exponent)){ if(Exponent[0] & 1) a *= Base; Base *= Base; divide_by_2(Exponent); } return a;}BigInt operator^(BigInt & a,BigInt & b){ BigInt temp(a); temp ^= b; return temp;} void divide_by_2(BigInt & a){ int add = 0; for (int i = a.digits.size() - 1; i >= 0;i--){ int digit = (a.digits[i] >> 1) + add; add = ((a.digits[i] & 1) * 5); a.digits[i] = digit; } while(a.digits.size() > 1 && !a.digits.back()) a.digits.pop_back();} BigInt sqrt(BigInt & a){ BigInt left(1), right(a), v(1), mid, prod; divide_by_2(right); while(left <= right){ mid += left; mid += right; divide_by_2(mid); prod = (mid * mid); if(prod <= a){ v = mid; ++mid; left = mid; } else{ --mid; right = mid; } mid = BigInt(); } return v;} BigInt NthCatalan(int n){ BigInt a(1),b; for (int i = 2; i <= n;i++) a *= i; b = a; for (int i = n + 1; i <= 2 * n;i++) b *= i; a *= a; a *= (n + 1); b /= a; return b;} BigInt NthFibonacci(int n){ BigInt a(1), b(1), c; if(!n) return c; n--; while(n--){ c = a + b; b = a; a = c; } return b;} BigInt Factorial(int n){ BigInt f(1); for (int i = 2; i <= n;i++) f *= i; return f;} istream &operator>>(istream &in,BigInt&a){ string s; in >> s; int n = s.size(); for (int i = n - 1; i >= 0;i--){ if(!isdigit(s[i])) throw(\"INVALID NUMBER\"); a.digits[n - i - 1] = s[i]; } return in;} ostream &operator<<(ostream &out,const BigInt &a){ for (int i = a.digits.size() - 1; i >= 0;i--) cout << (short)a.digits[i]; return cout;} //Driver code with some examplesint main(){ BigInt first(\"12345\"); cout << \"The number of digits\" << \" in first big integer = \" << Length(first) << '\\n'; BigInt second(12345); if (first == second) { cout << \"first and second are equal!\\n\"; } else cout << \"Not equal!\\n\"; BigInt third(\"10000\"); BigInt fourth(\"100000\"); if (third < fourth) { cout << \"third is smaller than fourth!\\n\"; } BigInt fifth(\"10000000\"); if (fifth > fourth) { cout << \"fifth is larger than fourth!\\n\"; } // Printing all the numbers cout << \"first = \" << first << '\\n'; cout << \"second = \" << second << '\\n'; cout << \"third = \" << third << '\\n'; cout << \"fourth = \" << fourth<< '\\n'; cout << \"fifth = \" << fifth<< '\\n'; // Incrementing the value of first first++; cout << \"After incrementing the\" << \" value of first is : \"; cout << first << '\\n'; BigInt sum; sum = (fourth + fifth); cout << \"Sum of fourth and fifth = \" << sum << '\\n'; BigInt product; product = second * third; cout << \"Product of second and third = \" << product << '\\n'; // Print the fibonaccii number from 1 to 100 cout << \"-------------------------Fibonacci\" << \"------------------------------\\n\"; for (int i = 0; i <= 100; i++) { BigInt Fib; Fib = NthFibonacci(i); cout << \"Fibonacci \" << i << \" = \" << Fib<<'\\n'; } cout << \"-------------------------Catalan\" << \"------------------------------\\n\"; for (int i = 0; i <= 100; i++) { BigInt Cat; Cat = NthCatalan(i); cout << \"Catalan \" << i << \" = \" << Cat<<'\\n'; } // Calculating factorial of from 1 to 100 cout << \"-------------------------Factorial\" << \"------------------------------\\n\"; for (int i = 0; i <= 100; i++) { BigInt fact; fact = Factorial(i); cout << \"Factorial of \" << i << \" = \"; cout << fact << '\\n'; } // This code is contributed // by Gatea David}",
"e": 41305,
"s": 29579,
"text": null
},
{
"code": null,
"e": 57646,
"s": 41305,
"text": "The number of digits in first big integer = 5\nfirst and second are equal!\nthird is smaller than fourth!\nfifth is larger than fourth!\nfirst = 12345\nsecond = 12345\nthird = 10000\nfourth = 100000\nfifth = 10000000\nAfter incrementing the value of first is : 12346\nSum of fourth and fifth = 10100000\nProduct of second and third = 123450000\n-------------------------Fibonacci------------------------------\nFibonacci 0 = 0\nFibonacci 1 = 1\nFibonacci 2 = 1\nFibonacci 3 = 2\nFibonacci 4 = 3\nFibonacci 5 = 5\nFibonacci 6 = 8\nFibonacci 7 = 13\nFibonacci 8 = 21\nFibonacci 9 = 34\nFibonacci 10 = 55\nFibonacci 11 = 89\nFibonacci 12 = 144\nFibonacci 13 = 233\nFibonacci 14 = 377\nFibonacci 15 = 610\nFibonacci 16 = 987\nFibonacci 17 = 1597\nFibonacci 18 = 2584\nFibonacci 19 = 4181\nFibonacci 20 = 6765\nFibonacci 21 = 10946\nFibonacci 22 = 17711\nFibonacci 23 = 28657\nFibonacci 24 = 46368\nFibonacci 25 = 75025\nFibonacci 26 = 121393\nFibonacci 27 = 196418\nFibonacci 28 = 317811\nFibonacci 29 = 514229\nFibonacci 30 = 832040\nFibonacci 31 = 1346269\nFibonacci 32 = 2178309\nFibonacci 33 = 3524578\nFibonacci 34 = 5702887\nFibonacci 35 = 9227465\nFibonacci 36 = 14930352\nFibonacci 37 = 24157817\nFibonacci 38 = 39088169\nFibonacci 39 = 63245986\nFibonacci 40 = 102334155\nFibonacci 41 = 165580141\nFibonacci 42 = 267914296\nFibonacci 43 = 433494437\nFibonacci 44 = 701408733\nFibonacci 45 = 1134903170\nFibonacci 46 = 1836311903\nFibonacci 47 = 2971215073\nFibonacci 48 = 4807526976\nFibonacci 49 = 7778742049\nFibonacci 50 = 12586269025\nFibonacci 51 = 20365011074\nFibonacci 52 = 32951280099\nFibonacci 53 = 53316291173\nFibonacci 54 = 86267571272\nFibonacci 55 = 139583862445\nFibonacci 56 = 225851433717\nFibonacci 57 = 365435296162\nFibonacci 58 = 591286729879\nFibonacci 59 = 956722026041\nFibonacci 60 = 1548008755920\nFibonacci 61 = 2504730781961\nFibonacci 62 = 4052739537881\nFibonacci 63 = 6557470319842\nFibonacci 64 = 10610209857723\nFibonacci 65 = 17167680177565\nFibonacci 66 = 27777890035288\nFibonacci 67 = 44945570212853\nFibonacci 68 = 72723460248141\nFibonacci 69 = 117669030460994\nFibonacci 70 = 190392490709135\nFibonacci 71 = 308061521170129\nFibonacci 72 = 498454011879264\nFibonacci 73 = 806515533049393\nFibonacci 74 = 1304969544928657\nFibonacci 75 = 2111485077978050\nFibonacci 76 = 3416454622906707\nFibonacci 77 = 5527939700884757\nFibonacci 78 = 8944394323791464\nFibonacci 79 = 14472334024676221\nFibonacci 80 = 23416728348467685\nFibonacci 81 = 37889062373143906\nFibonacci 82 = 61305790721611591\nFibonacci 83 = 99194853094755497\nFibonacci 84 = 160500643816367088\nFibonacci 85 = 259695496911122585\nFibonacci 86 = 420196140727489673\nFibonacci 87 = 679891637638612258\nFibonacci 88 = 1100087778366101931\nFibonacci 89 = 1779979416004714189\nFibonacci 90 = 2880067194370816120\nFibonacci 91 = 4660046610375530309\nFibonacci 92 = 7540113804746346429\nFibonacci 93 = 12200160415121876738\nFibonacci 94 = 19740274219868223167\nFibonacci 95 = 31940434634990099905\nFibonacci 96 = 51680708854858323072\nFibonacci 97 = 83621143489848422977\nFibonacci 98 = 135301852344706746049\nFibonacci 99 = 218922995834555169026\nFibonacci 100 = 354224848179261915075\n-------------------------Catalan------------------------------\nCatalan 0 = 1\nCatalan 1 = 1\nCatalan 2 = 2\nCatalan 3 = 5\nCatalan 4 = 14\nCatalan 5 = 42\nCatalan 6 = 132\nCatalan 7 = 429\nCatalan 8 = 1430\nCatalan 9 = 4862\nCatalan 10 = 16796\nCatalan 11 = 58786\nCatalan 12 = 208012\nCatalan 13 = 742900\nCatalan 14 = 2674440\nCatalan 15 = 9694845\nCatalan 16 = 35357670\nCatalan 17 = 129644790\nCatalan 18 = 477638700\nCatalan 19 = 1767263190\nCatalan 20 = 6564120420\nCatalan 21 = 24466267020\nCatalan 22 = 91482563640\nCatalan 23 = 343059613650\nCatalan 24 = 1289904147324\nCatalan 25 = 4861946401452\nCatalan 26 = 18367353072152\nCatalan 27 = 69533550916004\nCatalan 28 = 263747951750360\nCatalan 29 = 1002242216651368\nCatalan 30 = 3814986502092304\nCatalan 31 = 14544636039226909\nCatalan 32 = 55534064877048198\nCatalan 33 = 212336130412243110\nCatalan 34 = 812944042149730764\nCatalan 35 = 3116285494907301262\nCatalan 36 = 11959798385860453492\nCatalan 37 = 45950804324621742364\nCatalan 38 = 176733862787006701400\nCatalan 39 = 680425371729975800390\nCatalan 40 = 2622127042276492108820\nCatalan 41 = 10113918591637898134020\nCatalan 42 = 39044429911904443959240\nCatalan 43 = 150853479205085351660700\nCatalan 44 = 583300119592996693088040\nCatalan 45 = 2257117854077248073253720\nCatalan 46 = 8740328711533173390046320\nCatalan 47 = 33868773757191046886429490\nCatalan 48 = 131327898242169365477991900\nCatalan 49 = 509552245179617138054608572\nCatalan 50 = 1978261657756160653623774456\nCatalan 51 = 7684785670514316385230816156\nCatalan 52 = 29869166945772625950142417512\nCatalan 53 = 116157871455782434250553845880\nCatalan 54 = 451959718027953471447609509424\nCatalan 55 = 1759414616608818870992479875972\nCatalan 56 = 6852456927844873497549658464312\nCatalan 57 = 26700952856774851904245220912664\nCatalan 58 = 104088460289122304033498318812080\nCatalan 59 = 405944995127576985730643443367112\nCatalan 60 = 1583850964596120042686772779038896\nCatalan 61 = 6182127958584855650487080847216336\nCatalan 62 = 24139737743045626825711458546273312\nCatalan 63 = 94295850558771979787935384946380125\nCatalan 64 = 368479169875816659479009042713546950\nCatalan 65 = 1440418573150919668872489894243865350\nCatalan 66 = 5632681584560312734993915705849145100\nCatalan 67 = 22033725021956517463358552614056949950\nCatalan 68 = 86218923998960285726185640663701108500\nCatalan 69 = 337485502510215975556783793455058624700\nCatalan 70 = 1321422108420282270489942177190229544600\nCatalan 71 = 5175569924646105559418940193995065716350\nCatalan 72 = 20276890389709399862928998568254641025700\nCatalan 73 = 79463489365077377841208237632349268884500\nCatalan 74 = 311496878311103321137536291518809134027240\nCatalan 75 = 1221395654430378811828760722007962130791020\nCatalan 76 = 4790408930363303911328386208394864461024520\nCatalan 77 = 18793142726809884575211361279087545193250040\nCatalan 78 = 73745243611532458459690151854647329239335600\nCatalan 79 = 289450081175264899454283846029490767264392230\nCatalan 80 = 1136359577947336271931632877004667456667613940\nCatalan 81 = 4462290049988320482463241297506133183499654740\nCatalan 82 = 17526585015616776834735140517915655636396234280\nCatalan 83 = 68854441132780194707888052034668647142985206100\nCatalan 84 = 270557451039395118028642463289168566420671280440\nCatalan 85 = 1063353702922273835973036658043476458723103404520\nCatalan 86 = 4180080073556524734514695828170907458428751314320\nCatalan 87 = 16435314834665426797069144960762886143367590394940\nCatalan 88 = 64633260585762914370496637486146181462681535261000\nCatalan 89 = 254224158304000796523953440778841647086547372026600\nCatalan 90 = 1000134600800354781929399250536541864362461089950800\nCatalan 91 = 3935312233584004685417853572763349509774031680023800\nCatalan 92 = 15487357822491889407128326963778343232013931127835600\nCatalan 93 = 60960876535340415751462563580829648891969728907438000\nCatalan 94 = 239993345518077005168915776623476723006280827488229600\nCatalan 95 = 944973797977428207852605870454939596837230758234904050\nCatalan 96 = 3721443204405954385563870541379246659709506697378694300\nCatalan 97 = 14657929356129575437016877846657032761712954950899755100\nCatalan 98 = 57743358069601357782187700608042856334020731624756611000\nCatalan 99 = 227508830794229349661819540395688853956041682601541047340\nCatalan 100 = 896519947090131496687170070074100632420837521538745909320\n-------------------------Factorial------------------------------\nFactorial of 0 = 1\nFactorial of 1 = 1\nFactorial of 2 = 2\nFactorial of 3 = 6\nFactorial of 4 = 24\nFactorial of 5 = 120\nFactorial of 6 = 720\nFactorial of 7 = 5040\nFactorial of 8 = 40320\nFactorial of 9 = 362880\nFactorial of 10 = 3628800\nFactorial of 11 = 39916800\nFactorial of 12 = 479001600\nFactorial of 13 = 6227020800\nFactorial of 14 = 87178291200\nFactorial of 15 = 1307674368000\nFactorial of 16 = 20922789888000\nFactorial of 17 = 355687428096000\nFactorial of 18 = 6402373705728000\nFactorial of 19 = 121645100408832000\nFactorial of 20 = 2432902008176640000\nFactorial of 21 = 51090942171709440000\nFactorial of 22 = 1124000727777607680000\nFactorial of 23 = 25852016738884976640000\nFactorial of 24 = 620448401733239439360000\nFactorial of 25 = 15511210043330985984000000\nFactorial of 26 = 403291461126605635584000000\nFactorial of 27 = 10888869450418352160768000000\nFactorial of 28 = 304888344611713860501504000000\nFactorial of 29 = 8841761993739701954543616000000\nFactorial of 30 = 265252859812191058636308480000000\nFactorial of 31 = 8222838654177922817725562880000000\nFactorial of 32 = 263130836933693530167218012160000000\nFactorial of 33 = 8683317618811886495518194401280000000\nFactorial of 34 = 295232799039604140847618609643520000000\nFactorial of 35 = 10333147966386144929666651337523200000000\nFactorial of 36 = 371993326789901217467999448150835200000000\nFactorial of 37 = 13763753091226345046315979581580902400000000\nFactorial of 38 = 523022617466601111760007224100074291200000000\nFactorial of 39 = 20397882081197443358640281739902897356800000000\nFactorial of 40 = 815915283247897734345611269596115894272000000000\nFactorial of 41 = 33452526613163807108170062053440751665152000000000\nFactorial of 42 = 1405006117752879898543142606244511569936384000000000\nFactorial of 43 = 60415263063373835637355132068513997507264512000000000\nFactorial of 44 = 2658271574788448768043625811014615890319638528000000000\nFactorial of 45 = 119622220865480194561963161495657715064383733760000000000\nFactorial of 46 = 5502622159812088949850305428800254892961651752960000000000\nFactorial of 47 = 258623241511168180642964355153611979969197632389120000000000\nFactorial of 48 = 12413915592536072670862289047373375038521486354677760000000000\nFactorial of 49 = 608281864034267560872252163321295376887552831379210240000000000\nFactorial of 50 = 30414093201713378043612608166064768844377641568960512000000000000\nFactorial of 51 = 1551118753287382280224243016469303211063259720016986112000000000000\nFactorial of 52 = 80658175170943878571660636856403766975289505440883277824000000000000\nFactorial of 53 = 4274883284060025564298013753389399649690343788366813724672000000000000\nFactorial of 54 = 230843697339241380472092742683027581083278564571807941132288000000000000\nFactorial of 55 = 12696403353658275925965100847566516959580321051449436762275840000000000000\nFactorial of 56 = 710998587804863451854045647463724949736497978881168458687447040000000000000\nFactorial of 57 = 40526919504877216755680601905432322134980384796226602145184481280000000000000\nFactorial of 58 = 2350561331282878571829474910515074683828862318181142924420699914240000000000000\nFactorial of 59 = 138683118545689835737939019720389406345902876772687432540821294940160000000000000\nFactorial of 60 = 8320987112741390144276341183223364380754172606361245952449277696409600000000000000\nFactorial of 61 = 507580213877224798800856812176625227226004528988036003099405939480985600000000000000\nFactorial of 62 = 31469973260387937525653122354950764088012280797258232192163168247821107200000000000000\nFactorial of 63 = 1982608315404440064116146708361898137544773690227268628106279599612729753600000000000000\nFactorial of 64 = 126886932185884164103433389335161480802865516174545192198801894375214704230400000000000000\nFactorial of 65 = 8247650592082470666723170306785496252186258551345437492922123134388955774976000000000000000\nFactorial of 66 = 544344939077443064003729240247842752644293064388798874532860126869671081148416000000000000000\nFactorial of 67 = 36471110918188685288249859096605464427167635314049524593701628500267962436943872000000000000000\nFactorial of 68 = 2480035542436830599600990418569171581047399201355367672371710738018221445712183296000000000000000\nFactorial of 69 = 171122452428141311372468338881272839092270544893520369393648040923257279754140647424000000000000000\nFactorial of 70 = 11978571669969891796072783721689098736458938142546425857555362864628009582789845319680000000000000000\nFactorial of 71 = 850478588567862317521167644239926010288584608120796235886430763388588680378079017697280000000000000000\nFactorial of 72 = 61234458376886086861524070385274672740778091784697328983823014963978384987221689274204160000000000000000\nFactorial of 73 = 4470115461512684340891257138125051110076800700282905015819080092370422104067183317016903680000000000000000\nFactorial of 74 = 330788544151938641225953028221253782145683251820934971170611926835411235700971565459250872320000000000000000\nFactorial of 75 = 24809140811395398091946477116594033660926243886570122837795894512655842677572867409443815424000000000000000000\nFactorial of 76 = 1885494701666050254987932260861146558230394535379329335672487982961844043495537923117729972224000000000000000000\nFactorial of 77 = 145183092028285869634070784086308284983740379224208358846781574688061991349156420080065207861248000000000000000000\nFactorial of 78 = 11324281178206297831457521158732046228731749579488251990048962825668835325234200766245086213177344000000000000000000\nFactorial of 79 = 894618213078297528685144171539831652069808216779571907213868063227837990693501860533361810841010176000000000000000000\nFactorial of 80 = 71569457046263802294811533723186532165584657342365752577109445058227039255480148842668944867280814080000000000000000000\nFactorial of 81 = 5797126020747367985879734231578109105412357244731625958745865049716390179693892056256184534249745940480000000000000000000\nFactorial of 82 = 475364333701284174842138206989404946643813294067993328617160934076743994734899148613007131808479167119360000000000000000000\nFactorial of 83 = 39455239697206586511897471180120610571436503407643446275224357528369751562996629334879591940103770870906880000000000000000000\nFactorial of 84 = 3314240134565353266999387579130131288000666286242049487118846032383059131291716864129885722968716753156177920000000000000000000\nFactorial of 85 = 281710411438055027694947944226061159480056634330574206405101912752560026159795933451040286452340924018275123200000000000000000000\nFactorial of 86 = 24227095383672732381765523203441259715284870552429381750838764496720162249742450276789464634901319465571660595200000000000000000000\nFactorial of 87 = 2107757298379527717213600518699389595229783738061356212322972511214654115727593174080683423236414793504734471782400000000000000000000\nFactorial of 88 = 185482642257398439114796845645546284380220968949399346684421580986889562184028199319100141244804501828416633516851200000000000000000000\nFactorial of 89 = 16507955160908461081216919262453619309839666236496541854913520707833171034378509739399912570787600662729080382999756800000000000000000000\nFactorial of 90 = 1485715964481761497309522733620825737885569961284688766942216863704985393094065876545992131370884059645617234469978112000000000000000000000\nFactorial of 91 = 135200152767840296255166568759495142147586866476906677791741734597153670771559994765685283954750449427751168336768008192000000000000000000000\nFactorial of 92 = 12438414054641307255475324325873553077577991715875414356840239582938137710983519518443046123837041347353107486982656753664000000000000000000000\nFactorial of 93 = 1156772507081641574759205162306240436214753229576413535186142281213246807121467315215203289516844845303838996289387078090752000000000000000000000\nFactorial of 94 = 108736615665674308027365285256786601004186803580182872307497374434045199869417927630229109214583415458560865651202385340530688000000000000000000000\nFactorial of 95 = 10329978488239059262599702099394727095397746340117372869212250571234293987594703124871765375385424468563282236864226607350415360000000000000000000000\nFactorial of 96 = 991677934870949689209571401541893801158183648651267795444376054838492222809091499987689476037000748982075094738965754305639874560000000000000000000000\nFactorial of 97 = 96192759682482119853328425949563698712343813919172976158104477319333745612481875498805879175589072651261284189679678167647067832320000000000000000000000\nFactorial of 98 = 9426890448883247745626185743057242473809693764078951663494238777294707070023223798882976159207729119823605850588608460429412647567360000000000000000000000\nFactorial of 99 = 933262154439441526816992388562667004907159682643816214685929638952175999932299156089414639761565182862536979208272237582511852109168640000000000000000000000\nFactorial of 100 = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000"
},
{
"code": null,
"e": 57658,
"s": 57646,
"text": "erichfrazer"
},
{
"code": null,
"e": 57671,
"s": 57658,
"text": "davidgatea21"
},
{
"code": null,
"e": 57683,
"s": 57671,
"text": "anikakapoor"
},
{
"code": null,
"e": 57692,
"s": 57683,
"text": "sweetyty"
},
{
"code": null,
"e": 57701,
"s": 57692,
"text": "rkbhola5"
},
{
"code": null,
"e": 57705,
"s": 57701,
"text": "C++"
},
{
"code": null,
"e": 57709,
"s": 57705,
"text": "CPP"
},
{
"code": null,
"e": 57807,
"s": 57709,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 57835,
"s": 57807,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 57855,
"s": 57835,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 57888,
"s": 57855,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 57912,
"s": 57888,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 57937,
"s": 57912,
"text": "std::string class in C++"
},
{
"code": null,
"e": 57990,
"s": 57937,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 58014,
"s": 57990,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 58050,
"s": 58014,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 58094,
"s": 58050,
"text": "Pair in C++ Standard Template Library (STL)"
}
] |
How to convert MySQL null to 0 using COALESCE() function?
|
You can use the COALESCE() function to convert MySQL null to 0
SELECT COALESCE(yourColumnName,0) AS anyAliasName FROM yourTableName;
Let us first create a table. The query to create a table is as follows
mysql> create table convertNullToZeroDemo
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> Name varchar(20),
-> Salary int
-> );
Query OK, 0 rows affected (1.28 sec)
Insert some records in the table using insert command.
The query is as follows
mysql> insert into convertNullToZeroDemo(Name,Salary) values('John',NULL);
Query OK, 1 row affected (0.20 sec)
mysql> insert into convertNullToZeroDemo(Name,Salary) values('Carol',5610);
Query OK, 1 row affected (0.10 sec)
mysql> insert into convertNullToZeroDemo(Name,Salary) values('Bob',NULL);
Query OK, 1 row affected (0.15 sec)
mysql> insert into convertNullToZeroDemo(Name,Salary) values('David',NULL);
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from convertNullToZeroDemo;
The following is the output
+----+-------+--------+
| Id | Name | Salary |
+----+-------+--------+
| 1 | John | NULL |
| 2 | Carol | 5610 |
| 3 | Bob | NULL |
| 4 | David | NULL |
+----+-------+--------+
4 rows in set (0.05 sec)
Here is the query to convert MySQL NULL to 0 using COALESCE() function
mysql> select coalesce(Salary,0) as `CONVERT_NULL _TO_0` from convertNullToZeroDemo;
The following is the output
+--------------------+
| CONVERT_NULL _TO_0 |
+--------------------+
| 0 |
| 5610 |
| 0 |
| 0 |
+--------------------+
4 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1125,
"s": 1062,
"text": "You can use the COALESCE() function to convert MySQL null to 0"
},
{
"code": null,
"e": 1195,
"s": 1125,
"text": "SELECT COALESCE(yourColumnName,0) AS anyAliasName FROM yourTableName;"
},
{
"code": null,
"e": 1266,
"s": 1195,
"text": "Let us first create a table. The query to create a table is as follows"
},
{
"code": null,
"e": 1453,
"s": 1266,
"text": "mysql> create table convertNullToZeroDemo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> Name varchar(20),\n -> Salary int\n -> );\nQuery OK, 0 rows affected (1.28 sec)"
},
{
"code": null,
"e": 1508,
"s": 1453,
"text": "Insert some records in the table using insert command."
},
{
"code": null,
"e": 1532,
"s": 1508,
"text": "The query is as follows"
},
{
"code": null,
"e": 1977,
"s": 1532,
"text": "mysql> insert into convertNullToZeroDemo(Name,Salary) values('John',NULL);\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into convertNullToZeroDemo(Name,Salary) values('Carol',5610);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into convertNullToZeroDemo(Name,Salary) values('Bob',NULL);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into convertNullToZeroDemo(Name,Salary) values('David',NULL);\nQuery OK, 1 row affected (0.12 sec)"
},
{
"code": null,
"e": 2036,
"s": 1977,
"text": "Display all records from the table using select statement."
},
{
"code": null,
"e": 2060,
"s": 2036,
"text": "The query is as follows"
},
{
"code": null,
"e": 2103,
"s": 2060,
"text": "mysql> select *from convertNullToZeroDemo;"
},
{
"code": null,
"e": 2131,
"s": 2103,
"text": "The following is the output"
},
{
"code": null,
"e": 2348,
"s": 2131,
"text": "+----+-------+--------+\n| Id | Name | Salary |\n+----+-------+--------+\n| 1 | John | NULL |\n| 2 | Carol | 5610 |\n| 3 | Bob | NULL |\n| 4 | David | NULL |\n+----+-------+--------+\n4 rows in set (0.05 sec)"
},
{
"code": null,
"e": 2419,
"s": 2348,
"text": "Here is the query to convert MySQL NULL to 0 using COALESCE() function"
},
{
"code": null,
"e": 2504,
"s": 2419,
"text": "mysql> select coalesce(Salary,0) as `CONVERT_NULL _TO_0` from convertNullToZeroDemo;"
},
{
"code": null,
"e": 2532,
"s": 2504,
"text": "The following is the output"
},
{
"code": null,
"e": 2741,
"s": 2532,
"text": "+--------------------+\n| CONVERT_NULL _TO_0 |\n+--------------------+\n| 0 |\n| 5610 |\n| 0 |\n| 0 |\n+--------------------+\n4 rows in set (0.00 sec)"
}
] |
How to check if Pandas column has value from list of string? - GeeksforGeeks
|
28 Nov, 2021
In this article, we are going to see how to check if the pandas column has a value from a list of strings in Python.
List of strings means a list contains strings as elements, we will check if the pandas dataframe has values from a list of strings and display them when they are present. We will get the dataframe columns where the strings in the list contain.
Python3
#import pandasimport pandas # create dataframedata = pandas.DataFrame({'name': ['sireesha', 'priyank', 'ojaswi', 'gnanesh'], 'subjects': ['java', 'networks', 'c', 'c#']}) # displaydata
Output:
In this scenario, the isin() function check the pandas column containing the string present in the list and return the column values when present, otherwise it will not select the dataframe columns.
Syntax: dataframe[dataframe[βcolumn_nameβ].isin(list_of_strings)]
where
dataframe is the input dataframe
list_of_strings is the list that contains strings
column_name is the column to check the list of strings present in that column
Example: Python program to check if pandas column has a value from a list of strings
Python3
#import pandasimport pandas # create dataframedata = pandas.DataFrame({'name': ['sireesha', 'priyank', 'ojaswi', 'gnanesh'], 'subjects': ['java', 'networks', 'c', 'c#']}) # consider a listlist1 = ['sireesha', 'priyank'] # check the pandas name column# contain the given list if stringsprint(data[data['name'].isin(list1)]) # consider a listlist2 = ['java', 'c'] # check the pandas subjects column# contain the given list if stringsprint(data[data['subjects'].isin(list2)])
Output:
Here NumPy also uses isin() operator to check if pandas column has a value from a list of strings.
Syntax: dataframe[~numpy.isin(dataframe[βcolumnβ], list_of_value)]
Example:
Python3
# import pandasimport pandas # import numpyimport numpy # create dataframedata = pandas.DataFrame({'name': ['sireesha', 'priyank', 'ojaswi', 'gnanesh'], 'subjects': ['java', 'networks', 'c', 'c#']}) # consider a listlist1 = ['sireesha', 'priyank'] # check the pandas name column# contain the given list if stringsprint(data[data['name'].isin(list1)]) # consider a listlist2 = ['java', 'c'] # check the pandas subjects column# contain the given list if stringsdata[~numpy.isin(data['subjects'], list1)]
Output:
pandas-dataframe-program
Picked
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
|
[
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 24329,
"s": 24212,
"text": "In this article, we are going to see how to check if the pandas column has a value from a list of strings in Python."
},
{
"code": null,
"e": 24573,
"s": 24329,
"text": "List of strings means a list contains strings as elements, we will check if the pandas dataframe has values from a list of strings and display them when they are present. We will get the dataframe columns where the strings in the list contain."
},
{
"code": null,
"e": 24581,
"s": 24573,
"text": "Python3"
},
{
"code": "#import pandasimport pandas # create dataframedata = pandas.DataFrame({'name': ['sireesha', 'priyank', 'ojaswi', 'gnanesh'], 'subjects': ['java', 'networks', 'c', 'c#']}) # displaydata",
"e": 24864,
"s": 24581,
"text": null
},
{
"code": null,
"e": 24872,
"s": 24864,
"text": "Output:"
},
{
"code": null,
"e": 25071,
"s": 24872,
"text": "In this scenario, the isin() function check the pandas column containing the string present in the list and return the column values when present, otherwise it will not select the dataframe columns."
},
{
"code": null,
"e": 25137,
"s": 25071,
"text": "Syntax: dataframe[dataframe[βcolumn_nameβ].isin(list_of_strings)]"
},
{
"code": null,
"e": 25143,
"s": 25137,
"text": "where"
},
{
"code": null,
"e": 25176,
"s": 25143,
"text": "dataframe is the input dataframe"
},
{
"code": null,
"e": 25226,
"s": 25176,
"text": "list_of_strings is the list that contains strings"
},
{
"code": null,
"e": 25304,
"s": 25226,
"text": "column_name is the column to check the list of strings present in that column"
},
{
"code": null,
"e": 25390,
"s": 25304,
"text": "Example: Python program to check if pandas column has a value from a list of strings"
},
{
"code": null,
"e": 25398,
"s": 25390,
"text": "Python3"
},
{
"code": "#import pandasimport pandas # create dataframedata = pandas.DataFrame({'name': ['sireesha', 'priyank', 'ojaswi', 'gnanesh'], 'subjects': ['java', 'networks', 'c', 'c#']}) # consider a listlist1 = ['sireesha', 'priyank'] # check the pandas name column# contain the given list if stringsprint(data[data['name'].isin(list1)]) # consider a listlist2 = ['java', 'c'] # check the pandas subjects column# contain the given list if stringsprint(data[data['subjects'].isin(list2)])",
"e": 25970,
"s": 25398,
"text": null
},
{
"code": null,
"e": 25978,
"s": 25970,
"text": "Output:"
},
{
"code": null,
"e": 26077,
"s": 25978,
"text": "Here NumPy also uses isin() operator to check if pandas column has a value from a list of strings."
},
{
"code": null,
"e": 26144,
"s": 26077,
"text": "Syntax: dataframe[~numpy.isin(dataframe[βcolumnβ], list_of_value)]"
},
{
"code": null,
"e": 26153,
"s": 26144,
"text": "Example:"
},
{
"code": null,
"e": 26161,
"s": 26153,
"text": "Python3"
},
{
"code": "# import pandasimport pandas # import numpyimport numpy # create dataframedata = pandas.DataFrame({'name': ['sireesha', 'priyank', 'ojaswi', 'gnanesh'], 'subjects': ['java', 'networks', 'c', 'c#']}) # consider a listlist1 = ['sireesha', 'priyank'] # check the pandas name column# contain the given list if stringsprint(data[data['name'].isin(list1)]) # consider a listlist2 = ['java', 'c'] # check the pandas subjects column# contain the given list if stringsdata[~numpy.isin(data['subjects'], list1)]",
"e": 26765,
"s": 26161,
"text": null
},
{
"code": null,
"e": 26773,
"s": 26765,
"text": "Output:"
},
{
"code": null,
"e": 26798,
"s": 26773,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 26805,
"s": 26798,
"text": "Picked"
},
{
"code": null,
"e": 26829,
"s": 26805,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 26843,
"s": 26829,
"text": "Python-pandas"
},
{
"code": null,
"e": 26850,
"s": 26843,
"text": "Python"
},
{
"code": null,
"e": 26948,
"s": 26850,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26957,
"s": 26948,
"text": "Comments"
},
{
"code": null,
"e": 26970,
"s": 26957,
"text": "Old Comments"
},
{
"code": null,
"e": 27002,
"s": 26970,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27058,
"s": 27002,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27079,
"s": 27058,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 27118,
"s": 27079,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27160,
"s": 27118,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27187,
"s": 27160,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27218,
"s": 27187,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27260,
"s": 27218,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27296,
"s": 27260,
"text": "Python | Pandas dataframe.groupby()"
}
] |
How to Scrape Dynamic Web pages with Selenium and Beautiful Soup | by Alan Jones | Towards Data Science
|
Beautiful Soup is an excellent library for scraping data from the web but it doesnβt deal with dynamically created content. Thatβs not in any way a criticism β Beautiful Soup does precisely the job it is supposed to do and that does not include rendering the webpage as a browser would.
In order to get that dynamic content the web page must be interpreted by a browser so the Javascript that creates the dynamic content can do its work. But how do we get at the HTML code that is rendered by the browser? One answer is by using a headless browser and the Selenium Python library. And that is what Iβm going to demonstrate here.
We are going to use a very simple HTML file that contains some dynamically rendered text. Here it is:
<html><head> <title>Dynamic web page</title></head><body> <div id="text">Placeholder text</div> <script> document.getElementById("text").innerHTML="This is the text we want" </script></body></html>
All we have here is a HTML file with a single <div> in the body that contains some text (βPlaceholder textβ) but when the page is loaded that text is replaced with the text generated by the Javascript further down. The script locates the <div> by its id, βtextβ and then sets the internal text to : βThis is the text we wantβ.
So, if we view the page in a web browser we see the text that is dynamically generated by the Javascript.
Letβs see what happens when we run this by Beautiful Soup and try and scrape the text from the <div>.
from bs4 import BeautifulSoupimport ossoup_file=open(os.getcwd() +"\\test.html")soup = BeautifulSoup(soup_file)print(soup.title.get_text())print(soup.find(id=βtextβ).get_text())
The code above imports BeautifulSoup and the os library, opens the file test.html from the local directory and creates a BS object which is stored in the variable soup.
Then we have two print statements. The first gets the text from the title in the BS object and prints that. The second does a similar thing but finds the tag with the id βtextβ and gets the text from that.
And the nnn
Dynamic web pagePlaceholder text
Oh dear β not what we want. BeautifulSoup is correctly parsing the code but finding the default text in the <div> rather than the text that was rendered in the browser. If we had been looking at a table of say stock market prices that were filled from data in a database, we would likely see only null values in the table, not the dynamically loaded prices.
What we need is the HTML to be run in a browser in order to see the correct values and then be able to capture those values programmatically.
The way to do this is with a headless browser. A headless browser is essentially a browser with no user interface. It does not render its output to a screen but rather to a text object.
Most, if not all, modern browsers will run in headless mode but they need a driver in order to communicate the results back to the user. Also, in order to use the results in a Python program, we need a library that will talk to the driver.
The Python library is Selenium and the driver that it communicates with is known as a webdriver. In the example below, I will use Chrome as the headless browser and so I need the Chrome web driver which you can download from chromedriver.chromium.org/downloads. If you use a different browser just search for βwebdriver Edgeβ, βwebdriver Firefoxβ, etc to find the appropriate download. Then download the webdriver and place it in your working directory. You will also need to conda/pip install Selenium.
The first thing to do is import the necessary parts of Selenium and then set the appropriate options. In the code below, the --headless argument will tell the browser that it should run in headless mode (obviously), then Iβve specified the location of the Chrome binary. As you can see Iβm using a portable version of Chrome and it is located in a folder in my working directory β I like to keep things self-contained. You may not need to specify where the binary is if you have a standard installation.
The webdriver is in the local directory and I set a variable to its path.
Next I instantiate a driver object using the previously set options and the location of the Chrome webdriver. With this driver I can load a web page which will be interpreted by the Chrome browser. The result will be loaded into the driver object where we can access the text of the page in the page_source attribute.
from selenium import webdriverfrom selenium.webdriver.chrome.options import Options# Instantiate an Options object# and add the "--headless" argumentopts = Options()opts.add_argument(" --headless")# If necessary set the path to you browserβs locationopts.binary_location= os.getcwd() +'\\GoogleChromePortable\GoogleChromePortable.exe'# Set the location of the webdriverchrome_driver = os.getcwd() +"\\chromedriver.exe"# Instantiate a webdriverdriver = webdriver.Chrome(options=opts, executable_path=chrome_driver)# Load the HTML pagedriver.get(os.getcwd() +"\\test.html")# To scrape a url rather than a local file # just do something like this# driver.get("https://your.url")
The next step is to create a Beautiful Soup object and load the page source into it. We can then scrape data from this source. In the code below you can see that we do much the same as in the previous exercise. But this time the result will be different. Hereβs the code:
# Put the page source into a variable and create a BS object from itsoup_file=driver.page_sourcesoup = BeautifulSoup(soup_file)# Load and print the title and the text of the <div>print(soup.title.get_text())print(soup.find(id='text').get_text())
And this is the result:
Dynamic web pageThis is the text we want
As you can see, now we are using the code that has been processed by the headless web browser, the result is what would be rendered in a browser window, not the original source as in our first attempt.
Finally, we need to close the browser:
# Close the browserdriver.quit()
And that is all there is to it. With the code above and your own Beautiful Soup code, you are now equipped to start scraping data from dynamic web pages.
Thanks for reading and if you would like to keep up to date with the articles that I publish please consider subscribing to my free newsletter here. You can catch up with older ones from the same link.
|
[
{
"code": null,
"e": 459,
"s": 172,
"text": "Beautiful Soup is an excellent library for scraping data from the web but it doesnβt deal with dynamically created content. Thatβs not in any way a criticism β Beautiful Soup does precisely the job it is supposed to do and that does not include rendering the webpage as a browser would."
},
{
"code": null,
"e": 801,
"s": 459,
"text": "In order to get that dynamic content the web page must be interpreted by a browser so the Javascript that creates the dynamic content can do its work. But how do we get at the HTML code that is rendered by the browser? One answer is by using a headless browser and the Selenium Python library. And that is what Iβm going to demonstrate here."
},
{
"code": null,
"e": 903,
"s": 801,
"text": "We are going to use a very simple HTML file that contains some dynamically rendered text. Here it is:"
},
{
"code": null,
"e": 1114,
"s": 903,
"text": "<html><head> <title>Dynamic web page</title></head><body> <div id=\"text\">Placeholder text</div> <script> document.getElementById(\"text\").innerHTML=\"This is the text we want\" </script></body></html>"
},
{
"code": null,
"e": 1441,
"s": 1114,
"text": "All we have here is a HTML file with a single <div> in the body that contains some text (βPlaceholder textβ) but when the page is loaded that text is replaced with the text generated by the Javascript further down. The script locates the <div> by its id, βtextβ and then sets the internal text to : βThis is the text we wantβ."
},
{
"code": null,
"e": 1547,
"s": 1441,
"text": "So, if we view the page in a web browser we see the text that is dynamically generated by the Javascript."
},
{
"code": null,
"e": 1649,
"s": 1547,
"text": "Letβs see what happens when we run this by Beautiful Soup and try and scrape the text from the <div>."
},
{
"code": null,
"e": 1827,
"s": 1649,
"text": "from bs4 import BeautifulSoupimport ossoup_file=open(os.getcwd() +\"\\\\test.html\")soup = BeautifulSoup(soup_file)print(soup.title.get_text())print(soup.find(id=βtextβ).get_text())"
},
{
"code": null,
"e": 1996,
"s": 1827,
"text": "The code above imports BeautifulSoup and the os library, opens the file test.html from the local directory and creates a BS object which is stored in the variable soup."
},
{
"code": null,
"e": 2202,
"s": 1996,
"text": "Then we have two print statements. The first gets the text from the title in the BS object and prints that. The second does a similar thing but finds the tag with the id βtextβ and gets the text from that."
},
{
"code": null,
"e": 2214,
"s": 2202,
"text": "And the nnn"
},
{
"code": null,
"e": 2247,
"s": 2214,
"text": "Dynamic web pagePlaceholder text"
},
{
"code": null,
"e": 2605,
"s": 2247,
"text": "Oh dear β not what we want. BeautifulSoup is correctly parsing the code but finding the default text in the <div> rather than the text that was rendered in the browser. If we had been looking at a table of say stock market prices that were filled from data in a database, we would likely see only null values in the table, not the dynamically loaded prices."
},
{
"code": null,
"e": 2747,
"s": 2605,
"text": "What we need is the HTML to be run in a browser in order to see the correct values and then be able to capture those values programmatically."
},
{
"code": null,
"e": 2933,
"s": 2747,
"text": "The way to do this is with a headless browser. A headless browser is essentially a browser with no user interface. It does not render its output to a screen but rather to a text object."
},
{
"code": null,
"e": 3173,
"s": 2933,
"text": "Most, if not all, modern browsers will run in headless mode but they need a driver in order to communicate the results back to the user. Also, in order to use the results in a Python program, we need a library that will talk to the driver."
},
{
"code": null,
"e": 3677,
"s": 3173,
"text": "The Python library is Selenium and the driver that it communicates with is known as a webdriver. In the example below, I will use Chrome as the headless browser and so I need the Chrome web driver which you can download from chromedriver.chromium.org/downloads. If you use a different browser just search for βwebdriver Edgeβ, βwebdriver Firefoxβ, etc to find the appropriate download. Then download the webdriver and place it in your working directory. You will also need to conda/pip install Selenium."
},
{
"code": null,
"e": 4181,
"s": 3677,
"text": "The first thing to do is import the necessary parts of Selenium and then set the appropriate options. In the code below, the --headless argument will tell the browser that it should run in headless mode (obviously), then Iβve specified the location of the Chrome binary. As you can see Iβm using a portable version of Chrome and it is located in a folder in my working directory β I like to keep things self-contained. You may not need to specify where the binary is if you have a standard installation."
},
{
"code": null,
"e": 4255,
"s": 4181,
"text": "The webdriver is in the local directory and I set a variable to its path."
},
{
"code": null,
"e": 4573,
"s": 4255,
"text": "Next I instantiate a driver object using the previously set options and the location of the Chrome webdriver. With this driver I can load a web page which will be interpreted by the Chrome browser. The result will be loaded into the driver object where we can access the text of the page in the page_source attribute."
},
{
"code": null,
"e": 5249,
"s": 4573,
"text": "from selenium import webdriverfrom selenium.webdriver.chrome.options import Options# Instantiate an Options object# and add the \"--headless\" argumentopts = Options()opts.add_argument(\" --headless\")# If necessary set the path to you browserβs locationopts.binary_location= os.getcwd() +'\\\\GoogleChromePortable\\GoogleChromePortable.exe'# Set the location of the webdriverchrome_driver = os.getcwd() +\"\\\\chromedriver.exe\"# Instantiate a webdriverdriver = webdriver.Chrome(options=opts, executable_path=chrome_driver)# Load the HTML pagedriver.get(os.getcwd() +\"\\\\test.html\")# To scrape a url rather than a local file # just do something like this# driver.get(\"https://your.url\")"
},
{
"code": null,
"e": 5521,
"s": 5249,
"text": "The next step is to create a Beautiful Soup object and load the page source into it. We can then scrape data from this source. In the code below you can see that we do much the same as in the previous exercise. But this time the result will be different. Hereβs the code:"
},
{
"code": null,
"e": 5767,
"s": 5521,
"text": "# Put the page source into a variable and create a BS object from itsoup_file=driver.page_sourcesoup = BeautifulSoup(soup_file)# Load and print the title and the text of the <div>print(soup.title.get_text())print(soup.find(id='text').get_text())"
},
{
"code": null,
"e": 5791,
"s": 5767,
"text": "And this is the result:"
},
{
"code": null,
"e": 5832,
"s": 5791,
"text": "Dynamic web pageThis is the text we want"
},
{
"code": null,
"e": 6034,
"s": 5832,
"text": "As you can see, now we are using the code that has been processed by the headless web browser, the result is what would be rendered in a browser window, not the original source as in our first attempt."
},
{
"code": null,
"e": 6073,
"s": 6034,
"text": "Finally, we need to close the browser:"
},
{
"code": null,
"e": 6106,
"s": 6073,
"text": "# Close the browserdriver.quit()"
},
{
"code": null,
"e": 6260,
"s": 6106,
"text": "And that is all there is to it. With the code above and your own Beautiful Soup code, you are now equipped to start scraping data from dynamic web pages."
}
] |
Minimum steps for increasing and decreasing Array to reach either 0 or N - GeeksforGeeks
|
28 Feb, 2022
Given an integer N and two arrays increasing[] and decreasing[], such that they have elements from 1 to N only. The task is to find the minimum number of steps for each element of the two arrays to reach either 0 or N. A step is defined as follows:
In one step, all the elements of the increasing[] array increases by 1, and all the elements of the decreasing[] array decreases by 1.
When an element becomes either 0 or N, no more increase or decrease operation is performed on it.
Examples:
Input: N = 5, increasing[] = {1, 2}, decreasing[] = {3, 4} Output: 4Explanation: Step 1: increasing[] array becomes {2, 3}, decreasing[] = {2, 3} Step 2: increasing[] array becomes {3, 4}, decreasing[] = {1, 2} Step 3: increasing[] array becomes {4, 5}, decreasing[] = {0, 1} Step 4: increasing[] array becomes {5, 5}, decreasing[] = {0, 0} 4 Steps are required for all elements to become either 0 or N. Hence, the output is 4.
Input: N = 7, increasing[] = {3, 5}, decreasing[] = {6} Output: 6
Approach: The idea is to find the maximum between the steps required by all the elements of the increasing[] array and the decreasing[] array to reach N and 0 respectively. Below are the steps:
Find the minimum element of the array increasing[].The maximum steps taken by all the elements of the increasing[] array to reach N is given by N β min(increasing[]).Find the maximum element of the array decreasing[].The maximum steps taken by all the elements of the decreasing[] array to reach 0 is given by max(decreasing[]).Therefore, the minimum number of steps when all the elements become either 0 or N is given by max(N β min(increasing[]), max(decreasing[])).
Find the minimum element of the array increasing[].
The maximum steps taken by all the elements of the increasing[] array to reach N is given by N β min(increasing[]).
Find the maximum element of the array decreasing[].
The maximum steps taken by all the elements of the decreasing[] array to reach 0 is given by max(decreasing[]).
Therefore, the minimum number of steps when all the elements become either 0 or N is given by max(N β min(increasing[]), max(decreasing[])).
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 finds the minimum// steps to reach either 0 or N for// given increasing and decreasing// arraysvoid minSteps(int N, int increasing[], int decreasing[], int m1, int m2){ // Initialize variable to // find the minimum element int mini = INT_MAX; // Find minimum element in // increasing[] array for(int i = 0; i < m1; i++) { if (mini > increasing[i]) mini = increasing[i]; } // Initialize variable to // find the maximum element int maxi = INT_MIN; // Find maximum element in // decreasing[] array for(int i = 0; i < m2; i++) { if (maxi < decreasing[i]) maxi = decreasing[i]; } // Find the minimum steps int minSteps = max(maxi, N - mini); // Print the minimum steps cout << minSteps << endl;} // Driver codeint main(){ // Given N int N = 7; // Given increasing // and decreasing array int increasing[] = { 3, 5 }; int decreasing[] = { 6 }; // Find length of arrays // increasing and decreasing int m1 = sizeof(increasing) /sizeof(increasing[0]); int m2 = sizeof(decreasing) / sizeof(decreasing[0]); // Function call minSteps(N, increasing, decreasing, m1, m2);} // This code is contributed by Manne Sree Charan
// Java program for the above approachimport java.util.*; public class GFG { // Function that finds the minimum // steps to reach either 0 or N for // given increasing and decreasing // arrays public static void minSteps(int N, int[] increasing, int[] decreasing) { // Initialize variable to // find the minimum element int min = Integer.MAX_VALUE; // Find minimum element in // increasing[] array for (int i : increasing) { if (min > i) min = i; } // Initialize variable to // find the maximum element int max = Integer.MIN_VALUE; // Find maximum element in // decreasing[] array for (int i : decreasing) { if (max < i) max = i; } // Find the minimum steps int minSteps = Math.max(max, N - min); // Print the minimum steps System.out.println(minSteps); } // Driver Code public static void main(String[] args) { // Given N int N = 7; // Given increasing // and decreasing array int increasing[] = { 3, 5 }; int decreasing[] = { 6 }; // Function call minSteps(N, increasing, decreasing); }}
# Python3 program for# the above approachimport sys # Function that finds the minimum# steps to reach either 0 or N for# given increasing and decreasing# arraysdef minSteps(N, increasing, decreasing): # Initialize variable to # find the minimum element Min = sys.maxsize; # Find minimum element in # increasing array for i in increasing: if (Min > i): Min = i; # Initialize variable to # find the maximum element Max = -sys.maxsize; # Find maximum element in # decreasing array for i in decreasing: if (Max < i): Max = i; # Find the minimum steps minSteps = max(Max, N - Min); # Print the minimum steps print(minSteps); # Driver Codeif __name__ == '__main__': # Given N N = 7; # Given increasing # and decreasing array increasing = [3, 5]; decreasing = [6]; # Function call minSteps(N, increasing, decreasing); # This code contributed by Rajput-Ji
// C# program for the above approachusing System; class GFG{ // Function that finds the minimum// steps to reach either 0 or N for// given increasing and decreasing// arrayspublic static void minSteps(int N, int[] increasing, int[] decreasing){ // Initialize variable to // find the minimum element int min = int.MaxValue; // Find minimum element in // increasing[] array foreach(int i in increasing) { if (min > i) min = i; } // Initialize variable to // find the maximum element int max = int.MinValue; // Find maximum element in // decreasing[] array foreach(int i in decreasing) { if (max < i) max = i; } // Find the minimum steps int minSteps = Math.Max(max, N - min); // Print the minimum steps Console.WriteLine(minSteps);} // Driver Codepublic static void Main(String[] args){ // Given N int N = 7; // Given increasing // and decreasing array int []increasing = { 3, 5 }; int []decreasing = { 6 }; // Function call minSteps(N, increasing, decreasing);}} // This code is contributed by Amit Katiyar
<script> // Javascript program for the above approach // Function that finds the minimum// steps to reach either 0 or N for// given increasing and decreasing// arraysfunction minSteps(N, increasing, decreasing, m1, m2){ // Initialize variable to // find the minimum element var mini = 2147483647; var i; // Find minimum element in // increasing[] array for(i = 0; i < m1; i++) { if (mini > increasing[i]) mini = increasing[i]; } // Initialize variable to // find the maximum element var maxi = -2147483648; // Find maximum element in // decreasing[] array for(i = 0; i < m2; i++) { if (maxi < decreasing[i]) maxi = decreasing[i]; } // Find the minimum steps var minSteps = Math.max(maxi,N - mini); // Print the minimum steps document.write(minSteps);} // Driver code // Given N var N = 7; // Given increasing // and decreasing array var increasing = [3, 5]; var decreasing = [6]; // Find length of arrays // increasing and decreasing var m1 = increasing.length; var m2 = decreasing.length; // Function call minSteps(N, increasing, decreasing, m1, m2); // This code is contributed by bgangwar59.</script>
6
Time Complexity: O(N)Auxiliary Space: O(1)
hunter2000
amit143katiyar
Rajput-Ji
bgangwar59
simranarora5sos
Arrays
Greedy
Mathematical
Arrays
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
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
Write a program to print all permutations of a given string
Huffman Coding | Greedy Algo-3
|
[
{
"code": null,
"e": 26067,
"s": 26039,
"text": "\n28 Feb, 2022"
},
{
"code": null,
"e": 26316,
"s": 26067,
"text": "Given an integer N and two arrays increasing[] and decreasing[], such that they have elements from 1 to N only. The task is to find the minimum number of steps for each element of the two arrays to reach either 0 or N. A step is defined as follows:"
},
{
"code": null,
"e": 26451,
"s": 26316,
"text": "In one step, all the elements of the increasing[] array increases by 1, and all the elements of the decreasing[] array decreases by 1."
},
{
"code": null,
"e": 26549,
"s": 26451,
"text": "When an element becomes either 0 or N, no more increase or decrease operation is performed on it."
},
{
"code": null,
"e": 26559,
"s": 26549,
"text": "Examples:"
},
{
"code": null,
"e": 26987,
"s": 26559,
"text": "Input: N = 5, increasing[] = {1, 2}, decreasing[] = {3, 4} Output: 4Explanation: Step 1: increasing[] array becomes {2, 3}, decreasing[] = {2, 3} Step 2: increasing[] array becomes {3, 4}, decreasing[] = {1, 2} Step 3: increasing[] array becomes {4, 5}, decreasing[] = {0, 1} Step 4: increasing[] array becomes {5, 5}, decreasing[] = {0, 0} 4 Steps are required for all elements to become either 0 or N. Hence, the output is 4."
},
{
"code": null,
"e": 27053,
"s": 26987,
"text": "Input: N = 7, increasing[] = {3, 5}, decreasing[] = {6} Output: 6"
},
{
"code": null,
"e": 27247,
"s": 27053,
"text": "Approach: The idea is to find the maximum between the steps required by all the elements of the increasing[] array and the decreasing[] array to reach N and 0 respectively. Below are the steps:"
},
{
"code": null,
"e": 27716,
"s": 27247,
"text": "Find the minimum element of the array increasing[].The maximum steps taken by all the elements of the increasing[] array to reach N is given by N β min(increasing[]).Find the maximum element of the array decreasing[].The maximum steps taken by all the elements of the decreasing[] array to reach 0 is given by max(decreasing[]).Therefore, the minimum number of steps when all the elements become either 0 or N is given by max(N β min(increasing[]), max(decreasing[]))."
},
{
"code": null,
"e": 27768,
"s": 27716,
"text": "Find the minimum element of the array increasing[]."
},
{
"code": null,
"e": 27884,
"s": 27768,
"text": "The maximum steps taken by all the elements of the increasing[] array to reach N is given by N β min(increasing[])."
},
{
"code": null,
"e": 27936,
"s": 27884,
"text": "Find the maximum element of the array decreasing[]."
},
{
"code": null,
"e": 28048,
"s": 27936,
"text": "The maximum steps taken by all the elements of the decreasing[] array to reach 0 is given by max(decreasing[])."
},
{
"code": null,
"e": 28189,
"s": 28048,
"text": "Therefore, the minimum number of steps when all the elements become either 0 or N is given by max(N β min(increasing[]), max(decreasing[]))."
},
{
"code": null,
"e": 28240,
"s": 28189,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28244,
"s": 28240,
"text": "C++"
},
{
"code": null,
"e": 28249,
"s": 28244,
"text": "Java"
},
{
"code": null,
"e": 28257,
"s": 28249,
"text": "Python3"
},
{
"code": null,
"e": 28260,
"s": 28257,
"text": "C#"
},
{
"code": null,
"e": 28271,
"s": 28260,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function that finds the minimum// steps to reach either 0 or N for// given increasing and decreasing// arraysvoid minSteps(int N, int increasing[], int decreasing[], int m1, int m2){ // Initialize variable to // find the minimum element int mini = INT_MAX; // Find minimum element in // increasing[] array for(int i = 0; i < m1; i++) { if (mini > increasing[i]) mini = increasing[i]; } // Initialize variable to // find the maximum element int maxi = INT_MIN; // Find maximum element in // decreasing[] array for(int i = 0; i < m2; i++) { if (maxi < decreasing[i]) maxi = decreasing[i]; } // Find the minimum steps int minSteps = max(maxi, N - mini); // Print the minimum steps cout << minSteps << endl;} // Driver codeint main(){ // Given N int N = 7; // Given increasing // and decreasing array int increasing[] = { 3, 5 }; int decreasing[] = { 6 }; // Find length of arrays // increasing and decreasing int m1 = sizeof(increasing) /sizeof(increasing[0]); int m2 = sizeof(decreasing) / sizeof(decreasing[0]); // Function call minSteps(N, increasing, decreasing, m1, m2);} // This code is contributed by Manne Sree Charan",
"e": 29668,
"s": 28271,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; public class GFG { // Function that finds the minimum // steps to reach either 0 or N for // given increasing and decreasing // arrays public static void minSteps(int N, int[] increasing, int[] decreasing) { // Initialize variable to // find the minimum element int min = Integer.MAX_VALUE; // Find minimum element in // increasing[] array for (int i : increasing) { if (min > i) min = i; } // Initialize variable to // find the maximum element int max = Integer.MIN_VALUE; // Find maximum element in // decreasing[] array for (int i : decreasing) { if (max < i) max = i; } // Find the minimum steps int minSteps = Math.max(max, N - min); // Print the minimum steps System.out.println(minSteps); } // Driver Code public static void main(String[] args) { // Given N int N = 7; // Given increasing // and decreasing array int increasing[] = { 3, 5 }; int decreasing[] = { 6 }; // Function call minSteps(N, increasing, decreasing); }}",
"e": 30980,
"s": 29668,
"text": null
},
{
"code": "# Python3 program for# the above approachimport sys # Function that finds the minimum# steps to reach either 0 or N for# given increasing and decreasing# arraysdef minSteps(N, increasing, decreasing): # Initialize variable to # find the minimum element Min = sys.maxsize; # Find minimum element in # increasing array for i in increasing: if (Min > i): Min = i; # Initialize variable to # find the maximum element Max = -sys.maxsize; # Find maximum element in # decreasing array for i in decreasing: if (Max < i): Max = i; # Find the minimum steps minSteps = max(Max, N - Min); # Print the minimum steps print(minSteps); # Driver Codeif __name__ == '__main__': # Given N N = 7; # Given increasing # and decreasing array increasing = [3, 5]; decreasing = [6]; # Function call minSteps(N, increasing, decreasing); # This code contributed by Rajput-Ji",
"e": 31946,
"s": 30980,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function that finds the minimum// steps to reach either 0 or N for// given increasing and decreasing// arrayspublic static void minSteps(int N, int[] increasing, int[] decreasing){ // Initialize variable to // find the minimum element int min = int.MaxValue; // Find minimum element in // increasing[] array foreach(int i in increasing) { if (min > i) min = i; } // Initialize variable to // find the maximum element int max = int.MinValue; // Find maximum element in // decreasing[] array foreach(int i in decreasing) { if (max < i) max = i; } // Find the minimum steps int minSteps = Math.Max(max, N - min); // Print the minimum steps Console.WriteLine(minSteps);} // Driver Codepublic static void Main(String[] args){ // Given N int N = 7; // Given increasing // and decreasing array int []increasing = { 3, 5 }; int []decreasing = { 6 }; // Function call minSteps(N, increasing, decreasing);}} // This code is contributed by Amit Katiyar",
"e": 33146,
"s": 31946,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function that finds the minimum// steps to reach either 0 or N for// given increasing and decreasing// arraysfunction minSteps(N, increasing, decreasing, m1, m2){ // Initialize variable to // find the minimum element var mini = 2147483647; var i; // Find minimum element in // increasing[] array for(i = 0; i < m1; i++) { if (mini > increasing[i]) mini = increasing[i]; } // Initialize variable to // find the maximum element var maxi = -2147483648; // Find maximum element in // decreasing[] array for(i = 0; i < m2; i++) { if (maxi < decreasing[i]) maxi = decreasing[i]; } // Find the minimum steps var minSteps = Math.max(maxi,N - mini); // Print the minimum steps document.write(minSteps);} // Driver code // Given N var N = 7; // Given increasing // and decreasing array var increasing = [3, 5]; var decreasing = [6]; // Find length of arrays // increasing and decreasing var m1 = increasing.length; var m2 = decreasing.length; // Function call minSteps(N, increasing, decreasing, m1, m2); // This code is contributed by bgangwar59.</script>",
"e": 34408,
"s": 33146,
"text": null
},
{
"code": null,
"e": 34410,
"s": 34408,
"text": "6"
},
{
"code": null,
"e": 34453,
"s": 34410,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 34464,
"s": 34453,
"text": "hunter2000"
},
{
"code": null,
"e": 34479,
"s": 34464,
"text": "amit143katiyar"
},
{
"code": null,
"e": 34489,
"s": 34479,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 34500,
"s": 34489,
"text": "bgangwar59"
},
{
"code": null,
"e": 34516,
"s": 34500,
"text": "simranarora5sos"
},
{
"code": null,
"e": 34523,
"s": 34516,
"text": "Arrays"
},
{
"code": null,
"e": 34530,
"s": 34523,
"text": "Greedy"
},
{
"code": null,
"e": 34543,
"s": 34530,
"text": "Mathematical"
},
{
"code": null,
"e": 34550,
"s": 34543,
"text": "Arrays"
},
{
"code": null,
"e": 34557,
"s": 34550,
"text": "Greedy"
},
{
"code": null,
"e": 34570,
"s": 34557,
"text": "Mathematical"
},
{
"code": null,
"e": 34668,
"s": 34570,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34695,
"s": 34668,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 34726,
"s": 34695,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 34751,
"s": 34726,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 34789,
"s": 34751,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 34810,
"s": 34789,
"text": "Next Greater Element"
},
{
"code": null,
"e": 34861,
"s": 34810,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 34912,
"s": 34861,
"text": "Primβs Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 34970,
"s": 34912,
"text": "Kruskalβs Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 35030,
"s": 34970,
"text": "Write a program to print all permutations of a given string"
}
] |
Split the given string into Primes : Digit DP - GeeksforGeeks
|
02 Jun, 2021
Given a string str that represents a large number, the task is to find the minimum number of segments the given string can be divided such that each segment is a prime number in the range of 1 to 106.
Examples:
Input: str = β13499315β Output: 3 Explanation: The number can be segmented as [13499, 31, 5]
Input: str = β43β Output: 1 Explanation: The number can be segmented as [43]
Naive Approach: The idea is to consider every prefix up to 6 digits( Since it is given that the primes are less than 106) and check if it is a prime number or not. If the prefix is a prime number, then recursively call the function to check the remaining string. If a non-negative number is returned, then it is considered as a possible arrangement. If none of the possible combinations returns a positive number, then -1 is printed.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include <iostream>#include <string>using namespace std; // Function to check whether a string// is a prime number or notbool checkPrime(string number){ int num = stoi(number); for (int i = 2; i * i <= num; i++) if ((num % i) == 0) return false; return true;} // A recursive function to find the minimum// number of segments the given string can// be divided such that every segment is a primeint splitIntoPrimes(string number){ // If the number is null if (number.length() == 0) return 0; // checkPrime function is called to check if // the number is a prime or not. if (number.length() <= 6 and checkPrime(number)) return 1; else { int numLen = number.length(); // A very large number denoting maximum int ans = 1000000; // Consider a minimum of 6 and length // since the primes are less than 10 ^ 6 for (int i = 1; i <= 6 && i <= numLen; i++) { if (checkPrime(number.substr(0, i))) { // Recursively call the function // to check for the remaining string int val = splitIntoPrimes(number.substr(i)); if (val != -1) { // Evaluating minimum splits // into Primes for the suffix ans = min(ans, 1 + val); } } } // Checks if no combination found if (ans == 1000000) return -1; return ans; }} // Driver codeint main(){ cout << splitIntoPrimes("13499315") << "\n"; cout << splitIntoPrimes("43") << "\n"; return 0;}
// Java implementation of the above approachimport java.util.*; class GFG{ // Function to check whether a String// is a prime number or notstatic boolean checkPrime(String number){ int num = Integer.valueOf(number); for (int i = 2; i * i <= num; i++) if ((num % i) == 0) return false; return true;} // A recursive function to find the minimum// number of segments the given String can// be divided such that every segment is a primestatic int splitIntoPrimes(String number){ // If the number is null if (number.length() == 0) return 0; // checkPrime function is called to check if // the number is a prime or not. if (number.length() <= 6 && checkPrime(number)) return 1; else { int numLen = number.length(); // A very large number denoting maximum int ans = 1000000; // Consider a minimum of 6 and length // since the primes are less than 10 ^ 6 for (int i = 1; i <= 6 && i <= numLen; i++) { if (checkPrime(number.substring(0, i))) { // Recursively call the function // to check for the remaining String int val = splitIntoPrimes(number.substring(i)); if (val != -1) { // Evaluating minimum splits // into Primes for the suffix ans = Math.min(ans, 1 + val); } } } // Checks if no combination found if (ans == 1000000) return -1; return ans; }} // Driver codepublic static void main(String[] args){ System.out.print(splitIntoPrimes("13499315")+ "\n"); System.out.print(splitIntoPrimes("43")+ "\n");}} // This code is contributed by Rajput-Ji
# Python3 implementation of the above approach # Function to check whether a string# is a prime number or notdef checkPrime(number) : num = int(number) for i in range(2, int(num**0.5)) : if((num % i) == 0) : return False return True # A recursive function to find the minimum# number of segments the given string can# be divided such that every segment is a primedef splitIntoPrimes(number) : # If the number is null if( number == '' ) : return 0 # checkPrime function is called to check if # the number is a prime or not. if( len(number)<= 6 and checkPrime(number) ) : return 1 else : numLen = len(number) # A very large number denoting maximum ans = 1000000 # Consider a minimum of 6 and length # since the primes are less than 10 ^ 6 for i in range( 1, (min( 6, numLen ) + 1) ) : if( checkPrime( number[:i] ) ) : # Recursively call the function # to check for the remaining string val = splitIntoPrimes( number[i:] ) if(val != -1) : # Evaluating minimum splits # into Primes for the suffix ans = min(ans, 1 + val) # Checks if no combination found if( ans == 1000000 ) : return -1 return ans # Driver codeprint(splitIntoPrimes("13499315"))print(splitIntoPrimes("43"))
// C# implementation of the above approachusing System; class GFG{ // Function to check whether a String// is a prime number or notstatic bool checkPrime(String number){ int num = Int32.Parse(number); for (int i = 2; i * i <= num; i++) if ((num % i) == 0) return false; return true;} // A recursive function to find the minimum// number of segments the given String can// be divided such that every segment is a primestatic int splitIntoPrimes(String number){ // If the number is null if (number.Length == 0) return 0; // checkPrime function is called to check if // the number is a prime or not. if (number.Length <= 6 && checkPrime(number)) return 1; else { int numLen = number.Length; // A very large number denoting maximum int ans = 1000000; // Consider a minimum of 6 and length // since the primes are less than 10 ^ 6 for (int i = 1; i <= 6 && i <= numLen; i++) { if (checkPrime(number.Substring(0, i))) { // Recursively call the function // to check for the remaining String int val = splitIntoPrimes(number.Substring(i)); if (val != -1) { // Evaluating minimum splits // into Primes for the suffix ans = Math.Min(ans, 1 + val); } } } // Checks if no combination found if (ans == 1000000) return -1; return ans; }} // Driver codepublic static void Main(String[] args){ Console.Write(splitIntoPrimes("13499315")+ "\n"); Console.Write(splitIntoPrimes("43")+ "\n");}} // This code is contributed by sapnasingh4991
<script> // JavaScript implementation of the above approach // Function to check whether a string// is a prime number or notfunction checkPrime(number){ let num = String(number); for (let i = 2; i * i <= num; i++) if ((num % i) == 0) return false; return true;} // A recursive function to find the minimum// number of segments the given string can// be divided such that every segment is a primefunction splitIntoPrimes(number){ // If the number is null if (number.length == 0) return 0; // checkPrime function is called to check if // the number is a prime or not. if (number.length <= 6 && checkPrime(number)) return 1; else { let numLen = number.length; // A very large number denoting maximum let ans = 1000000; // Consider a minimum of 6 and length // since the primes are less than 10 ^ 6 for (let i = 1; i <= 6 && i <= numLen; i++) { if (checkPrime(number.substr(0, i))) { // Recursively call the function // to check for the remaining string let val = splitIntoPrimes(number.substr(i)); if (val != -1) { // Evaluating minimum splits // into Primes for the suffix ans = Math.min(ans, 1 + val); } } } // Checks if no combination found if (ans == 1000000) return -1; return ans; }} // Driver code document.write(splitIntoPrimes("13499315") + "<br>");document.write(splitIntoPrimes("43") + "<br>"); // This code is contributed by gfgking </script>
3
1
Time Complexity:
The time complexity for the above approach would be of O(N5/2) where N is the length of the input string.
The complexity to find all the possible combinations recursively is O(N2).
For every combination, to check if the number is a prime number or not, an additional O(N0.5) time is used.
This makes the time complexity O(N5/2).
Dynamic Programming Approach: The given problem is seen to exhibit an overlapping subproblem property. Therefore, dynamic programming can be used to efficiently solve this question. A splitDP[] array is defined and used where splitDP[i] denotes the minimum number of splits required in the prefix string of length βiβ to break it into the prime subdivision. The splitDP[] array is filled in the following way:
A for loop is used to iterate through all the indices of the given string.
For every index βiβ from the above loop, another loop is iterated from 1 to 6 to check if the substring from (i + j)th index forms a prime or not.
If it forms a prime number, then the value at splitDP[] is updated as:
splitDP[i + j] = min(splitDP[i + j], 1 + splitDP[i]);
After updating all the values of the array, the value at the last index is the minimum number of splits for the entire string.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to check whether a string// is a prime number or notbool checkPrime(string number){ int num = stoi(number); for (int i = 2; i * i <= num; i++) if ((num % i) == 0) return false; return true;} // A function to find the minimum// number of segments the given string// can be divided such that every// segment is a primeint splitIntoPrimes(string number){ int numLen = number.length(); // Declare a splitdp[] array // and initialize to -1 int splitDP[numLen + 1]; memset(splitDP, -1, sizeof(splitDP)); // Build the DP table in // a bottom-up manner for (int i = 1; i <= numLen; i++) { // Initially Check if the entire prefix is Prime if (i <= 6 && checkPrime(number.substr(0, i))) splitDP[i] = 1; // If the Given Prefix can be split into Primes // then for the remaining string from i to j // Check if Prime. If yes calculate // the minimum split till j if (splitDP[i] != -1) { for (int j = 1; j <= 6 && i + j <= numLen; j++) { // To check if the substring from i to j // is a prime number or not if (checkPrime(number.substr(i, j))) { // If it is a prime, then update the dp array if (splitDP[i + j] == -1) splitDP[i + j] = 1 + splitDP[i]; else splitDP[i + j] = min(splitDP[i + j], 1 + splitDP[i]); } } } } // Return the minimum number of splits // for the entire string return splitDP[numLen];} // Driver codeint main(){ cout << splitIntoPrimes("13499315") << "\n"; cout << splitIntoPrimes("43") << "\n"; return 0;}
// Java implementation of the above approach import java.util.*; class GFG{ // Function to check whether a String// is a prime number or notstatic boolean checkPrime(String number){ if(number.length()==0) return true; int num = Integer.parseInt(number); for (int i = 2; i * i <= num; i++) if ((num % i) == 0) return false; return true;} // A function to find the minimum// number of segments the given String// can be divided such that every// segment is a primestatic int splitIntoPrimes(String number){ int numLen = number.length(); // Declare a splitdp[] array // and initialize to -1 int []splitDP = new int[numLen + 1]; Arrays.fill(splitDP, -1); // Build the DP table in // a bottom-up manner for (int i = 1; i <= numLen; i++) { // Initially Check if the entire prefix is Prime if (i <= 6 && checkPrime(number.substring(0, i))) splitDP[i] = 1; // If the Given Prefix can be split into Primes // then for the remaining String from i to j // Check if Prime. If yes calculate // the minimum split till j if (splitDP[i] != -1) { for (int j = 1; j <= 6 && i + j <= numLen; j++) { // To check if the subString from i to j // is a prime number or not if (checkPrime(number.substring(i, i+j))) { // If it is a prime, then update the dp array if (splitDP[i + j] == -1) splitDP[i + j] = 1 + splitDP[i]; else splitDP[i + j] = Math.min(splitDP[i + j], 1 + splitDP[i]); } } } } // Return the minimum number of splits // for the entire String return splitDP[numLen];} // Driver codepublic static void main(String[] args){ System.out.print(splitIntoPrimes("13499315")+ "\n"); System.out.print(splitIntoPrimes("43")+ "\n");}} // This code contributed by Princi Singh
# Python 3 implementation of the above approachfrom math import sqrt # Function to check whether a string# is a prime number or notdef checkPrime(number): if(len(number) == 0): return True num = int(number) for i in range(2,int(sqrt(num)) + 1, 1): if ((num % i) == 0): return False return True # A function to find the minimum# number of segments the given string# can be divided such that every# segment is a primedef splitIntoPrimes(number): numLen = len(number) # Declare a splitdp[] array # and initialize to -1 splitDP = [-1 for i in range(numLen + 1)] # Build the DP table in # a bottom-up manner for i in range(1, numLen + 1, 1): # Initially Check if the entire prefix is Prime if (i <= 6 and checkPrime(number[0:i])): splitDP[i] = 1 # If the Given Prefix can be split into Primes # then for the remaining string from i to j # Check if Prime. If yes calculate # the minimum split till j if (splitDP[i] != -1): j = 1 while(j <= 6 and i + j <= numLen): # To check if the substring from i to j # is a prime number or not if (checkPrime(number[i:i+j])): # If it is a prime, then update the dp array if (splitDP[i + j] == -1): splitDP[i + j] = 1 + splitDP[i] else: splitDP[i + j] = min(splitDP[i + j], 1 + splitDP[i]) j += 1 # Return the minimum number of splits # for the entire string return splitDP[numLen] # Driver codeif __name__ == '__main__': print(splitIntoPrimes("13499315")) print(splitIntoPrimes("43")) # This code is contributed by Surendra_Gangwar
// C# implementation of the above approachusing System; class GFG{ // Function to check whether a String// is a prime number or notstatic bool checkPrime(String number){ if(number.Length==0) return true; int num = Int32.Parse(number); for (int i = 2; i * i <= num; i++) if ((num % i) == 0) return false; return true;} // A function to find the minimum// number of segments the given String// can be divided such that every// segment is a primestatic int splitIntoPrimes(String number){ int numLen = number.Length; // Declare a splitdp[] array // and initialize to -1 int []splitDP = new int[numLen + 1]; for (int i = 0; i <= numLen; i++) splitDP[i] = -1; // Build the DP table in // a bottom-up manner for (int i = 1; i <= numLen; i++) { // Initially Check if the entire prefix is Prime if (i <= 6 && checkPrime(number.Substring(0, i))) splitDP[i] = 1; // If the Given Prefix can be split into Primes // then for the remaining String from i to j // Check if Prime. If yes calculate // the minimum split till j if (splitDP[i] != -1) { for (int j = 1; j <= 6 && i + j <= numLen; j++) { // To check if the subString from i to j // is a prime number or not if (checkPrime(number.Substring(i, j))) { // If it is a prime, then update the dp array if (splitDP[i + j] == -1) splitDP[i + j] = 1 + splitDP[i]; else splitDP[i + j] = Math.Min(splitDP[i + j], 1 + splitDP[i]); } } } } // Return the minimum number of splits // for the entire String return splitDP[numLen];} // Driver codepublic static void Main(String[] args){ Console.Write(splitIntoPrimes("13499315")+ "\n"); Console.Write(splitIntoPrimes("43")+ "\n");}} // This code is contributed by Rajput-Ji
<script> // Javascript implementation of the above approach // Function to check whether a String// is a prime number or notfunction checkPrime(number){ if (number.length == 0) return true; let num = parseInt(number); for(let i = 2; i * i <= num; i++) if ((num % i) == 0) return false; return true;} // A function to find the minimum// number of segments the given String// can be divided such that every// segment is a primefunction splitIntoPrimes(number){ let numLen = number.length; // Declare a splitdp[] array // and initialize to -1 let splitDP = new Array(numLen + 1); for(let i = 0; i < splitDP.length; i++) { splitDP[i] = -1; } // Build the DP table in // a bottom-up manner for(let i = 1; i <= numLen; i++) { // Initially Check if the entire prefix is Prime if (i <= 6 && checkPrime(number.substring(0, i))) splitDP[i] = 1; // If the Given Prefix can be split into Primes // then for the remaining String from i to j // Check if Prime. If yes calculate // the minimum split till j if (splitDP[i] != -1) { for(let j = 1; j <= 6 && i + j <= numLen; j++) { // To check if the subString from i to j // is a prime number or not if (checkPrime(number.substring(i, i + j))) { // If it is a prime, then update the // dp array if (splitDP[i + j] == -1) splitDP[i + j] = 1 + splitDP[i]; else splitDP[i + j] = Math.min( splitDP[i + j], 1 + splitDP[i]); } } } } // Return the minimum number of splits // for the entire String return splitDP[numLen];} // Driver codedocument.write(splitIntoPrimes("13499315") + "<br>");document.write(splitIntoPrimes("43") + "<br>"); // This code is contributed by avanitrachhadiya2155 </script>
3
1
Time Complexity:
The time complexity of the above approach is O(N3/2) where N is the length of the input string.
The time to iterate through all the indices is O(N).
Since the inner for loop runs a constant number of times for every index, itβs run time can be considered as constant.
For every index, the time taken to check whether the number is a prime or not is of O(N0.5).
Therefore, the overall time complexity is O(N3/2).
Optimized Dynamic Programming Approach: The above approach can further be optimized by using the concept Sieve of Eratosthenes to precompute and store whether a number is prime or not and reducing the time complexity to check for a number at every iteration.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to precompute all the primes// upto 1000000 and store it in a set// using Sieve of Eratosthenesvoid getPrimesFromSeive(set<string>& primes){ bool prime[1000001]; memset(prime, true, sizeof(prime)); prime[0] = prime[1] = false; for (int i = 2; i * i <= 1000000; i++) { if (prime[i] == true) { for (int j = i * i; j <= 1000000; j += i) prime[j] = false; } } // Here to_string() is used // for converting int to string for (int i = 2; i <= 1000000; i++) { if (prime[i] == true) primes.insert(to_string(i)); }} // A function to find the minimum// number of segments the given string// can be divided such that every// segment is a primeint splitIntoPrimes(string number){ int numLen = number.length(); // Declare a splitdp[] array // and initialize to -1 int splitDP[numLen + 1]; memset(splitDP, -1, sizeof(splitDP)); // Call sieve function to store primes in // primes array set<string> primes; getPrimesFromSeive(primes); // Build the DP table in a bottom-up manner for (int i = 1; i <= numLen; i++) { // If the prefix is prime then the prefix // will be found in the prime set if (i <= 6 && (primes.find(number.substr(0, i)) != primes.end())) splitDP[i] = 1; // If the Given Prefix can be split into Primes // then for the remaining string from i to j // Check if Prime. If yes calculate // the minimum split till j if (splitDP[i] != -1) { for (int j = 1; j <= 6 && i + j <= numLen; j++) { // To check if the substring from i to j // is a prime number or not if (primes.find(number.substr(i, j)) != primes.end()) { // If it is a prime, then update the dp array if (splitDP[i + j] == -1) splitDP[i + j] = 1 + splitDP[i]; else splitDP[i + j] = min(splitDP[i + j], 1 + splitDP[i]); } } } } // Return the minimum number of splits // for the entire string return splitDP[numLen];} int main(){ cout << splitIntoPrimes("13499315") << "\n"; cout << splitIntoPrimes("43") << "\n"; return 0;}
// Java implementation of the above approach import java.util.*; class GFG{ // Function to precompute all the primes// upto 1000000 and store it in a set// using Sieve of Eratosthenesstatic void getPrimesFromSeive(HashSet<String> primes){ boolean []prime = new boolean[1000001]; Arrays.fill(prime, true); prime[0] = prime[1] = false; for (int i = 2; i * i <= 1000000; i++) { if (prime[i] == true) { for (int j = i * i; j <= 1000000; j += i) prime[j] = false; } } // Here to_String() is used // for converting int to String for (int i = 2; i <= 1000000; i++) { if (prime[i] == true) primes.add(String.valueOf(i)); }} // A function to find the minimum// number of segments the given String// can be divided such that every// segment is a primestatic int splitIntoPrimes(String number){ int numLen = number.length(); // Declare a splitdp[] array // and initialize to -1 int []splitDP = new int[numLen + 1]; Arrays.fill(splitDP, -1); // Call sieve function to store primes in // primes array HashSet<String> primes = new HashSet<String>(); getPrimesFromSeive(primes); // Build the DP table in a bottom-up manner for (int i = 1; i <= numLen; i++) { // If the prefix is prime then the prefix // will be found in the prime set if (i <= 6 && (primes.contains(number.substring(0, i)))) splitDP[i] = 1; // If the Given Prefix can be split into Primes // then for the remaining String from i to j // Check if Prime. If yes calculate // the minimum split till j if (splitDP[i] != -1) { for (int j = 1; j <= 6 && i + j <= numLen; j++) { // To check if the subString from i to j // is a prime number or not if (primes.contains(number.substring(i, i+j))) { // If it is a prime, then update the dp array if (splitDP[i + j] == -1) splitDP[i + j] = 1 + splitDP[i]; else splitDP[i + j] = Math.min(splitDP[i + j], 1 + splitDP[i]); } } } } // Return the minimum number of splits // for the entire String return splitDP[numLen];} public static void main(String[] args){ System.out.print(splitIntoPrimes("13499315")+ "\n"); System.out.print(splitIntoPrimes("43")+ "\n");}} // This code contributed by Princi Singh
# Python3 implementation of the above approach # Function to precompute all the primes# upto 1000000 and store it in a set# using Sieve of Eratosthenesdef getPrimesFromSeive(primes): prime = [True] * (1000001) prime[0], prime[1] = False, False i = 2 while (i * i <= 1000000): if (prime[i] == True): for j in range(i * i, 1000001, i): prime[j] = False i += 1 # Here str() is used for # converting int to string for i in range(2, 1000001): if (prime[i] == True): primes.append(str(i)) # A function to find the minimum# number of segments the given string# can be divided such that every# segment is a primedef splitIntoPrimes(number): numLen = len(number) # Declare a splitdp[] array # and initialize to -1 splitDP = [-1] * (numLen + 1) # Call sieve function to store # primes in primes array primes = [] getPrimesFromSeive(primes) # Build the DP table in a bottom-up manner for i in range(1, numLen + 1): # If the prefix is prime then the prefix # will be found in the prime set if (i <= 6 and (number[0 : i] in primes)): splitDP[i] = 1 # If the Given Prefix can be split into Primes # then for the remaining string from i to j # Check if Prime. If yes calculate # the minimum split till j if (splitDP[i] != -1): j = 1 while (j <= 6 and (i + j <= numLen)): # To check if the substring from i to j # is a prime number or not if (number[i : i + j] in primes): # If it is a prime, then # update the dp array if (splitDP[i + j] == -1): splitDP[i + j] = 1 + splitDP[i] else: splitDP[i + j] = min(splitDP[i + j], 1 + splitDP[i]) j += 1 # Return the minimum number of # splits for the entire string return splitDP[numLen] # Driver codeprint(splitIntoPrimes("13499315"))print(splitIntoPrimes("43")) # This code is contributed by chitranayal
// C# implementation of the above approachusing System;using System.Collections.Generic; class GFG{ // Function to precompute all the primes// upto 1000000 and store it in a set// using Sieve of Eratosthenesstatic void getPrimesFromSeive(HashSet<String> primes){ bool []prime = new bool[1000001]; for(int i = 0; i < 1000001; i++) prime[i] = true; prime[0] = prime[1] = false; for(int i = 2; i * i <= 1000000; i++) { if (prime[i] == true) { for(int j = i * i; j <= 1000000; j += i) prime[j] = false; } } // Converting int to String for(int i = 2; i <= 1000000; i++) { if (prime[i] == true) primes.Add(String.Join("", i)); }} // A function to find the minimum// number of segments the given String// can be divided such that every// segment is a primestatic int splitIntoPrimes(String number){ int numLen = number.Length; // Declare a splitdp[] array // and initialize to -1 int []splitDP = new int[numLen + 1]; for(int i = 0; i < numLen + 1; i++) splitDP[i] = -1; // Call sieve function to store primes // in primes array HashSet<String> primes = new HashSet<String>(); getPrimesFromSeive(primes); // Build the DP table in a bottom-up manner for(int i = 1; i <= numLen; i++) { // If the prefix is prime then the prefix // will be found in the prime set if (i <= 6 && (primes.Contains (number.Substring(0, i)))) splitDP[i] = 1; // If the given prefix can be split into // primes, then for the remaining String // from i to j check if prime. If yes // calculate the minimum split till j if (splitDP[i] != -1) { for(int j = 1; j <= 6 && i + j <= numLen; j++) { // To check if the subString from // i to j is a prime number or not if (primes.Contains(number.Substring(i, j))) { // If it is a prime, then update // the dp array if (splitDP[i + j] == -1) splitDP[i + j] = 1 + splitDP[i]; else splitDP[i + j] = Math.Min(splitDP[i + j], 1 + splitDP[i]); } } } } // Return the minimum number of // splits for the entire String return splitDP[numLen];} public static void Main(String[] args){ Console.Write(splitIntoPrimes("13499315") + "\n"); Console.Write(splitIntoPrimes("43") + "\n");}} // This code is contributed by sapnasingh4991
<script>// Javascript implementation of the above approach // Function to precompute all the primes// upto 1000000 and store it in a set// using Sieve of Eratosthenesfunction getPrimesFromSeive(primes){ let prime = new Array(1000001); for(let i=0;i<prime.length;i++) { prime[i]=true; } prime[0] = prime[1] = false; for (let i = 2; i * i <= 1000000; i++) { if (prime[i] == true) { for (let j = i * i; j <= 1000000; j += i) prime[j] = false; } } // Here to_String() is used // for converting int to String for (let i = 2; i <= 1000000; i++) { if (prime[i] == true) primes.add((i).toString()); }} // A function to find the minimum// number of segments the given String// can be divided such that every// segment is a primefunction splitIntoPrimes(number){ let numLen = number.length; // Declare a splitdp[] array // and initialize to -1 let splitDP = new Array(numLen + 1); for(let i=0;i<splitDP.length;i++) { splitDP[i]=-1; } // Call sieve function to store primes in // primes array let primes = new Set(); getPrimesFromSeive(primes); // Build the DP table in a bottom-up manner for (let i = 1; i <= numLen; i++) { // If the prefix is prime then the prefix // will be found in the prime set if (i <= 6 && (primes.has(number.substring(0, i)))) splitDP[i] = 1; // If the Given Prefix can be split into Primes // then for the remaining String from i to j // Check if Prime. If yes calculate // the minimum split till j if (splitDP[i] != -1) { for (let j = 1; j <= 6 && i + j <= numLen; j++) { // To check if the subString from i to j // is a prime number or not if (primes.has(number.substring(i, i+j))) { // If it is a prime, then update the dp array if (splitDP[i + j] == -1) splitDP[i + j] = 1 + splitDP[i]; else splitDP[i + j] = Math.min(splitDP[i + j], 1 + splitDP[i]); } } } } // Return the minimum number of splits // for the entire String return splitDP[numLen];} document.write(splitIntoPrimes("13499315")+ "<br>");document.write(splitIntoPrimes("43")+ "<br>"); // This code is contributed by rag2127</script>
3
1
Time Complexity:
This is the most efficient method as this runs in O(N) time complexity where N is the length of the input string.
Since the sieve of Eratosthenes has a run time of O(N*log(log(N))) and the list of primes up to 106, the precomputation complexity can be calculated. However, since this is performed only once for any number of strings, it is not counted in calculating time complexity.
SURENDRA_GANGWAR
Rajput-Ji
sapnasingh4991
princi singh
ukasp
gfgking
avanitrachhadiya2155
rag2127
Arrays
Dynamic Programming
Strings
Arrays
Strings
Dynamic Programming
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
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
0-1 Knapsack Problem | DP-10
Program for Fibonacci numbers
Longest Common Subsequence | DP-4
BellmanβFord Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
|
[
{
"code": null,
"e": 26089,
"s": 26061,
"text": "\n02 Jun, 2021"
},
{
"code": null,
"e": 26290,
"s": 26089,
"text": "Given a string str that represents a large number, the task is to find the minimum number of segments the given string can be divided such that each segment is a prime number in the range of 1 to 106."
},
{
"code": null,
"e": 26301,
"s": 26290,
"text": "Examples: "
},
{
"code": null,
"e": 26394,
"s": 26301,
"text": "Input: str = β13499315β Output: 3 Explanation: The number can be segmented as [13499, 31, 5]"
},
{
"code": null,
"e": 26473,
"s": 26394,
"text": "Input: str = β43β Output: 1 Explanation: The number can be segmented as [43] "
},
{
"code": null,
"e": 26908,
"s": 26473,
"text": "Naive Approach: The idea is to consider every prefix up to 6 digits( Since it is given that the primes are less than 106) and check if it is a prime number or not. If the prefix is a prime number, then recursively call the function to check the remaining string. If a non-negative number is returned, then it is considered as a possible arrangement. If none of the possible combinations returns a positive number, then -1 is printed. "
},
{
"code": null,
"e": 26960,
"s": 26908,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26964,
"s": 26960,
"text": "C++"
},
{
"code": null,
"e": 26969,
"s": 26964,
"text": "Java"
},
{
"code": null,
"e": 26977,
"s": 26969,
"text": "Python3"
},
{
"code": null,
"e": 26980,
"s": 26977,
"text": "C#"
},
{
"code": null,
"e": 26991,
"s": 26980,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include <iostream>#include <string>using namespace std; // Function to check whether a string// is a prime number or notbool checkPrime(string number){ int num = stoi(number); for (int i = 2; i * i <= num; i++) if ((num % i) == 0) return false; return true;} // A recursive function to find the minimum// number of segments the given string can// be divided such that every segment is a primeint splitIntoPrimes(string number){ // If the number is null if (number.length() == 0) return 0; // checkPrime function is called to check if // the number is a prime or not. if (number.length() <= 6 and checkPrime(number)) return 1; else { int numLen = number.length(); // A very large number denoting maximum int ans = 1000000; // Consider a minimum of 6 and length // since the primes are less than 10 ^ 6 for (int i = 1; i <= 6 && i <= numLen; i++) { if (checkPrime(number.substr(0, i))) { // Recursively call the function // to check for the remaining string int val = splitIntoPrimes(number.substr(i)); if (val != -1) { // Evaluating minimum splits // into Primes for the suffix ans = min(ans, 1 + val); } } } // Checks if no combination found if (ans == 1000000) return -1; return ans; }} // Driver codeint main(){ cout << splitIntoPrimes(\"13499315\") << \"\\n\"; cout << splitIntoPrimes(\"43\") << \"\\n\"; return 0;}",
"e": 28657,
"s": 26991,
"text": null
},
{
"code": "// Java implementation of the above approachimport java.util.*; class GFG{ // Function to check whether a String// is a prime number or notstatic boolean checkPrime(String number){ int num = Integer.valueOf(number); for (int i = 2; i * i <= num; i++) if ((num % i) == 0) return false; return true;} // A recursive function to find the minimum// number of segments the given String can// be divided such that every segment is a primestatic int splitIntoPrimes(String number){ // If the number is null if (number.length() == 0) return 0; // checkPrime function is called to check if // the number is a prime or not. if (number.length() <= 6 && checkPrime(number)) return 1; else { int numLen = number.length(); // A very large number denoting maximum int ans = 1000000; // Consider a minimum of 6 and length // since the primes are less than 10 ^ 6 for (int i = 1; i <= 6 && i <= numLen; i++) { if (checkPrime(number.substring(0, i))) { // Recursively call the function // to check for the remaining String int val = splitIntoPrimes(number.substring(i)); if (val != -1) { // Evaluating minimum splits // into Primes for the suffix ans = Math.min(ans, 1 + val); } } } // Checks if no combination found if (ans == 1000000) return -1; return ans; }} // Driver codepublic static void main(String[] args){ System.out.print(splitIntoPrimes(\"13499315\")+ \"\\n\"); System.out.print(splitIntoPrimes(\"43\")+ \"\\n\");}} // This code is contributed by Rajput-Ji",
"e": 30419,
"s": 28657,
"text": null
},
{
"code": "# Python3 implementation of the above approach # Function to check whether a string# is a prime number or notdef checkPrime(number) : num = int(number) for i in range(2, int(num**0.5)) : if((num % i) == 0) : return False return True # A recursive function to find the minimum# number of segments the given string can# be divided such that every segment is a primedef splitIntoPrimes(number) : # If the number is null if( number == '' ) : return 0 # checkPrime function is called to check if # the number is a prime or not. if( len(number)<= 6 and checkPrime(number) ) : return 1 else : numLen = len(number) # A very large number denoting maximum ans = 1000000 # Consider a minimum of 6 and length # since the primes are less than 10 ^ 6 for i in range( 1, (min( 6, numLen ) + 1) ) : if( checkPrime( number[:i] ) ) : # Recursively call the function # to check for the remaining string val = splitIntoPrimes( number[i:] ) if(val != -1) : # Evaluating minimum splits # into Primes for the suffix ans = min(ans, 1 + val) # Checks if no combination found if( ans == 1000000 ) : return -1 return ans # Driver codeprint(splitIntoPrimes(\"13499315\"))print(splitIntoPrimes(\"43\"))",
"e": 32019,
"s": 30419,
"text": null
},
{
"code": "// C# implementation of the above approachusing System; class GFG{ // Function to check whether a String// is a prime number or notstatic bool checkPrime(String number){ int num = Int32.Parse(number); for (int i = 2; i * i <= num; i++) if ((num % i) == 0) return false; return true;} // A recursive function to find the minimum// number of segments the given String can// be divided such that every segment is a primestatic int splitIntoPrimes(String number){ // If the number is null if (number.Length == 0) return 0; // checkPrime function is called to check if // the number is a prime or not. if (number.Length <= 6 && checkPrime(number)) return 1; else { int numLen = number.Length; // A very large number denoting maximum int ans = 1000000; // Consider a minimum of 6 and length // since the primes are less than 10 ^ 6 for (int i = 1; i <= 6 && i <= numLen; i++) { if (checkPrime(number.Substring(0, i))) { // Recursively call the function // to check for the remaining String int val = splitIntoPrimes(number.Substring(i)); if (val != -1) { // Evaluating minimum splits // into Primes for the suffix ans = Math.Min(ans, 1 + val); } } } // Checks if no combination found if (ans == 1000000) return -1; return ans; }} // Driver codepublic static void Main(String[] args){ Console.Write(splitIntoPrimes(\"13499315\")+ \"\\n\"); Console.Write(splitIntoPrimes(\"43\")+ \"\\n\");}} // This code is contributed by sapnasingh4991",
"e": 33769,
"s": 32019,
"text": null
},
{
"code": "<script> // JavaScript implementation of the above approach // Function to check whether a string// is a prime number or notfunction checkPrime(number){ let num = String(number); for (let i = 2; i * i <= num; i++) if ((num % i) == 0) return false; return true;} // A recursive function to find the minimum// number of segments the given string can// be divided such that every segment is a primefunction splitIntoPrimes(number){ // If the number is null if (number.length == 0) return 0; // checkPrime function is called to check if // the number is a prime or not. if (number.length <= 6 && checkPrime(number)) return 1; else { let numLen = number.length; // A very large number denoting maximum let ans = 1000000; // Consider a minimum of 6 and length // since the primes are less than 10 ^ 6 for (let i = 1; i <= 6 && i <= numLen; i++) { if (checkPrime(number.substr(0, i))) { // Recursively call the function // to check for the remaining string let val = splitIntoPrimes(number.substr(i)); if (val != -1) { // Evaluating minimum splits // into Primes for the suffix ans = Math.min(ans, 1 + val); } } } // Checks if no combination found if (ans == 1000000) return -1; return ans; }} // Driver code document.write(splitIntoPrimes(\"13499315\") + \"<br>\");document.write(splitIntoPrimes(\"43\") + \"<br>\"); // This code is contributed by gfgking </script>",
"e": 35425,
"s": 33769,
"text": null
},
{
"code": null,
"e": 35429,
"s": 35425,
"text": "3\n1"
},
{
"code": null,
"e": 35449,
"s": 35431,
"text": "Time Complexity: "
},
{
"code": null,
"e": 35555,
"s": 35449,
"text": "The time complexity for the above approach would be of O(N5/2) where N is the length of the input string."
},
{
"code": null,
"e": 35630,
"s": 35555,
"text": "The complexity to find all the possible combinations recursively is O(N2)."
},
{
"code": null,
"e": 35738,
"s": 35630,
"text": "For every combination, to check if the number is a prime number or not, an additional O(N0.5) time is used."
},
{
"code": null,
"e": 35778,
"s": 35738,
"text": "This makes the time complexity O(N5/2)."
},
{
"code": null,
"e": 36189,
"s": 35778,
"text": "Dynamic Programming Approach: The given problem is seen to exhibit an overlapping subproblem property. Therefore, dynamic programming can be used to efficiently solve this question. A splitDP[] array is defined and used where splitDP[i] denotes the minimum number of splits required in the prefix string of length βiβ to break it into the prime subdivision. The splitDP[] array is filled in the following way: "
},
{
"code": null,
"e": 36264,
"s": 36189,
"text": "A for loop is used to iterate through all the indices of the given string."
},
{
"code": null,
"e": 36411,
"s": 36264,
"text": "For every index βiβ from the above loop, another loop is iterated from 1 to 6 to check if the substring from (i + j)th index forms a prime or not."
},
{
"code": null,
"e": 36482,
"s": 36411,
"text": "If it forms a prime number, then the value at splitDP[] is updated as:"
},
{
"code": null,
"e": 36536,
"s": 36482,
"text": "splitDP[i + j] = min(splitDP[i + j], 1 + splitDP[i]);"
},
{
"code": null,
"e": 36663,
"s": 36536,
"text": "After updating all the values of the array, the value at the last index is the minimum number of splits for the entire string."
},
{
"code": null,
"e": 36716,
"s": 36663,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 36720,
"s": 36716,
"text": "C++"
},
{
"code": null,
"e": 36725,
"s": 36720,
"text": "Java"
},
{
"code": null,
"e": 36733,
"s": 36725,
"text": "Python3"
},
{
"code": null,
"e": 36736,
"s": 36733,
"text": "C#"
},
{
"code": null,
"e": 36747,
"s": 36736,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to check whether a string// is a prime number or notbool checkPrime(string number){ int num = stoi(number); for (int i = 2; i * i <= num; i++) if ((num % i) == 0) return false; return true;} // A function to find the minimum// number of segments the given string// can be divided such that every// segment is a primeint splitIntoPrimes(string number){ int numLen = number.length(); // Declare a splitdp[] array // and initialize to -1 int splitDP[numLen + 1]; memset(splitDP, -1, sizeof(splitDP)); // Build the DP table in // a bottom-up manner for (int i = 1; i <= numLen; i++) { // Initially Check if the entire prefix is Prime if (i <= 6 && checkPrime(number.substr(0, i))) splitDP[i] = 1; // If the Given Prefix can be split into Primes // then for the remaining string from i to j // Check if Prime. If yes calculate // the minimum split till j if (splitDP[i] != -1) { for (int j = 1; j <= 6 && i + j <= numLen; j++) { // To check if the substring from i to j // is a prime number or not if (checkPrime(number.substr(i, j))) { // If it is a prime, then update the dp array if (splitDP[i + j] == -1) splitDP[i + j] = 1 + splitDP[i]; else splitDP[i + j] = min(splitDP[i + j], 1 + splitDP[i]); } } } } // Return the minimum number of splits // for the entire string return splitDP[numLen];} // Driver codeint main(){ cout << splitIntoPrimes(\"13499315\") << \"\\n\"; cout << splitIntoPrimes(\"43\") << \"\\n\"; return 0;}",
"e": 38636,
"s": 36747,
"text": null
},
{
"code": "// Java implementation of the above approach import java.util.*; class GFG{ // Function to check whether a String// is a prime number or notstatic boolean checkPrime(String number){ if(number.length()==0) return true; int num = Integer.parseInt(number); for (int i = 2; i * i <= num; i++) if ((num % i) == 0) return false; return true;} // A function to find the minimum// number of segments the given String// can be divided such that every// segment is a primestatic int splitIntoPrimes(String number){ int numLen = number.length(); // Declare a splitdp[] array // and initialize to -1 int []splitDP = new int[numLen + 1]; Arrays.fill(splitDP, -1); // Build the DP table in // a bottom-up manner for (int i = 1; i <= numLen; i++) { // Initially Check if the entire prefix is Prime if (i <= 6 && checkPrime(number.substring(0, i))) splitDP[i] = 1; // If the Given Prefix can be split into Primes // then for the remaining String from i to j // Check if Prime. If yes calculate // the minimum split till j if (splitDP[i] != -1) { for (int j = 1; j <= 6 && i + j <= numLen; j++) { // To check if the subString from i to j // is a prime number or not if (checkPrime(number.substring(i, i+j))) { // If it is a prime, then update the dp array if (splitDP[i + j] == -1) splitDP[i + j] = 1 + splitDP[i]; else splitDP[i + j] = Math.min(splitDP[i + j], 1 + splitDP[i]); } } } } // Return the minimum number of splits // for the entire String return splitDP[numLen];} // Driver codepublic static void main(String[] args){ System.out.print(splitIntoPrimes(\"13499315\")+ \"\\n\"); System.out.print(splitIntoPrimes(\"43\")+ \"\\n\");}} // This code contributed by Princi Singh",
"e": 40684,
"s": 38636,
"text": null
},
{
"code": "# Python 3 implementation of the above approachfrom math import sqrt # Function to check whether a string# is a prime number or notdef checkPrime(number): if(len(number) == 0): return True num = int(number) for i in range(2,int(sqrt(num)) + 1, 1): if ((num % i) == 0): return False return True # A function to find the minimum# number of segments the given string# can be divided such that every# segment is a primedef splitIntoPrimes(number): numLen = len(number) # Declare a splitdp[] array # and initialize to -1 splitDP = [-1 for i in range(numLen + 1)] # Build the DP table in # a bottom-up manner for i in range(1, numLen + 1, 1): # Initially Check if the entire prefix is Prime if (i <= 6 and checkPrime(number[0:i])): splitDP[i] = 1 # If the Given Prefix can be split into Primes # then for the remaining string from i to j # Check if Prime. If yes calculate # the minimum split till j if (splitDP[i] != -1): j = 1 while(j <= 6 and i + j <= numLen): # To check if the substring from i to j # is a prime number or not if (checkPrime(number[i:i+j])): # If it is a prime, then update the dp array if (splitDP[i + j] == -1): splitDP[i + j] = 1 + splitDP[i] else: splitDP[i + j] = min(splitDP[i + j], 1 + splitDP[i]) j += 1 # Return the minimum number of splits # for the entire string return splitDP[numLen] # Driver codeif __name__ == '__main__': print(splitIntoPrimes(\"13499315\")) print(splitIntoPrimes(\"43\")) # This code is contributed by Surendra_Gangwar",
"e": 42472,
"s": 40684,
"text": null
},
{
"code": "// C# implementation of the above approachusing System; class GFG{ // Function to check whether a String// is a prime number or notstatic bool checkPrime(String number){ if(number.Length==0) return true; int num = Int32.Parse(number); for (int i = 2; i * i <= num; i++) if ((num % i) == 0) return false; return true;} // A function to find the minimum// number of segments the given String// can be divided such that every// segment is a primestatic int splitIntoPrimes(String number){ int numLen = number.Length; // Declare a splitdp[] array // and initialize to -1 int []splitDP = new int[numLen + 1]; for (int i = 0; i <= numLen; i++) splitDP[i] = -1; // Build the DP table in // a bottom-up manner for (int i = 1; i <= numLen; i++) { // Initially Check if the entire prefix is Prime if (i <= 6 && checkPrime(number.Substring(0, i))) splitDP[i] = 1; // If the Given Prefix can be split into Primes // then for the remaining String from i to j // Check if Prime. If yes calculate // the minimum split till j if (splitDP[i] != -1) { for (int j = 1; j <= 6 && i + j <= numLen; j++) { // To check if the subString from i to j // is a prime number or not if (checkPrime(number.Substring(i, j))) { // If it is a prime, then update the dp array if (splitDP[i + j] == -1) splitDP[i + j] = 1 + splitDP[i]; else splitDP[i + j] = Math.Min(splitDP[i + j], 1 + splitDP[i]); } } } } // Return the minimum number of splits // for the entire String return splitDP[numLen];} // Driver codepublic static void Main(String[] args){ Console.Write(splitIntoPrimes(\"13499315\")+ \"\\n\"); Console.Write(splitIntoPrimes(\"43\")+ \"\\n\");}} // This code is contributed by Rajput-Ji",
"e": 44533,
"s": 42472,
"text": null
},
{
"code": "<script> // Javascript implementation of the above approach // Function to check whether a String// is a prime number or notfunction checkPrime(number){ if (number.length == 0) return true; let num = parseInt(number); for(let i = 2; i * i <= num; i++) if ((num % i) == 0) return false; return true;} // A function to find the minimum// number of segments the given String// can be divided such that every// segment is a primefunction splitIntoPrimes(number){ let numLen = number.length; // Declare a splitdp[] array // and initialize to -1 let splitDP = new Array(numLen + 1); for(let i = 0; i < splitDP.length; i++) { splitDP[i] = -1; } // Build the DP table in // a bottom-up manner for(let i = 1; i <= numLen; i++) { // Initially Check if the entire prefix is Prime if (i <= 6 && checkPrime(number.substring(0, i))) splitDP[i] = 1; // If the Given Prefix can be split into Primes // then for the remaining String from i to j // Check if Prime. If yes calculate // the minimum split till j if (splitDP[i] != -1) { for(let j = 1; j <= 6 && i + j <= numLen; j++) { // To check if the subString from i to j // is a prime number or not if (checkPrime(number.substring(i, i + j))) { // If it is a prime, then update the // dp array if (splitDP[i + j] == -1) splitDP[i + j] = 1 + splitDP[i]; else splitDP[i + j] = Math.min( splitDP[i + j], 1 + splitDP[i]); } } } } // Return the minimum number of splits // for the entire String return splitDP[numLen];} // Driver codedocument.write(splitIntoPrimes(\"13499315\") + \"<br>\");document.write(splitIntoPrimes(\"43\") + \"<br>\"); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 46725,
"s": 44533,
"text": null
},
{
"code": null,
"e": 46729,
"s": 46725,
"text": "3\n1"
},
{
"code": null,
"e": 46749,
"s": 46731,
"text": "Time Complexity: "
},
{
"code": null,
"e": 46845,
"s": 46749,
"text": "The time complexity of the above approach is O(N3/2) where N is the length of the input string."
},
{
"code": null,
"e": 46898,
"s": 46845,
"text": "The time to iterate through all the indices is O(N)."
},
{
"code": null,
"e": 47017,
"s": 46898,
"text": "Since the inner for loop runs a constant number of times for every index, itβs run time can be considered as constant."
},
{
"code": null,
"e": 47110,
"s": 47017,
"text": "For every index, the time taken to check whether the number is a prime or not is of O(N0.5)."
},
{
"code": null,
"e": 47161,
"s": 47110,
"text": "Therefore, the overall time complexity is O(N3/2)."
},
{
"code": null,
"e": 47421,
"s": 47161,
"text": "Optimized Dynamic Programming Approach: The above approach can further be optimized by using the concept Sieve of Eratosthenes to precompute and store whether a number is prime or not and reducing the time complexity to check for a number at every iteration. "
},
{
"code": null,
"e": 47474,
"s": 47421,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 47478,
"s": 47474,
"text": "C++"
},
{
"code": null,
"e": 47483,
"s": 47478,
"text": "Java"
},
{
"code": null,
"e": 47491,
"s": 47483,
"text": "Python3"
},
{
"code": null,
"e": 47494,
"s": 47491,
"text": "C#"
},
{
"code": null,
"e": 47505,
"s": 47494,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to precompute all the primes// upto 1000000 and store it in a set// using Sieve of Eratosthenesvoid getPrimesFromSeive(set<string>& primes){ bool prime[1000001]; memset(prime, true, sizeof(prime)); prime[0] = prime[1] = false; for (int i = 2; i * i <= 1000000; i++) { if (prime[i] == true) { for (int j = i * i; j <= 1000000; j += i) prime[j] = false; } } // Here to_string() is used // for converting int to string for (int i = 2; i <= 1000000; i++) { if (prime[i] == true) primes.insert(to_string(i)); }} // A function to find the minimum// number of segments the given string// can be divided such that every// segment is a primeint splitIntoPrimes(string number){ int numLen = number.length(); // Declare a splitdp[] array // and initialize to -1 int splitDP[numLen + 1]; memset(splitDP, -1, sizeof(splitDP)); // Call sieve function to store primes in // primes array set<string> primes; getPrimesFromSeive(primes); // Build the DP table in a bottom-up manner for (int i = 1; i <= numLen; i++) { // If the prefix is prime then the prefix // will be found in the prime set if (i <= 6 && (primes.find(number.substr(0, i)) != primes.end())) splitDP[i] = 1; // If the Given Prefix can be split into Primes // then for the remaining string from i to j // Check if Prime. If yes calculate // the minimum split till j if (splitDP[i] != -1) { for (int j = 1; j <= 6 && i + j <= numLen; j++) { // To check if the substring from i to j // is a prime number or not if (primes.find(number.substr(i, j)) != primes.end()) { // If it is a prime, then update the dp array if (splitDP[i + j] == -1) splitDP[i + j] = 1 + splitDP[i]; else splitDP[i + j] = min(splitDP[i + j], 1 + splitDP[i]); } } } } // Return the minimum number of splits // for the entire string return splitDP[numLen];} int main(){ cout << splitIntoPrimes(\"13499315\") << \"\\n\"; cout << splitIntoPrimes(\"43\") << \"\\n\"; return 0;}",
"e": 49979,
"s": 47505,
"text": null
},
{
"code": "// Java implementation of the above approach import java.util.*; class GFG{ // Function to precompute all the primes// upto 1000000 and store it in a set// using Sieve of Eratosthenesstatic void getPrimesFromSeive(HashSet<String> primes){ boolean []prime = new boolean[1000001]; Arrays.fill(prime, true); prime[0] = prime[1] = false; for (int i = 2; i * i <= 1000000; i++) { if (prime[i] == true) { for (int j = i * i; j <= 1000000; j += i) prime[j] = false; } } // Here to_String() is used // for converting int to String for (int i = 2; i <= 1000000; i++) { if (prime[i] == true) primes.add(String.valueOf(i)); }} // A function to find the minimum// number of segments the given String// can be divided such that every// segment is a primestatic int splitIntoPrimes(String number){ int numLen = number.length(); // Declare a splitdp[] array // and initialize to -1 int []splitDP = new int[numLen + 1]; Arrays.fill(splitDP, -1); // Call sieve function to store primes in // primes array HashSet<String> primes = new HashSet<String>(); getPrimesFromSeive(primes); // Build the DP table in a bottom-up manner for (int i = 1; i <= numLen; i++) { // If the prefix is prime then the prefix // will be found in the prime set if (i <= 6 && (primes.contains(number.substring(0, i)))) splitDP[i] = 1; // If the Given Prefix can be split into Primes // then for the remaining String from i to j // Check if Prime. If yes calculate // the minimum split till j if (splitDP[i] != -1) { for (int j = 1; j <= 6 && i + j <= numLen; j++) { // To check if the subString from i to j // is a prime number or not if (primes.contains(number.substring(i, i+j))) { // If it is a prime, then update the dp array if (splitDP[i + j] == -1) splitDP[i + j] = 1 + splitDP[i]; else splitDP[i + j] = Math.min(splitDP[i + j], 1 + splitDP[i]); } } } } // Return the minimum number of splits // for the entire String return splitDP[numLen];} public static void main(String[] args){ System.out.print(splitIntoPrimes(\"13499315\")+ \"\\n\"); System.out.print(splitIntoPrimes(\"43\")+ \"\\n\");}} // This code contributed by Princi Singh",
"e": 52530,
"s": 49979,
"text": null
},
{
"code": "# Python3 implementation of the above approach # Function to precompute all the primes# upto 1000000 and store it in a set# using Sieve of Eratosthenesdef getPrimesFromSeive(primes): prime = [True] * (1000001) prime[0], prime[1] = False, False i = 2 while (i * i <= 1000000): if (prime[i] == True): for j in range(i * i, 1000001, i): prime[j] = False i += 1 # Here str() is used for # converting int to string for i in range(2, 1000001): if (prime[i] == True): primes.append(str(i)) # A function to find the minimum# number of segments the given string# can be divided such that every# segment is a primedef splitIntoPrimes(number): numLen = len(number) # Declare a splitdp[] array # and initialize to -1 splitDP = [-1] * (numLen + 1) # Call sieve function to store # primes in primes array primes = [] getPrimesFromSeive(primes) # Build the DP table in a bottom-up manner for i in range(1, numLen + 1): # If the prefix is prime then the prefix # will be found in the prime set if (i <= 6 and (number[0 : i] in primes)): splitDP[i] = 1 # If the Given Prefix can be split into Primes # then for the remaining string from i to j # Check if Prime. If yes calculate # the minimum split till j if (splitDP[i] != -1): j = 1 while (j <= 6 and (i + j <= numLen)): # To check if the substring from i to j # is a prime number or not if (number[i : i + j] in primes): # If it is a prime, then # update the dp array if (splitDP[i + j] == -1): splitDP[i + j] = 1 + splitDP[i] else: splitDP[i + j] = min(splitDP[i + j], 1 + splitDP[i]) j += 1 # Return the minimum number of # splits for the entire string return splitDP[numLen] # Driver codeprint(splitIntoPrimes(\"13499315\"))print(splitIntoPrimes(\"43\")) # This code is contributed by chitranayal",
"e": 54747,
"s": 52530,
"text": null
},
{
"code": "// C# implementation of the above approachusing System;using System.Collections.Generic; class GFG{ // Function to precompute all the primes// upto 1000000 and store it in a set// using Sieve of Eratosthenesstatic void getPrimesFromSeive(HashSet<String> primes){ bool []prime = new bool[1000001]; for(int i = 0; i < 1000001; i++) prime[i] = true; prime[0] = prime[1] = false; for(int i = 2; i * i <= 1000000; i++) { if (prime[i] == true) { for(int j = i * i; j <= 1000000; j += i) prime[j] = false; } } // Converting int to String for(int i = 2; i <= 1000000; i++) { if (prime[i] == true) primes.Add(String.Join(\"\", i)); }} // A function to find the minimum// number of segments the given String// can be divided such that every// segment is a primestatic int splitIntoPrimes(String number){ int numLen = number.Length; // Declare a splitdp[] array // and initialize to -1 int []splitDP = new int[numLen + 1]; for(int i = 0; i < numLen + 1; i++) splitDP[i] = -1; // Call sieve function to store primes // in primes array HashSet<String> primes = new HashSet<String>(); getPrimesFromSeive(primes); // Build the DP table in a bottom-up manner for(int i = 1; i <= numLen; i++) { // If the prefix is prime then the prefix // will be found in the prime set if (i <= 6 && (primes.Contains (number.Substring(0, i)))) splitDP[i] = 1; // If the given prefix can be split into // primes, then for the remaining String // from i to j check if prime. If yes // calculate the minimum split till j if (splitDP[i] != -1) { for(int j = 1; j <= 6 && i + j <= numLen; j++) { // To check if the subString from // i to j is a prime number or not if (primes.Contains(number.Substring(i, j))) { // If it is a prime, then update // the dp array if (splitDP[i + j] == -1) splitDP[i + j] = 1 + splitDP[i]; else splitDP[i + j] = Math.Min(splitDP[i + j], 1 + splitDP[i]); } } } } // Return the minimum number of // splits for the entire String return splitDP[numLen];} public static void Main(String[] args){ Console.Write(splitIntoPrimes(\"13499315\") + \"\\n\"); Console.Write(splitIntoPrimes(\"43\") + \"\\n\");}} // This code is contributed by sapnasingh4991",
"e": 57430,
"s": 54747,
"text": null
},
{
"code": "<script>// Javascript implementation of the above approach // Function to precompute all the primes// upto 1000000 and store it in a set// using Sieve of Eratosthenesfunction getPrimesFromSeive(primes){ let prime = new Array(1000001); for(let i=0;i<prime.length;i++) { prime[i]=true; } prime[0] = prime[1] = false; for (let i = 2; i * i <= 1000000; i++) { if (prime[i] == true) { for (let j = i * i; j <= 1000000; j += i) prime[j] = false; } } // Here to_String() is used // for converting int to String for (let i = 2; i <= 1000000; i++) { if (prime[i] == true) primes.add((i).toString()); }} // A function to find the minimum// number of segments the given String// can be divided such that every// segment is a primefunction splitIntoPrimes(number){ let numLen = number.length; // Declare a splitdp[] array // and initialize to -1 let splitDP = new Array(numLen + 1); for(let i=0;i<splitDP.length;i++) { splitDP[i]=-1; } // Call sieve function to store primes in // primes array let primes = new Set(); getPrimesFromSeive(primes); // Build the DP table in a bottom-up manner for (let i = 1; i <= numLen; i++) { // If the prefix is prime then the prefix // will be found in the prime set if (i <= 6 && (primes.has(number.substring(0, i)))) splitDP[i] = 1; // If the Given Prefix can be split into Primes // then for the remaining String from i to j // Check if Prime. If yes calculate // the minimum split till j if (splitDP[i] != -1) { for (let j = 1; j <= 6 && i + j <= numLen; j++) { // To check if the subString from i to j // is a prime number or not if (primes.has(number.substring(i, i+j))) { // If it is a prime, then update the dp array if (splitDP[i + j] == -1) splitDP[i + j] = 1 + splitDP[i]; else splitDP[i + j] = Math.min(splitDP[i + j], 1 + splitDP[i]); } } } } // Return the minimum number of splits // for the entire String return splitDP[numLen];} document.write(splitIntoPrimes(\"13499315\")+ \"<br>\");document.write(splitIntoPrimes(\"43\")+ \"<br>\"); // This code is contributed by rag2127</script>",
"e": 59933,
"s": 57430,
"text": null
},
{
"code": null,
"e": 59937,
"s": 59933,
"text": "3\n1"
},
{
"code": null,
"e": 59957,
"s": 59939,
"text": "Time Complexity: "
},
{
"code": null,
"e": 60071,
"s": 59957,
"text": "This is the most efficient method as this runs in O(N) time complexity where N is the length of the input string."
},
{
"code": null,
"e": 60341,
"s": 60071,
"text": "Since the sieve of Eratosthenes has a run time of O(N*log(log(N))) and the list of primes up to 106, the precomputation complexity can be calculated. However, since this is performed only once for any number of strings, it is not counted in calculating time complexity."
},
{
"code": null,
"e": 60360,
"s": 60343,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 60370,
"s": 60360,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 60385,
"s": 60370,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 60398,
"s": 60385,
"text": "princi singh"
},
{
"code": null,
"e": 60404,
"s": 60398,
"text": "ukasp"
},
{
"code": null,
"e": 60412,
"s": 60404,
"text": "gfgking"
},
{
"code": null,
"e": 60433,
"s": 60412,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 60441,
"s": 60433,
"text": "rag2127"
},
{
"code": null,
"e": 60448,
"s": 60441,
"text": "Arrays"
},
{
"code": null,
"e": 60468,
"s": 60448,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 60476,
"s": 60468,
"text": "Strings"
},
{
"code": null,
"e": 60483,
"s": 60476,
"text": "Arrays"
},
{
"code": null,
"e": 60491,
"s": 60483,
"text": "Strings"
},
{
"code": null,
"e": 60511,
"s": 60491,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 60609,
"s": 60511,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 60677,
"s": 60609,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 60700,
"s": 60677,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 60732,
"s": 60700,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 60746,
"s": 60732,
"text": "Linear Search"
},
{
"code": null,
"e": 60767,
"s": 60746,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 60796,
"s": 60767,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 60826,
"s": 60796,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 60860,
"s": 60826,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 60891,
"s": 60860,
"text": "BellmanβFord Algorithm | DP-23"
}
] |
Creating a table in Cassandra - GeeksforGeeks
|
28 Apr, 2020
In this article, we are going to discuss how we can create a table in Cassandra and also discuss column definitions, keys role, Table options (compact storage and clustering order), etc.
In Cassandra, the CQL table has a name and it stores rows. when you create a table, you define the columns for the rows, a mandatory primary key to identify each row, column data type, and any other additional you may choose.
To create a table used βcreating a tableβ statement given below as following.
The following is a typical table creation statement.
Syntax: Creating a Table.
CREATE TABLE [ IF NOT EXISTS ] table_name
'('
column_definition
( ', ' column_definition )*
[ ', ' PRIMARY KEY '(' primary_key ')' ]
')' [ WITH table_options ]
Now, here you can use any existing keyspace such as named App_data.
use App_data;
Now, you can create table User_data in which Name, id, address are the fields in the table.
CREATE TABLE User_data (
Name text,
id uuid,
address text,
PRIMARY KEY (id)
);
Now, you can verify the table whether it is created or not, and if it is created then verify the table definition.By using existing keyspace such as App_data.
cassandra@cqlsh> use App_data;
cassandra@cqlsh:app_data>
cassandra@cqlsh:app_data> CREATE TABLE User_data (
... id uuid,
... Name text,
... address text,
... PRIMARY KEY (id)
... );
In Cassandra, A primary key consists of the first column or columns is the mandatory partition key, followed by one or more clustering columns.
COLUMN_DEFINITIONIn Cassandra, a column_definition clause consists of the name of the column and its type, as well as two modifiers.
Static: In Cassandra, a static column has the same value for all rows that share the same partition key (explained in a little bit). Of course, only non-primary keys can be static.
Primary key: A primary key uniquely identifies a row, and It is a good practice all tables must define a primary key.
Now, here you can verify the created table User_data.
cassandra@cqlsh:app_data> describe User_data;
CREATE TABLE app_data.user_data (
id uuid PRIMARY KEY,
address text,
name text
) WITH bloom_filter_fp_chance = 0.01
AND caching = {'keys': 'ALL', 'rows_per_partition': 'NONE'}
AND comment = ''
AND compaction =
{
'class': 'org.apache.cassandra.db.compaction
.SizeTieredCompactionStrategy',
'max_threshold': '32', 'min_threshold': '4'
}
AND compression = {'chunk_length_in_kb': '64',
'class': 'org.apache.cassandra.io
.compress.LZ4Compressor'}
AND crc_check_chance = 1.0
AND dclocal_read_repair_chance = 0.1
AND default_time_to_live = 0
AND gc_grace_seconds = 864000
AND max_index_interval = 2048
AND memtable_flush_period_in_ms = 0
AND min_index_interval = 128
AND read_repair_chance = 0.0
AND speculative_retry = '99PERCENTILE';
Apache
NoSQL
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matplotlib.pyplot.colors() in Python
Loops in R (for, while, repeat)
Object Oriented Analysis and Design
R Programming Language - Introduction
Matplotlib.pyplot.fill_between() in Python
Chat Bot in Python with ChatterBot Module
Time Durations in Golang
random.choices() method in Python
Simple Plot in Python using Matplotlib
How to get user location in Android
|
[
{
"code": null,
"e": 25889,
"s": 25861,
"text": "\n28 Apr, 2020"
},
{
"code": null,
"e": 26076,
"s": 25889,
"text": "In this article, we are going to discuss how we can create a table in Cassandra and also discuss column definitions, keys role, Table options (compact storage and clustering order), etc."
},
{
"code": null,
"e": 26302,
"s": 26076,
"text": "In Cassandra, the CQL table has a name and it stores rows. when you create a table, you define the columns for the rows, a mandatory primary key to identify each row, column data type, and any other additional you may choose."
},
{
"code": null,
"e": 26380,
"s": 26302,
"text": "To create a table used βcreating a tableβ statement given below as following."
},
{
"code": null,
"e": 26433,
"s": 26380,
"text": "The following is a typical table creation statement."
},
{
"code": null,
"e": 26621,
"s": 26433,
"text": "Syntax: Creating a Table.\n\nCREATE TABLE [ IF NOT EXISTS ] table_name\n'('\ncolumn_definition\n( ', ' column_definition )*\n[ ', ' PRIMARY KEY '(' primary_key ')' ]\n')' [ WITH table_options ] "
},
{
"code": null,
"e": 26689,
"s": 26621,
"text": "Now, here you can use any existing keyspace such as named App_data."
},
{
"code": null,
"e": 26703,
"s": 26689,
"text": "use App_data;"
},
{
"code": null,
"e": 26795,
"s": 26703,
"text": "Now, you can create table User_data in which Name, id, address are the fields in the table."
},
{
"code": null,
"e": 26954,
"s": 26795,
"text": "CREATE TABLE User_data (\n Name text,\n id uuid,\n address text,\n PRIMARY KEY (id)\n ); "
},
{
"code": null,
"e": 27113,
"s": 26954,
"text": "Now, you can verify the table whether it is created or not, and if it is created then verify the table definition.By using existing keyspace such as App_data."
},
{
"code": null,
"e": 27382,
"s": 27113,
"text": "cassandra@cqlsh> use App_data;\ncassandra@cqlsh:app_data> \n\ncassandra@cqlsh:app_data> CREATE TABLE User_data (\n ... id uuid,\n ... Name text,\n ... address text,\n ... PRIMARY KEY (id)\n ... ); "
},
{
"code": null,
"e": 27526,
"s": 27382,
"text": "In Cassandra, A primary key consists of the first column or columns is the mandatory partition key, followed by one or more clustering columns."
},
{
"code": null,
"e": 27659,
"s": 27526,
"text": "COLUMN_DEFINITIONIn Cassandra, a column_definition clause consists of the name of the column and its type, as well as two modifiers."
},
{
"code": null,
"e": 27840,
"s": 27659,
"text": "Static: In Cassandra, a static column has the same value for all rows that share the same partition key (explained in a little bit). Of course, only non-primary keys can be static."
},
{
"code": null,
"e": 27958,
"s": 27840,
"text": "Primary key: A primary key uniquely identifies a row, and It is a good practice all tables must define a primary key."
},
{
"code": null,
"e": 28012,
"s": 27958,
"text": "Now, here you can verify the created table User_data."
},
{
"code": null,
"e": 28972,
"s": 28012,
"text": "cassandra@cqlsh:app_data> describe User_data;\n\nCREATE TABLE app_data.user_data (\n id uuid PRIMARY KEY,\n address text,\n name text\n) WITH bloom_filter_fp_chance = 0.01\n AND caching = {'keys': 'ALL', 'rows_per_partition': 'NONE'}\n AND comment = ''\n AND compaction = \n {\n 'class': 'org.apache.cassandra.db.compaction\n .SizeTieredCompactionStrategy', \n 'max_threshold': '32', 'min_threshold': '4'\n }\n AND compression = {'chunk_length_in_kb': '64', \n 'class': 'org.apache.cassandra.io\n .compress.LZ4Compressor'}\n AND crc_check_chance = 1.0\n AND dclocal_read_repair_chance = 0.1\n AND default_time_to_live = 0\n AND gc_grace_seconds = 864000\n AND max_index_interval = 2048\n AND memtable_flush_period_in_ms = 0\n AND min_index_interval = 128\n AND read_repair_chance = 0.0\n AND speculative_retry = '99PERCENTILE'; "
},
{
"code": null,
"e": 28979,
"s": 28972,
"text": "Apache"
},
{
"code": null,
"e": 28985,
"s": 28979,
"text": "NoSQL"
},
{
"code": null,
"e": 29001,
"s": 28985,
"text": "Write From Home"
},
{
"code": null,
"e": 29099,
"s": 29001,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29136,
"s": 29099,
"text": "Matplotlib.pyplot.colors() in Python"
},
{
"code": null,
"e": 29168,
"s": 29136,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 29204,
"s": 29168,
"text": "Object Oriented Analysis and Design"
},
{
"code": null,
"e": 29242,
"s": 29204,
"text": "R Programming Language - Introduction"
},
{
"code": null,
"e": 29285,
"s": 29242,
"text": "Matplotlib.pyplot.fill_between() in Python"
},
{
"code": null,
"e": 29327,
"s": 29285,
"text": "Chat Bot in Python with ChatterBot Module"
},
{
"code": null,
"e": 29352,
"s": 29327,
"text": "Time Durations in Golang"
},
{
"code": null,
"e": 29386,
"s": 29352,
"text": "random.choices() method in Python"
},
{
"code": null,
"e": 29425,
"s": 29386,
"text": "Simple Plot in Python using Matplotlib"
}
] |
Replace every vowels with lexicographically next vowel in a String - GeeksforGeeks
|
06 May, 2022
Given string str of size N, which contains lowercase English alphabets. The task is to replace each vowel with the next immediate vowel lexicographically, i.e.,
βaβ will be replaced by βeβ, βeβ will be replaced by βiβ, βiβ will be replaced by βoβ, βoβ will be replaced by βuβ, βuβ will be replaced by βaβ.
Examples:
Input: str = βgeeksforgeeksβ Output: giiksfurgiiks Explanation: e is replace by i o is replace by u So final string will be βgiiksfurgiiksβ.
Input: str = βgfgβ Output: gfg
Approach: We will create a Hashing of size 5 to store all vowels so that the replacement can be done easily for each vowel.
Create a map and store all vowels.
Iterate the string elements from left to right.
It the string element is a vowel, then change it to the next vowels.
Finally, print the final string.
Here is the implementation of the above approach:
C++14
Java
Python3
C#
Javascript
// C++ program to convert all the vowels in// in the string to the next vowel #include <bits/stdc++.h>using namespace std; // Function to replace every vowel// with next vowel lexicographicallystring print_next_vovel_string(string str){ // Storing the vowels in the map with // custom numbers showing their index map<char, int> m; m['a'] = 0; m['e'] = 1; m['i'] = 2; m['o'] = 3; m['u'] = 4; char arr[5] = { 'a', 'e', 'i', 'o', 'u' }; int N = str.length(); // Iterate over the string for (int i = 0; i < N; i++) { char c = str[i]; // If the current character is a vowel // Find the index in Hash and // Replace it with next vowel from Hash if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { int index = m + 1; int newindex = index % 5; str[i] = arr[newindex]; } } return str;} // Driver functionint main(){ string str = "geeksforgeeks"; cout << print_next_vovel_string(str); return 0;}
// Java program to convert all the vowels in// in the String to the next vowelimport java.util.*; class GFG{ // Function to replace every vowel// with next vowel lexicographicallystatic String print_next_vovel_String(char []str){ // storing the vowels in the map with // custom numbers showing their index HashMap<Character, Integer> m = new HashMap<Character, Integer>(); m.put('a', 0); m.put('e', 1); m.put('i', 2); m.put('o', 3); m.put('u', 4); char arr[] = { 'a', 'e', 'i', 'o', 'u' }; int N = str.length; // Iterate over the String for(int i = 0; i < N; i++) { char c = str[i]; // If the current character is a vowel // Find the index in Hash and // Replace it with next vowel from Hash if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { int index = m.get(c) + 1; int newindex = index % 5; str[i] = arr[newindex]; } } return String.valueOf(str);} // Driver codepublic static void main(String[] args){ String str = "geeksforgeeks"; System.out.print(print_next_vovel_String( str.toCharArray()));}} // This code is contributed by Amit Katiyar
# Python3 program to convert# all the vowels in the string# to the next vowel # Function to replace every vowel# with next vowel lexicographicallydef print_next_vovel_string(st): # Storing the vowels in # the map with custom # numbers showing their index m = {} m['a'] = 0 m['e'] = 1 m['i'] = 2 m['o'] = 3 m['u'] = 4 arr = ['a', 'e', 'i', 'o', 'u'] N = len(st) # Iterate over the string for i in range (N): c = st[i] # If the current character # is a vowel # Find the index in Hash # and Replace it with next # vowel from Hash if (c == 'a' or c == 'e' or c == 'i'or c == 'o' or c == 'u'): index = m[st[i]] + 1 newindex = index % 5 st = st.replace(st[i], arr[newindex], 1) return st # Driver functionif __name__ == "__main__": st = "geeksforgeeks" print (print_next_vovel_string(st)) # This code is contributed by Chitranayal
// C# program to convert all the vowels in// in the String to the next vowelusing System;using System.Collections.Generic; class GFG{ // Function to replace every vowel// with next vowel lexicographicallystatic String print_next_vovel_String(char []str){ // Storing the vowels in the map with // custom numbers showing their index Dictionary<char, int> m = new Dictionary<char, int>(); m.Add('a', 0); m.Add('e', 1); m.Add('i', 2); m.Add('o', 3); m.Add('u', 4); char []arr = { 'a', 'e', 'i', 'o', 'u' }; int N = str.Length; // Iterate over the String for(int i = 0; i < N; i++) { char c = str[i]; // If the current character is a vowel // Find the index in Hash and // Replace it with next vowel from Hash if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { int index = m + 1; int newindex = index % 5; str[i] = arr[newindex]; } } return String.Join("", str);} // Driver codepublic static void Main(String[] args){ String str = "geeksforgeeks"; Console.Write(print_next_vovel_String( str.ToCharArray()));}} // This code is contributed by Amit Katiyar
<script> // JavaScript program to convert // all the vowels in the string // to the next vowel // Function to replace every vowel // with next vowel lexicographically function print_next_vovel_string(st) { // Storing the vowels in // the map with custom // numbers showing their index var m = {}; m["a"] = 0; m["e"] = 1; m["i"] = 2; m["o"] = 3; m["u"] = 4; var arr = ["a", "e", "i", "o", "u"]; var N = st.length; // Iterate over the string for (let i = 0; i < N; i++) { var c = st[i]; // If the current character // is a vowel // Find the index in Hash // and Replace it with next // vowel from Hash if (c === "a" || c === "e" || c === "i" || c === "o" || c === "u") { index = m[st[i]] + 1; newindex = index % 5; st = st.replace(st[i], arr[newindex]); } } return st; } // Driver function var st = "geeksforgeeks"; document.write(print_next_vovel_string(st)); </script>
giiksfurgiiks
Time Complexity: O (N) Auxiliary Space: O (1)
amit143katiyar
ukasp
rdtank
avtarkumar719
lexicographic-ordering
vowel-consonant
Arrays
Strings
Arrays
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Longest Common Subsequence | DP-4
Check for Balanced Brackets in an expression (well-formedness) using Stack
|
[
{
"code": null,
"e": 26066,
"s": 26038,
"text": "\n06 May, 2022"
},
{
"code": null,
"e": 26228,
"s": 26066,
"text": "Given string str of size N, which contains lowercase English alphabets. The task is to replace each vowel with the next immediate vowel lexicographically, i.e., "
},
{
"code": null,
"e": 26373,
"s": 26228,
"text": "βaβ will be replaced by βeβ, βeβ will be replaced by βiβ, βiβ will be replaced by βoβ, βoβ will be replaced by βuβ, βuβ will be replaced by βaβ."
},
{
"code": null,
"e": 26385,
"s": 26373,
"text": "Examples: "
},
{
"code": null,
"e": 26526,
"s": 26385,
"text": "Input: str = βgeeksforgeeksβ Output: giiksfurgiiks Explanation: e is replace by i o is replace by u So final string will be βgiiksfurgiiksβ."
},
{
"code": null,
"e": 26558,
"s": 26526,
"text": "Input: str = βgfgβ Output: gfg "
},
{
"code": null,
"e": 26683,
"s": 26558,
"text": "Approach: We will create a Hashing of size 5 to store all vowels so that the replacement can be done easily for each vowel. "
},
{
"code": null,
"e": 26718,
"s": 26683,
"text": "Create a map and store all vowels."
},
{
"code": null,
"e": 26766,
"s": 26718,
"text": "Iterate the string elements from left to right."
},
{
"code": null,
"e": 26835,
"s": 26766,
"text": "It the string element is a vowel, then change it to the next vowels."
},
{
"code": null,
"e": 26868,
"s": 26835,
"text": "Finally, print the final string."
},
{
"code": null,
"e": 26918,
"s": 26868,
"text": "Here is the implementation of the above approach:"
},
{
"code": null,
"e": 26924,
"s": 26918,
"text": "C++14"
},
{
"code": null,
"e": 26929,
"s": 26924,
"text": "Java"
},
{
"code": null,
"e": 26937,
"s": 26929,
"text": "Python3"
},
{
"code": null,
"e": 26940,
"s": 26937,
"text": "C#"
},
{
"code": null,
"e": 26951,
"s": 26940,
"text": "Javascript"
},
{
"code": "// C++ program to convert all the vowels in// in the string to the next vowel #include <bits/stdc++.h>using namespace std; // Function to replace every vowel// with next vowel lexicographicallystring print_next_vovel_string(string str){ // Storing the vowels in the map with // custom numbers showing their index map<char, int> m; m['a'] = 0; m['e'] = 1; m['i'] = 2; m['o'] = 3; m['u'] = 4; char arr[5] = { 'a', 'e', 'i', 'o', 'u' }; int N = str.length(); // Iterate over the string for (int i = 0; i < N; i++) { char c = str[i]; // If the current character is a vowel // Find the index in Hash and // Replace it with next vowel from Hash if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { int index = m + 1; int newindex = index % 5; str[i] = arr[newindex]; } } return str;} // Driver functionint main(){ string str = \"geeksforgeeks\"; cout << print_next_vovel_string(str); return 0;}",
"e": 27995,
"s": 26951,
"text": null
},
{
"code": "// Java program to convert all the vowels in// in the String to the next vowelimport java.util.*; class GFG{ // Function to replace every vowel// with next vowel lexicographicallystatic String print_next_vovel_String(char []str){ // storing the vowels in the map with // custom numbers showing their index HashMap<Character, Integer> m = new HashMap<Character, Integer>(); m.put('a', 0); m.put('e', 1); m.put('i', 2); m.put('o', 3); m.put('u', 4); char arr[] = { 'a', 'e', 'i', 'o', 'u' }; int N = str.length; // Iterate over the String for(int i = 0; i < N; i++) { char c = str[i]; // If the current character is a vowel // Find the index in Hash and // Replace it with next vowel from Hash if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { int index = m.get(c) + 1; int newindex = index % 5; str[i] = arr[newindex]; } } return String.valueOf(str);} // Driver codepublic static void main(String[] args){ String str = \"geeksforgeeks\"; System.out.print(print_next_vovel_String( str.toCharArray()));}} // This code is contributed by Amit Katiyar",
"e": 29281,
"s": 27995,
"text": null
},
{
"code": "# Python3 program to convert# all the vowels in the string# to the next vowel # Function to replace every vowel# with next vowel lexicographicallydef print_next_vovel_string(st): # Storing the vowels in # the map with custom # numbers showing their index m = {} m['a'] = 0 m['e'] = 1 m['i'] = 2 m['o'] = 3 m['u'] = 4 arr = ['a', 'e', 'i', 'o', 'u'] N = len(st) # Iterate over the string for i in range (N): c = st[i] # If the current character # is a vowel # Find the index in Hash # and Replace it with next # vowel from Hash if (c == 'a' or c == 'e' or c == 'i'or c == 'o' or c == 'u'): index = m[st[i]] + 1 newindex = index % 5 st = st.replace(st[i], arr[newindex], 1) return st # Driver functionif __name__ == \"__main__\": st = \"geeksforgeeks\" print (print_next_vovel_string(st)) # This code is contributed by Chitranayal",
"e": 30279,
"s": 29281,
"text": null
},
{
"code": "// C# program to convert all the vowels in// in the String to the next vowelusing System;using System.Collections.Generic; class GFG{ // Function to replace every vowel// with next vowel lexicographicallystatic String print_next_vovel_String(char []str){ // Storing the vowels in the map with // custom numbers showing their index Dictionary<char, int> m = new Dictionary<char, int>(); m.Add('a', 0); m.Add('e', 1); m.Add('i', 2); m.Add('o', 3); m.Add('u', 4); char []arr = { 'a', 'e', 'i', 'o', 'u' }; int N = str.Length; // Iterate over the String for(int i = 0; i < N; i++) { char c = str[i]; // If the current character is a vowel // Find the index in Hash and // Replace it with next vowel from Hash if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { int index = m + 1; int newindex = index % 5; str[i] = arr[newindex]; } } return String.Join(\"\", str);} // Driver codepublic static void Main(String[] args){ String str = \"geeksforgeeks\"; Console.Write(print_next_vovel_String( str.ToCharArray()));}} // This code is contributed by Amit Katiyar",
"e": 31576,
"s": 30279,
"text": null
},
{
"code": "<script> // JavaScript program to convert // all the vowels in the string // to the next vowel // Function to replace every vowel // with next vowel lexicographically function print_next_vovel_string(st) { // Storing the vowels in // the map with custom // numbers showing their index var m = {}; m[\"a\"] = 0; m[\"e\"] = 1; m[\"i\"] = 2; m[\"o\"] = 3; m[\"u\"] = 4; var arr = [\"a\", \"e\", \"i\", \"o\", \"u\"]; var N = st.length; // Iterate over the string for (let i = 0; i < N; i++) { var c = st[i]; // If the current character // is a vowel // Find the index in Hash // and Replace it with next // vowel from Hash if (c === \"a\" || c === \"e\" || c === \"i\" || c === \"o\" || c === \"u\") { index = m[st[i]] + 1; newindex = index % 5; st = st.replace(st[i], arr[newindex]); } } return st; } // Driver function var st = \"geeksforgeeks\"; document.write(print_next_vovel_string(st)); </script>",
"e": 32712,
"s": 31576,
"text": null
},
{
"code": null,
"e": 32726,
"s": 32712,
"text": "giiksfurgiiks"
},
{
"code": null,
"e": 32774,
"s": 32728,
"text": "Time Complexity: O (N) Auxiliary Space: O (1)"
},
{
"code": null,
"e": 32789,
"s": 32774,
"text": "amit143katiyar"
},
{
"code": null,
"e": 32795,
"s": 32789,
"text": "ukasp"
},
{
"code": null,
"e": 32802,
"s": 32795,
"text": "rdtank"
},
{
"code": null,
"e": 32816,
"s": 32802,
"text": "avtarkumar719"
},
{
"code": null,
"e": 32839,
"s": 32816,
"text": "lexicographic-ordering"
},
{
"code": null,
"e": 32855,
"s": 32839,
"text": "vowel-consonant"
},
{
"code": null,
"e": 32862,
"s": 32855,
"text": "Arrays"
},
{
"code": null,
"e": 32870,
"s": 32862,
"text": "Strings"
},
{
"code": null,
"e": 32877,
"s": 32870,
"text": "Arrays"
},
{
"code": null,
"e": 32885,
"s": 32877,
"text": "Strings"
},
{
"code": null,
"e": 32983,
"s": 32885,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33010,
"s": 32983,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 33041,
"s": 33010,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 33066,
"s": 33041,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 33104,
"s": 33066,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 33125,
"s": 33104,
"text": "Next Greater Element"
},
{
"code": null,
"e": 33150,
"s": 33125,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 33210,
"s": 33150,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 33225,
"s": 33210,
"text": "C++ Data Types"
},
{
"code": null,
"e": 33259,
"s": 33225,
"text": "Longest Common Subsequence | DP-4"
}
] |
Java 8 | Arrays parallelSort() method with Examples - GeeksforGeeks
|
11 Dec, 2018
Java 8 introduced a new method called as parallelSort() in java.util.Arrays Class. It uses Parallel Sorting of array elements
Algorithm of parallelSort()
1. The array is divided into sub-arrays and that
sub-arrays is again divided into their sub-arrays,
until the minimum level of detail in a set of array.
2. Arrays are sorted individually by multiple thread.
3. The parallel sort uses Fork/Join Concept for sorting.
4. Sorted sub-arrays are then merged.
Syntax :
For sorting data in ascending order :public static void parallelSort(Object obj[])
For sorting data in specified range in ascending order :public static void parallelSort(Object obj[], int from, int to)
For sorting data in ascending order :public static void parallelSort(Object obj[])
For sorting data in specified range in ascending order :public static void parallelSort(Object obj[], int from, int to)
public static void parallelSort(Object obj[])
For sorting data in specified range in ascending order :public static void parallelSort(Object obj[], int from, int to)
For sorting data in specified range in ascending order :public static void parallelSort(Object obj[], int from, int to)
public static void parallelSort(Object obj[], int from, int to)
Advantage :parallelSort() method uses concept of MultiThreading which makes the sorting faster as compared to normal sorting method.
Example
Below are the program that will illustrate the use of Arrays.parallelSort():
Program 1: To demonstrate use of Parallel Sort
// Java program to demonstrate// Arrays.parallelSort() method import java.util.Arrays; public class ParallelSort { public static void main(String[] args) { // Creating an array int numbers[] = { 9, 8, 7, 6, 3, 1 }; // Printing unsorted Array System.out.print("Unsorted Array: "); // Iterating the Elements using stream Arrays.stream(numbers) .forEach(n -> System.out.print(n + " ")); System.out.println(); // Using Arrays.parallelSort() Arrays.parallelSort(numbers); // Printing sorted Array System.out.print("Sorted Array: "); // Iterating the Elements using stream Arrays.stream(numbers) .forEach(n -> System.out.print(n + " ")); }}
Unsorted Array: 9 8 7 6 3 1
Sorted Array: 1 3 6 7 8 9
Time Complexity is O(nlogn)
Program 2: To demonstrate use of Parallel Sort w.r.t. Series Sort (Normal Sort)
// Java program to demonstrate impact // of Parallel Sort vs Serial Sort import java.util.Arrays; import java.util.Random; public class ParallelSort { public static void main(String[] args) { // Creating an array int numbers[] = new int[100]; // Iterating Loop till i = 1000 // with interval of 10 for (int i = 0; i < 1000; i += 10) { System.out.println("\nFor iteration number: " + (i / 10 + 1)); // Random Int Array Generation Random rand = new Random(); for (int j = 0; j < 100; j++) { numbers[j] = rand.nextInt(); } // Start and End Time of Arrays.sort() long startTime = System.nanoTime(); // Performing Serial Sort Arrays.sort(numbers); long endTime = System.nanoTime(); // Printing result of Serial Sort System.out.println("Start and End Time in Serial (in ns): " + startTime + ":" + endTime); System.out.println("Time taken by Serial Sort(in ns): " + (endTime - startTime)); // Start and End Time of Arrays.parallelSort() startTime = System.nanoTime(); // Performing Parallel Sort Arrays.parallelSort(numbers); endTime = System.nanoTime(); // Printing result of Parallel Sort System.out.println("Start and End Time in parallel (in ns): " + startTime + ":" + endTime); System.out.println("Time taken by Parallel Sort(in ns): " + (endTime - startTime)); System.out.println(); } } }
For iteration number: 1
Start and End Time in Serial (in ns): 3951000637977:3951000870361
Time taken by Serial Sort(in ns): 232384
Start and End Time in parallel (in ns): 3951000960823:3951000971044
Time taken by Parallel Sort(in ns): 10221
For iteration number: 2
Start and End Time in Serial (in ns): 3951001142284:3951001201757
Time taken by Serial Sort(in ns): 59473
Start and End Time in parallel (in ns): 3951001256643:3951001264039
Time taken by Parallel Sort(in ns): 7396
.
.
.
For iteration number: 99
Start and End Time in Serial (in ns): 3951050723541:3951050731520
Time taken by Serial Sort(in ns): 7979
Start and End Time in parallel (in ns): 3951050754238:3951050756130
Time taken by Parallel Sort(in ns): 1892
For iteration number: 100
Start and End Time in Serial (in ns): 3951050798392:3951050804741
Time taken by Serial Sort(in ns): 6349
Start and End Time in parallel (in ns): 3951050828544:3951050830582
Time taken by Parallel Sort(in ns): 2038
Note : Different time intervals will be printed But parallel sort will be done before normal sort.
Environment: 2.6 GHz Intel Core i7, java version 8
Java-Arrays
java-basics
Java-Functions
Sorting Quiz
Divide and Conquer
Java
Java Programs
Recursion
Sorting
Recursion
Divide and Conquer
Sorting
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for Tower of Hanoi
Divide and Conquer Algorithm | Introduction
Median of two sorted arrays of different sizes
Write a program to calculate pow(x,n)
Count number of occurrences (or frequency) in a sorted array
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Arrays.sort() in Java with examples
|
[
{
"code": null,
"e": 25357,
"s": 25329,
"text": "\n11 Dec, 2018"
},
{
"code": null,
"e": 25483,
"s": 25357,
"text": "Java 8 introduced a new method called as parallelSort() in java.util.Arrays Class. It uses Parallel Sorting of array elements"
},
{
"code": null,
"e": 25511,
"s": 25483,
"text": "Algorithm of parallelSort()"
},
{
"code": null,
"e": 25822,
"s": 25511,
"text": "1. The array is divided into sub-arrays and that \n sub-arrays is again divided into their sub-arrays, \n until the minimum level of detail in a set of array.\n2. Arrays are sorted individually by multiple thread. \n3. The parallel sort uses Fork/Join Concept for sorting.\n4. Sorted sub-arrays are then merged."
},
{
"code": null,
"e": 25831,
"s": 25822,
"text": "Syntax :"
},
{
"code": null,
"e": 26039,
"s": 25831,
"text": "For sorting data in ascending order :public static void parallelSort(Object obj[])\n\n For sorting data in specified range in ascending order :public static void parallelSort(Object obj[], int from, int to)"
},
{
"code": null,
"e": 26247,
"s": 26039,
"text": "For sorting data in ascending order :public static void parallelSort(Object obj[])\n\n For sorting data in specified range in ascending order :public static void parallelSort(Object obj[], int from, int to)"
},
{
"code": null,
"e": 26418,
"s": 26247,
"text": "public static void parallelSort(Object obj[])\n\n For sorting data in specified range in ascending order :public static void parallelSort(Object obj[], int from, int to)"
},
{
"code": null,
"e": 26538,
"s": 26418,
"text": "For sorting data in specified range in ascending order :public static void parallelSort(Object obj[], int from, int to)"
},
{
"code": null,
"e": 26602,
"s": 26538,
"text": "public static void parallelSort(Object obj[], int from, int to)"
},
{
"code": null,
"e": 26735,
"s": 26602,
"text": "Advantage :parallelSort() method uses concept of MultiThreading which makes the sorting faster as compared to normal sorting method."
},
{
"code": null,
"e": 26743,
"s": 26735,
"text": "Example"
},
{
"code": null,
"e": 26820,
"s": 26743,
"text": "Below are the program that will illustrate the use of Arrays.parallelSort():"
},
{
"code": null,
"e": 26867,
"s": 26820,
"text": "Program 1: To demonstrate use of Parallel Sort"
},
{
"code": "// Java program to demonstrate// Arrays.parallelSort() method import java.util.Arrays; public class ParallelSort { public static void main(String[] args) { // Creating an array int numbers[] = { 9, 8, 7, 6, 3, 1 }; // Printing unsorted Array System.out.print(\"Unsorted Array: \"); // Iterating the Elements using stream Arrays.stream(numbers) .forEach(n -> System.out.print(n + \" \")); System.out.println(); // Using Arrays.parallelSort() Arrays.parallelSort(numbers); // Printing sorted Array System.out.print(\"Sorted Array: \"); // Iterating the Elements using stream Arrays.stream(numbers) .forEach(n -> System.out.print(n + \" \")); }}",
"e": 27632,
"s": 26867,
"text": null
},
{
"code": null,
"e": 27688,
"s": 27632,
"text": "Unsorted Array: 9 8 7 6 3 1 \nSorted Array: 1 3 6 7 8 9\n"
},
{
"code": null,
"e": 27716,
"s": 27688,
"text": "Time Complexity is O(nlogn)"
},
{
"code": null,
"e": 27796,
"s": 27716,
"text": "Program 2: To demonstrate use of Parallel Sort w.r.t. Series Sort (Normal Sort)"
},
{
"code": "// Java program to demonstrate impact // of Parallel Sort vs Serial Sort import java.util.Arrays; import java.util.Random; public class ParallelSort { public static void main(String[] args) { // Creating an array int numbers[] = new int[100]; // Iterating Loop till i = 1000 // with interval of 10 for (int i = 0; i < 1000; i += 10) { System.out.println(\"\\nFor iteration number: \" + (i / 10 + 1)); // Random Int Array Generation Random rand = new Random(); for (int j = 0; j < 100; j++) { numbers[j] = rand.nextInt(); } // Start and End Time of Arrays.sort() long startTime = System.nanoTime(); // Performing Serial Sort Arrays.sort(numbers); long endTime = System.nanoTime(); // Printing result of Serial Sort System.out.println(\"Start and End Time in Serial (in ns): \" + startTime + \":\" + endTime); System.out.println(\"Time taken by Serial Sort(in ns): \" + (endTime - startTime)); // Start and End Time of Arrays.parallelSort() startTime = System.nanoTime(); // Performing Parallel Sort Arrays.parallelSort(numbers); endTime = System.nanoTime(); // Printing result of Parallel Sort System.out.println(\"Start and End Time in parallel (in ns): \" + startTime + \":\" + endTime); System.out.println(\"Time taken by Parallel Sort(in ns): \" + (endTime - startTime)); System.out.println(); } } } ",
"e": 29588,
"s": 27796,
"text": null
},
{
"code": null,
"e": 30558,
"s": 29588,
"text": "For iteration number: 1\nStart and End Time in Serial (in ns): 3951000637977:3951000870361\nTime taken by Serial Sort(in ns): 232384\nStart and End Time in parallel (in ns): 3951000960823:3951000971044\nTime taken by Parallel Sort(in ns): 10221\n\n\nFor iteration number: 2\nStart and End Time in Serial (in ns): 3951001142284:3951001201757\nTime taken by Serial Sort(in ns): 59473\nStart and End Time in parallel (in ns): 3951001256643:3951001264039\nTime taken by Parallel Sort(in ns): 7396\n.\n.\n.\nFor iteration number: 99\nStart and End Time in Serial (in ns): 3951050723541:3951050731520\nTime taken by Serial Sort(in ns): 7979\nStart and End Time in parallel (in ns): 3951050754238:3951050756130\nTime taken by Parallel Sort(in ns): 1892\n\n\nFor iteration number: 100\nStart and End Time in Serial (in ns): 3951050798392:3951050804741\nTime taken by Serial Sort(in ns): 6349\nStart and End Time in parallel (in ns): 3951050828544:3951050830582\nTime taken by Parallel Sort(in ns): 2038\n"
},
{
"code": null,
"e": 30657,
"s": 30558,
"text": "Note : Different time intervals will be printed But parallel sort will be done before normal sort."
},
{
"code": null,
"e": 30708,
"s": 30657,
"text": "Environment: 2.6 GHz Intel Core i7, java version 8"
},
{
"code": null,
"e": 30720,
"s": 30708,
"text": "Java-Arrays"
},
{
"code": null,
"e": 30732,
"s": 30720,
"text": "java-basics"
},
{
"code": null,
"e": 30747,
"s": 30732,
"text": "Java-Functions"
},
{
"code": null,
"e": 30760,
"s": 30747,
"text": "Sorting Quiz"
},
{
"code": null,
"e": 30779,
"s": 30760,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 30784,
"s": 30779,
"text": "Java"
},
{
"code": null,
"e": 30798,
"s": 30784,
"text": "Java Programs"
},
{
"code": null,
"e": 30808,
"s": 30798,
"text": "Recursion"
},
{
"code": null,
"e": 30816,
"s": 30808,
"text": "Sorting"
},
{
"code": null,
"e": 30826,
"s": 30816,
"text": "Recursion"
},
{
"code": null,
"e": 30845,
"s": 30826,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 30853,
"s": 30845,
"text": "Sorting"
},
{
"code": null,
"e": 30858,
"s": 30853,
"text": "Java"
},
{
"code": null,
"e": 30956,
"s": 30858,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30983,
"s": 30956,
"text": "Program for Tower of Hanoi"
},
{
"code": null,
"e": 31027,
"s": 30983,
"text": "Divide and Conquer Algorithm | Introduction"
},
{
"code": null,
"e": 31074,
"s": 31027,
"text": "Median of two sorted arrays of different sizes"
},
{
"code": null,
"e": 31112,
"s": 31074,
"text": "Write a program to calculate pow(x,n)"
},
{
"code": null,
"e": 31173,
"s": 31112,
"text": "Count number of occurrences (or frequency) in a sorted array"
},
{
"code": null,
"e": 31188,
"s": 31173,
"text": "Arrays in Java"
},
{
"code": null,
"e": 31232,
"s": 31188,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 31254,
"s": 31232,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 31305,
"s": 31254,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
How to find length of dictionary values? - GeeksforGeeks
|
10 May, 2020
In Python, Dictionary is a collection of unordered data values. Dictionaries are also changeable and indexed. Dictionary holds key:value pair and they are written inside curly brackets. Each key:value pair maps the key to its associated value.
Here we use isinstance() method to check the type of the value whether it is a list, int, str, tuple, etc. isinstance() method which is an inbuilt method in Python. It returns a boolean if the object passed is an instance of the given class or not.
Letβs discuss different methods to find the length of dictionary values.
Note: In the below methods the length of the string value is takes as one.
Method #1 Using in operator
Example: 1
# Python program to find the # length of dictionary values def main(): # Defining the dictionary dict1 = {'a':[1, 2, 3], 'b'1, 2, 3), 'c':5, 'd':"nopqrs", 'e':["A", "B", "C"]} # Initialize count count = 0 # using in operator for k in dict1: # Check the type of value # is int or not if isinstance(dict1[k], int): count += 1 # Check the type of value # is str or not elif isinstance(dict1[k], str): count += 1 else: count += len(dict1[k]) print("The total length of value is:", count) # Driver Codeif __name__ == '__main__': main()
Output:
The total length of value is: 11
Example :2
# Python program to find the# length of dictionary values def main(): # Defining the dictionary dict1 = {'A':"abcd", 'B':set([1, 2, 3]), 'C'12, "number"), 'D':[1, 2, 4, 5, 5, 5]} # Create a empty dictionary dict2 = {} # using in operator for k in dict1: # Check the type of value # is int or not if isinstance(dict1[k], int): dict2[k] = 1 # Check the type of value # is str or not elif isinstance(dict1[k], str): dict2[k] = 1 else: dict2[k] = len(dict1[k]) print("The length of values associated\ with their keys are:", dict2) print("The length of value associated\ with key 'B' is:", dict2['B']) # Driver Codeif __name__ == '__main__': main()
Output:
The length of values associated with their keys are: {βAβ: 1, βBβ: 3, βCβ: 2, βDβ: 6}The length of value associated with key βBβ is: 3
Method #2 Using list comprehension
# Python program to find the # length of dictionary values def main(): # Defining the dictionary dict1 = {'a':[1, 2, 3], 'b'1, 2, 3), 'c':5, 'd':"nopqrs", 'e':["A", "B", "C"]} # using list comprehension count = sum([1 if isinstance(dict1[k], (str, int)) else len(dict1[k]) for k in dict1]) print("The total length of values is:", count) # Driver Codeif __name__ == '__main__': main()
Output:
The total length of values is: 11
Method #3 Using dictionary Comprehension
# Python program to find the # length of dictionary values def main(): # Defining the dictionary dict1 = {'A': "abcd", 'B': set([1, 2, 3]), 'C': (12, "number"), 'D': [1, 2, 4, 5, 5, 5]} # using dictionary comprehension dict2 = {k:1 if isinstance(dict1[k], (str, int)) else len(dict1[k]) for k in dict1} print("The length of values associated \ with their keys are:", dict2) print("The length of value associated \ with key 'B' is:", dict2['B']) # Driver Codeif __name__ == '__main__': main()
Output:
The length of values associated with their keys are: {βAβ: 1, βBβ: 3, βCβ: 2, βDβ: 6}The length of value associated with key βBβ is: 3
Method #4 Using dict.items()
Example :1
# Python program to find the# length of dictionary values def main(): # Defining the dictionary dict1 = {'a':[1, 2, 3], 'b'1, 2, 3), 'c':5, 'd':"nopqrs", 'e':["A", "B", "C"]} # Initialize count count = 0 # using dict.items() for key, val in dict1.items(): # Check the type of value # is int or not if isinstance(val, int): count += 1 # Check the type of value # is str or not elif isinstance(val, str): count += 1 else: count += len(val) print("The total length of value is:", count) # Driver codeif __name__ == '__main__': main()
Output:
The total length of values is: 11
Example :2
# Python program to find the# length of dictionary values def main(): # Defining the dictionary dict1 = {'A': "abcd", 'B': set([1, 2, 3]), 'C': (12, "number"), 'D': [1, 2, 4, 5, 5, 5]} # Create a empty dictionary dict2 = {} # using dict.items() for key, val in dict1.items(): # Check the type of value # is int or not if isinstance(val, int): dict2[key] = 1 # Check the type of value # is str or not elif isinstance(val, str): dict2[key] = 1 else: dict2[key] = len(val) print("The length of values associated \ with their keys are:", dict2) print("The length of value associated \ with key 'B' is:", dict2['B']) # Driver Codeif __name__ == '__main__': main()
Output:
The length of values associated with their keys are: {βAβ: 1, βBβ: 3, βCβ: 2, βDβ: 6}The length of value associated with key βBβ is: 3
Method #5 Using enumerate()
Example :1
# Python program to find the# length of dictionary values def main(): # Defining the dictionary dict1 = {'a':[1, 2, 3], 'b'1, 2, 3), 'c':5, 'd':"nopqrs", 'e':["A", "B", "C"]} # Initialize count count = 0 # using enumerate() for k in enumerate(dict1.items()): # Check the type of value # is int or not if isinstance(k[1][1], int): count += 1 # Check the type of value # is str or not elif isinstance(k[1][1], str): count += 1 else: count += len(k[1][1]) print("The total length of value is:", count) # Driver Codeif __name__ == '__main__': main()
Output:
The total length of value is: 11
Example :2
# Python program to find the# length of dictionary values def main(): # Defining the dictionary dict1 = {'A': "abcd", 'B': set([1, 2, 3]), 'C': (12, "number"), 'D': [1, 2, 4, 5, 5, 5]} # Create a empty dictionary dict2 = {} # using enumerate() for k in enumerate(dict1.items()): # Check the type of value # is int or not if isinstance(k[1][1], int): dict2[k[1][0]] = 1 # Check the type of value # is str or not elif isinstance(k[1][1], str): dict2[k[1][0]] = 1 else: dict2[k[1][0]] = len(k[1][1]) print("The length of values associated\ with their keys are:", dict2) print("The length of value associated \ with key 'B' is:", dict2['B']) # Driver Codeif __name__ == '__main__': main()
Output:
The length of values associated with their keys are: {βAβ: 1, βBβ: 3, βCβ: 2, βDβ: 6}The length of value associated with key βBβ is: 3
python-dict
Python
python-dict
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": 26057,
"s": 26029,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 26301,
"s": 26057,
"text": "In Python, Dictionary is a collection of unordered data values. Dictionaries are also changeable and indexed. Dictionary holds key:value pair and they are written inside curly brackets. Each key:value pair maps the key to its associated value."
},
{
"code": null,
"e": 26550,
"s": 26301,
"text": "Here we use isinstance() method to check the type of the value whether it is a list, int, str, tuple, etc. isinstance() method which is an inbuilt method in Python. It returns a boolean if the object passed is an instance of the given class or not."
},
{
"code": null,
"e": 26623,
"s": 26550,
"text": "Letβs discuss different methods to find the length of dictionary values."
},
{
"code": null,
"e": 26698,
"s": 26623,
"text": "Note: In the below methods the length of the string value is takes as one."
},
{
"code": null,
"e": 26726,
"s": 26698,
"text": "Method #1 Using in operator"
},
{
"code": null,
"e": 26737,
"s": 26726,
"text": "Example: 1"
},
{
"code": "# Python program to find the # length of dictionary values def main(): # Defining the dictionary dict1 = {'a':[1, 2, 3], 'b'1, 2, 3), 'c':5, 'd':\"nopqrs\", 'e':[\"A\", \"B\", \"C\"]} # Initialize count count = 0 # using in operator for k in dict1: # Check the type of value # is int or not if isinstance(dict1[k], int): count += 1 # Check the type of value # is str or not elif isinstance(dict1[k], str): count += 1 else: count += len(dict1[k]) print(\"The total length of value is:\", count) # Driver Codeif __name__ == '__main__': main()",
"e": 27472,
"s": 26737,
"text": null
},
{
"code": null,
"e": 27480,
"s": 27472,
"text": "Output:"
},
{
"code": null,
"e": 27513,
"s": 27480,
"text": "The total length of value is: 11"
},
{
"code": null,
"e": 27524,
"s": 27513,
"text": "Example :2"
},
{
"code": "# Python program to find the# length of dictionary values def main(): # Defining the dictionary dict1 = {'A':\"abcd\", 'B':set([1, 2, 3]), 'C'12, \"number\"), 'D':[1, 2, 4, 5, 5, 5]} # Create a empty dictionary dict2 = {} # using in operator for k in dict1: # Check the type of value # is int or not if isinstance(dict1[k], int): dict2[k] = 1 # Check the type of value # is str or not elif isinstance(dict1[k], str): dict2[k] = 1 else: dict2[k] = len(dict1[k]) print(\"The length of values associated\\ with their keys are:\", dict2) print(\"The length of value associated\\ with key 'B' is:\", dict2['B']) # Driver Codeif __name__ == '__main__': main()",
"e": 28380,
"s": 27524,
"text": null
},
{
"code": null,
"e": 28388,
"s": 28380,
"text": "Output:"
},
{
"code": null,
"e": 28523,
"s": 28388,
"text": "The length of values associated with their keys are: {βAβ: 1, βBβ: 3, βCβ: 2, βDβ: 6}The length of value associated with key βBβ is: 3"
},
{
"code": null,
"e": 28558,
"s": 28523,
"text": "Method #2 Using list comprehension"
},
{
"code": "# Python program to find the # length of dictionary values def main(): # Defining the dictionary dict1 = {'a':[1, 2, 3], 'b'1, 2, 3), 'c':5, 'd':\"nopqrs\", 'e':[\"A\", \"B\", \"C\"]} # using list comprehension count = sum([1 if isinstance(dict1[k], (str, int)) else len(dict1[k]) for k in dict1]) print(\"The total length of values is:\", count) # Driver Codeif __name__ == '__main__': main()",
"e": 29057,
"s": 28558,
"text": null
},
{
"code": null,
"e": 29065,
"s": 29057,
"text": "Output:"
},
{
"code": null,
"e": 29099,
"s": 29065,
"text": "The total length of values is: 11"
},
{
"code": null,
"e": 29140,
"s": 29099,
"text": "Method #3 Using dictionary Comprehension"
},
{
"code": "# Python program to find the # length of dictionary values def main(): # Defining the dictionary dict1 = {'A': \"abcd\", 'B': set([1, 2, 3]), 'C': (12, \"number\"), 'D': [1, 2, 4, 5, 5, 5]} # using dictionary comprehension dict2 = {k:1 if isinstance(dict1[k], (str, int)) else len(dict1[k]) for k in dict1} print(\"The length of values associated \\ with their keys are:\", dict2) print(\"The length of value associated \\ with key 'B' is:\", dict2['B']) # Driver Codeif __name__ == '__main__': main()",
"e": 29744,
"s": 29140,
"text": null
},
{
"code": null,
"e": 29752,
"s": 29744,
"text": "Output:"
},
{
"code": null,
"e": 29887,
"s": 29752,
"text": "The length of values associated with their keys are: {βAβ: 1, βBβ: 3, βCβ: 2, βDβ: 6}The length of value associated with key βBβ is: 3"
},
{
"code": null,
"e": 29916,
"s": 29887,
"text": "Method #4 Using dict.items()"
},
{
"code": null,
"e": 29927,
"s": 29916,
"text": "Example :1"
},
{
"code": "# Python program to find the# length of dictionary values def main(): # Defining the dictionary dict1 = {'a':[1, 2, 3], 'b'1, 2, 3), 'c':5, 'd':\"nopqrs\", 'e':[\"A\", \"B\", \"C\"]} # Initialize count count = 0 # using dict.items() for key, val in dict1.items(): # Check the type of value # is int or not if isinstance(val, int): count += 1 # Check the type of value # is str or not elif isinstance(val, str): count += 1 else: count += len(val) print(\"The total length of value is:\", count) # Driver codeif __name__ == '__main__': main()",
"e": 30654,
"s": 29927,
"text": null
},
{
"code": null,
"e": 30662,
"s": 30654,
"text": "Output:"
},
{
"code": null,
"e": 30697,
"s": 30662,
"text": "The total length of values is: 11\n"
},
{
"code": null,
"e": 30708,
"s": 30697,
"text": "Example :2"
},
{
"code": "# Python program to find the# length of dictionary values def main(): # Defining the dictionary dict1 = {'A': \"abcd\", 'B': set([1, 2, 3]), 'C': (12, \"number\"), 'D': [1, 2, 4, 5, 5, 5]} # Create a empty dictionary dict2 = {} # using dict.items() for key, val in dict1.items(): # Check the type of value # is int or not if isinstance(val, int): dict2[key] = 1 # Check the type of value # is str or not elif isinstance(val, str): dict2[key] = 1 else: dict2[key] = len(val) print(\"The length of values associated \\ with their keys are:\", dict2) print(\"The length of value associated \\ with key 'B' is:\", dict2['B']) # Driver Codeif __name__ == '__main__': main()",
"e": 31563,
"s": 30708,
"text": null
},
{
"code": null,
"e": 31571,
"s": 31563,
"text": "Output:"
},
{
"code": null,
"e": 31706,
"s": 31571,
"text": "The length of values associated with their keys are: {βAβ: 1, βBβ: 3, βCβ: 2, βDβ: 6}The length of value associated with key βBβ is: 3"
},
{
"code": null,
"e": 31734,
"s": 31706,
"text": "Method #5 Using enumerate()"
},
{
"code": null,
"e": 31745,
"s": 31734,
"text": "Example :1"
},
{
"code": "# Python program to find the# length of dictionary values def main(): # Defining the dictionary dict1 = {'a':[1, 2, 3], 'b'1, 2, 3), 'c':5, 'd':\"nopqrs\", 'e':[\"A\", \"B\", \"C\"]} # Initialize count count = 0 # using enumerate() for k in enumerate(dict1.items()): # Check the type of value # is int or not if isinstance(k[1][1], int): count += 1 # Check the type of value # is str or not elif isinstance(k[1][1], str): count += 1 else: count += len(k[1][1]) print(\"The total length of value is:\", count) # Driver Codeif __name__ == '__main__': main()",
"e": 32507,
"s": 31745,
"text": null
},
{
"code": null,
"e": 32515,
"s": 32507,
"text": "Output:"
},
{
"code": null,
"e": 32548,
"s": 32515,
"text": "The total length of value is: 11"
},
{
"code": null,
"e": 32559,
"s": 32548,
"text": "Example :2"
},
{
"code": "# Python program to find the# length of dictionary values def main(): # Defining the dictionary dict1 = {'A': \"abcd\", 'B': set([1, 2, 3]), 'C': (12, \"number\"), 'D': [1, 2, 4, 5, 5, 5]} # Create a empty dictionary dict2 = {} # using enumerate() for k in enumerate(dict1.items()): # Check the type of value # is int or not if isinstance(k[1][1], int): dict2[k[1][0]] = 1 # Check the type of value # is str or not elif isinstance(k[1][1], str): dict2[k[1][0]] = 1 else: dict2[k[1][0]] = len(k[1][1]) print(\"The length of values associated\\ with their keys are:\", dict2) print(\"The length of value associated \\ with key 'B' is:\", dict2['B']) # Driver Codeif __name__ == '__main__': main()",
"e": 33455,
"s": 32559,
"text": null
},
{
"code": null,
"e": 33463,
"s": 33455,
"text": "Output:"
},
{
"code": null,
"e": 33598,
"s": 33463,
"text": "The length of values associated with their keys are: {βAβ: 1, βBβ: 3, βCβ: 2, βDβ: 6}The length of value associated with key βBβ is: 3"
},
{
"code": null,
"e": 33610,
"s": 33598,
"text": "python-dict"
},
{
"code": null,
"e": 33617,
"s": 33610,
"text": "Python"
},
{
"code": null,
"e": 33629,
"s": 33617,
"text": "python-dict"
},
{
"code": null,
"e": 33727,
"s": 33629,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33745,
"s": 33727,
"text": "Python Dictionary"
},
{
"code": null,
"e": 33780,
"s": 33745,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 33812,
"s": 33780,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 33834,
"s": 33812,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 33876,
"s": 33834,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 33906,
"s": 33876,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 33935,
"s": 33906,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 33979,
"s": 33935,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 34016,
"s": 33979,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Reservoir Sampling - GeeksforGeeks
|
21 Oct, 2021
Reservoir sampling is a family of randomized algorithms for randomly choosing k samples from a list of n items, where n is either a very large or unknown number. Typically n is large enough that the list doesnβt fit into main memory. For example, a list of search queries in Google and Facebook.So we are given a big array (or stream) of numbers (to simplify), and we need to write an efficient function to randomly select k numbers where 1 <= k <= n. Let the input array be stream[].
A simple solution is to create an array reservoir[] of maximum size k. One by one randomly select an item from stream[0..n-1]. If the selected item is not previously selected, then put it in reservoir[]. To check if an item is previously selected or not, we need to search the item in reservoir[]. The time complexity of this algorithm will be O(k^2). This can be costly if k is big. Also, this is not efficient if the input is in the form of a stream.
It can be solved in O(n) time. The solution also suits well for input in the form of stream. The idea is similar to this post. Following are the steps.1) Create an array reservoir[0..k-1] and copy first k items of stream[] to it. 2) Now one by one consider all items from (k+1)th item to nth item. ...a) Generate a random number from 0 to i where i is the index of the current item in stream[]. Let the generated random number is j. ...b) If j is in range 0 to k-1, replace reservoir[j] with stream[i]
Following is the implementation of the above algorithm.
C++
C
Java
Python3
C#
PHP
Javascript
// An efficient program to randomly select// k items from a stream of items#include <bits/stdc++.h>#include <time.h>using namespace std; // A utility function to print an arrayvoid printArray(int stream[], int n){ for (int i = 0; i < n; i++) cout << stream[i] << " "; cout << endl;} // A function to randomly select// k items from stream[0..n-1].void selectKItems(int stream[], int n, int k){ int i; // index for elements in stream[] // reservoir[] is the output array. Initialize // it with first k elements from stream[] int reservoir[k]; for (i = 0; i < k; i++) reservoir[i] = stream[i]; // Use a different seed value so that we don't get // same result each time we run this program srand(time(NULL)); // Iterate from the (k+1)th element to nth element for (; i < n; i++) { // Pick a random index from 0 to i. int j = rand() % (i + 1); // If the randomly picked index is smaller than k, // then replace the element present at the index // with new element from stream if (j < k) reservoir[j] = stream[i]; } cout << "Following are k randomly selected items \n"; printArray(reservoir, k);} // Driver Codeint main(){ int stream[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; int n = sizeof(stream)/sizeof(stream[0]); int k = 5; selectKItems(stream, n, k); return 0;} // This is code is contributed by rathbhupendra
// An efficient program to randomly select k items from a stream of items #include <stdio.h>#include <stdlib.h>#include <time.h> // A utility function to print an arrayvoid printArray(int stream[], int n){ for (int i = 0; i < n; i++) printf("%d ", stream[i]); printf("\n");} // A function to randomly select k items from stream[0..n-1].void selectKItems(int stream[], int n, int k){ int i; // index for elements in stream[] // reservoir[] is the output array. Initialize it with // first k elements from stream[] int reservoir[k]; for (i = 0; i < k; i++) reservoir[i] = stream[i]; // Use a different seed value so that we don't get // same result each time we run this program srand(time(NULL)); // Iterate from the (k+1)th element to nth element for (; i < n; i++) { // Pick a random index from 0 to i. int j = rand() % (i+1); // If the randomly picked index is smaller than k, then replace // the element present at the index with new element from stream if (j < k) reservoir[j] = stream[i]; } printf("Following are k randomly selected items \n"); printArray(reservoir, k);} // Driver program to test above function.int main(){ int stream[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; int n = sizeof(stream)/sizeof(stream[0]); int k = 5; selectKItems(stream, n, k); return 0;}
// An efficient Java program to randomly// select k items from a stream of itemsimport java.util.Arrays;import java.util.Random;public class ReservoirSampling { // A function to randomly select k items from // stream[0..n-1]. static void selectKItems(int stream[], int n, int k) { int i; // index for elements in stream[] // reservoir[] is the output array. Initialize it // with first k elements from stream[] int reservoir[] = new int[k]; for (i = 0; i < k; i++) reservoir[i] = stream[i]; Random r = new Random(); // Iterate from the (k+1)th element to nth element for (; i < n; i++) { // Pick a random index from 0 to i. int j = r.nextInt(i + 1); // If the randomly picked index is smaller than // k, then replace the element present at the // index with new element from stream if (j < k) reservoir[j] = stream[i]; } System.out.println( "Following are k randomly selected items"); System.out.println(Arrays.toString(reservoir)); } // Driver Program to test above method public static void main(String[] args) { int stream[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; int n = stream.length; int k = 5; selectKItems(stream, n, k); }}// This code is contributed by Sumit Ghosh
# An efficient Python3 program# to randomly select k items# from a stream of itemsimport random# A utility function# to print an arraydef printArray(stream,n): for i in range(n): print(stream[i],end=" "); print(); # A function to randomly select# k items from stream[0..n-1].def selectKItems(stream, n, k): i=0; # index for elements # in stream[] # reservoir[] is the output # array. Initialize it with # first k elements from stream[] reservoir = [0]*k; for i in range(k): reservoir[i] = stream[i]; # Iterate from the (k+1)th # element to nth element while(i < n): # Pick a random index # from 0 to i. j = random.randrange(i+1); # If the randomly picked # index is smaller than k, # then replace the element # present at the index # with new element from stream if(j < k): reservoir[j] = stream[i]; i+=1; print("Following are k randomly selected items"); printArray(reservoir, k); # Driver Code if __name__ == "__main__": stream = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; n = len(stream); k = 5; selectKItems(stream, n, k); # This code is contributed by mits
// An efficient C# program to randomly// select k items from a stream of itemsusing System;using System.Collections; public class ReservoirSampling{ // A function to randomly select k // items from stream[0..n-1]. static void selectKItems(int []stream, int n, int k) { // index for elements in stream[] int i; // reservoir[] is the output array. // Initialize it with first k // elements from stream[] int[] reservoir = new int[k]; for (i = 0; i < k; i++) reservoir[i] = stream[i]; Random r = new Random(); // Iterate from the (k+1)th // element to nth element for (; i < n; i++) { // Pick a random index from 0 to i. int j = r.Next(i + 1); // If the randomly picked index // is smaller than k, then replace // the element present at the index // with new element from stream if(j < k) reservoir[j] = stream[i]; } Console.WriteLine("Following are k " + "randomly selected items"); for (i = 0; i < k; i++) Console.Write(reservoir[i]+" "); } //Driver code static void Main() { int []stream = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; int n = stream.Length; int k = 5; selectKItems(stream, n, k); }} // This code is contributed by mits
<?php// An efficient PHP program// to randomly select k items// from a stream of items // A utility function// to print an arrayfunction printArray($stream,$n){ for ($i = 0; $i < $n; $i++) echo $stream[$i]." "; echo "\n";} // A function to randomly select// k items from stream[0..n-1].function selectKItems($stream, $n, $k) { $i; // index for elements // in stream[] // reservoir[] is the output // array. Initialize it with // first k elements from stream[] $reservoir = array_fill(0, $k, 0); for ($i = 0; $i < $k; $i++) $reservoir[$i] = $stream[$i]; // Iterate from the (k+1)th // element to nth element for (; $i < $n; $i++) { // Pick a random index // from 0 to i. $j = rand(0,$i + 1); // If the randomly picked // index is smaller than k, // then replace the element // present at the index // with new element from stream if($j < $k) $reservoir[$j] = $stream[$i]; } echo "Following are k randomly ". "selected items\n"; printArray($reservoir, $k); } // Driver Code$stream = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);$n = count($stream);$k = 5;selectKItems($stream, $n, $k); // This code is contributed by mits?>
<script> // An efficient program to randomly select// k items from a stream of items // A utility function to print an arrayfunction printArray(stream, n){ for(let i = 0; i < n; i++) document.write(stream[i] + " "); document.write('\n');} // A function to randomly select// k items from stream[0..n-1].function selectKItems(stream, n, k){ // Index for elements in stream[] let i; // reservoir[] is the output array. Initialize // it with first k elements from stream[] let reservoir = []; for(i = 0; i < k; i++) reservoir[i] = stream[i]; // Use a different seed value so that // we don't get same result each time // we run this program // Iterate from the (k+1)th element // to nth element for(; i < n; i++) { // Pick a random index from 0 to i. let j = (Math.floor(Math.random() * 100000000) % (i + 1)); // If the randomly picked index is // smaller than k, then replace the // element present at the index // with new element from stream if (j < k) reservoir[j] = stream[i]; } document.write("Following are k randomly " + "selected items \n"); printArray(reservoir, k);} // Driver Codelet stream = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ];let n = stream.length;let k = 5; selectKItems(stream, n, k); // This code is contributed by rohan07 </script>
Output:
Following are k randomly selected items
6 2 11 8 12
Note: Output will differ every time as it selects and prints random elements
Time Complexity: O(n)
Auxiliary Space: O(k)
How does this work? To prove that this solution works perfectly, we must prove that the probability that any item stream[i] where 0 <= i < n will be in final reservoir[] is k/n. Let us divide the proof in two cases as first k items are treated differently.
Case 1: For last n-k stream items, i.e., for stream[i] where k <= i < n For every such stream item stream[i], we pick a random index from 0 to i and if the picked index is one of the first k indexes, we replace the element at picked index with stream[i]To simplify the proof, let us first consider the last item. The probability that the last item is in final reservoir = The probability that one of the first k indexes is picked for last item = k/n (the probability of picking one of the k items from a list of size n)Let us now consider the second last item. The probability that the second last item is in final reservoir[] = [Probability that one of the first k indexes is picked in iteration for stream[n-2]] X [Probability that the index picked in iteration for stream[n-1] is not same as index picked for stream[n-2] ] = [k/(n-1)]*[(n-1)/n] = k/n.Similarly, we can consider other items for all stream items from stream[n-1] to stream[k] and generalize the proof.
Case 2: For first k stream items, i.e., for stream[i] where 0 <= i < k The first k items are initially copied to reservoir[] and may be removed later in iterations for stream[k] to stream[n]. The probability that an item from stream[0..k-1] is in final array = Probability that the item is not picked when items stream[k], stream[k+1], .... stream[n-1] are considered = [k/(k+1)] x [(k+1)/(k+2)] x [(k+2)/(k+3)] x ... x [(n-1)/n] = k/n
References: http://en.wikipedia.org/wiki/Reservoir_samplingPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Mithun Kumar
rathbhupendra
navaneethnvnthr
rohan07
subhammahato348
Articles
Mathematical
Randomized
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tree Traversals (Inorder, Preorder and Postorder)
SQL | Join (Inner, Left, Right and Full Joins)
find command in Linux with examples
How to write a Pseudo Code?
SQL Interview Questions
C++ Data Types
Set in C++ Standard Template Library (STL)
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
|
[
{
"code": null,
"e": 35839,
"s": 35811,
"text": "\n21 Oct, 2021"
},
{
"code": null,
"e": 36325,
"s": 35839,
"text": "Reservoir sampling is a family of randomized algorithms for randomly choosing k samples from a list of n items, where n is either a very large or unknown number. Typically n is large enough that the list doesnβt fit into main memory. For example, a list of search queries in Google and Facebook.So we are given a big array (or stream) of numbers (to simplify), and we need to write an efficient function to randomly select k numbers where 1 <= k <= n. Let the input array be stream[]. "
},
{
"code": null,
"e": 36779,
"s": 36325,
"text": "A simple solution is to create an array reservoir[] of maximum size k. One by one randomly select an item from stream[0..n-1]. If the selected item is not previously selected, then put it in reservoir[]. To check if an item is previously selected or not, we need to search the item in reservoir[]. The time complexity of this algorithm will be O(k^2). This can be costly if k is big. Also, this is not efficient if the input is in the form of a stream. "
},
{
"code": null,
"e": 37281,
"s": 36779,
"text": "It can be solved in O(n) time. The solution also suits well for input in the form of stream. The idea is similar to this post. Following are the steps.1) Create an array reservoir[0..k-1] and copy first k items of stream[] to it. 2) Now one by one consider all items from (k+1)th item to nth item. ...a) Generate a random number from 0 to i where i is the index of the current item in stream[]. Let the generated random number is j. ...b) If j is in range 0 to k-1, replace reservoir[j] with stream[i]"
},
{
"code": null,
"e": 37338,
"s": 37281,
"text": "Following is the implementation of the above algorithm. "
},
{
"code": null,
"e": 37342,
"s": 37338,
"text": "C++"
},
{
"code": null,
"e": 37344,
"s": 37342,
"text": "C"
},
{
"code": null,
"e": 37349,
"s": 37344,
"text": "Java"
},
{
"code": null,
"e": 37357,
"s": 37349,
"text": "Python3"
},
{
"code": null,
"e": 37360,
"s": 37357,
"text": "C#"
},
{
"code": null,
"e": 37364,
"s": 37360,
"text": "PHP"
},
{
"code": null,
"e": 37375,
"s": 37364,
"text": "Javascript"
},
{
"code": "// An efficient program to randomly select// k items from a stream of items#include <bits/stdc++.h>#include <time.h>using namespace std; // A utility function to print an arrayvoid printArray(int stream[], int n){ for (int i = 0; i < n; i++) cout << stream[i] << \" \"; cout << endl;} // A function to randomly select// k items from stream[0..n-1].void selectKItems(int stream[], int n, int k){ int i; // index for elements in stream[] // reservoir[] is the output array. Initialize // it with first k elements from stream[] int reservoir[k]; for (i = 0; i < k; i++) reservoir[i] = stream[i]; // Use a different seed value so that we don't get // same result each time we run this program srand(time(NULL)); // Iterate from the (k+1)th element to nth element for (; i < n; i++) { // Pick a random index from 0 to i. int j = rand() % (i + 1); // If the randomly picked index is smaller than k, // then replace the element present at the index // with new element from stream if (j < k) reservoir[j] = stream[i]; } cout << \"Following are k randomly selected items \\n\"; printArray(reservoir, k);} // Driver Codeint main(){ int stream[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; int n = sizeof(stream)/sizeof(stream[0]); int k = 5; selectKItems(stream, n, k); return 0;} // This is code is contributed by rathbhupendra",
"e": 38839,
"s": 37375,
"text": null
},
{
"code": "// An efficient program to randomly select k items from a stream of items #include <stdio.h>#include <stdlib.h>#include <time.h> // A utility function to print an arrayvoid printArray(int stream[], int n){ for (int i = 0; i < n; i++) printf(\"%d \", stream[i]); printf(\"\\n\");} // A function to randomly select k items from stream[0..n-1].void selectKItems(int stream[], int n, int k){ int i; // index for elements in stream[] // reservoir[] is the output array. Initialize it with // first k elements from stream[] int reservoir[k]; for (i = 0; i < k; i++) reservoir[i] = stream[i]; // Use a different seed value so that we don't get // same result each time we run this program srand(time(NULL)); // Iterate from the (k+1)th element to nth element for (; i < n; i++) { // Pick a random index from 0 to i. int j = rand() % (i+1); // If the randomly picked index is smaller than k, then replace // the element present at the index with new element from stream if (j < k) reservoir[j] = stream[i]; } printf(\"Following are k randomly selected items \\n\"); printArray(reservoir, k);} // Driver program to test above function.int main(){ int stream[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; int n = sizeof(stream)/sizeof(stream[0]); int k = 5; selectKItems(stream, n, k); return 0;}",
"e": 40245,
"s": 38839,
"text": null
},
{
"code": "// An efficient Java program to randomly// select k items from a stream of itemsimport java.util.Arrays;import java.util.Random;public class ReservoirSampling { // A function to randomly select k items from // stream[0..n-1]. static void selectKItems(int stream[], int n, int k) { int i; // index for elements in stream[] // reservoir[] is the output array. Initialize it // with first k elements from stream[] int reservoir[] = new int[k]; for (i = 0; i < k; i++) reservoir[i] = stream[i]; Random r = new Random(); // Iterate from the (k+1)th element to nth element for (; i < n; i++) { // Pick a random index from 0 to i. int j = r.nextInt(i + 1); // If the randomly picked index is smaller than // k, then replace the element present at the // index with new element from stream if (j < k) reservoir[j] = stream[i]; } System.out.println( \"Following are k randomly selected items\"); System.out.println(Arrays.toString(reservoir)); } // Driver Program to test above method public static void main(String[] args) { int stream[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; int n = stream.length; int k = 5; selectKItems(stream, n, k); }}// This code is contributed by Sumit Ghosh",
"e": 41681,
"s": 40245,
"text": null
},
{
"code": "# An efficient Python3 program# to randomly select k items# from a stream of itemsimport random# A utility function# to print an arraydef printArray(stream,n): for i in range(n): print(stream[i],end=\" \"); print(); # A function to randomly select# k items from stream[0..n-1].def selectKItems(stream, n, k): i=0; # index for elements # in stream[] # reservoir[] is the output # array. Initialize it with # first k elements from stream[] reservoir = [0]*k; for i in range(k): reservoir[i] = stream[i]; # Iterate from the (k+1)th # element to nth element while(i < n): # Pick a random index # from 0 to i. j = random.randrange(i+1); # If the randomly picked # index is smaller than k, # then replace the element # present at the index # with new element from stream if(j < k): reservoir[j] = stream[i]; i+=1; print(\"Following are k randomly selected items\"); printArray(reservoir, k); # Driver Code if __name__ == \"__main__\": stream = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; n = len(stream); k = 5; selectKItems(stream, n, k); # This code is contributed by mits",
"e": 43037,
"s": 41681,
"text": null
},
{
"code": "// An efficient C# program to randomly// select k items from a stream of itemsusing System;using System.Collections; public class ReservoirSampling{ // A function to randomly select k // items from stream[0..n-1]. static void selectKItems(int []stream, int n, int k) { // index for elements in stream[] int i; // reservoir[] is the output array. // Initialize it with first k // elements from stream[] int[] reservoir = new int[k]; for (i = 0; i < k; i++) reservoir[i] = stream[i]; Random r = new Random(); // Iterate from the (k+1)th // element to nth element for (; i < n; i++) { // Pick a random index from 0 to i. int j = r.Next(i + 1); // If the randomly picked index // is smaller than k, then replace // the element present at the index // with new element from stream if(j < k) reservoir[j] = stream[i]; } Console.WriteLine(\"Following are k \" + \"randomly selected items\"); for (i = 0; i < k; i++) Console.Write(reservoir[i]+\" \"); } //Driver code static void Main() { int []stream = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; int n = stream.Length; int k = 5; selectKItems(stream, n, k); }} // This code is contributed by mits",
"e": 44571,
"s": 43037,
"text": null
},
{
"code": "<?php// An efficient PHP program// to randomly select k items// from a stream of items // A utility function// to print an arrayfunction printArray($stream,$n){ for ($i = 0; $i < $n; $i++) echo $stream[$i].\" \"; echo \"\\n\";} // A function to randomly select// k items from stream[0..n-1].function selectKItems($stream, $n, $k) { $i; // index for elements // in stream[] // reservoir[] is the output // array. Initialize it with // first k elements from stream[] $reservoir = array_fill(0, $k, 0); for ($i = 0; $i < $k; $i++) $reservoir[$i] = $stream[$i]; // Iterate from the (k+1)th // element to nth element for (; $i < $n; $i++) { // Pick a random index // from 0 to i. $j = rand(0,$i + 1); // If the randomly picked // index is smaller than k, // then replace the element // present at the index // with new element from stream if($j < $k) $reservoir[$j] = $stream[$i]; } echo \"Following are k randomly \". \"selected items\\n\"; printArray($reservoir, $k); } // Driver Code$stream = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);$n = count($stream);$k = 5;selectKItems($stream, $n, $k); // This code is contributed by mits?>",
"e": 46023,
"s": 44571,
"text": null
},
{
"code": "<script> // An efficient program to randomly select// k items from a stream of items // A utility function to print an arrayfunction printArray(stream, n){ for(let i = 0; i < n; i++) document.write(stream[i] + \" \"); document.write('\\n');} // A function to randomly select// k items from stream[0..n-1].function selectKItems(stream, n, k){ // Index for elements in stream[] let i; // reservoir[] is the output array. Initialize // it with first k elements from stream[] let reservoir = []; for(i = 0; i < k; i++) reservoir[i] = stream[i]; // Use a different seed value so that // we don't get same result each time // we run this program // Iterate from the (k+1)th element // to nth element for(; i < n; i++) { // Pick a random index from 0 to i. let j = (Math.floor(Math.random() * 100000000) % (i + 1)); // If the randomly picked index is // smaller than k, then replace the // element present at the index // with new element from stream if (j < k) reservoir[j] = stream[i]; } document.write(\"Following are k randomly \" + \"selected items \\n\"); printArray(reservoir, k);} // Driver Codelet stream = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ];let n = stream.length;let k = 5; selectKItems(stream, n, k); // This code is contributed by rohan07 </script>",
"e": 47488,
"s": 46023,
"text": null
},
{
"code": null,
"e": 47497,
"s": 47488,
"text": "Output: "
},
{
"code": null,
"e": 47626,
"s": 47497,
"text": "Following are k randomly selected items\n6 2 11 8 12\nNote: Output will differ every time as it selects and prints random elements"
},
{
"code": null,
"e": 47648,
"s": 47626,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 47670,
"s": 47648,
"text": "Auxiliary Space: O(k)"
},
{
"code": null,
"e": 47927,
"s": 47670,
"text": "How does this work? To prove that this solution works perfectly, we must prove that the probability that any item stream[i] where 0 <= i < n will be in final reservoir[] is k/n. Let us divide the proof in two cases as first k items are treated differently."
},
{
"code": null,
"e": 48897,
"s": 47927,
"text": "Case 1: For last n-k stream items, i.e., for stream[i] where k <= i < n For every such stream item stream[i], we pick a random index from 0 to i and if the picked index is one of the first k indexes, we replace the element at picked index with stream[i]To simplify the proof, let us first consider the last item. The probability that the last item is in final reservoir = The probability that one of the first k indexes is picked for last item = k/n (the probability of picking one of the k items from a list of size n)Let us now consider the second last item. The probability that the second last item is in final reservoir[] = [Probability that one of the first k indexes is picked in iteration for stream[n-2]] X [Probability that the index picked in iteration for stream[n-1] is not same as index picked for stream[n-2] ] = [k/(n-1)]*[(n-1)/n] = k/n.Similarly, we can consider other items for all stream items from stream[n-1] to stream[k] and generalize the proof."
},
{
"code": null,
"e": 49333,
"s": 48897,
"text": "Case 2: For first k stream items, i.e., for stream[i] where 0 <= i < k The first k items are initially copied to reservoir[] and may be removed later in iterations for stream[k] to stream[n]. The probability that an item from stream[0..k-1] is in final array = Probability that the item is not picked when items stream[k], stream[k+1], .... stream[n-1] are considered = [k/(k+1)] x [(k+1)/(k+2)] x [(k+2)/(k+3)] x ... x [(n-1)/n] = k/n"
},
{
"code": null,
"e": 49517,
"s": 49333,
"text": "References: http://en.wikipedia.org/wiki/Reservoir_samplingPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 49530,
"s": 49517,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 49544,
"s": 49530,
"text": "rathbhupendra"
},
{
"code": null,
"e": 49560,
"s": 49544,
"text": "navaneethnvnthr"
},
{
"code": null,
"e": 49568,
"s": 49560,
"text": "rohan07"
},
{
"code": null,
"e": 49584,
"s": 49568,
"text": "subhammahato348"
},
{
"code": null,
"e": 49593,
"s": 49584,
"text": "Articles"
},
{
"code": null,
"e": 49606,
"s": 49593,
"text": "Mathematical"
},
{
"code": null,
"e": 49617,
"s": 49606,
"text": "Randomized"
},
{
"code": null,
"e": 49630,
"s": 49617,
"text": "Mathematical"
},
{
"code": null,
"e": 49728,
"s": 49630,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 49778,
"s": 49728,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 49825,
"s": 49778,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 49861,
"s": 49825,
"text": "find command in Linux with examples"
},
{
"code": null,
"e": 49889,
"s": 49861,
"text": "How to write a Pseudo Code?"
},
{
"code": null,
"e": 49913,
"s": 49889,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 49928,
"s": 49913,
"text": "C++ Data Types"
},
{
"code": null,
"e": 49971,
"s": 49928,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 49995,
"s": 49971,
"text": "Merge two sorted arrays"
}
] |
Calendar getTimeInMillis() Method in Java with Examples - GeeksforGeeks
|
26 Jul, 2021
The getTimeInMillis() method in Calendar class is used to return the current time of this Calendar in Milliseconds.Syntax:
public long getTimeInMillis()
Parameters: The method does not take any parameters.Return Value: The method returns the current time of this Calendar in millisecond.Below programs illustrate the working of getTimeInMillis() Method of Calendar class: Example 1:
Java
// Java code to illustrate// getTimeInMillis() method import java.util.*; public class Calendar_Demo { public static void main(String args[]) throws InterruptedException { // Creating a calendar Calendar calndr1 = Calendar.getInstance(); // Displaying the current time System.out.println("The Current Time" + " is: " + calndr1.getTimeInMillis()); // Adding few delay Thread.sleep(10000); // Creating another calendar Calendar calndr2 = Calendar.getInstance(); // Displaying the upcoming time System.out.println("The Upcoming Time" + " is: " + calndr2.getTimeInMillis()); }}
The Current Time is: 1550725664034
The Upcoming Time is: 1550725674053
Example 2:
Java
// Java code to illustrate// getTimeInMillis() method import java.util.*; public class Calendar_Demo { public static void main(String args[]) throws InterruptedException { // Creating a calendar Calendar calndr1 = Calendar.getInstance(); // Displaying the current time System.out.println("The Current Time" + " is: " + calndr1.getTimeInMillis()); // Adding few delay Thread.sleep(5000); // Creating another calendar Calendar calndr2 = Calendar.getInstance(); // Displaying the upcoming time System.out.println("The Upcoming Time" + " is: " + calndr2.getTimeInMillis()); }}
The Current Time is: 1550725683182
The Upcoming Time is: 1550725688208
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#getTimeInMillisβ
manikarora059
Java - util package
Java-Calendar
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
|
[
{
"code": null,
"e": 26251,
"s": 26223,
"text": "\n26 Jul, 2021"
},
{
"code": null,
"e": 26376,
"s": 26251,
"text": "The getTimeInMillis() method in Calendar class is used to return the current time of this Calendar in Milliseconds.Syntax: "
},
{
"code": null,
"e": 26406,
"s": 26376,
"text": "public long getTimeInMillis()"
},
{
"code": null,
"e": 26637,
"s": 26406,
"text": "Parameters: The method does not take any parameters.Return Value: The method returns the current time of this Calendar in millisecond.Below programs illustrate the working of getTimeInMillis() Method of Calendar class: Example 1: "
},
{
"code": null,
"e": 26642,
"s": 26637,
"text": "Java"
},
{
"code": "// Java code to illustrate// getTimeInMillis() method import java.util.*; public class Calendar_Demo { public static void main(String args[]) throws InterruptedException { // Creating a calendar Calendar calndr1 = Calendar.getInstance(); // Displaying the current time System.out.println(\"The Current Time\" + \" is: \" + calndr1.getTimeInMillis()); // Adding few delay Thread.sleep(10000); // Creating another calendar Calendar calndr2 = Calendar.getInstance(); // Displaying the upcoming time System.out.println(\"The Upcoming Time\" + \" is: \" + calndr2.getTimeInMillis()); }}",
"e": 27412,
"s": 26642,
"text": null
},
{
"code": null,
"e": 27483,
"s": 27412,
"text": "The Current Time is: 1550725664034\nThe Upcoming Time is: 1550725674053"
},
{
"code": null,
"e": 27498,
"s": 27485,
"text": "Example 2: "
},
{
"code": null,
"e": 27503,
"s": 27498,
"text": "Java"
},
{
"code": "// Java code to illustrate// getTimeInMillis() method import java.util.*; public class Calendar_Demo { public static void main(String args[]) throws InterruptedException { // Creating a calendar Calendar calndr1 = Calendar.getInstance(); // Displaying the current time System.out.println(\"The Current Time\" + \" is: \" + calndr1.getTimeInMillis()); // Adding few delay Thread.sleep(5000); // Creating another calendar Calendar calndr2 = Calendar.getInstance(); // Displaying the upcoming time System.out.println(\"The Upcoming Time\" + \" is: \" + calndr2.getTimeInMillis()); }}",
"e": 28272,
"s": 27503,
"text": null
},
{
"code": null,
"e": 28343,
"s": 28272,
"text": "The Current Time is: 1550725683182\nThe Upcoming Time is: 1550725688208"
},
{
"code": null,
"e": 28440,
"s": 28345,
"text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#getTimeInMillisβ "
},
{
"code": null,
"e": 28454,
"s": 28440,
"text": "manikarora059"
},
{
"code": null,
"e": 28474,
"s": 28454,
"text": "Java - util package"
},
{
"code": null,
"e": 28488,
"s": 28474,
"text": "Java-Calendar"
},
{
"code": null,
"e": 28503,
"s": 28488,
"text": "Java-Functions"
},
{
"code": null,
"e": 28508,
"s": 28503,
"text": "Java"
},
{
"code": null,
"e": 28513,
"s": 28508,
"text": "Java"
},
{
"code": null,
"e": 28611,
"s": 28513,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28662,
"s": 28611,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 28692,
"s": 28662,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 28707,
"s": 28692,
"text": "Stream In Java"
},
{
"code": null,
"e": 28726,
"s": 28707,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28757,
"s": 28726,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 28775,
"s": 28757,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 28807,
"s": 28775,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28827,
"s": 28807,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 28859,
"s": 28827,
"text": "Multidimensional Arrays in Java"
}
] |
Python | Extract digits from given string - GeeksforGeeks
|
08 Feb, 2022
While programming, sometimes, we just require a certain type of data and need to discard other. This type of problem is quite common in Data Science domain, and since Data Science uses Python worldwide, its important to know how to extract specific elements. This article discusses certain ways in which only digit can be extracted. Letβs discuss the same.Method #1 : Using join() + isdigit() + filter()This task can be performed using the combination of above functions. The filter function filters the digits detected by the isdigit function and join function performs the task of reconstruction of join function.
Python3
# Python3 code to demonstrate# Extract digit string# using join() + isdigit() + filter() # initializing stringtest_string = 'g1eeks4geeks5' # printing original strings print("The original string : " + test_string) # using join() + isdigit() + filter()# Extract digit stringres = ''.join(filter(lambda i: i.isdigit(), test_string)) # print resultprint("The digits string is : " + str(res))
The original string : g1eeks4geeks5
The digits string is : 145
Method #2 : Using re The regular expressions can also be used to perform this particular task. We can define the digit type requirement, using β\Dβ, and only digits are extracted from the string.
Python3
# Python3 code to demonstrate# Extract digit string# using reimport re # initializing stringtest_string = 'g1eeks4geeks5' # printing original strings print("The original string : " + test_string) # using re# Extract digit stringres = re.sub("\D", "", test_string) # print resultprint("The digits string is : " + str(res))
The original string : g1eeks4geeks5
The digits string is : 145
Method 3: Using loops:
This task is done by using for loop.
Python3
# Python3 code to demonstrate# Extract digit strings="g1eeks4geeks5"#using for loopfor i in s: # using isdigit() function if(i.isdigit()): print(i,end="")
Output:
The original string : g1eeks4geeks5
The digits string is : 145
vaibhavkumar303
Python string-programs
Python
Python Programs
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
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
|
[
{
"code": null,
"e": 26139,
"s": 26111,
"text": "\n08 Feb, 2022"
},
{
"code": null,
"e": 26757,
"s": 26139,
"text": "While programming, sometimes, we just require a certain type of data and need to discard other. This type of problem is quite common in Data Science domain, and since Data Science uses Python worldwide, its important to know how to extract specific elements. This article discusses certain ways in which only digit can be extracted. Letβs discuss the same.Method #1 : Using join() + isdigit() + filter()This task can be performed using the combination of above functions. The filter function filters the digits detected by the isdigit function and join function performs the task of reconstruction of join function. "
},
{
"code": null,
"e": 26765,
"s": 26757,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# Extract digit string# using join() + isdigit() + filter() # initializing stringtest_string = 'g1eeks4geeks5' # printing original strings print(\"The original string : \" + test_string) # using join() + isdigit() + filter()# Extract digit stringres = ''.join(filter(lambda i: i.isdigit(), test_string)) # print resultprint(\"The digits string is : \" + str(res))",
"e": 27158,
"s": 26765,
"text": null
},
{
"code": null,
"e": 27221,
"s": 27158,
"text": "The original string : g1eeks4geeks5\nThe digits string is : 145"
},
{
"code": null,
"e": 27421,
"s": 27223,
"text": " Method #2 : Using re The regular expressions can also be used to perform this particular task. We can define the digit type requirement, using β\\Dβ, and only digits are extracted from the string. "
},
{
"code": null,
"e": 27429,
"s": 27421,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# Extract digit string# using reimport re # initializing stringtest_string = 'g1eeks4geeks5' # printing original strings print(\"The original string : \" + test_string) # using re# Extract digit stringres = re.sub(\"\\D\", \"\", test_string) # print resultprint(\"The digits string is : \" + str(res))",
"e": 27755,
"s": 27429,
"text": null
},
{
"code": null,
"e": 27818,
"s": 27755,
"text": "The original string : g1eeks4geeks5\nThe digits string is : 145"
},
{
"code": null,
"e": 27843,
"s": 27820,
"text": "Method 3: Using loops:"
},
{
"code": null,
"e": 27880,
"s": 27843,
"text": "This task is done by using for loop."
},
{
"code": null,
"e": 27888,
"s": 27880,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# Extract digit strings=\"g1eeks4geeks5\"#using for loopfor i in s: # using isdigit() function if(i.isdigit()): print(i,end=\"\")",
"e": 28048,
"s": 27888,
"text": null
},
{
"code": null,
"e": 28119,
"s": 28048,
"text": "Output:\nThe original string : g1eeks4geeks5\nThe digits string is : 145"
},
{
"code": null,
"e": 28135,
"s": 28119,
"text": "vaibhavkumar303"
},
{
"code": null,
"e": 28158,
"s": 28135,
"text": "Python string-programs"
},
{
"code": null,
"e": 28165,
"s": 28158,
"text": "Python"
},
{
"code": null,
"e": 28181,
"s": 28165,
"text": "Python Programs"
},
{
"code": null,
"e": 28279,
"s": 28181,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28297,
"s": 28279,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28329,
"s": 28297,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28351,
"s": 28329,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28393,
"s": 28351,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28423,
"s": 28393,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28466,
"s": 28423,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28488,
"s": 28466,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28527,
"s": 28488,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28573,
"s": 28527,
"text": "Python | Split string into list of characters"
}
] |
Month getValue() method in Java - GeeksforGeeks
|
22 Mar, 2019
The getValue() method is a built-in method of the Month ENUM which is used to get the value of the month-of-year from this Month instance as an integer.
The value returned by this method is in the range of 1-12, representing months from January to December.
Syntax:
public int getValue()
Parameters: This method does not accepts any parameters.
Return Value: This method returns the value of month-of-year from this Month instance as an integer.
Below programs illustrate the above method:
Program 1:
import java.time.*;import java.time.Month;import java.time.temporal.ChronoField; class monthEnum { public static void main(String[] args) { // Create a month instance Month month = Month.MARCH; // Get the value of month-of-year as int System.out.println(month.getValue()); }}
3
Program 2:
import java.time.*;import java.time.Month;import java.time.temporal.ChronoField; class monthEnum { public static void main(String[] args) { // Create a month instance Month month = Month.DECEMBER; // Get the value of month-of-year as int System.out.println(month.getValue()); }}
12
Reference: https://docs.oracle.com/javase/8/docs/api/java/time/Month.html#getValueβ
Java-Functions
Java-Month
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Stream In Java
ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Multithreading in Java
Collections in Java
Queue Interface In Java
LinkedList in Java
|
[
{
"code": null,
"e": 25429,
"s": 25401,
"text": "\n22 Mar, 2019"
},
{
"code": null,
"e": 25582,
"s": 25429,
"text": "The getValue() method is a built-in method of the Month ENUM which is used to get the value of the month-of-year from this Month instance as an integer."
},
{
"code": null,
"e": 25687,
"s": 25582,
"text": "The value returned by this method is in the range of 1-12, representing months from January to December."
},
{
"code": null,
"e": 25695,
"s": 25687,
"text": "Syntax:"
},
{
"code": null,
"e": 25718,
"s": 25695,
"text": "public int getValue()\n"
},
{
"code": null,
"e": 25775,
"s": 25718,
"text": "Parameters: This method does not accepts any parameters."
},
{
"code": null,
"e": 25876,
"s": 25775,
"text": "Return Value: This method returns the value of month-of-year from this Month instance as an integer."
},
{
"code": null,
"e": 25920,
"s": 25876,
"text": "Below programs illustrate the above method:"
},
{
"code": null,
"e": 25931,
"s": 25920,
"text": "Program 1:"
},
{
"code": "import java.time.*;import java.time.Month;import java.time.temporal.ChronoField; class monthEnum { public static void main(String[] args) { // Create a month instance Month month = Month.MARCH; // Get the value of month-of-year as int System.out.println(month.getValue()); }}",
"e": 26247,
"s": 25931,
"text": null
},
{
"code": null,
"e": 26250,
"s": 26247,
"text": "3\n"
},
{
"code": null,
"e": 26261,
"s": 26250,
"text": "Program 2:"
},
{
"code": "import java.time.*;import java.time.Month;import java.time.temporal.ChronoField; class monthEnum { public static void main(String[] args) { // Create a month instance Month month = Month.DECEMBER; // Get the value of month-of-year as int System.out.println(month.getValue()); }}",
"e": 26580,
"s": 26261,
"text": null
},
{
"code": null,
"e": 26584,
"s": 26580,
"text": "12\n"
},
{
"code": null,
"e": 26668,
"s": 26584,
"text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/time/Month.html#getValueβ"
},
{
"code": null,
"e": 26683,
"s": 26668,
"text": "Java-Functions"
},
{
"code": null,
"e": 26694,
"s": 26683,
"text": "Java-Month"
},
{
"code": null,
"e": 26712,
"s": 26694,
"text": "Java-time package"
},
{
"code": null,
"e": 26717,
"s": 26712,
"text": "Java"
},
{
"code": null,
"e": 26722,
"s": 26717,
"text": "Java"
},
{
"code": null,
"e": 26820,
"s": 26722,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26839,
"s": 26820,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 26854,
"s": 26839,
"text": "Stream In Java"
},
{
"code": null,
"e": 26872,
"s": 26854,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 26892,
"s": 26872,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 26924,
"s": 26892,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 26948,
"s": 26924,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 26971,
"s": 26948,
"text": "Multithreading in Java"
},
{
"code": null,
"e": 26991,
"s": 26971,
"text": "Collections in Java"
},
{
"code": null,
"e": 27015,
"s": 26991,
"text": "Queue Interface In Java"
}
] |
Reading an image in OpenCV using Python - GeeksforGeeks
|
15 Dec, 2020
Prerequisite: Basics of OpenCV
In this article, weβll try to open an image by using OpenCV (Open Source Computer Vision). To use the OpenCV library in python, we need to install these libraries as a prerequisite:
Numpy Library (Necessary, because OpenCV uses it in the background).OpenCV python
Numpy Library (Necessary, because OpenCV uses it in the background).
OpenCV python
To install these libraries, we need to run these pip commands in cmd:
pip install opencv-python
pip install numpy
pip install matplotlib
To read the images cv2.imread() method is used. This method loads an image from the specified file. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format) then this method returns an empty matrix.
Syntax: cv2.imread(path, flag)
Parameters:path: A string representing the path of the image to be read.flag: It specifies the way in which image should be read. Itβs default value is cv2.IMREAD_COLOR
Return Value: This method returns an image that is loaded from the specified file.
Note: The image should be in the working directory or a full path of image should be given.
All three types of flags are described below:
cv2.IMREAD_COLOR: It specifies to load a color image. Any transparency of image will be neglected. It is the default flag. Alternatively, we can pass integer value 1 for this flag.cv2.IMREAD_GRAYSCALE: It specifies to load an image in grayscale mode. Alternatively, we can pass integer value 0 for this flag.cv2.IMREAD_UNCHANGED: It specifies to load an image as such including alpha channel. Alternatively, we can pass integer value -1 for this flag.
Below codes are implementations to read images and display images on the screen using OpenCV and matplotlib libraries functions. Example #1 (Using OpenCV) :
Image Used:
Python3
# Python code to read imageimport cv2 # To read image from disk, we use# cv2.imread function, in below method,img = cv2.imread("geeksforgeeks.png", cv2.IMREAD_COLOR) # Creating GUI window to display an image on screen# first Parameter is windows title (should be in string format)# Second Parameter is image arraycv2.imshow("Cute Kitens", img) # To hold the window on screen, we use cv2.waitKey method# Once it detected the close input, it will release the control# To the next line# First Parameter is for holding screen for specified milliseconds# It should be positive integer. If 0 pass an parameter, then it will# hold the screen until user close it.cv2.waitKey(0) # It is for removing/deleting created GUI window from screen# and memorycv2.destroyAllWindows()
Output:
Example #2: Opening in grascale mode
Python
# Python program to explain cv2.imread() method # importing cv2import cv2 # pathpath = r'geeksforgeeks.png' # Using cv2.imread() method# Using 0 to read image in grayscale modeimg = cv2.imread(path, 0) # Displaying the imagecv2.imshow('image', img)
Output :
himanshukanojiya
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
|
[
{
"code": null,
"e": 42676,
"s": 42648,
"text": "\n15 Dec, 2020"
},
{
"code": null,
"e": 42707,
"s": 42676,
"text": "Prerequisite: Basics of OpenCV"
},
{
"code": null,
"e": 42889,
"s": 42707,
"text": "In this article, weβll try to open an image by using OpenCV (Open Source Computer Vision). To use the OpenCV library in python, we need to install these libraries as a prerequisite:"
},
{
"code": null,
"e": 42972,
"s": 42889,
"text": "Numpy Library (Necessary, because OpenCV uses it in the background).OpenCV python "
},
{
"code": null,
"e": 43041,
"s": 42972,
"text": "Numpy Library (Necessary, because OpenCV uses it in the background)."
},
{
"code": null,
"e": 43056,
"s": 43041,
"text": "OpenCV python "
},
{
"code": null,
"e": 43126,
"s": 43056,
"text": "To install these libraries, we need to run these pip commands in cmd:"
},
{
"code": null,
"e": 43193,
"s": 43126,
"text": "pip install opencv-python\npip install numpy\npip install matplotlib"
},
{
"code": null,
"e": 43443,
"s": 43193,
"text": " To read the images cv2.imread() method is used. This method loads an image from the specified file. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format) then this method returns an empty matrix."
},
{
"code": null,
"e": 43474,
"s": 43443,
"text": "Syntax: cv2.imread(path, flag)"
},
{
"code": null,
"e": 43643,
"s": 43474,
"text": "Parameters:path: A string representing the path of the image to be read.flag: It specifies the way in which image should be read. Itβs default value is cv2.IMREAD_COLOR"
},
{
"code": null,
"e": 43726,
"s": 43643,
"text": "Return Value: This method returns an image that is loaded from the specified file."
},
{
"code": null,
"e": 43818,
"s": 43726,
"text": "Note: The image should be in the working directory or a full path of image should be given."
},
{
"code": null,
"e": 43864,
"s": 43818,
"text": "All three types of flags are described below:"
},
{
"code": null,
"e": 44316,
"s": 43864,
"text": "cv2.IMREAD_COLOR: It specifies to load a color image. Any transparency of image will be neglected. It is the default flag. Alternatively, we can pass integer value 1 for this flag.cv2.IMREAD_GRAYSCALE: It specifies to load an image in grayscale mode. Alternatively, we can pass integer value 0 for this flag.cv2.IMREAD_UNCHANGED: It specifies to load an image as such including alpha channel. Alternatively, we can pass integer value -1 for this flag."
},
{
"code": null,
"e": 44474,
"s": 44316,
"text": "Below codes are implementations to read images and display images on the screen using OpenCV and matplotlib libraries functions. Example #1 (Using OpenCV) : "
},
{
"code": null,
"e": 44486,
"s": 44474,
"text": "Image Used:"
},
{
"code": null,
"e": 44494,
"s": 44486,
"text": "Python3"
},
{
"code": "# Python code to read imageimport cv2 # To read image from disk, we use# cv2.imread function, in below method,img = cv2.imread(\"geeksforgeeks.png\", cv2.IMREAD_COLOR) # Creating GUI window to display an image on screen# first Parameter is windows title (should be in string format)# Second Parameter is image arraycv2.imshow(\"Cute Kitens\", img) # To hold the window on screen, we use cv2.waitKey method# Once it detected the close input, it will release the control# To the next line# First Parameter is for holding screen for specified milliseconds# It should be positive integer. If 0 pass an parameter, then it will# hold the screen until user close it.cv2.waitKey(0) # It is for removing/deleting created GUI window from screen# and memorycv2.destroyAllWindows()",
"e": 45260,
"s": 44494,
"text": null
},
{
"code": null,
"e": 45268,
"s": 45260,
"text": "Output:"
},
{
"code": null,
"e": 45305,
"s": 45268,
"text": "Example #2: Opening in grascale mode"
},
{
"code": null,
"e": 45312,
"s": 45305,
"text": "Python"
},
{
"code": "# Python program to explain cv2.imread() method # importing cv2import cv2 # pathpath = r'geeksforgeeks.png' # Using cv2.imread() method# Using 0 to read image in grayscale modeimg = cv2.imread(path, 0) # Displaying the imagecv2.imshow('image', img)",
"e": 45561,
"s": 45312,
"text": null
},
{
"code": null,
"e": 45571,
"s": 45561,
"text": "Output : "
},
{
"code": null,
"e": 45588,
"s": 45571,
"text": "himanshukanojiya"
},
{
"code": null,
"e": 45605,
"s": 45588,
"text": "Image-Processing"
},
{
"code": null,
"e": 45612,
"s": 45605,
"text": "OpenCV"
},
{
"code": null,
"e": 45619,
"s": 45612,
"text": "Python"
},
{
"code": null,
"e": 45717,
"s": 45619,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 45745,
"s": 45717,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 45795,
"s": 45745,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 45817,
"s": 45795,
"text": "Python map() function"
},
{
"code": null,
"e": 45861,
"s": 45817,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 45896,
"s": 45861,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 45928,
"s": 45896,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 45950,
"s": 45928,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 45992,
"s": 45950,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 46022,
"s": 45992,
"text": "Iterate over a list in Python"
}
] |
How to delete a property of an object in JavaScript?
|
To delete a property of an object, delete key word should be used. Delete key word can be used with both the methods such as Dot method and Bracket method.
delete object.property;
In the following example initially when the property "country" is executed its value "England" is displayed in the output. But when that property is deleted using delete keyword,instead of "England", undefined is displayed as shown in the output.
Live Demo
<html>
<body>
<script>
var txt = "";
var person = {
"name":"Ram",
"age":27,
"address": {
"houseno" : 123,
"streetname" : "Baker street",
"country": "England"
}
}
document.write("Before deletion :" + " "+ person.address.country);
delete person.address.country;
document.write("</br>");
document.write("After deletion :" + " "+ person.address.country);
</script>
</body>
</html>
Before deletion : England
After deletion : undefined
|
[
{
"code": null,
"e": 1218,
"s": 1062,
"text": "To delete a property of an object, delete key word should be used. Delete key word can be used with both the methods such as Dot method and Bracket method."
},
{
"code": null,
"e": 1242,
"s": 1218,
"text": "delete object.property;"
},
{
"code": null,
"e": 1489,
"s": 1242,
"text": "In the following example initially when the property \"country\" is executed its value \"England\" is displayed in the output. But when that property is deleted using delete keyword,instead of \"England\", undefined is displayed as shown in the output."
},
{
"code": null,
"e": 1499,
"s": 1489,
"text": "Live Demo"
},
{
"code": null,
"e": 1948,
"s": 1499,
"text": "<html>\n<body>\n<script>\n var txt = \"\";\n var person = {\n \"name\":\"Ram\",\n \"age\":27,\n \"address\": {\n \"houseno\" : 123,\n \"streetname\" : \"Baker street\",\n \"country\": \"England\"\n }\n }\n document.write(\"Before deletion :\" + \" \"+ person.address.country);\n delete person.address.country;\n document.write(\"</br>\");\n document.write(\"After deletion :\" + \" \"+ person.address.country);\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2001,
"s": 1948,
"text": "Before deletion : England\nAfter deletion : undefined"
}
] |
C# | Performing Specified action on each element of Array - GeeksforGeeks
|
06 Oct, 2021
Array.ForEach(T[], Action<T>) Method is used to perform the specified action on each element of the specified array.
Syntax:
public static void ForEach<T> (T[] array, Action<T> action);
Parameters:
array: The one-dimensional, zero-based Array on whose elements the action is to be performed. action: The Action to perform on each element of array.
Exception: This method throws ArgumentNullException array is null or action is null.Below programs illustrate the use of Array.ForEach(T[], Action) Method:Example 1:
CSHARP
// C# program to demonstrate// Array.ForEach(T[], Action<T>)// Methodusing System;using System.Collections.Generic; class GFG { // Main Method public static void Main() { try { // Creating and initializing // new Array of int int[] myArr = { 2, 3, 4, 5 }; // Display the values of the myArr. Console.Write("Initial Array: "); // calling the PrintIndexAndValues() // method to print PrintIndexAndValues(myArr); // set a delegate for // the SetSquares method Action<int> action = new Action<int>(SetSquares); // performing the action // using ForEach() method Array.ForEach(myArr, action); } catch (ArgumentNullException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } } // Defining the method // PrintIndexAndValues public static void PrintIndexAndValues(int[] myArr) { for (int i = 0; i < myArr.Length; i++) { Console.Write("{0} ", myArr[i]); } Console.WriteLine(); Console.WriteLine(); } // Defining the method // ShowSquares private static void SetSquares(int val) { Console.WriteLine("{0} squared = {1}", val, val * val); }}
Initial Array: 2 3 4 5
2 squared = 4
3 squared = 9
4 squared = 16
5 squared = 25
Example 2:
CSHARP
// C# program to demonstrate// Array.ForEach(T[], Action<T>)// Methodusing System;using System.Collections.Generic; public class GFG { // Main Method public static void Main() { try { // Creating and initializing // new Array of with null int[] myArr = null; // set a delegate for // the Set Squares method Action<int> action = new Action<int>(SetSquares); // performing the action // using ForEach() method Console.WriteLine("Trying to perform " +"action on a null Array"); Console.WriteLine(); Array.ForEach(myArr, action); } catch (ArgumentNullException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } } // Defining the method // PrintIndexAndValues public static void PrintIndexAndValues(int[] myArr) { for (int i = 0; i < myArr.Length; i++) { Console.Write("{0} ", myArr[i]); } Console.WriteLine(); Console.WriteLine(); } // Defining the method // ShowSquares private static void SetSquares(int val) { Console.WriteLine("{0} squared = {1}", val, val * val); }}
Trying to perform action on a null Array
Exception Thrown: System.ArgumentNullException
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.array.foreach?view=netframework-4.7.2
surindertarika1234
simranarora5sos
CSharp-Arrays
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 C# Interview Questions & Answers
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
C# | Inheritance
Convert String to Character Array in C#
Linked List Implementation in C#
C# | How to insert an element in an Array?
C# | List Class
Difference between Hashtable and Dictionary in C#
|
[
{
"code": null,
"e": 23911,
"s": 23883,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 24029,
"s": 23911,
"text": "Array.ForEach(T[], Action<T>) Method is used to perform the specified action on each element of the specified array. "
},
{
"code": null,
"e": 24039,
"s": 24029,
"text": "Syntax: "
},
{
"code": null,
"e": 24100,
"s": 24039,
"text": "public static void ForEach<T> (T[] array, Action<T> action);"
},
{
"code": null,
"e": 24113,
"s": 24100,
"text": "Parameters: "
},
{
"code": null,
"e": 24265,
"s": 24113,
"text": "array: The one-dimensional, zero-based Array on whose elements the action is to be performed. action: The Action to perform on each element of array. "
},
{
"code": null,
"e": 24432,
"s": 24265,
"text": "Exception: This method throws ArgumentNullException array is null or action is null.Below programs illustrate the use of Array.ForEach(T[], Action) Method:Example 1: "
},
{
"code": null,
"e": 24439,
"s": 24432,
"text": "CSHARP"
},
{
"code": "// C# program to demonstrate// Array.ForEach(T[], Action<T>)// Methodusing System;using System.Collections.Generic; class GFG { // Main Method public static void Main() { try { // Creating and initializing // new Array of int int[] myArr = { 2, 3, 4, 5 }; // Display the values of the myArr. Console.Write(\"Initial Array: \"); // calling the PrintIndexAndValues() // method to print PrintIndexAndValues(myArr); // set a delegate for // the SetSquares method Action<int> action = new Action<int>(SetSquares); // performing the action // using ForEach() method Array.ForEach(myArr, action); } catch (ArgumentNullException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } } // Defining the method // PrintIndexAndValues public static void PrintIndexAndValues(int[] myArr) { for (int i = 0; i < myArr.Length; i++) { Console.Write(\"{0} \", myArr[i]); } Console.WriteLine(); Console.WriteLine(); } // Defining the method // ShowSquares private static void SetSquares(int val) { Console.WriteLine(\"{0} squared = {1}\", val, val * val); }}",
"e": 25841,
"s": 24439,
"text": null
},
{
"code": null,
"e": 25924,
"s": 25841,
"text": "Initial Array: 2 3 4 5 \n\n2 squared = 4\n3 squared = 9\n4 squared = 16\n5 squared = 25"
},
{
"code": null,
"e": 25937,
"s": 25926,
"text": "Example 2:"
},
{
"code": null,
"e": 25944,
"s": 25937,
"text": "CSHARP"
},
{
"code": "// C# program to demonstrate// Array.ForEach(T[], Action<T>)// Methodusing System;using System.Collections.Generic; public class GFG { // Main Method public static void Main() { try { // Creating and initializing // new Array of with null int[] myArr = null; // set a delegate for // the Set Squares method Action<int> action = new Action<int>(SetSquares); // performing the action // using ForEach() method Console.WriteLine(\"Trying to perform \" +\"action on a null Array\"); Console.WriteLine(); Array.ForEach(myArr, action); } catch (ArgumentNullException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } } // Defining the method // PrintIndexAndValues public static void PrintIndexAndValues(int[] myArr) { for (int i = 0; i < myArr.Length; i++) { Console.Write(\"{0} \", myArr[i]); } Console.WriteLine(); Console.WriteLine(); } // Defining the method // ShowSquares private static void SetSquares(int val) { Console.WriteLine(\"{0} squared = {1}\", val, val * val); }}",
"e": 27242,
"s": 25944,
"text": null
},
{
"code": null,
"e": 27331,
"s": 27242,
"text": "Trying to perform action on a null Array\n\nException Thrown: System.ArgumentNullException"
},
{
"code": null,
"e": 27345,
"s": 27333,
"text": "Reference: "
},
{
"code": null,
"e": 27434,
"s": 27345,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.array.foreach?view=netframework-4.7.2"
},
{
"code": null,
"e": 27453,
"s": 27434,
"text": "surindertarika1234"
},
{
"code": null,
"e": 27469,
"s": 27453,
"text": "simranarora5sos"
},
{
"code": null,
"e": 27483,
"s": 27469,
"text": "CSharp-Arrays"
},
{
"code": null,
"e": 27497,
"s": 27483,
"text": "CSharp-method"
},
{
"code": null,
"e": 27500,
"s": 27497,
"text": "C#"
},
{
"code": null,
"e": 27598,
"s": 27500,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27607,
"s": 27598,
"text": "Comments"
},
{
"code": null,
"e": 27620,
"s": 27607,
"text": "Old Comments"
},
{
"code": null,
"e": 27660,
"s": 27620,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 27683,
"s": 27660,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27711,
"s": 27683,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 27733,
"s": 27711,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 27750,
"s": 27733,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 27790,
"s": 27750,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 27823,
"s": 27790,
"text": "Linked List Implementation in C#"
},
{
"code": null,
"e": 27866,
"s": 27823,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 27882,
"s": 27866,
"text": "C# | List Class"
}
] |
Node.js - Response Object
|
The res object represents the HTTP response that an Express app sends when it gets an HTTP request.
Following is the list of few properties associated with response object.
res.app
This property holds a reference to the instance of the express application that is using the middleware.
res.headersSent
Boolean property that indicates if the app sent HTTP headers for the response.
res.locals
An object that contains response local variables scoped to the request
res.append(field [, value])
This method appends the specified value to the HTTP response header field. Following are a few examples β
res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);
res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');
res.append('Warning', '199 Miscellaneous warning');
res.attachment([filename])
This method is used to send a file as an attachment in the HTTP response. Following are a few examples β
res.attachment('path/to/logo.png');
res.cookie(name, value [, options])
This method is used to set cookie name to value. The value parameter may be a string or object converted to JSON. Following are a few examples β
res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true });
res.cookie('cart', { items: [1,2,3] });
res.cookie('cart', { items: [1,2,3] }, { maxAge: 900000 });
res.clearCookie(name [, options])
This method is used to clear the cookie specified by name. Following are a few examples β
res.cookie('name', 'tobi', { path: '/admin' });
res.clearCookie('name', { path: '/admin' });
res.download(path [, filename] [, fn])
This method is used to transfer the file at path as an "attachment". Typically, browsers will prompt the user for download. Following are a few examples β
res.download('/report-12345.pdf');
res.download('/report-12345.pdf', 'report.pdf');
res.download('/report-12345.pdf', 'report.pdf', function(err){
});
res.end([data] [, encoding])
This method is used to end the response process. Following are a few examples β
res.end();
res.status(404).end();
res.format(object)
This method is used to perform content-negotiation on the Accept HTTP header on the request object, when present. Following are a few examples β
res.format ({
'text/plain': function() {
res.send('hey');
},
'text/html': function() {
res.send('hey');
},
'application/json': function() {
res.send({ message: 'hey' });
},
'default': function() {
// log the request and respond with 406
res.status(406).send('Not Acceptable');
}
});
res.get(field)
This method is used to return the HTTP response header specified by field. Here is an examples β
res.get('Content-Type');
res.json([body])
This method is used to send a JSON response. Following are a few examples β
res.json(null)
res.json({ user: 'tobi' })
res.status(500).json({ error: 'message' })
res.jsonp([body])
This method is used to send a JSON response with JSONP support. Following are a few examples β
res.jsonp(null)
res.jsonp({ user: 'tobi' })
res.status(500).jsonp({ error: 'message' })
res.links(links)
This method is used to join the links provided as properties of the parameter to populate the responseβs Link HTTP header field. Following are a few examples β
res.links ({
next: 'http://api.example.com/users?page=2',
last: 'http://api.example.com/users?page=5'
});
res.location(path)
This method is used to set the response Location HTTP header field based on the specified path parameter. Following are a few examples β
res.location('/foo/bar');
res.location('foo/bar');
res.location('http://example.com');
res.redirect([status,] path)
This method is used to redirect to the URL dervied from the specified path, with specified HTTP status code status. Following are a few examples β
res.redirect('/foo/bar');
res.redirect('http://example.com');
res.redirect(301, 'http://example.com');
res.render(view [, locals] [, callback])
This method is used to render a view and sends the rendered HTML string to the client. Following are a few examples β
// send the rendered view to the client
res.render('index');
// pass a local variable to the view
res.render('user', { name: 'Tobi' }, function(err, html) {
// ...
});
res.send([body])
This method is used to send the HTTP response. Following are a few examples β
res.send(new Buffer('whoop'));
res.send({ some: 'json' });
res.send('<p>some html</p>');
res.sendFile(path [, options] [, fn])
This method is used to transfer the file at the given path. Sets the Content-Type response HTTP header field based on the filenameβs extension. Here is an example β
res.sendFile(fileName, options, function (err) {
// ...
});
res.sendStatus(statusCode)
This method is used to set the response HTTP status code to statusCode and send its string representation as the response body. Following are a few examples β
res.sendStatus(200); // equivalent to res.status(200).send('OK')
res.sendStatus(403); // equivalent to res.status(403).send('Forbidden')
res.sendStatus(404); // equivalent to res.status(404).send('Not Found')
res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error')
res.set(field [, value])
This method is used to set the responseβs HTTP header field to value. Following are a few examples β
res.set('Content-Type', 'text/plain');
res.set ({
'Content-Type': 'text/plain',
'Content-Length': '123',
'ETag': '12345'
})
res.status(code)
This method is used to set the HTTP status for the response. Following are a few examples β
res.status(403).end();
res.status(400).send('Bad Request');
res.status(404).sendFile('/absolute/path/to/404.png');
res.type(type)
This method is used to set the Content-Type HTTP header to the MIME type. Following are a few examples β
res.type('.html'); // => 'text/html'
res.type('html'); // => 'text/html'
res.type('json'); // => 'application/json'
res.type('application/json'); // => 'application/json'
res.type('png'); // => image/png:
44 Lectures
7.5 hours
Eduonix Learning Solutions
88 Lectures
17 hours
Eduonix Learning Solutions
32 Lectures
1.5 hours
Richard Wells
8 Lectures
33 mins
Anant Rungta
9 Lectures
2.5 hours
SHIVPRASAD KOIRALA
97 Lectures
6 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2118,
"s": 2018,
"text": "The res object represents the HTTP response that an Express app sends when it gets an HTTP request."
},
{
"code": null,
"e": 2191,
"s": 2118,
"text": "Following is the list of few properties associated with response object."
},
{
"code": null,
"e": 2199,
"s": 2191,
"text": "res.app"
},
{
"code": null,
"e": 2304,
"s": 2199,
"text": "This property holds a reference to the instance of the express application that is using the middleware."
},
{
"code": null,
"e": 2320,
"s": 2304,
"text": "res.headersSent"
},
{
"code": null,
"e": 2399,
"s": 2320,
"text": "Boolean property that indicates if the app sent HTTP headers for the response."
},
{
"code": null,
"e": 2410,
"s": 2399,
"text": "res.locals"
},
{
"code": null,
"e": 2481,
"s": 2410,
"text": "An object that contains response local variables scoped to the request"
},
{
"code": null,
"e": 2510,
"s": 2481,
"text": "res.append(field [, value])\n"
},
{
"code": null,
"e": 2616,
"s": 2510,
"text": "This method appends the specified value to the HTTP response header field. Following are a few examples β"
},
{
"code": null,
"e": 2796,
"s": 2616,
"text": "res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);\nres.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');\nres.append('Warning', '199 Miscellaneous warning');"
},
{
"code": null,
"e": 2824,
"s": 2796,
"text": "res.attachment([filename])\n"
},
{
"code": null,
"e": 2929,
"s": 2824,
"text": "This method is used to send a file as an attachment in the HTTP response. Following are a few examples β"
},
{
"code": null,
"e": 2966,
"s": 2929,
"text": "res.attachment('path/to/logo.png');\n"
},
{
"code": null,
"e": 3003,
"s": 2966,
"text": "res.cookie(name, value [, options])\n"
},
{
"code": null,
"e": 3148,
"s": 3003,
"text": "This method is used to set cookie name to value. The value parameter may be a string or object converted to JSON. Following are a few examples β"
},
{
"code": null,
"e": 3335,
"s": 3148,
"text": "res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true });\n\nres.cookie('cart', { items: [1,2,3] });\nres.cookie('cart', { items: [1,2,3] }, { maxAge: 900000 });"
},
{
"code": null,
"e": 3370,
"s": 3335,
"text": "res.clearCookie(name [, options])\n"
},
{
"code": null,
"e": 3460,
"s": 3370,
"text": "This method is used to clear the cookie specified by name. Following are a few examples β"
},
{
"code": null,
"e": 3554,
"s": 3460,
"text": "res.cookie('name', 'tobi', { path: '/admin' });\nres.clearCookie('name', { path: '/admin' });\n"
},
{
"code": null,
"e": 3594,
"s": 3554,
"text": "res.download(path [, filename] [, fn])\n"
},
{
"code": null,
"e": 3749,
"s": 3594,
"text": "This method is used to transfer the file at path as an \"attachment\". Typically, browsers will prompt the user for download. Following are a few examples β"
},
{
"code": null,
"e": 3903,
"s": 3749,
"text": "res.download('/report-12345.pdf');\n\nres.download('/report-12345.pdf', 'report.pdf');\n\nres.download('/report-12345.pdf', 'report.pdf', function(err){\n\n});"
},
{
"code": null,
"e": 3933,
"s": 3903,
"text": "res.end([data] [, encoding])\n"
},
{
"code": null,
"e": 4013,
"s": 3933,
"text": "This method is used to end the response process. Following are a few examples β"
},
{
"code": null,
"e": 4049,
"s": 4013,
"text": "res.end();\n\nres.status(404).end();\n"
},
{
"code": null,
"e": 4069,
"s": 4049,
"text": "res.format(object)\n"
},
{
"code": null,
"e": 4214,
"s": 4069,
"text": "This method is used to perform content-negotiation on the Accept HTTP header on the request object, when present. Following are a few examples β"
},
{
"code": null,
"e": 4555,
"s": 4214,
"text": "res.format ({\n 'text/plain': function() {\n res.send('hey');\n },\n\n 'text/html': function() {\n res.send('hey'); \n },\n\n 'application/json': function() {\n res.send({ message: 'hey' });\n },\n\n 'default': function() {\n // log the request and respond with 406\n res.status(406).send('Not Acceptable');\n }\n});"
},
{
"code": null,
"e": 4571,
"s": 4555,
"text": "res.get(field)\n"
},
{
"code": null,
"e": 4668,
"s": 4571,
"text": "This method is used to return the HTTP response header specified by field. Here is an examples β"
},
{
"code": null,
"e": 4694,
"s": 4668,
"text": "res.get('Content-Type');\n"
},
{
"code": null,
"e": 4712,
"s": 4694,
"text": "res.json([body])\n"
},
{
"code": null,
"e": 4788,
"s": 4712,
"text": "This method is used to send a JSON response. Following are a few examples β"
},
{
"code": null,
"e": 4873,
"s": 4788,
"text": "res.json(null)\nres.json({ user: 'tobi' })\nres.status(500).json({ error: 'message' })"
},
{
"code": null,
"e": 4892,
"s": 4873,
"text": "res.jsonp([body])\n"
},
{
"code": null,
"e": 4987,
"s": 4892,
"text": "This method is used to send a JSON response with JSONP support. Following are a few examples β"
},
{
"code": null,
"e": 5075,
"s": 4987,
"text": "res.jsonp(null)\nres.jsonp({ user: 'tobi' })\nres.status(500).jsonp({ error: 'message' })"
},
{
"code": null,
"e": 5093,
"s": 5075,
"text": "res.links(links)\n"
},
{
"code": null,
"e": 5253,
"s": 5093,
"text": "This method is used to join the links provided as properties of the parameter to populate the responseβs Link HTTP header field. Following are a few examples β"
},
{
"code": null,
"e": 5365,
"s": 5253,
"text": "res.links ({\n next: 'http://api.example.com/users?page=2',\n last: 'http://api.example.com/users?page=5'\n});"
},
{
"code": null,
"e": 5385,
"s": 5365,
"text": "res.location(path)\n"
},
{
"code": null,
"e": 5522,
"s": 5385,
"text": "This method is used to set the response Location HTTP header field based on the specified path parameter. Following are a few examples β"
},
{
"code": null,
"e": 5609,
"s": 5522,
"text": "res.location('/foo/bar');\nres.location('foo/bar');\nres.location('http://example.com');"
},
{
"code": null,
"e": 5639,
"s": 5609,
"text": "res.redirect([status,] path)\n"
},
{
"code": null,
"e": 5786,
"s": 5639,
"text": "This method is used to redirect to the URL dervied from the specified path, with specified HTTP status code status. Following are a few examples β"
},
{
"code": null,
"e": 5889,
"s": 5786,
"text": "res.redirect('/foo/bar');\nres.redirect('http://example.com');\nres.redirect(301, 'http://example.com');"
},
{
"code": null,
"e": 5931,
"s": 5889,
"text": "res.render(view [, locals] [, callback])\n"
},
{
"code": null,
"e": 6049,
"s": 5931,
"text": "This method is used to render a view and sends the rendered HTML string to the client. Following are a few examples β"
},
{
"code": null,
"e": 6221,
"s": 6049,
"text": "// send the rendered view to the client\nres.render('index');\n\n// pass a local variable to the view\nres.render('user', { name: 'Tobi' }, function(err, html) {\n // ...\n});"
},
{
"code": null,
"e": 6239,
"s": 6221,
"text": "res.send([body])\n"
},
{
"code": null,
"e": 6317,
"s": 6239,
"text": "This method is used to send the HTTP response. Following are a few examples β"
},
{
"code": null,
"e": 6406,
"s": 6317,
"text": "res.send(new Buffer('whoop'));\nres.send({ some: 'json' });\nres.send('<p>some html</p>');"
},
{
"code": null,
"e": 6445,
"s": 6406,
"text": "res.sendFile(path [, options] [, fn])\n"
},
{
"code": null,
"e": 6610,
"s": 6445,
"text": "This method is used to transfer the file at the given path. Sets the Content-Type response HTTP header field based on the filenameβs extension. Here is an example β"
},
{
"code": null,
"e": 6673,
"s": 6610,
"text": "res.sendFile(fileName, options, function (err) {\n // ...\n});"
},
{
"code": null,
"e": 6701,
"s": 6673,
"text": "res.sendStatus(statusCode)\n"
},
{
"code": null,
"e": 6860,
"s": 6701,
"text": "This method is used to set the response HTTP status code to statusCode and send its string representation as the response body. Following are a few examples β"
},
{
"code": null,
"e": 7153,
"s": 6860,
"text": "res.sendStatus(200); // equivalent to res.status(200).send('OK')\nres.sendStatus(403); // equivalent to res.status(403).send('Forbidden')\nres.sendStatus(404); // equivalent to res.status(404).send('Not Found')\nres.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error')"
},
{
"code": null,
"e": 7179,
"s": 7153,
"text": "res.set(field [, value])\n"
},
{
"code": null,
"e": 7281,
"s": 7179,
"text": "This method is used to set the responseβs HTTP header field to value. Following are a few examples β"
},
{
"code": null,
"e": 7415,
"s": 7281,
"text": "res.set('Content-Type', 'text/plain');\n\nres.set ({\n 'Content-Type': 'text/plain',\n 'Content-Length': '123',\n 'ETag': '12345'\n})"
},
{
"code": null,
"e": 7433,
"s": 7415,
"text": "res.status(code)\n"
},
{
"code": null,
"e": 7525,
"s": 7433,
"text": "This method is used to set the HTTP status for the response. Following are a few examples β"
},
{
"code": null,
"e": 7640,
"s": 7525,
"text": "res.status(403).end();\nres.status(400).send('Bad Request');\nres.status(404).sendFile('/absolute/path/to/404.png');"
},
{
"code": null,
"e": 7656,
"s": 7640,
"text": "res.type(type)\n"
},
{
"code": null,
"e": 7761,
"s": 7656,
"text": "This method is used to set the Content-Type HTTP header to the MIME type. Following are a few examples β"
},
{
"code": null,
"e": 8024,
"s": 7761,
"text": "res.type('.html'); // => 'text/html'\nres.type('html'); // => 'text/html'\nres.type('json'); // => 'application/json'\nres.type('application/json'); // => 'application/json'\nres.type('png'); // => image/png:"
},
{
"code": null,
"e": 8059,
"s": 8024,
"text": "\n 44 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 8087,
"s": 8059,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 8121,
"s": 8087,
"text": "\n 88 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 8149,
"s": 8121,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 8184,
"s": 8149,
"text": "\n 32 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8199,
"s": 8184,
"text": " Richard Wells"
},
{
"code": null,
"e": 8230,
"s": 8199,
"text": "\n 8 Lectures \n 33 mins\n"
},
{
"code": null,
"e": 8244,
"s": 8230,
"text": " Anant Rungta"
},
{
"code": null,
"e": 8278,
"s": 8244,
"text": "\n 9 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8298,
"s": 8278,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 8331,
"s": 8298,
"text": "\n 97 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 8351,
"s": 8331,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 8358,
"s": 8351,
"text": " Print"
},
{
"code": null,
"e": 8369,
"s": 8358,
"text": " Add Notes"
}
] |
Java Program to sort Integer list in reversed order
|
Following is our integer array:
Integer[] arr = {20, 50, 100, 150, 200, 250, 300, 350, 400, 500};
Now convert the above Integer array to List:
List<Integer> list = new ArrayList<>(Arrays.asList(arr));
Now, to sort the above Integer list in reversed order:
Comparator<Integer> initialComp = Integer::compare;
Comparator<Integer> revComp = initialComp.reversed();
Collections.sort(list, revComp);
The following is an example to sort Integer list in reversed order:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Demo {
public static void main(String[] args) {
Integer[] arr = {20, 50, 100, 150, 200, 250, 300, 350, 400, 500};
List<Integer> list = new ArrayList<>(Arrays.asList(arr));
System.out.println("Integer List = "+list);
Comparator<Integer> initialComp = Integer::compare;
Comparator<Integer> revComp = initialComp.reversed();
Collections.sort(list, revComp);
System.out.println("Integer in reversed order...");
list
.stream()
.forEach(c -> System.out.print(c + "\n"));
}
}
Integer List = [20, 50, 100, 150, 200, 250, 300, 350, 400, 500]
Integer in reversed order...
500
400
350
300
250
200
150
100
50
20
|
[
{
"code": null,
"e": 1094,
"s": 1062,
"text": "Following is our integer array:"
},
{
"code": null,
"e": 1160,
"s": 1094,
"text": "Integer[] arr = {20, 50, 100, 150, 200, 250, 300, 350, 400, 500};"
},
{
"code": null,
"e": 1205,
"s": 1160,
"text": "Now convert the above Integer array to List:"
},
{
"code": null,
"e": 1263,
"s": 1205,
"text": "List<Integer> list = new ArrayList<>(Arrays.asList(arr));"
},
{
"code": null,
"e": 1318,
"s": 1263,
"text": "Now, to sort the above Integer list in reversed order:"
},
{
"code": null,
"e": 1457,
"s": 1318,
"text": "Comparator<Integer> initialComp = Integer::compare;\nComparator<Integer> revComp = initialComp.reversed();\nCollections.sort(list, revComp);"
},
{
"code": null,
"e": 1525,
"s": 1457,
"text": "The following is an example to sort Integer list in reversed order:"
},
{
"code": null,
"e": 2214,
"s": 1525,
"text": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.List;\npublic class Demo {\n public static void main(String[] args) {\n Integer[] arr = {20, 50, 100, 150, 200, 250, 300, 350, 400, 500};\n List<Integer> list = new ArrayList<>(Arrays.asList(arr));\n System.out.println(\"Integer List = \"+list);\n Comparator<Integer> initialComp = Integer::compare;\n Comparator<Integer> revComp = initialComp.reversed();\n Collections.sort(list, revComp);\n System.out.println(\"Integer in reversed order...\");\n list\n .stream()\n .forEach(c -> System.out.print(c + \"\\n\"));\n }\n}"
},
{
"code": null,
"e": 2345,
"s": 2214,
"text": "Integer List = [20, 50, 100, 150, 200, 250, 300, 350, 400, 500]\nInteger in reversed order...\n500\n400\n350\n300\n250\n200\n150\n100\n50\n20"
}
] |
Matplotlib and Custom Fonts. A More Definitive Guide | by Ryan Louis Stevens | Towards Data Science
|
Thereβs two scenarios Iβve needed to use custom fonts. First, Iβm on an OS with a limited number of pre-installed fonts (*cough* Microsoft *cough*). Second, I need to match the design aesthetic for a specific company Iβm working for, or a project Iβm working on.
To install a custom font to matplotlib requires two steps:
1. Installing custom font on your computer 2. Cleaning up and re-creating matplotlibs cache that stores font info
I will walk through both steps.
While there are plenty of resources online for using custom fonts in matplotlib, they suffer from two problems. First, they are sometimes not a complete guide, only showing you bits and pieces (such as how to re-load the matplotlib cache). Second, they abstract from interacting with fonts and their properties from within matplotlib. To understand fonts from within matplotlib, I will playing a lot with font_manager class, which has a lot of tools to improve both your font game, but also make writing reuseable code a lot simpler.
This walk through is focused on getting fonts to work, because of that I have provided links for how to install the fonts onto your computer.
We will be working with the βProxima Novaβ font.
Installing custom fonts on your computer is very easy. For Mac, you can use the βFont Booksβ app. For Windows, there is a similar workflow where you download a font and then drag and drop into an equivalent Windowsβ fonts app.
For this exercise, I am on a Mac and have installed the βProxima Novaβ font. What does installing a font even mean? Well in our case, it means installing a .ttf (true type font) or .otf (original type font) file to a directory on the computer that Mac recognizes as the font directory. Specifically, one file it installed was this one :
ProximaNova-Regular.otf
This is an important point : fonts are just files on your computer.
All matplotlib does is assign a name, fname, in matplotlib to a file, name which is a location of a .ttf (or .otf) file on your computer.
To map font names to font files, matplotlib has a dictionary (or json file) located in its cache directory. Note, this file is not always in the same place, but usually sits at the home directory. If you are on mac (windows), it usually sits at whereever your HOME (%HOME%) environmental variable is set to.
To get matplotlib to recognize that we have a new font file on our computer, we just need to delete and reload this dictionary mapping font names to font files:
(1) Delete matplotlib font cache file (2) Re-create this file using matplotlib
For (1), you can remove the font list file from the command line. This is on Mac:
rm ~/.matplotlib/fontlist-v300.json
For (2), we are recreating that same json file we just deleted using the font_manager class from within python
from matplotlib import font_manager# Rebuild font cachefont_manager.__rebuild()
While this process tends to work, I have run into problems (especially on my other Windows machine). So before you run those two commands, letβs look at a few ways to verify what fonts matplotlib actually sees, i.e. those fonts available to be used from within matplotlib.
One way is to do a simple word search on the cache file fontlist-v300.json above. This file is in json format (basically a nested dictionary), each entry has a font and the fonts associated properties, such as the file associated with the font, fname, as well as, the associated weight (or thickness) of the font, weight.
One interesting thing is that you can see that font names repeat themselves. There are multiple entries that share the Helvetica font name attribute, but have different font files, which are shown in the fname attribute. Why is there a different font file for the same name? Because these are not the same exact font! The different font files are associated with different weight attributes (or how thick your characters are). There is separate files for the bold and normal font weight. Once again, fonts are just files.
I started this by saying you can inspect the cache file, so I went looking for name βProxima Novaβ in this file, and lo and behold it is not in the json cache file.
While the font cache file is nice, it would be a bit easier to inspect these within matplotlib. Luckily our font_manager class is able to do that. One way to inspect fonts is to get the list of FontEntry objects using our font_manager class. These are special objects that allow us to inspect fonts their properties. We see below we are accessing the ttflist attribute, which makes sense because β.ttfβ files are the types of files fonts come from.
I showed above a rudimentary way to find all font names with Arial. However, matplotlib is already one step ahead of you. Within our font_manager class, there is a find_font function, which employs a nearest neighbor search method to try and a find a font with the name you give it. What we see if that it canβt find a Proxima Nova font file (as expected), and instead defaults to Deja Vu Sans.
After inspecting the files using the steps above, I returned to Step 2, deleted and re-created the cache. We can now check (from within python) that βProxima Novaβ can be found by our font_manager class. What we see now is that our βProxima Novaβ font can be found!
We can see that when we set the global rc param, that our font is now useable.
Another way of accomplishing similar goals is to set the font for specific objects on your plot. Here we change the global font to Comic Sans, and then change only the title of the plot to Proxima Nova. We use one of my favorite sub-classes of the font_manager class, the FontProperties classes. Here my variable myFont is a instance of this class, specifically, itβs a size 30, Proxima Nova font. The nice thing about this is you can create templates much easier if you simply create different FontProperties instances for different objects in your graph (such as title or axis label instance).
Getting custom fonts to work in matplotlib is a simple process, download the font files and then reload matplotlib caches. The main takeaway from this exercise is that fonts are files, and getting custom fonts to work is a process of getting matplotlib to find those files. To get deeper into all the methods and instances of the font_manager class, I suggest you checkout the font_manager class page from matplotlib developers. Happy plotting!
|
[
{
"code": null,
"e": 435,
"s": 172,
"text": "Thereβs two scenarios Iβve needed to use custom fonts. First, Iβm on an OS with a limited number of pre-installed fonts (*cough* Microsoft *cough*). Second, I need to match the design aesthetic for a specific company Iβm working for, or a project Iβm working on."
},
{
"code": null,
"e": 494,
"s": 435,
"text": "To install a custom font to matplotlib requires two steps:"
},
{
"code": null,
"e": 608,
"s": 494,
"text": "1. Installing custom font on your computer 2. Cleaning up and re-creating matplotlibs cache that stores font info"
},
{
"code": null,
"e": 640,
"s": 608,
"text": "I will walk through both steps."
},
{
"code": null,
"e": 1174,
"s": 640,
"text": "While there are plenty of resources online for using custom fonts in matplotlib, they suffer from two problems. First, they are sometimes not a complete guide, only showing you bits and pieces (such as how to re-load the matplotlib cache). Second, they abstract from interacting with fonts and their properties from within matplotlib. To understand fonts from within matplotlib, I will playing a lot with font_manager class, which has a lot of tools to improve both your font game, but also make writing reuseable code a lot simpler."
},
{
"code": null,
"e": 1316,
"s": 1174,
"text": "This walk through is focused on getting fonts to work, because of that I have provided links for how to install the fonts onto your computer."
},
{
"code": null,
"e": 1365,
"s": 1316,
"text": "We will be working with the βProxima Novaβ font."
},
{
"code": null,
"e": 1592,
"s": 1365,
"text": "Installing custom fonts on your computer is very easy. For Mac, you can use the βFont Booksβ app. For Windows, there is a similar workflow where you download a font and then drag and drop into an equivalent Windowsβ fonts app."
},
{
"code": null,
"e": 1929,
"s": 1592,
"text": "For this exercise, I am on a Mac and have installed the βProxima Novaβ font. What does installing a font even mean? Well in our case, it means installing a .ttf (true type font) or .otf (original type font) file to a directory on the computer that Mac recognizes as the font directory. Specifically, one file it installed was this one :"
},
{
"code": null,
"e": 1953,
"s": 1929,
"text": "ProximaNova-Regular.otf"
},
{
"code": null,
"e": 2021,
"s": 1953,
"text": "This is an important point : fonts are just files on your computer."
},
{
"code": null,
"e": 2159,
"s": 2021,
"text": "All matplotlib does is assign a name, fname, in matplotlib to a file, name which is a location of a .ttf (or .otf) file on your computer."
},
{
"code": null,
"e": 2467,
"s": 2159,
"text": "To map font names to font files, matplotlib has a dictionary (or json file) located in its cache directory. Note, this file is not always in the same place, but usually sits at the home directory. If you are on mac (windows), it usually sits at whereever your HOME (%HOME%) environmental variable is set to."
},
{
"code": null,
"e": 2628,
"s": 2467,
"text": "To get matplotlib to recognize that we have a new font file on our computer, we just need to delete and reload this dictionary mapping font names to font files:"
},
{
"code": null,
"e": 2707,
"s": 2628,
"text": "(1) Delete matplotlib font cache file (2) Re-create this file using matplotlib"
},
{
"code": null,
"e": 2789,
"s": 2707,
"text": "For (1), you can remove the font list file from the command line. This is on Mac:"
},
{
"code": null,
"e": 2825,
"s": 2789,
"text": "rm ~/.matplotlib/fontlist-v300.json"
},
{
"code": null,
"e": 2936,
"s": 2825,
"text": "For (2), we are recreating that same json file we just deleted using the font_manager class from within python"
},
{
"code": null,
"e": 3016,
"s": 2936,
"text": "from matplotlib import font_manager# Rebuild font cachefont_manager.__rebuild()"
},
{
"code": null,
"e": 3289,
"s": 3016,
"text": "While this process tends to work, I have run into problems (especially on my other Windows machine). So before you run those two commands, letβs look at a few ways to verify what fonts matplotlib actually sees, i.e. those fonts available to be used from within matplotlib."
},
{
"code": null,
"e": 3611,
"s": 3289,
"text": "One way is to do a simple word search on the cache file fontlist-v300.json above. This file is in json format (basically a nested dictionary), each entry has a font and the fonts associated properties, such as the file associated with the font, fname, as well as, the associated weight (or thickness) of the font, weight."
},
{
"code": null,
"e": 4133,
"s": 3611,
"text": "One interesting thing is that you can see that font names repeat themselves. There are multiple entries that share the Helvetica font name attribute, but have different font files, which are shown in the fname attribute. Why is there a different font file for the same name? Because these are not the same exact font! The different font files are associated with different weight attributes (or how thick your characters are). There is separate files for the bold and normal font weight. Once again, fonts are just files."
},
{
"code": null,
"e": 4298,
"s": 4133,
"text": "I started this by saying you can inspect the cache file, so I went looking for name βProxima Novaβ in this file, and lo and behold it is not in the json cache file."
},
{
"code": null,
"e": 4747,
"s": 4298,
"text": "While the font cache file is nice, it would be a bit easier to inspect these within matplotlib. Luckily our font_manager class is able to do that. One way to inspect fonts is to get the list of FontEntry objects using our font_manager class. These are special objects that allow us to inspect fonts their properties. We see below we are accessing the ttflist attribute, which makes sense because β.ttfβ files are the types of files fonts come from."
},
{
"code": null,
"e": 5142,
"s": 4747,
"text": "I showed above a rudimentary way to find all font names with Arial. However, matplotlib is already one step ahead of you. Within our font_manager class, there is a find_font function, which employs a nearest neighbor search method to try and a find a font with the name you give it. What we see if that it canβt find a Proxima Nova font file (as expected), and instead defaults to Deja Vu Sans."
},
{
"code": null,
"e": 5408,
"s": 5142,
"text": "After inspecting the files using the steps above, I returned to Step 2, deleted and re-created the cache. We can now check (from within python) that βProxima Novaβ can be found by our font_manager class. What we see now is that our βProxima Novaβ font can be found!"
},
{
"code": null,
"e": 5487,
"s": 5408,
"text": "We can see that when we set the global rc param, that our font is now useable."
},
{
"code": null,
"e": 6083,
"s": 5487,
"text": "Another way of accomplishing similar goals is to set the font for specific objects on your plot. Here we change the global font to Comic Sans, and then change only the title of the plot to Proxima Nova. We use one of my favorite sub-classes of the font_manager class, the FontProperties classes. Here my variable myFont is a instance of this class, specifically, itβs a size 30, Proxima Nova font. The nice thing about this is you can create templates much easier if you simply create different FontProperties instances for different objects in your graph (such as title or axis label instance)."
}
] |
Delete alternate nodes of a Linked List in C++
|
In this tutorial, we are going to learn how to delete all prime nodes from a singly linked list.
Let's see the steps to solve the problem.
Write struct with data and next pointer.
Write struct with data and next pointer.
Write a function to insert the node into the singly linked list.
Write a function to insert the node into the singly linked list.
Initialize the singly linked list with dummy data.
Initialize the singly linked list with dummy data.
Iterate over the singly linked list.
Iterate over the singly linked list.
Delete alternate node by maintaining the previous node.
Delete alternate node by maintaining the previous node.
Write a function to delete the node. Consider the following three cases while deleting the node.If the node is head node, then move the head to next node.If the node is middle node, then link the next node to the previous nodeIf the node is end node, then remove the previous node link.
Let's see the code.
Write a function to delete the node. Consider the following three cases while deleting the node.
If the node is head node, then move the head to next node.
If the node is head node, then move the head to next node.
If the node is middle node, then link the next node to the previous node
If the node is middle node, then link the next node to the previous node
If the node is end node, then remove the previous node link.
Let's see the code.
If the node is end node, then remove the previous node link.
Let's see the code.
Live Demo
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *next;
};
void deleteAlternateNodes(Node *head) {
if (head == NULL)
return;
Node *prev = head;
Node *node = head->next;
while (prev != NULL && node != NULL) {
prev->next = node->next;
free(node);
prev = prev->next;
if (prev != NULL) {
node = prev->next;
}
}
}
void insertNode(Node** head_ref, int new_data) {
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printLinkedList(Node *node) {
while (node != NULL) {
cout << node->data << " -> ";
node = node->next;
}
}
int main() {
Node* head = NULL;
insertNode(&head, 1);
insertNode(&head, 2);
insertNode(&head, 3);
insertNode(&head, 4);
insertNode(&head, 5);
insertNode(&head, 6);
cout << "Linked List before deletion:" << endl;
printLinkedList(head);
deleteAlternateNodes(head);
cout << "\nLinked List after deletion:" << endl;
printLinkedList(head);
return 0;
}
If you execute the above program, then you will get the following result.
Linked List before deletion:
6 -> 5 -> 4 -> 3 -> 2 -> 1 ->
Linked List after deletion:
6 -> 4 -> 2 ->
If you have any queries in the tutorial, mention them in the comment section.
|
[
{
"code": null,
"e": 1159,
"s": 1062,
"text": "In this tutorial, we are going to learn how to delete all prime nodes from a singly linked list."
},
{
"code": null,
"e": 1201,
"s": 1159,
"text": "Let's see the steps to solve the problem."
},
{
"code": null,
"e": 1242,
"s": 1201,
"text": "Write struct with data and next pointer."
},
{
"code": null,
"e": 1283,
"s": 1242,
"text": "Write struct with data and next pointer."
},
{
"code": null,
"e": 1348,
"s": 1283,
"text": "Write a function to insert the node into the singly linked list."
},
{
"code": null,
"e": 1413,
"s": 1348,
"text": "Write a function to insert the node into the singly linked list."
},
{
"code": null,
"e": 1464,
"s": 1413,
"text": "Initialize the singly linked list with dummy data."
},
{
"code": null,
"e": 1515,
"s": 1464,
"text": "Initialize the singly linked list with dummy data."
},
{
"code": null,
"e": 1552,
"s": 1515,
"text": "Iterate over the singly linked list."
},
{
"code": null,
"e": 1589,
"s": 1552,
"text": "Iterate over the singly linked list."
},
{
"code": null,
"e": 1645,
"s": 1589,
"text": "Delete alternate node by maintaining the previous node."
},
{
"code": null,
"e": 1701,
"s": 1645,
"text": "Delete alternate node by maintaining the previous node."
},
{
"code": null,
"e": 2008,
"s": 1701,
"text": "Write a function to delete the node. Consider the following three cases while deleting the node.If the node is head node, then move the head to next node.If the node is middle node, then link the next node to the previous nodeIf the node is end node, then remove the previous node link.\nLet's see the code."
},
{
"code": null,
"e": 2105,
"s": 2008,
"text": "Write a function to delete the node. Consider the following three cases while deleting the node."
},
{
"code": null,
"e": 2164,
"s": 2105,
"text": "If the node is head node, then move the head to next node."
},
{
"code": null,
"e": 2223,
"s": 2164,
"text": "If the node is head node, then move the head to next node."
},
{
"code": null,
"e": 2296,
"s": 2223,
"text": "If the node is middle node, then link the next node to the previous node"
},
{
"code": null,
"e": 2369,
"s": 2296,
"text": "If the node is middle node, then link the next node to the previous node"
},
{
"code": null,
"e": 2450,
"s": 2369,
"text": "If the node is end node, then remove the previous node link.\nLet's see the code."
},
{
"code": null,
"e": 2531,
"s": 2450,
"text": "If the node is end node, then remove the previous node link.\nLet's see the code."
},
{
"code": null,
"e": 2542,
"s": 2531,
"text": " Live Demo"
},
{
"code": null,
"e": 3631,
"s": 2542,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nstruct Node {\n int data;\n Node *next;\n};\nvoid deleteAlternateNodes(Node *head) {\n if (head == NULL)\n return;\n Node *prev = head;\n Node *node = head->next;\n while (prev != NULL && node != NULL) {\n prev->next = node->next;\n free(node);\n prev = prev->next;\n if (prev != NULL) {\n node = prev->next;\n }\n }\n}\nvoid insertNode(Node** head_ref, int new_data) {\n Node* new_node = new Node();\n new_node->data = new_data;\n new_node->next = (*head_ref);\n (*head_ref) = new_node;\n}\nvoid printLinkedList(Node *node) {\n while (node != NULL) {\n cout << node->data << \" -> \";\n node = node->next;\n }\n}\nint main() {\n Node* head = NULL;\n insertNode(&head, 1);\n insertNode(&head, 2);\n insertNode(&head, 3);\n insertNode(&head, 4);\n insertNode(&head, 5);\n insertNode(&head, 6);\n cout << \"Linked List before deletion:\" << endl;\n printLinkedList(head);\n deleteAlternateNodes(head);\n cout << \"\\nLinked List after deletion:\" << endl;\n printLinkedList(head);\n return 0;\n}"
},
{
"code": null,
"e": 3705,
"s": 3631,
"text": "If you execute the above program, then you will get the following result."
},
{
"code": null,
"e": 3807,
"s": 3705,
"text": "Linked List before deletion:\n6 -> 5 -> 4 -> 3 -> 2 -> 1 ->\nLinked List after deletion:\n6 -> 4 -> 2 ->"
},
{
"code": null,
"e": 3885,
"s": 3807,
"text": "If you have any queries in the tutorial, mention them in the comment section."
}
] |
Drools - Sample Drools Program
|
In this chapter, we will create a Drools project for the following problem statement β
We will have two DRL files for our Drools project. The two DRL files will signify two cities in consideration (Pune and Nagpur) and four types of products (groceries, medicines, watches, and luxury goods).
The tax on medicines in both the cities is considered as zero.
The tax on medicines in both the cities is considered as zero.
For groceries, we have assumed a tax of Rs 2 in Pune and Rs 1 in Nagpur.
For groceries, we have assumed a tax of Rs 2 in Pune and Rs 1 in Nagpur.
We have used the same selling price to demonstrate different outputs. Note that all the rules are getting fired in the application.
Here is the model to hold each itemType β
package com.sample;
import java.math.BigDecimal;
public class ItemCity {
public enum City {
PUNE, NAGPUR
}
public enum Type {
GROCERIES, MEDICINES, WATCHES, LUXURYGOODS
}
private City purchaseCity;
private BigDecimal sellPrice;
private Type typeofItem;
private BigDecimal localTax;
public City getPurchaseCity() {
return purchaseCity;
}
public void setPurchaseCity(City purchaseCity) {
this.purchaseCity = purchaseCity;
}
public BigDecimal getSellPrice() {
return sellPrice;
}
public void setSellPrice(BigDecimal sellPrice) {
this.sellPrice = sellPrice;
}
public Type getTypeofItem() {
return typeofItem;
}
public void setTypeofItem(Type typeofItem) {
this.typeofItem = typeofItem;
}
public BigDecimal getLocalTax() {
return localTax;
}
public void setLocalTax(BigDecimal localTax) {
this.localTax = localTax;
}
}
As suggested earlier, we have used two DRL files here: Pune.drl and Nagpur.drl.
This is the DRL file that executes rules for Pune city.
// created on: Dec 24, 2014
package droolsexample
// list any import classes here.
import com.sample.ItemCity;
import java.math.BigDecimal;
// declare any global variables here
dialect "java"
rule "Pune Medicine Item"
when
item : ItemCity (purchaseCity == ItemCity.City.PUNE,
typeofItem == ItemCity.Type.MEDICINES)
then
BigDecimal tax = new BigDecimal(0.0);
item.setLocalTax(tax.multiply(item.getSellPrice()));
end
rule "Pune Groceries Item"
when
item : ItemCity(purchaseCity == ItemCity.City.PUNE,
typeofItem == ItemCity.Type.GROCERIES)
then
BigDecimal tax = new BigDecimal(2.0);
item.setLocalTax(tax.multiply(item.getSellPrice()));
end
This is the DRL file that executes rules for Nagpur city.
// created on: Dec 26, 2014
package droolsexample
// list any import classes here.
import com.sample.ItemCity;
import java.math.BigDecimal;
// declare any global variables here
dialect "java"
rule "Nagpur Medicine Item"
when
item : ItemCity(purchaseCity == ItemCity.City.NAGPUR,
typeofItem == ItemCity.Type.MEDICINES)
then
BigDecimal tax = new BigDecimal(0.0);
item.setLocalTax(tax.multiply(item.getSellPrice()));
end
rule "Nagpur Groceries Item"
when
item : ItemCity(purchaseCity == ItemCity.City.NAGPUR,
typeofItem == ItemCity.Type.GROCERIES)
then
BigDecimal tax = new BigDecimal(1.0);
item.setLocalTax(tax.multiply(item.getSellPrice()));
end
We have written the DRL files based on city, as it gives us extensibility to add any number of rule files later if new cities are being added.
To demonstrate that all the rules are getting triggered from our rule files, we have used two item types (medicines and groceries); and medicine is tax-free and groceries are taxed as per the city.
Our test class loads the rule files, inserts the facts into the session, and produces the output.
package com.sample;
import java.math.BigDecimal;
import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderError;
import org.drools.builder.KnowledgeBuilderErrors;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.io.ResourceFactory;
import org.drools.runtime.StatefulKnowledgeSession;
import com.sample.ItemCity.City;
import com.sample.ItemCity.Type;
/*
*This is a sample class to launch a rule.
*/
public class DroolsTest {
public static final void main(String[] args) {
try {
// load up the knowledge base
KnowledgeBase kbase = readKnowledgeBase();
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
ItemCity item1 = new ItemCity();
item1.setPurchaseCity(City.PUNE);
item1.setTypeofItem(Type.MEDICINES);
item1.setSellPrice(new BigDecimal(10));
ksession.insert(item1);
ItemCity item2 = new ItemCity();
item2.setPurchaseCity(City.PUNE);
item2.setTypeofItem(Type.GROCERIES);
item2.setSellPrice(new BigDecimal(10));
ksession.insert(item2);
ItemCity item3 = new ItemCity();
item3.setPurchaseCity(City.NAGPUR);
item3.setTypeofItem(Type.MEDICINES);
item3.setSellPrice(new BigDecimal(10));
ksession.insert(item3);
ItemCity item4 = new ItemCity();
item4.setPurchaseCity(City.NAGPUR);
item4.setTypeofItem(Type.GROCERIES);
item4.setSellPrice(new BigDecimal(10));
ksession.insert(item4);
ksession.fireAllRules();
System.out.println(item1.getPurchaseCity().toString() + " "
+ item1.getLocalTax().intValue());
System.out.println(item2.getPurchaseCity().toString() + " "
+ item2.getLocalTax().intValue());
System.out.println(item3.getPurchaseCity().toString() + " "
+ item3.getLocalTax().intValue());
System.out.println(item4.getPurchaseCity().toString() + " "
+ item4.getLocalTax().intValue());
} catch (Throwable t) {
t.printStackTrace();
}
}
private static KnowledgeBase readKnowledgeBase() throws Exception {
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add(ResourceFactory.newClassPathResource("Pune.drl"), ResourceType.DRL);
kbuilder.add(ResourceFactory.newClassPathResource("Nagpur.drl"), ResourceType.DRL);
KnowledgeBuilderErrors errors = kbuilder.getErrors();
if (errors.size() > 0) {
for (KnowledgeBuilderError error: errors) {
System.err.println(error);
}
throw new IllegalArgumentException("Could not parse knowledge.");
}
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
return kbase;
}
}
If you run this program, its output would be as follows β
PUNE 0
PUNE 20
NAGPUR 0
NAGPUR 10
For both Pune and Nagpur, when the item is a medicine, the local tax is zero; whereas when the item is a grocery product, the tax is as per the city. More rules can be added in the DRL files for other products. This is just a sample program.
Here we will demonstrate how to call a static function from a Java file within your DRL file.
First of all, create a class HelloCity.java in the same package com.sample.
package com.sample;
public class HelloCity {
public static void writeHello(String name) {
System.out.println("HELLO " + name + "!!!!!!");
}
}
Thereafter, add the import statement in the DRL file to call the writeHello method from the DRL file. In the following code block, the changes in the DRL file Pune.drl are highlighted in yellow.
// created on: Dec 24, 2014
package droolsexample
// list any import classes here.
import com.sample.ItemCity;
import java.math.BigDecimal;
import com.sample.HelloCity;
//declare any global variables here
dialect "java"
rule "Pune Medicine Item"
when
item : ItemCity(purchaseCity == ItemCity.City.PUNE,
typeofItem == ItemCity.Type.MEDICINES)
then
BigDecimal tax = new BigDecimal(0.0);
item.setLocalTax(tax.multiply(item.getSellPrice()));
HelloCity.writeHello(item.getPurchaseCity().toString());
end
rule "Pune Groceries Item"
when
item : ItemCity(purchaseCity == ItemCity.City.PUNE,
typeofItem == ItemCity.Type.GROCERIES)
then
BigDecimal tax = new BigDecimal(2.0);
item.setLocalTax(tax.multiply(item.getSellPrice()));
end
Run the program again and its output would be as follows β
HELLO PUNE!!!!!!
PUNE 0
PUNE 20
NAGPUR 0
NAGPUR 10
The difference now in the output is marked in yellow which shows the output of the static method in the Java class.
The advantage to call a Java method is that we can write any utility/helper function in Java and call the same from a DRL file.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1884,
"s": 1797,
"text": "In this chapter, we will create a Drools project for the following problem statement β"
},
{
"code": null,
"e": 2090,
"s": 1884,
"text": "We will have two DRL files for our Drools project. The two DRL files will signify two cities in consideration (Pune and Nagpur) and four types of products (groceries, medicines, watches, and luxury goods)."
},
{
"code": null,
"e": 2153,
"s": 2090,
"text": "The tax on medicines in both the cities is considered as zero."
},
{
"code": null,
"e": 2216,
"s": 2153,
"text": "The tax on medicines in both the cities is considered as zero."
},
{
"code": null,
"e": 2289,
"s": 2216,
"text": "For groceries, we have assumed a tax of Rs 2 in Pune and Rs 1 in Nagpur."
},
{
"code": null,
"e": 2362,
"s": 2289,
"text": "For groceries, we have assumed a tax of Rs 2 in Pune and Rs 1 in Nagpur."
},
{
"code": null,
"e": 2494,
"s": 2362,
"text": "We have used the same selling price to demonstrate different outputs. Note that all the rules are getting fired in the application."
},
{
"code": null,
"e": 2536,
"s": 2494,
"text": "Here is the model to hold each itemType β"
},
{
"code": null,
"e": 3486,
"s": 2536,
"text": "package com.sample;\nimport java.math.BigDecimal;\npublic class ItemCity {\n public enum City {\n PUNE, NAGPUR\n }\n public enum Type {\n GROCERIES, MEDICINES, WATCHES, LUXURYGOODS\n }\n private City purchaseCity;\n private BigDecimal sellPrice;\n private Type typeofItem;\n private BigDecimal localTax;\n \n public City getPurchaseCity() {\n return purchaseCity;\n }\n public void setPurchaseCity(City purchaseCity) {\n this.purchaseCity = purchaseCity;\n }\n public BigDecimal getSellPrice() {\n return sellPrice;\n }\n public void setSellPrice(BigDecimal sellPrice) {\n this.sellPrice = sellPrice;\n }\n public Type getTypeofItem() {\n return typeofItem;\n }\n public void setTypeofItem(Type typeofItem) {\n this.typeofItem = typeofItem;\n }\n public BigDecimal getLocalTax() {\n return localTax;\n }\n public void setLocalTax(BigDecimal localTax) {\n this.localTax = localTax;\n }\n}"
},
{
"code": null,
"e": 3566,
"s": 3486,
"text": "As suggested earlier, we have used two DRL files here: Pune.drl and Nagpur.drl."
},
{
"code": null,
"e": 3622,
"s": 3566,
"text": "This is the DRL file that executes rules for Pune city."
},
{
"code": null,
"e": 4329,
"s": 3622,
"text": "// created on: Dec 24, 2014\npackage droolsexample\n\n// list any import classes here.\nimport com.sample.ItemCity;\nimport java.math.BigDecimal;\n\n// declare any global variables here\ndialect \"java\"\nrule \"Pune Medicine Item\"\n when\n item : ItemCity (purchaseCity == ItemCity.City.PUNE,\n typeofItem == ItemCity.Type.MEDICINES)\n then\n BigDecimal tax = new BigDecimal(0.0);\n item.setLocalTax(tax.multiply(item.getSellPrice()));\nend\n\nrule \"Pune Groceries Item\"\n when\n item : ItemCity(purchaseCity == ItemCity.City.PUNE,\n typeofItem == ItemCity.Type.GROCERIES)\n then\n BigDecimal tax = new BigDecimal(2.0);\n item.setLocalTax(tax.multiply(item.getSellPrice()));\nend"
},
{
"code": null,
"e": 4387,
"s": 4329,
"text": "This is the DRL file that executes rules for Nagpur city."
},
{
"code": null,
"e": 5103,
"s": 4387,
"text": "// created on: Dec 26, 2014\npackage droolsexample\n\n// list any import classes here.\nimport com.sample.ItemCity;\nimport java.math.BigDecimal;\n\n// declare any global variables here\ndialect \"java\"\nrule \"Nagpur Medicine Item\"\n when\n item : ItemCity(purchaseCity == ItemCity.City.NAGPUR, \n typeofItem == ItemCity.Type.MEDICINES)\n then\n BigDecimal tax = new BigDecimal(0.0);\n item.setLocalTax(tax.multiply(item.getSellPrice()));\nend\n\nrule \"Nagpur Groceries Item\"\n when\n item : ItemCity(purchaseCity == ItemCity.City.NAGPUR, \n typeofItem == ItemCity.Type.GROCERIES)\n then\n BigDecimal tax = new BigDecimal(1.0);\n item.setLocalTax(tax.multiply(item.getSellPrice()));\nend"
},
{
"code": null,
"e": 5246,
"s": 5103,
"text": "We have written the DRL files based on city, as it gives us extensibility to add any number of rule files later if new cities are being added."
},
{
"code": null,
"e": 5444,
"s": 5246,
"text": "To demonstrate that all the rules are getting triggered from our rule files, we have used two item types (medicines and groceries); and medicine is tax-free and groceries are taxed as per the city."
},
{
"code": null,
"e": 5542,
"s": 5444,
"text": "Our test class loads the rule files, inserts the facts into the session, and produces the output."
},
{
"code": null,
"e": 8704,
"s": 5542,
"text": "package com.sample;\n\nimport java.math.BigDecimal;\nimport org.drools.KnowledgeBase;\nimport org.drools.KnowledgeBaseFactory;\nimport org.drools.builder.KnowledgeBuilder;\nimport org.drools.builder.KnowledgeBuilderError;\nimport org.drools.builder.KnowledgeBuilderErrors;\nimport org.drools.builder.KnowledgeBuilderFactory;\nimport org.drools.builder.ResourceType;\nimport org.drools.io.ResourceFactory;\nimport org.drools.runtime.StatefulKnowledgeSession;\nimport com.sample.ItemCity.City;\nimport com.sample.ItemCity.Type;\n\n/* \n *This is a sample class to launch a rule. \n*/\n\npublic class DroolsTest {\n public static final void main(String[] args) {\n try {\n // load up the knowledge base\n KnowledgeBase kbase = readKnowledgeBase();\n StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();\n \n ItemCity item1 = new ItemCity();\n item1.setPurchaseCity(City.PUNE);\n item1.setTypeofItem(Type.MEDICINES);\n item1.setSellPrice(new BigDecimal(10));\n ksession.insert(item1);\n \n ItemCity item2 = new ItemCity();\n item2.setPurchaseCity(City.PUNE);\n item2.setTypeofItem(Type.GROCERIES);\n item2.setSellPrice(new BigDecimal(10));\n ksession.insert(item2);\n \n ItemCity item3 = new ItemCity();\n item3.setPurchaseCity(City.NAGPUR);\n item3.setTypeofItem(Type.MEDICINES);\n item3.setSellPrice(new BigDecimal(10));\n ksession.insert(item3);\n \n ItemCity item4 = new ItemCity();\n item4.setPurchaseCity(City.NAGPUR);\n item4.setTypeofItem(Type.GROCERIES);\n item4.setSellPrice(new BigDecimal(10)); \n ksession.insert(item4);\n \n ksession.fireAllRules();\n \n System.out.println(item1.getPurchaseCity().toString() + \" \" \n + item1.getLocalTax().intValue());\n \n System.out.println(item2.getPurchaseCity().toString() + \" \"\n + item2.getLocalTax().intValue());\n \n System.out.println(item3.getPurchaseCity().toString() + \" \"\n + item3.getLocalTax().intValue());\n \n System.out.println(item4.getPurchaseCity().toString() + \" \"\n + item4.getLocalTax().intValue());\n \n } catch (Throwable t) {\n t.printStackTrace();\n }\n }\n private static KnowledgeBase readKnowledgeBase() throws Exception {\n KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();\n kbuilder.add(ResourceFactory.newClassPathResource(\"Pune.drl\"), ResourceType.DRL);\n kbuilder.add(ResourceFactory.newClassPathResource(\"Nagpur.drl\"), ResourceType.DRL);\n KnowledgeBuilderErrors errors = kbuilder.getErrors();\n \n if (errors.size() > 0) {\n for (KnowledgeBuilderError error: errors) {\n System.err.println(error);\n }\n throw new IllegalArgumentException(\"Could not parse knowledge.\");\n }\n KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();\n kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());\n return kbase;\n }\n}"
},
{
"code": null,
"e": 8762,
"s": 8704,
"text": "If you run this program, its output would be as follows β"
},
{
"code": null,
"e": 8797,
"s": 8762,
"text": "PUNE 0\nPUNE 20\nNAGPUR 0\nNAGPUR 10\n"
},
{
"code": null,
"e": 9039,
"s": 8797,
"text": "For both Pune and Nagpur, when the item is a medicine, the local tax is zero; whereas when the item is a grocery product, the tax is as per the city. More rules can be added in the DRL files for other products. This is just a sample program."
},
{
"code": null,
"e": 9133,
"s": 9039,
"text": "Here we will demonstrate how to call a static function from a Java file within your DRL file."
},
{
"code": null,
"e": 9209,
"s": 9133,
"text": "First of all, create a class HelloCity.java in the same package com.sample."
},
{
"code": null,
"e": 9364,
"s": 9209,
"text": "package com.sample;\n\npublic class HelloCity {\n public static void writeHello(String name) {\n System.out.println(\"HELLO \" + name + \"!!!!!!\");\n }\n}"
},
{
"code": null,
"e": 9559,
"s": 9364,
"text": "Thereafter, add the import statement in the DRL file to call the writeHello method from the DRL file. In the following code block, the changes in the DRL file Pune.drl are highlighted in yellow."
},
{
"code": null,
"e": 10361,
"s": 9559,
"text": "// created on: Dec 24, 2014\npackage droolsexample\n\n// list any import classes here.\nimport com.sample.ItemCity;\nimport java.math.BigDecimal;\n \nimport com.sample.HelloCity;\n\n//declare any global variables here\ndialect \"java\"\n\nrule \"Pune Medicine Item\"\n when\n item : ItemCity(purchaseCity == ItemCity.City.PUNE, \n typeofItem == ItemCity.Type.MEDICINES)\n then\n BigDecimal tax = new BigDecimal(0.0);\n item.setLocalTax(tax.multiply(item.getSellPrice()));\n HelloCity.writeHello(item.getPurchaseCity().toString());\nend\n\nrule \"Pune Groceries Item\"\n when\n item : ItemCity(purchaseCity == ItemCity.City.PUNE, \n typeofItem == ItemCity.Type.GROCERIES)\n then\n BigDecimal tax = new BigDecimal(2.0);\n item.setLocalTax(tax.multiply(item.getSellPrice()));\nend"
},
{
"code": null,
"e": 10420,
"s": 10361,
"text": "Run the program again and its output would be as follows β"
},
{
"code": null,
"e": 10472,
"s": 10420,
"text": "HELLO PUNE!!!!!!\nPUNE 0\nPUNE 20\nNAGPUR 0\nNAGPUR 10\n"
},
{
"code": null,
"e": 10588,
"s": 10472,
"text": "The difference now in the output is marked in yellow which shows the output of the static method in the Java class."
},
{
"code": null,
"e": 10716,
"s": 10588,
"text": "The advantage to call a Java method is that we can write any utility/helper function in Java and call the same from a DRL file."
},
{
"code": null,
"e": 10723,
"s": 10716,
"text": " Print"
},
{
"code": null,
"e": 10734,
"s": 10723,
"text": " Add Notes"
}
] |
Goto in Arduino
|
goto is a control structure in Arduino, like in C, and it is used to transfer the program flow to another point in the program. It is highly discouraged, as many programmers agree that you can write every algorithm you want without the use of goto.
Excessive use of goto makes it very difficult to debug programs, or, in some cases, creates program flows which are impossible to debug. It is assumed that you will read further only if you absolutely have to use goto.
The syntax for using goto is β
goto label;
label:
//statements
The following example demonstrates this β
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println();
int x = random(5);
Serial.print("Value of x is ");Serial.println(x);
if (x % 2 == 0) {
goto even_print;
} else {
goto odd_print;
}
Serial.println("End of setup");
even_print:
Serial.println("x is even");
odd_print:
Serial.println("x is odd");
}
void loop() {
// put your main code here, to run repeatedly:
Serial.println("Looping...");
delay(1000);
}
The Serial Monitor output is shown below. Note that I reset the Arduino a couple of times to get different values of x.
See that when x is even, "x is odd" also gets printed, because the odd_print label follows the even_print label. So, the next print statement follows the first one. This shows that even_print and odd_print are just markers; they donβt stop program execution.
The goto statement just changes the program flow using labels, but after the statements of one label are executed, the program proceeds linearly and executes the next line (odd_print statements in this case).
Also, note that "End of setup" never gets printed. This is because both the goto statements make the program flow skip that line. This illustrates that the program wonβt come back to the original line once the statements within the label are executed. It moves forward linearly unless, of course, it encounters another goto statement. This example would have given you an idea why use of goto is discouraged.
|
[
{
"code": null,
"e": 1311,
"s": 1062,
"text": "goto is a control structure in Arduino, like in C, and it is used to transfer the program flow to another point in the program. It is highly discouraged, as many programmers agree that you can write every algorithm you want without the use of goto."
},
{
"code": null,
"e": 1530,
"s": 1311,
"text": "Excessive use of goto makes it very difficult to debug programs, or, in some cases, creates program flows which are impossible to debug. It is assumed that you will read further only if you absolutely have to use goto."
},
{
"code": null,
"e": 1561,
"s": 1530,
"text": "The syntax for using goto is β"
},
{
"code": null,
"e": 1597,
"s": 1561,
"text": "goto label;\n\nlabel:\n //statements"
},
{
"code": null,
"e": 1639,
"s": 1597,
"text": "The following example demonstrates this β"
},
{
"code": null,
"e": 2156,
"s": 1639,
"text": "void setup() {\n // put your setup code here, to run once:\n Serial.begin(9600);\n Serial.println();\n int x = random(5);\n\n Serial.print(\"Value of x is \");Serial.println(x);\n\n if (x % 2 == 0) {\n goto even_print;\n } else {\n goto odd_print;\n }\n\n Serial.println(\"End of setup\");\n\n even_print:\n Serial.println(\"x is even\");\n odd_print:\n Serial.println(\"x is odd\");\n}\n\nvoid loop() {\n // put your main code here, to run repeatedly:\n Serial.println(\"Looping...\");\n delay(1000);\n}"
},
{
"code": null,
"e": 2276,
"s": 2156,
"text": "The Serial Monitor output is shown below. Note that I reset the Arduino a couple of times to get different values of x."
},
{
"code": null,
"e": 2535,
"s": 2276,
"text": "See that when x is even, \"x is odd\" also gets printed, because the odd_print label follows the even_print label. So, the next print statement follows the first one. This shows that even_print and odd_print are just markers; they donβt stop program execution."
},
{
"code": null,
"e": 2744,
"s": 2535,
"text": "The goto statement just changes the program flow using labels, but after the statements of one label are executed, the program proceeds linearly and executes the next line (odd_print statements in this case)."
},
{
"code": null,
"e": 3153,
"s": 2744,
"text": "Also, note that \"End of setup\" never gets printed. This is because both the goto statements make the program flow skip that line. This illustrates that the program wonβt come back to the original line once the statements within the label are executed. It moves forward linearly unless, of course, it encounters another goto statement. This example would have given you an idea why use of goto is discouraged."
}
] |
Convert Text to Speech in Python - GeeksforGeeks
|
15 Aug, 2021
There are several APIs available to convert text to speech in Python. One of such APIs is the Google Text to Speech API commonly known as the gTTS API. gTTS is a very easy to use tool which converts the text entered, into audio which can be saved as a mp3 file.
The gTTS API supports several languages including English, Hindi, Tamil, French, German and many more. The speech can be delivered in any one of the two available audio speeds, fast or slow. However, as of the latest update, it is not possible to change the voice of the generated audio.
YouTubeGeeksforGeeks501K subscribersConvert Text to Speech Using Python | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:56β’Liveβ’<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=buoSzgX9yM4" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
To install the gTTS API, open terminal and write
pip install gTTS
This works for any platform.Now we are all set to write a sample program that converts text to speech.
# Import the required module for text # to speech conversionfrom gtts import gTTS # This module is imported so that we can # play the converted audioimport os # The text that you want to convert to audiomytext = 'Welcome to geeksforgeeks!' # Language in which you want to convertlanguage = 'en' # Passing the text and language to the engine, # here we have marked slow=False. Which tells # the module that the converted audio should # have a high speedmyobj = gTTS(text=mytext, lang=language, slow=False) # Saving the converted audio in a mp3 file named# welcome myobj.save("welcome.mp3") # Playing the converted fileos.system("mpg321 welcome.mp3")
The output of the above program should be a
voice saying, 'Welcome to geeksforgeeks!'
This article is contributed by Akhil Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
python-utility
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
ML | Linear Regression
Decision Tree
Search Algorithms in AI
Python | Decision tree implementation
Reinforcement learning
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 24772,
"s": 24744,
"text": "\n15 Aug, 2021"
},
{
"code": null,
"e": 25034,
"s": 24772,
"text": "There are several APIs available to convert text to speech in Python. One of such APIs is the Google Text to Speech API commonly known as the gTTS API. gTTS is a very easy to use tool which converts the text entered, into audio which can be saved as a mp3 file."
},
{
"code": null,
"e": 25322,
"s": 25034,
"text": "The gTTS API supports several languages including English, Hindi, Tamil, French, German and many more. The speech can be delivered in any one of the two available audio speeds, fast or slow. However, as of the latest update, it is not possible to change the voice of the generated audio."
},
{
"code": null,
"e": 26156,
"s": 25322,
"text": "YouTubeGeeksforGeeks501K subscribersConvert Text to Speech Using Python | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:56β’Liveβ’<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=buoSzgX9yM4\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 26205,
"s": 26156,
"text": "To install the gTTS API, open terminal and write"
},
{
"code": null,
"e": 26223,
"s": 26205,
"text": "pip install gTTS\n"
},
{
"code": null,
"e": 26326,
"s": 26223,
"text": "This works for any platform.Now we are all set to write a sample program that converts text to speech."
},
{
"code": "# Import the required module for text # to speech conversionfrom gtts import gTTS # This module is imported so that we can # play the converted audioimport os # The text that you want to convert to audiomytext = 'Welcome to geeksforgeeks!' # Language in which you want to convertlanguage = 'en' # Passing the text and language to the engine, # here we have marked slow=False. Which tells # the module that the converted audio should # have a high speedmyobj = gTTS(text=mytext, lang=language, slow=False) # Saving the converted audio in a mp3 file named# welcome myobj.save(\"welcome.mp3\") # Playing the converted fileos.system(\"mpg321 welcome.mp3\")",
"e": 26981,
"s": 26326,
"text": null
},
{
"code": null,
"e": 27069,
"s": 26981,
"text": "The output of the above program should be a \nvoice saying, 'Welcome to geeksforgeeks!'\n"
},
{
"code": null,
"e": 27363,
"s": 27069,
"text": "This article is contributed by Akhil Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 27488,
"s": 27363,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 27503,
"s": 27488,
"text": "python-utility"
},
{
"code": null,
"e": 27520,
"s": 27503,
"text": "Machine Learning"
},
{
"code": null,
"e": 27527,
"s": 27520,
"text": "Python"
},
{
"code": null,
"e": 27544,
"s": 27527,
"text": "Machine Learning"
},
{
"code": null,
"e": 27642,
"s": 27544,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27651,
"s": 27642,
"text": "Comments"
},
{
"code": null,
"e": 27664,
"s": 27651,
"text": "Old Comments"
},
{
"code": null,
"e": 27687,
"s": 27664,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 27701,
"s": 27687,
"text": "Decision Tree"
},
{
"code": null,
"e": 27725,
"s": 27701,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 27763,
"s": 27725,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 27786,
"s": 27763,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 27814,
"s": 27786,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 27864,
"s": 27814,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 27886,
"s": 27864,
"text": "Python map() function"
}
] |
How to calculate the difference between neighboring elements in an array using NumPy - GeeksforGeeks
|
02 Sep, 2020
Letβs see how to calculate the difference between neighboring elements in an array using NumPy library.
So, We can find out the difference between neighboring elements using numpy.diff() function of NumPy library.
Syntax: numpy.diff(arr, n, axis)
Now, letβs see an example:
Example 1:
Python3
# import libraryimport numpy as np # create a numpy 1d-arrayarr = np.array([1, 12, 3, 14, 5, 16, 7, 18, 9, 110]) # finding the difference between# neighboring elementsresult = np.diff(arr) print(result)
Output:
[ 11 -9 11 -9 11 -9 11 -9 101]
Example 2:
Python3
# import libraryimport numpy as np # create a numpy 2d-arrayarr = np.array([[10, 12, 14], [25, 35, 45], [12, 18, 20]]) # finding the difference between# neighboring elements along rowresult = np.diff(arr, axis = 1) print(result)
Output:
[[ 2 2]
[10 10]
[ 6 2]]
Example 3:
Python3
# import libraryimport numpy as np # create a numpy 2d-arrayarr = np.array([[10, 12, 14], [25, 35, 45], [12, 18, 20]]) # finding the difference between# neighboring elements along columnresult = np.diff(arr, axis = 0) print(result)
Output:
[[ 15 23 31]
[-13 -17 -25]]
Python numpy-Mathematical Function
Python numpy-program
Python-numpy
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
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 24368,
"s": 24340,
"text": "\n02 Sep, 2020"
},
{
"code": null,
"e": 24472,
"s": 24368,
"text": "Letβs see how to calculate the difference between neighboring elements in an array using NumPy library."
},
{
"code": null,
"e": 24582,
"s": 24472,
"text": "So, We can find out the difference between neighboring elements using numpy.diff() function of NumPy library."
},
{
"code": null,
"e": 24615,
"s": 24582,
"text": "Syntax: numpy.diff(arr, n, axis)"
},
{
"code": null,
"e": 24642,
"s": 24615,
"text": "Now, letβs see an example:"
},
{
"code": null,
"e": 24653,
"s": 24642,
"text": "Example 1:"
},
{
"code": null,
"e": 24661,
"s": 24653,
"text": "Python3"
},
{
"code": "# import libraryimport numpy as np # create a numpy 1d-arrayarr = np.array([1, 12, 3, 14, 5, 16, 7, 18, 9, 110]) # finding the difference between# neighboring elementsresult = np.diff(arr) print(result)",
"e": 24880,
"s": 24661,
"text": null
},
{
"code": null,
"e": 24888,
"s": 24880,
"text": "Output:"
},
{
"code": null,
"e": 24926,
"s": 24888,
"text": "[ 11 -9 11 -9 11 -9 11 -9 101]"
},
{
"code": null,
"e": 24937,
"s": 24926,
"text": "Example 2:"
},
{
"code": null,
"e": 24945,
"s": 24937,
"text": "Python3"
},
{
"code": "# import libraryimport numpy as np # create a numpy 2d-arrayarr = np.array([[10, 12, 14], [25, 35, 45], [12, 18, 20]]) # finding the difference between# neighboring elements along rowresult = np.diff(arr, axis = 1) print(result)",
"e": 25208,
"s": 24945,
"text": null
},
{
"code": null,
"e": 25216,
"s": 25208,
"text": "Output:"
},
{
"code": null,
"e": 25242,
"s": 25216,
"text": "[[ 2 2]\n[10 10]\n[ 6 2]]"
},
{
"code": null,
"e": 25253,
"s": 25242,
"text": "Example 3:"
},
{
"code": null,
"e": 25261,
"s": 25253,
"text": "Python3"
},
{
"code": "# import libraryimport numpy as np # create a numpy 2d-arrayarr = np.array([[10, 12, 14], [25, 35, 45], [12, 18, 20]]) # finding the difference between# neighboring elements along columnresult = np.diff(arr, axis = 0) print(result)",
"e": 25527,
"s": 25261,
"text": null
},
{
"code": null,
"e": 25535,
"s": 25527,
"text": "Output:"
},
{
"code": null,
"e": 25565,
"s": 25535,
"text": "[[ 15 23 31]\n[-13 -17 -25]]"
},
{
"code": null,
"e": 25600,
"s": 25565,
"text": "Python numpy-Mathematical Function"
},
{
"code": null,
"e": 25621,
"s": 25600,
"text": "Python numpy-program"
},
{
"code": null,
"e": 25634,
"s": 25621,
"text": "Python-numpy"
},
{
"code": null,
"e": 25641,
"s": 25634,
"text": "Python"
},
{
"code": null,
"e": 25739,
"s": 25641,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25757,
"s": 25739,
"text": "Python Dictionary"
},
{
"code": null,
"e": 25792,
"s": 25757,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 25814,
"s": 25792,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25846,
"s": 25814,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25876,
"s": 25846,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 25918,
"s": 25876,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 25944,
"s": 25918,
"text": "Python String | replace()"
},
{
"code": null,
"e": 25981,
"s": 25944,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26024,
"s": 25981,
"text": "Python program to convert a list to string"
}
] |
Hamming distance between two Integers - GeeksforGeeks
|
16 Mar, 2022
Given two integers, the task is to find the hamming distance between two integers. Hamming Distance between two integers is the number of bits that are different at the same position in both numbers. Examples:
Input: n1 = 9, n2 = 14
Output: 3
9 = 1001, 14 = 1110
No. of Different bits = 3
Input: n1 = 4, n2 = 8
Output: 2
Approach:
Calculate the XOR of two numbers.Count the number of set bits.
Calculate the XOR of two numbers.
Count the number of set bits.
Below is the implementation of above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to calculate hamming distanceint hammingDistance(int n1, int n2){ int x = n1 ^ n2; int setBits = 0; while (x > 0) { setBits += x & 1; x >>= 1; } return setBits;} // Driver codeint main(){ int n1 = 9, n2 = 14; cout << hammingDistance(9, 14) << endl; return 0;}
// Java implementation of above approachclass GFG{ // Function to calculate hamming distancestatic int hammingDistance(int n1, int n2){ int x = n1 ^ n2; int setBits = 0; while (x > 0) { setBits += x & 1; x >>= 1; } return setBits;} // Driver codepublic static void main(String[] args){ int n1 = 9, n2 = 14; System.out.println(hammingDistance(n1, n2));}} // This code is contributed by Bilal
# Python3 implementation of above approach # Function to calculate hamming distancedef hammingDistance(n1, n2) : x = n1 ^ n2 setBits = 0 while (x > 0) : setBits += x & 1 x >>= 1 return setBits if __name__=='__main__': n1 = 9 n2 = 14 print(hammingDistance(9, 14)) # this code is contributed by Smitha Dinesh Semwal
// C# implementation of above approachclass GFG{ // Function to calculate// hamming distancestatic int hammingDistance(int n1, int n2){ int x = n1 ^ n2; int setBits = 0; while (x > 0) { setBits += x & 1; x >>= 1; } return setBits;} // Driver codestatic void Main(){ int n1 = 9, n2 = 14; System.Console.WriteLine(hammingDistance(n1, n2));}} // This code is contributed by mits
<?PHP// PHP implementation of above approach // Function to calculate hamming distancefunction hammingDistance($n1, $n2){ $x = $n1 ^ $n2; $setBits = 0; while ($x > 0) { $setBits += $x & 1; $x >>= 1; } return $setBits;} // Driver code$n1 = 9;$n2 = 14;echo(hammingDistance(9, 14)); // This code is contributed by Smitha?>
<script> // Javascript implementation of above approach // Function to calculate hamming distancefunction hammingDistance(n1, n2){ let x = n1 ^ n2; let setBits = 0; while (x > 0) { setBits += x & 1; x >>= 1; } return setBits;} // Driver code let n1 = 9, n2 = 14; document.write(hammingDistance(9, 14)); </script>
3
Note: No. of set bits can be count using __builtin_popcount() function.
Approach 2:
1. Calculate the maximum of both the numbers.
2.Check the set bits for both at each position.
C++
Python3
Javascript
#include <bits/stdc++.h>using namespace std;int hammingDistance(int x, int y){ int ans = 0; int m = max(x, y); while (m) { int c1 = x & 1; int c2 = y & 1; if (c1 != c2) ans += 1; m = m >> 1; x = x >> 1; y = y >> 1; } return ans;}int main(){ int n1 = 4, n2 = 8; int hdist = hammingDistance(n1, n2); cout << hdist << endl; return 0;}
# Python3 code for the same approachdef hammingDistance(x, y): ans = 0 m = max(x, y) while (m): c1 = x & 1 c2 = y & 1 if (c1 != c2): ans += 1 m = m >> 1 x = x >> 1 y = y >> 1 return ans # driver programn1 = 4n2 = 8hdist = hammingDistance(n1, n2)print(hdist) # This code is contributed by shinjanpatra
<script> // JavaScript code for the same approach function hammingDistance(x,y){ let ans = 0; let m = Math.max(x, y); while (m) { let c1 = x & 1; let c2 = y & 1; if (c1 != c2) ans += 1; m = m >> 1; x = x >> 1; y = y >> 1; } return ans;} // driver programlet n1 = 4,n2 = 8;let hdist = hammingDistance(n1, n2);document.write(hdist,"</br>"); // This code is contributed by shinjanpatra </script>
2
bilal-hungund
Mithun Kumar
Smitha Dinesh Semwal
subham348
adityamutharia
shinjanpatra
Bitwise-XOR
setBitCount
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Set, Clear and Toggle a given bit of a number in C
Program to find parity
Hamming code Implementation in C/C++
Check whether K-th bit is set or not
Write an Efficient Method to Check if a Number is Multiple of 3
Implementation of Bit Stuffing and Bit Destuffing
Builtin functions of GCC compiler
Find XOR of all elements in an Array
Swap bits in a given number
Count total bits in a number
|
[
{
"code": null,
"e": 25012,
"s": 24984,
"text": "\n16 Mar, 2022"
},
{
"code": null,
"e": 25224,
"s": 25012,
"text": "Given two integers, the task is to find the hamming distance between two integers. Hamming Distance between two integers is the number of bits that are different at the same position in both numbers. Examples: "
},
{
"code": null,
"e": 25336,
"s": 25224,
"text": "Input: n1 = 9, n2 = 14\nOutput: 3\n9 = 1001, 14 = 1110\nNo. of Different bits = 3\n\nInput: n1 = 4, n2 = 8\nOutput: 2"
},
{
"code": null,
"e": 25350,
"s": 25338,
"text": "Approach: "
},
{
"code": null,
"e": 25413,
"s": 25350,
"text": "Calculate the XOR of two numbers.Count the number of set bits."
},
{
"code": null,
"e": 25447,
"s": 25413,
"text": "Calculate the XOR of two numbers."
},
{
"code": null,
"e": 25477,
"s": 25447,
"text": "Count the number of set bits."
},
{
"code": null,
"e": 25526,
"s": 25477,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 25530,
"s": 25526,
"text": "C++"
},
{
"code": null,
"e": 25535,
"s": 25530,
"text": "Java"
},
{
"code": null,
"e": 25543,
"s": 25535,
"text": "Python3"
},
{
"code": null,
"e": 25546,
"s": 25543,
"text": "C#"
},
{
"code": null,
"e": 25550,
"s": 25546,
"text": "PHP"
},
{
"code": null,
"e": 25561,
"s": 25550,
"text": "Javascript"
},
{
"code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to calculate hamming distanceint hammingDistance(int n1, int n2){ int x = n1 ^ n2; int setBits = 0; while (x > 0) { setBits += x & 1; x >>= 1; } return setBits;} // Driver codeint main(){ int n1 = 9, n2 = 14; cout << hammingDistance(9, 14) << endl; return 0;}",
"e": 25958,
"s": 25561,
"text": null
},
{
"code": "// Java implementation of above approachclass GFG{ // Function to calculate hamming distancestatic int hammingDistance(int n1, int n2){ int x = n1 ^ n2; int setBits = 0; while (x > 0) { setBits += x & 1; x >>= 1; } return setBits;} // Driver codepublic static void main(String[] args){ int n1 = 9, n2 = 14; System.out.println(hammingDistance(n1, n2));}} // This code is contributed by Bilal",
"e": 26389,
"s": 25958,
"text": null
},
{
"code": "# Python3 implementation of above approach # Function to calculate hamming distancedef hammingDistance(n1, n2) : x = n1 ^ n2 setBits = 0 while (x > 0) : setBits += x & 1 x >>= 1 return setBits if __name__=='__main__': n1 = 9 n2 = 14 print(hammingDistance(9, 14)) # this code is contributed by Smitha Dinesh Semwal",
"e": 26745,
"s": 26389,
"text": null
},
{
"code": "// C# implementation of above approachclass GFG{ // Function to calculate// hamming distancestatic int hammingDistance(int n1, int n2){ int x = n1 ^ n2; int setBits = 0; while (x > 0) { setBits += x & 1; x >>= 1; } return setBits;} // Driver codestatic void Main(){ int n1 = 9, n2 = 14; System.Console.WriteLine(hammingDistance(n1, n2));}} // This code is contributed by mits",
"e": 27161,
"s": 26745,
"text": null
},
{
"code": "<?PHP// PHP implementation of above approach // Function to calculate hamming distancefunction hammingDistance($n1, $n2){ $x = $n1 ^ $n2; $setBits = 0; while ($x > 0) { $setBits += $x & 1; $x >>= 1; } return $setBits;} // Driver code$n1 = 9;$n2 = 14;echo(hammingDistance(9, 14)); // This code is contributed by Smitha?>",
"e": 27515,
"s": 27161,
"text": null
},
{
"code": "<script> // Javascript implementation of above approach // Function to calculate hamming distancefunction hammingDistance(n1, n2){ let x = n1 ^ n2; let setBits = 0; while (x > 0) { setBits += x & 1; x >>= 1; } return setBits;} // Driver code let n1 = 9, n2 = 14; document.write(hammingDistance(9, 14)); </script>",
"e": 27865,
"s": 27515,
"text": null
},
{
"code": null,
"e": 27867,
"s": 27865,
"text": "3"
},
{
"code": null,
"e": 27939,
"s": 27867,
"text": "Note: No. of set bits can be count using __builtin_popcount() function."
},
{
"code": null,
"e": 27951,
"s": 27939,
"text": "Approach 2:"
},
{
"code": null,
"e": 27997,
"s": 27951,
"text": "1. Calculate the maximum of both the numbers."
},
{
"code": null,
"e": 28045,
"s": 27997,
"text": "2.Check the set bits for both at each position."
},
{
"code": null,
"e": 28049,
"s": 28045,
"text": "C++"
},
{
"code": null,
"e": 28057,
"s": 28049,
"text": "Python3"
},
{
"code": null,
"e": 28068,
"s": 28057,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std;int hammingDistance(int x, int y){ int ans = 0; int m = max(x, y); while (m) { int c1 = x & 1; int c2 = y & 1; if (c1 != c2) ans += 1; m = m >> 1; x = x >> 1; y = y >> 1; } return ans;}int main(){ int n1 = 4, n2 = 8; int hdist = hammingDistance(n1, n2); cout << hdist << endl; return 0;}",
"e": 28480,
"s": 28068,
"text": null
},
{
"code": "# Python3 code for the same approachdef hammingDistance(x, y): ans = 0 m = max(x, y) while (m): c1 = x & 1 c2 = y & 1 if (c1 != c2): ans += 1 m = m >> 1 x = x >> 1 y = y >> 1 return ans # driver programn1 = 4n2 = 8hdist = hammingDistance(n1, n2)print(hdist) # This code is contributed by shinjanpatra",
"e": 28828,
"s": 28480,
"text": null
},
{
"code": "<script> // JavaScript code for the same approach function hammingDistance(x,y){ let ans = 0; let m = Math.max(x, y); while (m) { let c1 = x & 1; let c2 = y & 1; if (c1 != c2) ans += 1; m = m >> 1; x = x >> 1; y = y >> 1; } return ans;} // driver programlet n1 = 4,n2 = 8;let hdist = hammingDistance(n1, n2);document.write(hdist,\"</br>\"); // This code is contributed by shinjanpatra </script>",
"e": 29289,
"s": 28828,
"text": null
},
{
"code": null,
"e": 29291,
"s": 29289,
"text": "2"
},
{
"code": null,
"e": 29307,
"s": 29293,
"text": "bilal-hungund"
},
{
"code": null,
"e": 29320,
"s": 29307,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 29341,
"s": 29320,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 29351,
"s": 29341,
"text": "subham348"
},
{
"code": null,
"e": 29366,
"s": 29351,
"text": "adityamutharia"
},
{
"code": null,
"e": 29379,
"s": 29366,
"text": "shinjanpatra"
},
{
"code": null,
"e": 29391,
"s": 29379,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 29403,
"s": 29391,
"text": "setBitCount"
},
{
"code": null,
"e": 29413,
"s": 29403,
"text": "Bit Magic"
},
{
"code": null,
"e": 29423,
"s": 29413,
"text": "Bit Magic"
},
{
"code": null,
"e": 29521,
"s": 29423,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29530,
"s": 29521,
"text": "Comments"
},
{
"code": null,
"e": 29543,
"s": 29530,
"text": "Old Comments"
},
{
"code": null,
"e": 29594,
"s": 29543,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 29617,
"s": 29594,
"text": "Program to find parity"
},
{
"code": null,
"e": 29654,
"s": 29617,
"text": "Hamming code Implementation in C/C++"
},
{
"code": null,
"e": 29691,
"s": 29654,
"text": "Check whether K-th bit is set or not"
},
{
"code": null,
"e": 29755,
"s": 29691,
"text": "Write an Efficient Method to Check if a Number is Multiple of 3"
},
{
"code": null,
"e": 29805,
"s": 29755,
"text": "Implementation of Bit Stuffing and Bit Destuffing"
},
{
"code": null,
"e": 29839,
"s": 29805,
"text": "Builtin functions of GCC compiler"
},
{
"code": null,
"e": 29876,
"s": 29839,
"text": "Find XOR of all elements in an Array"
},
{
"code": null,
"e": 29904,
"s": 29876,
"text": "Swap bits in a given number"
}
] |
How to use Indexing for SQL Query Optimization | Towards Data Science
|
I assume that you like SQL and want to refine your querying skills to up your querying game. And you have probably heard that indexing is great for query optimization, but you are not sure about what exactly it is, why is it used, and how to use it.
Welcome! You are at the exact place where you should be. Iβll explain it in a very easy-to-understand manner, and I promise youβll enjoy learning about it.
Suppose you are in the e-Commerce Analytics team at Amazon. The data that youβre dealing with is huge. It has millions of rows. Iβll use the following hypothetical table called βproductβ containing 12 million products for all the demonstrations. (Fun Fact: Amazon sells more than 12 million products, excluding books, media, wine, and services.)
Letβs begin with a simple query.
SELECT COUNT(*)FROM productWHERE category = βelectronicsβ;
Now to run this query, the database has to scan all 12 million rows to check each record for a match. Letβs say this query takes 4 seconds to execute.
Can you make it faster? Yes, you can.
How? By indexing.
Let me explain the whole concept of indexing intuitively. Itβs named βindexingβ because of how an index works in a book. If youβre reading a book on statistics and you want to read about βlinear regressionβ, youβll not want to flip hundreds of pages one by one, to get to the chapter which talks about βlinear regressionβ.
Instead, youβll open the index page, look for βlinear regressionβ and go to the page directly.
This is the technique that databases use via indexing. When you create an index, the database somehow rapidly finds the data that the query wants. Iβll talk about this βsomehowβ later in the article.
Letβs create an index on the βproductβ table and include βcategoryβ in the index.
Syntax:CREATE INDEX [index_name]ON [table_name] ([column_name]);Query:CREATE INDEX product_category_indexON product (category);
When you execute this query, it will take much longer than a normal query. The database scans 12 million rows and builds a βcategoryβ index from scratch. Letβs say this takes 4 minutes.
Now, letβs test the performance of the old query with indexing.
SELECT COUNT(*)FROM productWHERE category = βelectronicsβ;
Youβll see that the query will be much faster this time. Itβll probably only take 400 milliseconds this time.
Even the queries which extend further than using βcategoryβ as a condition will benefit from the indexing on βcategoryβ. Letβs see an example.
SELECT COUNT(*)FROM productWHERE category = βelectronicsβAND product_subcategory = βheadphoneβ;
This query will take less time than what it would have normally taken, say 600 milliseconds for this query. The database can quickly find all βelectronicsβ products using the index. And from the smaller set of records, it finds headphones in a normal manner.
Now, letβs change the order of the conditions in the βWHEREβ clause.
SELECT COUNT(*)FROM productWHERE product_subcategory = βheadphoneβAND category = βelectronicsβ;
Even when the βproduct_categoryβ is mentioned before βcategoryβ, the database still picks the column which had an index, i.e. βcategoryβ, and then scans rows for finding the specified βproduct_subcategoryβ from that subset of records.
How does it know that?
The database considers all possible paths to execute the query and then chooses the most optimal path.
Itβs time for some database lingo now. Each of the possible paths is called a βQuery Planβ. It is essentially a sequence of steps used to access data in a SQL relational database management system (RDBMS).
And this feature of RDBMS that determines the most efficient way to execute a given query by considering all possible query plans is called βQuery Optimizerβ.
Now, letβs explore multi-column indexing.
An index can be made for more than one column.
CREATE INDEX product_category_product_subcategory_indexON product (category, product_subcategory);
Here, we have an index on both βcategoryβ and βproduct_subcategoryβ. The important thing to note here is that the order matters here. Itβs like sorting the data first by βcategoryβ and then by βproduct_subcategoryβ.
And the query gets even more fast by using this multi-column index. Letβs say it comes down to 60 milliseconds.
Moreover, a database can have more than one index.
Indexes speed up the performance of a database. And as the database gets larger, indexes become even more useful.
But there are two important things you should remember:
Indexes require storage
When you add data to the database, the original table is updated first, and then all the indexes of that table are updated
Thus, itβs good to use indexes on databases in data warehouses that get new data updated on a scheduled basis (off-peak hours) and not on production databases that would receive new updates all the time. This is because if the database is constantly receiving updates, then the indexes wonβt get updated and hence, will remain unusable.
Let me touch upon the two types of database indexes briefly, to give you a comprehensive understanding of the topic:
1. Clustered
2. Non-clustered
A clustered index is the unique index of the table that uses the primary key to organize the data within the table. A clustered index doesnβt have to be explicitly declared but is created by default when the primary key is defined. The primary key sorted in ascending order is used as the clustered index, by default.
Let me demonstrate this with an easy example.
This table βproductβ will have a clustered index βproduct_pkeyβ automatically created, organized around the primary key βproduct_idβ.
Now, when you run a query to search the table by βproduct_idβ (like in the query below), the clustered index will help the database to perform optimal searches, and return the result faster.
SELECT product_name, category, priceFROM productWHERE product_id = 3;
You must be wondering how exactly does it do that?
Indexes use an optimal search method known as binary search.
Binary search is an efficient algorithm for finding an entry from a sorted list of entries. It works by repeatedly dividing the data in half and checking if the entry you are searching for via your query comes before or after the entry in the middle of the data. If the value of your search entry is less than the entry in the middle, it narrows the search to the lower half, otherwise, it narrows the search to the upper half. It does this repeatedly until the value is found. This method decreases the number of searches required and thus, makes the execution of queries faster.
The following table helps to understand the impact of binary search in terms of number of searches:
Similarly, for our dataset with 12 million rows, only 24 searches at most are required instead of 12 million searches in the worst case scenario, if a binary search is employed. I think now you know the power of indexes.
Now the question is how to extend this power of indexing to columns other than the primary key. The answer is through non-clustered indexes.
All the queries that we learned to write at the beginning of the article to optimize the query performance were all using non-clustered indexes, the indexes which have to be explicitly defined.
A non-clustered index is stored in one place and the physical data in the table is stored in another place. Itβs like the index page of a book, that we talked about earlier. The index page of the book is located in one place and the contents of the book are located in another. This allows for more than one non-clustered index per table, as we saw earlier.
And how exactly is that done?
Suppose you write the query that involves searching for an entry in a column you have already created a non-clustered index for. The non-clustered index inherently contains the following:
column entries on which youβve created the index
addresses of the corresponding row (in the main table) that the column entry belongs to
You can see this visually in the left mini-table in the figure:
Let me explain this using a query.
CREATE INDEX product_category_indexON product (category);SELECT product_name, category, priceFROM productWHERE category = βelectronicsβ;
The database follows 3 steps:
Firstly, it goes to the non-clustered index (product_category_index), finds the column entry that you searched for (category = βelectronicsβ), using binary search.
Secondly, it looks for the address of the corresponding row in the main table that the column entry belongs to.
Finally, it goes to that row in the main table and fetches other column values, as per the requirement of your query (product_name, price).
So, thereβs an additional step (of finding the address and going to that row in the main table) involved in the working of a non-clustered index and hence, itβs slower than a clustered index.
This was all about the world of indexing for optimizing the performance of SQL queries, especially when youβre dealing with huge datasets. Iβll write more about the other methods of SQL query optimization very soon.
I hope I was able to deliver on my promise of making the article enjoyable and easy to understand. And I hope you found it useful.
To end with a powerful message by the greatest golfer of all time, Tiger Woods,
βNo matter how good you get you can always get better, and thatβs the exciting part.β
Feel free to have a look at the other articles that Iβve written around data analytics:
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
Feel free to provide feedback and follow me for more interesting articles on data analytics. Connect with me on LinkedIn.
|
[
{
"code": null,
"e": 421,
"s": 171,
"text": "I assume that you like SQL and want to refine your querying skills to up your querying game. And you have probably heard that indexing is great for query optimization, but you are not sure about what exactly it is, why is it used, and how to use it."
},
{
"code": null,
"e": 577,
"s": 421,
"text": "Welcome! You are at the exact place where you should be. Iβll explain it in a very easy-to-understand manner, and I promise youβll enjoy learning about it."
},
{
"code": null,
"e": 923,
"s": 577,
"text": "Suppose you are in the e-Commerce Analytics team at Amazon. The data that youβre dealing with is huge. It has millions of rows. Iβll use the following hypothetical table called βproductβ containing 12 million products for all the demonstrations. (Fun Fact: Amazon sells more than 12 million products, excluding books, media, wine, and services.)"
},
{
"code": null,
"e": 956,
"s": 923,
"text": "Letβs begin with a simple query."
},
{
"code": null,
"e": 1015,
"s": 956,
"text": "SELECT COUNT(*)FROM productWHERE category = βelectronicsβ;"
},
{
"code": null,
"e": 1166,
"s": 1015,
"text": "Now to run this query, the database has to scan all 12 million rows to check each record for a match. Letβs say this query takes 4 seconds to execute."
},
{
"code": null,
"e": 1204,
"s": 1166,
"text": "Can you make it faster? Yes, you can."
},
{
"code": null,
"e": 1222,
"s": 1204,
"text": "How? By indexing."
},
{
"code": null,
"e": 1545,
"s": 1222,
"text": "Let me explain the whole concept of indexing intuitively. Itβs named βindexingβ because of how an index works in a book. If youβre reading a book on statistics and you want to read about βlinear regressionβ, youβll not want to flip hundreds of pages one by one, to get to the chapter which talks about βlinear regressionβ."
},
{
"code": null,
"e": 1640,
"s": 1545,
"text": "Instead, youβll open the index page, look for βlinear regressionβ and go to the page directly."
},
{
"code": null,
"e": 1840,
"s": 1640,
"text": "This is the technique that databases use via indexing. When you create an index, the database somehow rapidly finds the data that the query wants. Iβll talk about this βsomehowβ later in the article."
},
{
"code": null,
"e": 1922,
"s": 1840,
"text": "Letβs create an index on the βproductβ table and include βcategoryβ in the index."
},
{
"code": null,
"e": 2050,
"s": 1922,
"text": "Syntax:CREATE INDEX [index_name]ON [table_name] ([column_name]);Query:CREATE INDEX product_category_indexON product (category);"
},
{
"code": null,
"e": 2236,
"s": 2050,
"text": "When you execute this query, it will take much longer than a normal query. The database scans 12 million rows and builds a βcategoryβ index from scratch. Letβs say this takes 4 minutes."
},
{
"code": null,
"e": 2300,
"s": 2236,
"text": "Now, letβs test the performance of the old query with indexing."
},
{
"code": null,
"e": 2359,
"s": 2300,
"text": "SELECT COUNT(*)FROM productWHERE category = βelectronicsβ;"
},
{
"code": null,
"e": 2469,
"s": 2359,
"text": "Youβll see that the query will be much faster this time. Itβll probably only take 400 milliseconds this time."
},
{
"code": null,
"e": 2612,
"s": 2469,
"text": "Even the queries which extend further than using βcategoryβ as a condition will benefit from the indexing on βcategoryβ. Letβs see an example."
},
{
"code": null,
"e": 2708,
"s": 2612,
"text": "SELECT COUNT(*)FROM productWHERE category = βelectronicsβAND product_subcategory = βheadphoneβ;"
},
{
"code": null,
"e": 2967,
"s": 2708,
"text": "This query will take less time than what it would have normally taken, say 600 milliseconds for this query. The database can quickly find all βelectronicsβ products using the index. And from the smaller set of records, it finds headphones in a normal manner."
},
{
"code": null,
"e": 3036,
"s": 2967,
"text": "Now, letβs change the order of the conditions in the βWHEREβ clause."
},
{
"code": null,
"e": 3132,
"s": 3036,
"text": "SELECT COUNT(*)FROM productWHERE product_subcategory = βheadphoneβAND category = βelectronicsβ;"
},
{
"code": null,
"e": 3367,
"s": 3132,
"text": "Even when the βproduct_categoryβ is mentioned before βcategoryβ, the database still picks the column which had an index, i.e. βcategoryβ, and then scans rows for finding the specified βproduct_subcategoryβ from that subset of records."
},
{
"code": null,
"e": 3390,
"s": 3367,
"text": "How does it know that?"
},
{
"code": null,
"e": 3493,
"s": 3390,
"text": "The database considers all possible paths to execute the query and then chooses the most optimal path."
},
{
"code": null,
"e": 3699,
"s": 3493,
"text": "Itβs time for some database lingo now. Each of the possible paths is called a βQuery Planβ. It is essentially a sequence of steps used to access data in a SQL relational database management system (RDBMS)."
},
{
"code": null,
"e": 3858,
"s": 3699,
"text": "And this feature of RDBMS that determines the most efficient way to execute a given query by considering all possible query plans is called βQuery Optimizerβ."
},
{
"code": null,
"e": 3900,
"s": 3858,
"text": "Now, letβs explore multi-column indexing."
},
{
"code": null,
"e": 3947,
"s": 3900,
"text": "An index can be made for more than one column."
},
{
"code": null,
"e": 4046,
"s": 3947,
"text": "CREATE INDEX product_category_product_subcategory_indexON product (category, product_subcategory);"
},
{
"code": null,
"e": 4262,
"s": 4046,
"text": "Here, we have an index on both βcategoryβ and βproduct_subcategoryβ. The important thing to note here is that the order matters here. Itβs like sorting the data first by βcategoryβ and then by βproduct_subcategoryβ."
},
{
"code": null,
"e": 4374,
"s": 4262,
"text": "And the query gets even more fast by using this multi-column index. Letβs say it comes down to 60 milliseconds."
},
{
"code": null,
"e": 4425,
"s": 4374,
"text": "Moreover, a database can have more than one index."
},
{
"code": null,
"e": 4539,
"s": 4425,
"text": "Indexes speed up the performance of a database. And as the database gets larger, indexes become even more useful."
},
{
"code": null,
"e": 4595,
"s": 4539,
"text": "But there are two important things you should remember:"
},
{
"code": null,
"e": 4619,
"s": 4595,
"text": "Indexes require storage"
},
{
"code": null,
"e": 4742,
"s": 4619,
"text": "When you add data to the database, the original table is updated first, and then all the indexes of that table are updated"
},
{
"code": null,
"e": 5079,
"s": 4742,
"text": "Thus, itβs good to use indexes on databases in data warehouses that get new data updated on a scheduled basis (off-peak hours) and not on production databases that would receive new updates all the time. This is because if the database is constantly receiving updates, then the indexes wonβt get updated and hence, will remain unusable."
},
{
"code": null,
"e": 5196,
"s": 5079,
"text": "Let me touch upon the two types of database indexes briefly, to give you a comprehensive understanding of the topic:"
},
{
"code": null,
"e": 5209,
"s": 5196,
"text": "1. Clustered"
},
{
"code": null,
"e": 5226,
"s": 5209,
"text": "2. Non-clustered"
},
{
"code": null,
"e": 5544,
"s": 5226,
"text": "A clustered index is the unique index of the table that uses the primary key to organize the data within the table. A clustered index doesnβt have to be explicitly declared but is created by default when the primary key is defined. The primary key sorted in ascending order is used as the clustered index, by default."
},
{
"code": null,
"e": 5590,
"s": 5544,
"text": "Let me demonstrate this with an easy example."
},
{
"code": null,
"e": 5724,
"s": 5590,
"text": "This table βproductβ will have a clustered index βproduct_pkeyβ automatically created, organized around the primary key βproduct_idβ."
},
{
"code": null,
"e": 5915,
"s": 5724,
"text": "Now, when you run a query to search the table by βproduct_idβ (like in the query below), the clustered index will help the database to perform optimal searches, and return the result faster."
},
{
"code": null,
"e": 5985,
"s": 5915,
"text": "SELECT product_name, category, priceFROM productWHERE product_id = 3;"
},
{
"code": null,
"e": 6036,
"s": 5985,
"text": "You must be wondering how exactly does it do that?"
},
{
"code": null,
"e": 6097,
"s": 6036,
"text": "Indexes use an optimal search method known as binary search."
},
{
"code": null,
"e": 6678,
"s": 6097,
"text": "Binary search is an efficient algorithm for finding an entry from a sorted list of entries. It works by repeatedly dividing the data in half and checking if the entry you are searching for via your query comes before or after the entry in the middle of the data. If the value of your search entry is less than the entry in the middle, it narrows the search to the lower half, otherwise, it narrows the search to the upper half. It does this repeatedly until the value is found. This method decreases the number of searches required and thus, makes the execution of queries faster."
},
{
"code": null,
"e": 6778,
"s": 6678,
"text": "The following table helps to understand the impact of binary search in terms of number of searches:"
},
{
"code": null,
"e": 6999,
"s": 6778,
"text": "Similarly, for our dataset with 12 million rows, only 24 searches at most are required instead of 12 million searches in the worst case scenario, if a binary search is employed. I think now you know the power of indexes."
},
{
"code": null,
"e": 7140,
"s": 6999,
"text": "Now the question is how to extend this power of indexing to columns other than the primary key. The answer is through non-clustered indexes."
},
{
"code": null,
"e": 7334,
"s": 7140,
"text": "All the queries that we learned to write at the beginning of the article to optimize the query performance were all using non-clustered indexes, the indexes which have to be explicitly defined."
},
{
"code": null,
"e": 7692,
"s": 7334,
"text": "A non-clustered index is stored in one place and the physical data in the table is stored in another place. Itβs like the index page of a book, that we talked about earlier. The index page of the book is located in one place and the contents of the book are located in another. This allows for more than one non-clustered index per table, as we saw earlier."
},
{
"code": null,
"e": 7722,
"s": 7692,
"text": "And how exactly is that done?"
},
{
"code": null,
"e": 7910,
"s": 7722,
"text": "Suppose you write the query that involves searching for an entry in a column you have already created a non-clustered index for. The non-clustered index inherently contains the following:"
},
{
"code": null,
"e": 7959,
"s": 7910,
"text": "column entries on which youβve created the index"
},
{
"code": null,
"e": 8047,
"s": 7959,
"text": "addresses of the corresponding row (in the main table) that the column entry belongs to"
},
{
"code": null,
"e": 8111,
"s": 8047,
"text": "You can see this visually in the left mini-table in the figure:"
},
{
"code": null,
"e": 8146,
"s": 8111,
"text": "Let me explain this using a query."
},
{
"code": null,
"e": 8283,
"s": 8146,
"text": "CREATE INDEX product_category_indexON product (category);SELECT product_name, category, priceFROM productWHERE category = βelectronicsβ;"
},
{
"code": null,
"e": 8313,
"s": 8283,
"text": "The database follows 3 steps:"
},
{
"code": null,
"e": 8477,
"s": 8313,
"text": "Firstly, it goes to the non-clustered index (product_category_index), finds the column entry that you searched for (category = βelectronicsβ), using binary search."
},
{
"code": null,
"e": 8589,
"s": 8477,
"text": "Secondly, it looks for the address of the corresponding row in the main table that the column entry belongs to."
},
{
"code": null,
"e": 8729,
"s": 8589,
"text": "Finally, it goes to that row in the main table and fetches other column values, as per the requirement of your query (product_name, price)."
},
{
"code": null,
"e": 8921,
"s": 8729,
"text": "So, thereβs an additional step (of finding the address and going to that row in the main table) involved in the working of a non-clustered index and hence, itβs slower than a clustered index."
},
{
"code": null,
"e": 9137,
"s": 8921,
"text": "This was all about the world of indexing for optimizing the performance of SQL queries, especially when youβre dealing with huge datasets. Iβll write more about the other methods of SQL query optimization very soon."
},
{
"code": null,
"e": 9268,
"s": 9137,
"text": "I hope I was able to deliver on my promise of making the article enjoyable and easy to understand. And I hope you found it useful."
},
{
"code": null,
"e": 9348,
"s": 9268,
"text": "To end with a powerful message by the greatest golfer of all time, Tiger Woods,"
},
{
"code": null,
"e": 9434,
"s": 9348,
"text": "βNo matter how good you get you can always get better, and thatβs the exciting part.β"
},
{
"code": null,
"e": 9522,
"s": 9434,
"text": "Feel free to have a look at the other articles that Iβve written around data analytics:"
},
{
"code": null,
"e": 9545,
"s": 9522,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9568,
"s": 9545,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9591,
"s": 9568,
"text": "towardsdatascience.com"
}
] |
Simple Stock Price Prediction with ML in Python β Learnerβs Guide to ML | by Alec Cunningham | Towards Data Science
|
One of the most prominent use cases of machine learning is βFintechβ (Financial Technology for those who aren't buzz-word aficionados); a large subset of which is in the stock market. Financial theorists, and data scientists for the better part of the last 50 years, have been employed to make sense of the marketplace in order to increase return on investment. However, due to the multidimensional nature of the problem, the scale of the system, and inherent variation with time, it has been an overwhelmingly tough challenge for humans to solve, even with the assistance of conventional data analytics tools. However, with the onset of recent advancements in machine learning applications, the field has been evolving to utilize non-deterministic solutions the βlearnβ what is going on in order to make more accurate predictions.
In this article I will demonstrate a simple stock price prediction model and exploring how βtuningβ the model affects the results. This article is intended to be easy to follow, as it is an introduction, so more advanced readers may need to bear with me.
One of the most important steps in machine learning and predictive modeling is gathering good data, performing the appropriate cleaning steps and realizing the limitations.
For this example I will be using stock price data from a single stock, Zimmer Biomet (ticker: ZBH). Simply go too finance.yahoo.com, search for the desired ticker. Once you are on the home page of the desired stock, simple navigate to the βHistorical Dataβ tab, input the range of dates you would like to include, and select βDownload Data.β I chose 5 years, but you can choose as far back as you would like.
Now that we have out data, letβs go ahead and see what we have. Simply open the file in Excel.
Looks like we have some goodies here. You may notice that all of the fields are numerical values, except that pesky date value... We need to fix this. The values that we are going to pass into our model need to be in a format that can be most easily understood. So, we need to perform some βdata preprocessingβ steps. In our case we are going to insert a new column after 1, name it βDate Value,β and copy all of the dates from column 1 into column 2. Then select all of the data and change the type from βDateβ to βText.β The results should look like the following:
Ok, so now save the file as βchoose_a_name.csvβ (make sure it is a β.csv βand not one of the excel default formats).
Before we start, lets talk about limitations. You will notice that the only data we feed this model is date and price. There are many external factors that affect the price outside of the historical price. Highly robust models might utilize external data such as news, time of the year, social media sentiment, weather, price of competitors, market volatility, market indices, etc. This model is very basic, but in time you can learn the skills to build a model that is more βawareβ of the overall marketplace. That being said, letβs move on.
So now that we have data cleaned up, we need to choose a model. In this case we are going to use a neural network to perform a regression function. A regression will spit out a numerical value on a continuous scale, a apposed to a model that may be used for classification efforts, which would yield a categorical output. In this situation, we are trying to predict the price of a stock on any given day (and if you are trying to make money, a day that hasn't happened yet).
To build our model we are going to use TensorFlow... well, a simplified module called TFANN which stands for βTensorFlow Artificial Neural Network.β In order to do this, we are going to use Google Colab. If you are not familiar with Colab, simply navigate to colab.research.google.com, it is a free virtual python notebook environment. (For those of you that will be following along and donβt know what you are doing, just copy paste the code below into a βcellβ and then hit run before creating a new one and copying more code).
First we need to install TFANN. Open a new Colab notebook (python 3). Colab has numerous libraries which can be accessed without installation; however, TFANN is not one of them so we need to execute the following command:
!pip install TFANN
Now letβs import our dependencies:
import numpy as npimport matplotlib.pyplot as mplfrom sklearn.preprocessing import scalefrom TFANN import ANNRfrom google.colab import files
NumPy will be used for our matrix operations, Matplotlib for graphs, sykit-learn for data processing, TFANN for the ML goodness, and google.colab files will help us upload data from the local machine to the virtual environment.
Now we need to import the data that we have already processed. To do this we will execute the following command, which will provide us with a window to upload the .csv file.
files.upload()
Easy, right?
You now have a virtual folder that contains this file. Execute the following command if you donβt believe me, it will print the names of the files in the current directory.
!ls
Now we can finally get to the meat of this project. Execute the following commands:
#reads data from the file and ceates a matrix with only the dates and the prices stock_data = np.loadtxt('ZBH_5y.csv', delimiter=",", skiprows=1, usecols=(1, 4))#scales the data to smaller valuesstock_data=scale(stock_data)#gets the price and dates from the matrixprices = stock_data[:, 1].reshape(-1, 1)dates = stock_data[:, 0].reshape(-1, 1)#creates a plot of the data and then displays itmpl.plot(dates[:, 0], prices[:, 0])mpl.show()
You should get a nice graph that looks like this:
Note, that the scale is no longer in dollars on the y-axis and those arbitrary integer-date values on the x-axis. We have scaled the data down to make the learning process more effective. Try writing some code to return the scale of the y-axis back to dollars and the x-axis to years!
Now, we need to construct the model. In this case we will use one input and output neuron (input date, output price) and will have three hidden layers of 25 neurons each. Each layer will have an βtanhβ activation function. If you do not understand these concepts, feel free to google it and come back, understanding the basics for neural network principals will be very helpful as you progress.
#Number of neurons in the input, output, and hidden layersinput = 1output = 1hidden = 50#array of layers, 3 hidden and 1 output, along with the tanh activation function layers = [('F', hidden), ('AF', 'tanh'), ('F', hidden), ('AF', 'tanh'), ('F', hidden), ('AF', 'tanh'), ('F', output)]#construct the model and dictate paramsmlpr = ANNR([input], layers, batchSize = 256, maxIter = 20000, tol = 0.2, reg = 1e-4, verbose = True)
We have now initialized the model and are ready to train!
#number of days for the hold-out period used to access progressholdDays = 5totalDays = len(dates)#fit the model to the data "Learning"mlpr.fit(dates[0:(totalDays-holdDays)], prices[0:(totalDays-holdDays)])
Once the training is complete, we can execute the following commands to see how we did.
#Predict the stock price using the modelpricePredict = mlpr.predict(dates)#Display the predicted reuslts agains the actual datampl.plot(dates, prices)mpl.plot(dates, pricePredict, c='#5aa9ab')mpl.show()
Not too bad! But we can do better.
Letβs think about some ways in which we can increase the fidelity of the model. We can think of about this as βwhat knobs can we turnβ to tune our model. Well the first is to simply decrease the error tolerance.
The first trial, the error tolerance was set as .2; however, we can lower this to a smaller number, say .1, lets give that a try!
Simply make the following changes. Note that I am also updating the name of the variables so that the values we already created/observed do not change. Certainly not the most effective method here, but I am sure you can create a better one!
#Number of neurons in the input, output, and hidden layersinput2 = 1output2 = 1hidden2 = 50#array of layers, 3 hidden and 1 output, along with the tanh activation function layers = [('F', hidden2), ('AF', 'tanh'), ('F', hidden2), ('AF', 'tanh'), ('F', hidden2), ('AF', 'tanh'), ('F', output2)]#construct the model and dictate paramsmlpr2 = ANNR([input2], layers, batchSize = 256, maxIter = 10000, tol = 0.1, reg = 1e-4, verbose = True)
Run the model again with the following commands and we get new results:
holdDays = 5totalDays = len(dates)mlpr2.fit(dates[0:(totalDays-holdDays)], prices[0:(totalDays-holdDays)])
Once it has finished training:
pricePredict2 = mlpr2.predict(dates)mpl.plot(dates, prices)mpl.plot(dates, pricePredict, c='#5aa9ab')mpl.plot(dates, pricePredict2, c='#8B008B')mpl.show()
Looking better! As you can see, lovering the error tolerance... well... lowered the error. So you might be wondering βwhy not just set the error to a really small number?β and that would be a great question. Go ahead and try it for yourself, re-execute the code you just ran with the tolerance set at .05. What you will observe is that the maximum number of iterations you use will stop the execution before it reached the desired level of error. Ok then, why not just increase the maximum number of iterations? Well, the problem lies in the given model parameters. The model itself has limitations, the lowest achievable error for the model we constructed may only be .8 (I have not checked exactly for this for this model). In this situation, it does not matter how many more iterations you add, the structure of the model will not yield better results, no matter how many iterations are run. It is simply capped out.
The next logical question to ask here would be βhow can we change the model to achieve greater error?β and that is what we are going to explore!
Models have what are known as βhyperparameters.β These are the parameters that govern the model, they define how the model is created. Altering these can give us better (or perhaps worse) results. Examples include: number of neurons in each hidden layer, the number of hidden layers, the activation function, etc.
Our goal here is to βtuneβ these hyperparameters to achieve a lower error tolerance than was possible with our first model. The simplest way to do this, in my opinion, is do increase the number of neurons in the hidden layers. I am by no means a leading source of knowledge on this topic, but I will venture far enough to say that increasing the number of neurons and/or the number of hidden layers increases the level of abstraction with which the model can represent the given data. So lets give that a try!
Increasing the number of neurons in each hidden layer from 50 to 100 and setting the tolerance to .075:
Much much better! The orange line is out newest prediction. Notice how much better it tracks the more recent prices than the last model did.
I think we have created a good model, and I am satisfied with the results! But this project can be continued to learn more about hyperparameters. Try changing the activation function to something besides βtanhβ, or perhaps adding an additional layer.
To add another layer, reference this line of code:
layers = [('F', hidden), ('AF', 'tanh'), ('F', hidden), ('AF', 'tanh'), ('F', hidden), ('AF', 'tanh'), ('F', output)]
Add one additional layer by adding another (βAFβ, hidden), (βAFβ, βtanhβ) before the output node. This adds the layer and the activation function applied to it before it is fed into the next layer.
layers = [('F', hidden), ('AF', 'tanh'), ('F', hidden), ('AF', 'tanh'), ('F', hidden), ('AF', 'tanh'),('F', hidden), ('AF', 'tanh'), ('F', output)]
Or perhaps you want a different number of neurons at each hidden layer, tapering them down is a common method. The example below tapers from 100 down to 25 nodes before the output:
layers = [('F', 100), ('AF', 'tanh'), ('F', 50), ('AF', 'tanh'), ('F', 25), ('AF', 'tanh'), ('F', output)]
So, there you have it! An easy introduction to machine learning and neural networks that you can do at home for free in about an hour!
I would like to recognize Nicholas T. Smith, whose model influenced the creation of this post.
Finally, if you have any questions, comments, suggestions, or concerns, feel free to reach out!
|
[
{
"code": null,
"e": 1003,
"s": 171,
"text": "One of the most prominent use cases of machine learning is βFintechβ (Financial Technology for those who aren't buzz-word aficionados); a large subset of which is in the stock market. Financial theorists, and data scientists for the better part of the last 50 years, have been employed to make sense of the marketplace in order to increase return on investment. However, due to the multidimensional nature of the problem, the scale of the system, and inherent variation with time, it has been an overwhelmingly tough challenge for humans to solve, even with the assistance of conventional data analytics tools. However, with the onset of recent advancements in machine learning applications, the field has been evolving to utilize non-deterministic solutions the βlearnβ what is going on in order to make more accurate predictions."
},
{
"code": null,
"e": 1258,
"s": 1003,
"text": "In this article I will demonstrate a simple stock price prediction model and exploring how βtuningβ the model affects the results. This article is intended to be easy to follow, as it is an introduction, so more advanced readers may need to bear with me."
},
{
"code": null,
"e": 1431,
"s": 1258,
"text": "One of the most important steps in machine learning and predictive modeling is gathering good data, performing the appropriate cleaning steps and realizing the limitations."
},
{
"code": null,
"e": 1840,
"s": 1431,
"text": "For this example I will be using stock price data from a single stock, Zimmer Biomet (ticker: ZBH). Simply go too finance.yahoo.com, search for the desired ticker. Once you are on the home page of the desired stock, simple navigate to the βHistorical Dataβ tab, input the range of dates you would like to include, and select βDownload Data.β I chose 5 years, but you can choose as far back as you would like."
},
{
"code": null,
"e": 1935,
"s": 1840,
"text": "Now that we have out data, letβs go ahead and see what we have. Simply open the file in Excel."
},
{
"code": null,
"e": 2502,
"s": 1935,
"text": "Looks like we have some goodies here. You may notice that all of the fields are numerical values, except that pesky date value... We need to fix this. The values that we are going to pass into our model need to be in a format that can be most easily understood. So, we need to perform some βdata preprocessingβ steps. In our case we are going to insert a new column after 1, name it βDate Value,β and copy all of the dates from column 1 into column 2. Then select all of the data and change the type from βDateβ to βText.β The results should look like the following:"
},
{
"code": null,
"e": 2619,
"s": 2502,
"text": "Ok, so now save the file as βchoose_a_name.csvβ (make sure it is a β.csv βand not one of the excel default formats)."
},
{
"code": null,
"e": 3162,
"s": 2619,
"text": "Before we start, lets talk about limitations. You will notice that the only data we feed this model is date and price. There are many external factors that affect the price outside of the historical price. Highly robust models might utilize external data such as news, time of the year, social media sentiment, weather, price of competitors, market volatility, market indices, etc. This model is very basic, but in time you can learn the skills to build a model that is more βawareβ of the overall marketplace. That being said, letβs move on."
},
{
"code": null,
"e": 3637,
"s": 3162,
"text": "So now that we have data cleaned up, we need to choose a model. In this case we are going to use a neural network to perform a regression function. A regression will spit out a numerical value on a continuous scale, a apposed to a model that may be used for classification efforts, which would yield a categorical output. In this situation, we are trying to predict the price of a stock on any given day (and if you are trying to make money, a day that hasn't happened yet)."
},
{
"code": null,
"e": 4167,
"s": 3637,
"text": "To build our model we are going to use TensorFlow... well, a simplified module called TFANN which stands for βTensorFlow Artificial Neural Network.β In order to do this, we are going to use Google Colab. If you are not familiar with Colab, simply navigate to colab.research.google.com, it is a free virtual python notebook environment. (For those of you that will be following along and donβt know what you are doing, just copy paste the code below into a βcellβ and then hit run before creating a new one and copying more code)."
},
{
"code": null,
"e": 4389,
"s": 4167,
"text": "First we need to install TFANN. Open a new Colab notebook (python 3). Colab has numerous libraries which can be accessed without installation; however, TFANN is not one of them so we need to execute the following command:"
},
{
"code": null,
"e": 4408,
"s": 4389,
"text": "!pip install TFANN"
},
{
"code": null,
"e": 4443,
"s": 4408,
"text": "Now letβs import our dependencies:"
},
{
"code": null,
"e": 4584,
"s": 4443,
"text": "import numpy as npimport matplotlib.pyplot as mplfrom sklearn.preprocessing import scalefrom TFANN import ANNRfrom google.colab import files"
},
{
"code": null,
"e": 4812,
"s": 4584,
"text": "NumPy will be used for our matrix operations, Matplotlib for graphs, sykit-learn for data processing, TFANN for the ML goodness, and google.colab files will help us upload data from the local machine to the virtual environment."
},
{
"code": null,
"e": 4986,
"s": 4812,
"text": "Now we need to import the data that we have already processed. To do this we will execute the following command, which will provide us with a window to upload the .csv file."
},
{
"code": null,
"e": 5001,
"s": 4986,
"text": "files.upload()"
},
{
"code": null,
"e": 5014,
"s": 5001,
"text": "Easy, right?"
},
{
"code": null,
"e": 5187,
"s": 5014,
"text": "You now have a virtual folder that contains this file. Execute the following command if you donβt believe me, it will print the names of the files in the current directory."
},
{
"code": null,
"e": 5191,
"s": 5187,
"text": "!ls"
},
{
"code": null,
"e": 5275,
"s": 5191,
"text": "Now we can finally get to the meat of this project. Execute the following commands:"
},
{
"code": null,
"e": 5712,
"s": 5275,
"text": "#reads data from the file and ceates a matrix with only the dates and the prices stock_data = np.loadtxt('ZBH_5y.csv', delimiter=\",\", skiprows=1, usecols=(1, 4))#scales the data to smaller valuesstock_data=scale(stock_data)#gets the price and dates from the matrixprices = stock_data[:, 1].reshape(-1, 1)dates = stock_data[:, 0].reshape(-1, 1)#creates a plot of the data and then displays itmpl.plot(dates[:, 0], prices[:, 0])mpl.show()"
},
{
"code": null,
"e": 5762,
"s": 5712,
"text": "You should get a nice graph that looks like this:"
},
{
"code": null,
"e": 6047,
"s": 5762,
"text": "Note, that the scale is no longer in dollars on the y-axis and those arbitrary integer-date values on the x-axis. We have scaled the data down to make the learning process more effective. Try writing some code to return the scale of the y-axis back to dollars and the x-axis to years!"
},
{
"code": null,
"e": 6442,
"s": 6047,
"text": "Now, we need to construct the model. In this case we will use one input and output neuron (input date, output price) and will have three hidden layers of 25 neurons each. Each layer will have an βtanhβ activation function. If you do not understand these concepts, feel free to google it and come back, understanding the basics for neural network principals will be very helpful as you progress."
},
{
"code": null,
"e": 6869,
"s": 6442,
"text": "#Number of neurons in the input, output, and hidden layersinput = 1output = 1hidden = 50#array of layers, 3 hidden and 1 output, along with the tanh activation function layers = [('F', hidden), ('AF', 'tanh'), ('F', hidden), ('AF', 'tanh'), ('F', hidden), ('AF', 'tanh'), ('F', output)]#construct the model and dictate paramsmlpr = ANNR([input], layers, batchSize = 256, maxIter = 20000, tol = 0.2, reg = 1e-4, verbose = True)"
},
{
"code": null,
"e": 6927,
"s": 6869,
"text": "We have now initialized the model and are ready to train!"
},
{
"code": null,
"e": 7133,
"s": 6927,
"text": "#number of days for the hold-out period used to access progressholdDays = 5totalDays = len(dates)#fit the model to the data \"Learning\"mlpr.fit(dates[0:(totalDays-holdDays)], prices[0:(totalDays-holdDays)])"
},
{
"code": null,
"e": 7221,
"s": 7133,
"text": "Once the training is complete, we can execute the following commands to see how we did."
},
{
"code": null,
"e": 7424,
"s": 7221,
"text": "#Predict the stock price using the modelpricePredict = mlpr.predict(dates)#Display the predicted reuslts agains the actual datampl.plot(dates, prices)mpl.plot(dates, pricePredict, c='#5aa9ab')mpl.show()"
},
{
"code": null,
"e": 7459,
"s": 7424,
"text": "Not too bad! But we can do better."
},
{
"code": null,
"e": 7671,
"s": 7459,
"text": "Letβs think about some ways in which we can increase the fidelity of the model. We can think of about this as βwhat knobs can we turnβ to tune our model. Well the first is to simply decrease the error tolerance."
},
{
"code": null,
"e": 7801,
"s": 7671,
"text": "The first trial, the error tolerance was set as .2; however, we can lower this to a smaller number, say .1, lets give that a try!"
},
{
"code": null,
"e": 8042,
"s": 7801,
"text": "Simply make the following changes. Note that I am also updating the name of the variables so that the values we already created/observed do not change. Certainly not the most effective method here, but I am sure you can create a better one!"
},
{
"code": null,
"e": 8478,
"s": 8042,
"text": "#Number of neurons in the input, output, and hidden layersinput2 = 1output2 = 1hidden2 = 50#array of layers, 3 hidden and 1 output, along with the tanh activation function layers = [('F', hidden2), ('AF', 'tanh'), ('F', hidden2), ('AF', 'tanh'), ('F', hidden2), ('AF', 'tanh'), ('F', output2)]#construct the model and dictate paramsmlpr2 = ANNR([input2], layers, batchSize = 256, maxIter = 10000, tol = 0.1, reg = 1e-4, verbose = True)"
},
{
"code": null,
"e": 8550,
"s": 8478,
"text": "Run the model again with the following commands and we get new results:"
},
{
"code": null,
"e": 8657,
"s": 8550,
"text": "holdDays = 5totalDays = len(dates)mlpr2.fit(dates[0:(totalDays-holdDays)], prices[0:(totalDays-holdDays)])"
},
{
"code": null,
"e": 8688,
"s": 8657,
"text": "Once it has finished training:"
},
{
"code": null,
"e": 8843,
"s": 8688,
"text": "pricePredict2 = mlpr2.predict(dates)mpl.plot(dates, prices)mpl.plot(dates, pricePredict, c='#5aa9ab')mpl.plot(dates, pricePredict2, c='#8B008B')mpl.show()"
},
{
"code": null,
"e": 9763,
"s": 8843,
"text": "Looking better! As you can see, lovering the error tolerance... well... lowered the error. So you might be wondering βwhy not just set the error to a really small number?β and that would be a great question. Go ahead and try it for yourself, re-execute the code you just ran with the tolerance set at .05. What you will observe is that the maximum number of iterations you use will stop the execution before it reached the desired level of error. Ok then, why not just increase the maximum number of iterations? Well, the problem lies in the given model parameters. The model itself has limitations, the lowest achievable error for the model we constructed may only be .8 (I have not checked exactly for this for this model). In this situation, it does not matter how many more iterations you add, the structure of the model will not yield better results, no matter how many iterations are run. It is simply capped out."
},
{
"code": null,
"e": 9908,
"s": 9763,
"text": "The next logical question to ask here would be βhow can we change the model to achieve greater error?β and that is what we are going to explore!"
},
{
"code": null,
"e": 10222,
"s": 9908,
"text": "Models have what are known as βhyperparameters.β These are the parameters that govern the model, they define how the model is created. Altering these can give us better (or perhaps worse) results. Examples include: number of neurons in each hidden layer, the number of hidden layers, the activation function, etc."
},
{
"code": null,
"e": 10732,
"s": 10222,
"text": "Our goal here is to βtuneβ these hyperparameters to achieve a lower error tolerance than was possible with our first model. The simplest way to do this, in my opinion, is do increase the number of neurons in the hidden layers. I am by no means a leading source of knowledge on this topic, but I will venture far enough to say that increasing the number of neurons and/or the number of hidden layers increases the level of abstraction with which the model can represent the given data. So lets give that a try!"
},
{
"code": null,
"e": 10836,
"s": 10732,
"text": "Increasing the number of neurons in each hidden layer from 50 to 100 and setting the tolerance to .075:"
},
{
"code": null,
"e": 10977,
"s": 10836,
"text": "Much much better! The orange line is out newest prediction. Notice how much better it tracks the more recent prices than the last model did."
},
{
"code": null,
"e": 11228,
"s": 10977,
"text": "I think we have created a good model, and I am satisfied with the results! But this project can be continued to learn more about hyperparameters. Try changing the activation function to something besides βtanhβ, or perhaps adding an additional layer."
},
{
"code": null,
"e": 11279,
"s": 11228,
"text": "To add another layer, reference this line of code:"
},
{
"code": null,
"e": 11397,
"s": 11279,
"text": "layers = [('F', hidden), ('AF', 'tanh'), ('F', hidden), ('AF', 'tanh'), ('F', hidden), ('AF', 'tanh'), ('F', output)]"
},
{
"code": null,
"e": 11595,
"s": 11397,
"text": "Add one additional layer by adding another (βAFβ, hidden), (βAFβ, βtanhβ) before the output node. This adds the layer and the activation function applied to it before it is fed into the next layer."
},
{
"code": null,
"e": 11743,
"s": 11595,
"text": "layers = [('F', hidden), ('AF', 'tanh'), ('F', hidden), ('AF', 'tanh'), ('F', hidden), ('AF', 'tanh'),('F', hidden), ('AF', 'tanh'), ('F', output)]"
},
{
"code": null,
"e": 11924,
"s": 11743,
"text": "Or perhaps you want a different number of neurons at each hidden layer, tapering them down is a common method. The example below tapers from 100 down to 25 nodes before the output:"
},
{
"code": null,
"e": 12031,
"s": 11924,
"text": "layers = [('F', 100), ('AF', 'tanh'), ('F', 50), ('AF', 'tanh'), ('F', 25), ('AF', 'tanh'), ('F', output)]"
},
{
"code": null,
"e": 12166,
"s": 12031,
"text": "So, there you have it! An easy introduction to machine learning and neural networks that you can do at home for free in about an hour!"
},
{
"code": null,
"e": 12261,
"s": 12166,
"text": "I would like to recognize Nicholas T. Smith, whose model influenced the creation of this post."
}
] |
char* vs std:string vs char[] in C++ - GeeksforGeeks
|
30 Mar, 2022
In this article, we are going to inspect three different ways of initializing strings in C++ and discuss differences between them.
1. Using char*
Here, str is basically a pointer to the (const)string literal.Syntax:
char* str = "This is GeeksForGeeks";
Pros:
Only one pointer is required to refer to whole string. That shows this is memory efficient.No need to declare the size of string beforehand.
Only one pointer is required to refer to whole string. That shows this is memory efficient.
No need to declare the size of string beforehand.
CPP
// CPP program to illustrate *char#include <iostream>using namespace std; int main(){ // pointer str points to const string literal "Hello". // No need to declare size. char* str1 = "This is GeeksForGeeks"; cout << str1 << endl; int size = 30; // can allocate size dynamically. char* str2 = (char*)malloc(sizeof(char) * size); str2 = "GeeksForGeeks For Everyone"; cout << str2; return 0;}
This is GeeksForGeeks
GeeksForGeeks For Everyone
Cons:
This works fine in C but writing in this form is a bad idea in C++. Thatβs why compiler shows warningof βdeprecated conversion from string constant to βchar*'β because in C string literals are arrays of char butin C++ they are constant array of char. Therefore use const keyword before char*.const char* str = "This is GeeksForGeeks";We cannot modify the string at later stage in program. We can change str to point something else but cannot change value present at str. Refer storage-for-strings-in-c for more detail.CPPCPP// CPP program to illustrate assigning// *char value to other variable #include <iostream>using namespace std; int main(){ // This initialization gives warning in C++. // "deprecated conversion from string constant // to 'char*'" char* str = "Hello"; const char* str1 = "Hello"; // No warning // trying to modify const string literal // gives Runtime error str[1] = 'o'; cout << str << endl; return 0;}Output:Segmentation Fault
This works fine in C but writing in this form is a bad idea in C++. Thatβs why compiler shows warningof βdeprecated conversion from string constant to βchar*'β because in C string literals are arrays of char butin C++ they are constant array of char. Therefore use const keyword before char*.const char* str = "This is GeeksForGeeks";
const char* str = "This is GeeksForGeeks";
We cannot modify the string at later stage in program. We can change str to point something else but cannot change value present at str. Refer storage-for-strings-in-c for more detail.CPPCPP// CPP program to illustrate assigning// *char value to other variable #include <iostream>using namespace std; int main(){ // This initialization gives warning in C++. // "deprecated conversion from string constant // to 'char*'" char* str = "Hello"; const char* str1 = "Hello"; // No warning // trying to modify const string literal // gives Runtime error str[1] = 'o'; cout << str << endl; return 0;}Output:Segmentation Fault
CPP
// CPP program to illustrate assigning// *char value to other variable #include <iostream>using namespace std; int main(){ // This initialization gives warning in C++. // "deprecated conversion from string constant // to 'char*'" char* str = "Hello"; const char* str1 = "Hello"; // No warning // trying to modify const string literal // gives Runtime error str[1] = 'o'; cout << str << endl; return 0;}
Segmentation Fault
2. Using std::string
Syntax:
std::string str = "This is GeeksForGeeks";
Here str is the object of std::string class which is an instantiation of the basic_string class template that uses char (i.e., bytes) as its character type.
Note: Do not use cstring or string.h functions when you are declaring string with std::string keyword because std::string strings are of basic_string class type and cstring strings are of const char* type.Pros:When dealing exclusively in C++ std:string is the best way to go because of better searching, replacement, and manipulation functions.Some of the useful std:string functions are discussed below.
CPP
// CPP program to illustrate // std::string functions#include <iostream>using namespace std; int main(){ // string assignment string s1 = "Hello"; string s2 = "World"; // return length of string cout << s1.size() << endl; // 5 cout << s2.length() << endl; // 5 // concatenate string using + operator. s1 = s1 + s2; cout << s1 << endl; // HelloWorld // append string s1.append("Geeks"); cout << s1 << endl; // HelloWorldGeeks string s3 = "HelloWorldGeeks"; // compare two strings if (s1.compare(s3) == 0) cout << "true" << endl; else cout << "false" << endl; // substring of string s1 // substr(pos, length_of_substring) string sub = s1.substr(0, 5); cout << sub << endl; // Hello // insert into string // insert(pos, string) s1.insert(10, "For"); cout << s1 << endl; // HelloWorldForGeeks string target = "World"; // find a target string in s1 size_t pos = s1.find(target); if (pos != std::string::npos) // npos=-1 cout << "Found at Position:" << pos << endl; // pos=5 // replace a portion of string s1 // replace(pos, length_of_portion, string_to_replace) cout << s1.replace(5, 5, "Geeks") << endl; // HelloGeeksForGeeks return 0;}
5
5
HelloWorld
HelloWorldGeeks
true
Hello
HelloWorldForGeeks
Found at Position:5
HelloGeeksForGeeks
Cases where you might prefer char* over std:string
When dealing with lower level access like talking to the OS, but usually, if youβre passing the string to theOS then std::string::c_str has it covered.Compatibility with old C code (although std::stringβs c_str() method handles most of this).To conserve memory (std::string will likely have more overhead).
When dealing with lower level access like talking to the OS, but usually, if youβre passing the string to theOS then std::string::c_str has it covered.
Compatibility with old C code (although std::stringβs c_str() method handles most of this).
To conserve memory (std::string will likely have more overhead).
3. Using char[]
Syntax:
char str[] = "This is GeeksForGeeks";
or
char str[size] = "This is GeeksForGeeks";
// Here str is a array of characters denoting the string.
Pros:
We can modify the string at later stage in program.
We can modify the string at later stage in program.
CPP
// CPP program to illustrate char#include <iostream>using namespace std; int main(){ char str[] = "Hello"; // or char str1[]={'H', 'e', 'l', 'l', 'o', '\0'}; // modify string to "Hollo" str[1] = 'o'; cout << str << endl; return 0;}
Hollo
Cons:
This is statically allocated sized array which consumes space in the stack.We need to take the large size of array if we want to concatenate or manipulate with other strings since the size of string is fixed. We can use C++ standard library cstring or string.h for that purpose.CPPCPP// CPP program to illustrate char// concatenation using standard functions#include <iostream>#include <cstring>using namespace std; int main(){ // take large size of array char str[10] = "Hello"; cout << "Before Concatenation : " << str << endl; // Hello strcat(str, " World"); cout << "After Concatenation : " << str; // Hello World return 0;}Output:Before Concatenation : Hello
After Concatenation : Hello World
This is statically allocated sized array which consumes space in the stack.
We need to take the large size of array if we want to concatenate or manipulate with other strings since the size of string is fixed. We can use C++ standard library cstring or string.h for that purpose.CPPCPP// CPP program to illustrate char// concatenation using standard functions#include <iostream>#include <cstring>using namespace std; int main(){ // take large size of array char str[10] = "Hello"; cout << "Before Concatenation : " << str << endl; // Hello strcat(str, " World"); cout << "After Concatenation : " << str; // Hello World return 0;}Output:Before Concatenation : Hello
After Concatenation : Hello World
CPP
// CPP program to illustrate char// concatenation using standard functions#include <iostream>#include <cstring>using namespace std; int main(){ // take large size of array char str[10] = "Hello"; cout << "Before Concatenation : " << str << endl; // Hello strcat(str, " World"); cout << "After Concatenation : " << str; // Hello World return 0;}
Before Concatenation : Hello
After Concatenation : Hello World
Here are couple of other useful functions of C++ standard library cstring.
CPP
#include <iostream>#include <cstring>using namespace std; int main(){ char s1[10] = "Hello"; // return length of s1 cout << strlen(s1) << endl; char s2[50]; // copies s1 into s2 strcpy(s2, s1); cout << s2 << endl; char s3[10] = "World"; // concatenates s3 into s2 strcat(s2, s3); cout << s2 << endl; char s4[50] = "HelloWorld"; // return 0 if s2 and s4 are equal. if (strcmp(s2, s4) == 0) cout << "true" << endl; else cout << "false" << endl; char s5[30]; // copies first 5 chars of s2 into s1 strncpy(s5, s4, 5); cout << s5 << endl; char target[10] = "Hello"; // search for target string in s4 if (strstr(s4, target) != NULL) cout << "true" << endl; else cout << "false" << endl; return 0;}
5
Hello
HelloWorld
true
Hello
true
This article is contributed by Kshitiz Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
SHSGM
simmytarika5
rajasachithanantham
cpp-string
cpp-strings-library
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Operator Overloading in C++
Socket Programming in C/C++
Bitwise Operators in C/C++
Multidimensional Arrays in C / C++
Virtual Function in C++
Constructors in C++
Templates in C++ with Examples
|
[
{
"code": null,
"e": 24674,
"s": 24646,
"text": "\n30 Mar, 2022"
},
{
"code": null,
"e": 24805,
"s": 24674,
"text": "In this article, we are going to inspect three different ways of initializing strings in C++ and discuss differences between them."
},
{
"code": null,
"e": 24820,
"s": 24805,
"text": "1. Using char*"
},
{
"code": null,
"e": 24890,
"s": 24820,
"text": "Here, str is basically a pointer to the (const)string literal.Syntax:"
},
{
"code": null,
"e": 24927,
"s": 24890,
"text": "char* str = \"This is GeeksForGeeks\";"
},
{
"code": null,
"e": 24933,
"s": 24927,
"text": "Pros:"
},
{
"code": null,
"e": 25074,
"s": 24933,
"text": "Only one pointer is required to refer to whole string. That shows this is memory efficient.No need to declare the size of string beforehand."
},
{
"code": null,
"e": 25166,
"s": 25074,
"text": "Only one pointer is required to refer to whole string. That shows this is memory efficient."
},
{
"code": null,
"e": 25216,
"s": 25166,
"text": "No need to declare the size of string beforehand."
},
{
"code": null,
"e": 25220,
"s": 25216,
"text": "CPP"
},
{
"code": "// CPP program to illustrate *char#include <iostream>using namespace std; int main(){ // pointer str points to const string literal \"Hello\". // No need to declare size. char* str1 = \"This is GeeksForGeeks\"; cout << str1 << endl; int size = 30; // can allocate size dynamically. char* str2 = (char*)malloc(sizeof(char) * size); str2 = \"GeeksForGeeks For Everyone\"; cout << str2; return 0;}",
"e": 25652,
"s": 25220,
"text": null
},
{
"code": null,
"e": 25701,
"s": 25652,
"text": "This is GeeksForGeeks\nGeeksForGeeks For Everyone"
},
{
"code": null,
"e": 25707,
"s": 25701,
"text": "Cons:"
},
{
"code": null,
"e": 26698,
"s": 25707,
"text": "This works fine in C but writing in this form is a bad idea in C++. Thatβs why compiler shows warningof βdeprecated conversion from string constant to βchar*'β because in C string literals are arrays of char butin C++ they are constant array of char. Therefore use const keyword before char*.const char* str = \"This is GeeksForGeeks\";We cannot modify the string at later stage in program. We can change str to point something else but cannot change value present at str. Refer storage-for-strings-in-c for more detail.CPPCPP// CPP program to illustrate assigning// *char value to other variable #include <iostream>using namespace std; int main(){ // This initialization gives warning in C++. // \"deprecated conversion from string constant // to 'char*'\" char* str = \"Hello\"; const char* str1 = \"Hello\"; // No warning // trying to modify const string literal // gives Runtime error str[1] = 'o'; cout << str << endl; return 0;}Output:Segmentation Fault"
},
{
"code": null,
"e": 27033,
"s": 26698,
"text": "This works fine in C but writing in this form is a bad idea in C++. Thatβs why compiler shows warningof βdeprecated conversion from string constant to βchar*'β because in C string literals are arrays of char butin C++ they are constant array of char. Therefore use const keyword before char*.const char* str = \"This is GeeksForGeeks\";"
},
{
"code": null,
"e": 27076,
"s": 27033,
"text": "const char* str = \"This is GeeksForGeeks\";"
},
{
"code": null,
"e": 27733,
"s": 27076,
"text": "We cannot modify the string at later stage in program. We can change str to point something else but cannot change value present at str. Refer storage-for-strings-in-c for more detail.CPPCPP// CPP program to illustrate assigning// *char value to other variable #include <iostream>using namespace std; int main(){ // This initialization gives warning in C++. // \"deprecated conversion from string constant // to 'char*'\" char* str = \"Hello\"; const char* str1 = \"Hello\"; // No warning // trying to modify const string literal // gives Runtime error str[1] = 'o'; cout << str << endl; return 0;}Output:Segmentation Fault"
},
{
"code": null,
"e": 27737,
"s": 27733,
"text": "CPP"
},
{
"code": "// CPP program to illustrate assigning// *char value to other variable #include <iostream>using namespace std; int main(){ // This initialization gives warning in C++. // \"deprecated conversion from string constant // to 'char*'\" char* str = \"Hello\"; const char* str1 = \"Hello\"; // No warning // trying to modify const string literal // gives Runtime error str[1] = 'o'; cout << str << endl; return 0;}",
"e": 28179,
"s": 27737,
"text": null
},
{
"code": null,
"e": 28198,
"s": 28179,
"text": "Segmentation Fault"
},
{
"code": null,
"e": 28219,
"s": 28198,
"text": "2. Using std::string"
},
{
"code": null,
"e": 28227,
"s": 28219,
"text": "Syntax:"
},
{
"code": null,
"e": 28270,
"s": 28227,
"text": "std::string str = \"This is GeeksForGeeks\";"
},
{
"code": null,
"e": 28427,
"s": 28270,
"text": "Here str is the object of std::string class which is an instantiation of the basic_string class template that uses char (i.e., bytes) as its character type."
},
{
"code": null,
"e": 28832,
"s": 28427,
"text": "Note: Do not use cstring or string.h functions when you are declaring string with std::string keyword because std::string strings are of basic_string class type and cstring strings are of const char* type.Pros:When dealing exclusively in C++ std:string is the best way to go because of better searching, replacement, and manipulation functions.Some of the useful std:string functions are discussed below."
},
{
"code": null,
"e": 28836,
"s": 28832,
"text": "CPP"
},
{
"code": "// CPP program to illustrate // std::string functions#include <iostream>using namespace std; int main(){ // string assignment string s1 = \"Hello\"; string s2 = \"World\"; // return length of string cout << s1.size() << endl; // 5 cout << s2.length() << endl; // 5 // concatenate string using + operator. s1 = s1 + s2; cout << s1 << endl; // HelloWorld // append string s1.append(\"Geeks\"); cout << s1 << endl; // HelloWorldGeeks string s3 = \"HelloWorldGeeks\"; // compare two strings if (s1.compare(s3) == 0) cout << \"true\" << endl; else cout << \"false\" << endl; // substring of string s1 // substr(pos, length_of_substring) string sub = s1.substr(0, 5); cout << sub << endl; // Hello // insert into string // insert(pos, string) s1.insert(10, \"For\"); cout << s1 << endl; // HelloWorldForGeeks string target = \"World\"; // find a target string in s1 size_t pos = s1.find(target); if (pos != std::string::npos) // npos=-1 cout << \"Found at Position:\" << pos << endl; // pos=5 // replace a portion of string s1 // replace(pos, length_of_portion, string_to_replace) cout << s1.replace(5, 5, \"Geeks\") << endl; // HelloGeeksForGeeks return 0;}",
"e": 30109,
"s": 28836,
"text": null
},
{
"code": null,
"e": 30209,
"s": 30109,
"text": "5\n5\nHelloWorld\nHelloWorldGeeks\ntrue\nHello\nHelloWorldForGeeks\nFound at Position:5\nHelloGeeksForGeeks"
},
{
"code": null,
"e": 30260,
"s": 30209,
"text": "Cases where you might prefer char* over std:string"
},
{
"code": null,
"e": 30567,
"s": 30260,
"text": "When dealing with lower level access like talking to the OS, but usually, if youβre passing the string to theOS then std::string::c_str has it covered.Compatibility with old C code (although std::stringβs c_str() method handles most of this).To conserve memory (std::string will likely have more overhead)."
},
{
"code": null,
"e": 30719,
"s": 30567,
"text": "When dealing with lower level access like talking to the OS, but usually, if youβre passing the string to theOS then std::string::c_str has it covered."
},
{
"code": null,
"e": 30811,
"s": 30719,
"text": "Compatibility with old C code (although std::stringβs c_str() method handles most of this)."
},
{
"code": null,
"e": 30876,
"s": 30811,
"text": "To conserve memory (std::string will likely have more overhead)."
},
{
"code": null,
"e": 30892,
"s": 30876,
"text": "3. Using char[]"
},
{
"code": null,
"e": 30900,
"s": 30892,
"text": "Syntax:"
},
{
"code": null,
"e": 31049,
"s": 30900,
"text": "char str[] = \"This is GeeksForGeeks\";\n or \nchar str[size] = \"This is GeeksForGeeks\";\n// Here str is a array of characters denoting the string.\n"
},
{
"code": null,
"e": 31055,
"s": 31049,
"text": "Pros:"
},
{
"code": null,
"e": 31107,
"s": 31055,
"text": "We can modify the string at later stage in program."
},
{
"code": null,
"e": 31159,
"s": 31107,
"text": "We can modify the string at later stage in program."
},
{
"code": null,
"e": 31163,
"s": 31159,
"text": "CPP"
},
{
"code": "// CPP program to illustrate char#include <iostream>using namespace std; int main(){ char str[] = \"Hello\"; // or char str1[]={'H', 'e', 'l', 'l', 'o', '\\0'}; // modify string to \"Hollo\" str[1] = 'o'; cout << str << endl; return 0;}",
"e": 31422,
"s": 31163,
"text": null
},
{
"code": null,
"e": 31428,
"s": 31422,
"text": "Hollo"
},
{
"code": null,
"e": 31434,
"s": 31428,
"text": "Cons:"
},
{
"code": null,
"e": 32156,
"s": 31434,
"text": "This is statically allocated sized array which consumes space in the stack.We need to take the large size of array if we want to concatenate or manipulate with other strings since the size of string is fixed. We can use C++ standard library cstring or string.h for that purpose.CPPCPP// CPP program to illustrate char// concatenation using standard functions#include <iostream>#include <cstring>using namespace std; int main(){ // take large size of array char str[10] = \"Hello\"; cout << \"Before Concatenation : \" << str << endl; // Hello strcat(str, \" World\"); cout << \"After Concatenation : \" << str; // Hello World return 0;}Output:Before Concatenation : Hello\nAfter Concatenation : Hello World\n"
},
{
"code": null,
"e": 32232,
"s": 32156,
"text": "This is statically allocated sized array which consumes space in the stack."
},
{
"code": null,
"e": 32879,
"s": 32232,
"text": "We need to take the large size of array if we want to concatenate or manipulate with other strings since the size of string is fixed. We can use C++ standard library cstring or string.h for that purpose.CPPCPP// CPP program to illustrate char// concatenation using standard functions#include <iostream>#include <cstring>using namespace std; int main(){ // take large size of array char str[10] = \"Hello\"; cout << \"Before Concatenation : \" << str << endl; // Hello strcat(str, \" World\"); cout << \"After Concatenation : \" << str; // Hello World return 0;}Output:Before Concatenation : Hello\nAfter Concatenation : Hello World\n"
},
{
"code": null,
"e": 32883,
"s": 32879,
"text": "CPP"
},
{
"code": "// CPP program to illustrate char// concatenation using standard functions#include <iostream>#include <cstring>using namespace std; int main(){ // take large size of array char str[10] = \"Hello\"; cout << \"Before Concatenation : \" << str << endl; // Hello strcat(str, \" World\"); cout << \"After Concatenation : \" << str; // Hello World return 0;}",
"e": 33251,
"s": 32883,
"text": null
},
{
"code": null,
"e": 33315,
"s": 33251,
"text": "Before Concatenation : Hello\nAfter Concatenation : Hello World\n"
},
{
"code": null,
"e": 33390,
"s": 33315,
"text": "Here are couple of other useful functions of C++ standard library cstring."
},
{
"code": null,
"e": 33394,
"s": 33390,
"text": "CPP"
},
{
"code": "#include <iostream>#include <cstring>using namespace std; int main(){ char s1[10] = \"Hello\"; // return length of s1 cout << strlen(s1) << endl; char s2[50]; // copies s1 into s2 strcpy(s2, s1); cout << s2 << endl; char s3[10] = \"World\"; // concatenates s3 into s2 strcat(s2, s3); cout << s2 << endl; char s4[50] = \"HelloWorld\"; // return 0 if s2 and s4 are equal. if (strcmp(s2, s4) == 0) cout << \"true\" << endl; else cout << \"false\" << endl; char s5[30]; // copies first 5 chars of s2 into s1 strncpy(s5, s4, 5); cout << s5 << endl; char target[10] = \"Hello\"; // search for target string in s4 if (strstr(s4, target) != NULL) cout << \"true\" << endl; else cout << \"false\" << endl; return 0;}",
"e": 34211,
"s": 33394,
"text": null
},
{
"code": null,
"e": 34246,
"s": 34211,
"text": "5\nHello\nHelloWorld\ntrue\nHello\ntrue"
},
{
"code": null,
"e": 34547,
"s": 34246,
"text": "This article is contributed by Kshitiz Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 34672,
"s": 34547,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 34678,
"s": 34672,
"text": "SHSGM"
},
{
"code": null,
"e": 34691,
"s": 34678,
"text": "simmytarika5"
},
{
"code": null,
"e": 34711,
"s": 34691,
"text": "rajasachithanantham"
},
{
"code": null,
"e": 34722,
"s": 34711,
"text": "cpp-string"
},
{
"code": null,
"e": 34742,
"s": 34722,
"text": "cpp-strings-library"
},
{
"code": null,
"e": 34746,
"s": 34742,
"text": "C++"
},
{
"code": null,
"e": 34750,
"s": 34746,
"text": "CPP"
},
{
"code": null,
"e": 34848,
"s": 34750,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34857,
"s": 34848,
"text": "Comments"
},
{
"code": null,
"e": 34870,
"s": 34857,
"text": "Old Comments"
},
{
"code": null,
"e": 34889,
"s": 34870,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 34932,
"s": 34889,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 34956,
"s": 34932,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 34984,
"s": 34956,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 35012,
"s": 34984,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 35039,
"s": 35012,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 35074,
"s": 35039,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 35098,
"s": 35074,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 35118,
"s": 35098,
"text": "Constructors in C++"
}
] |
Why start using sktime for forecasting? | by Joanna Lenczuk | Towards Data Science
|
One of the challenges faced by business owners is predicting future market conditions. Forecasts help to make informed decisions and form realistic expectations of results. This demand for predictions leads to the ongoing development of forecasting tools. They enable predicting future events by grasping useful information from past observations. Some of the recent forecasting frameworks include Facebookβs Prophet, Uberβs Orbit, or Linkedinβs Greykite. Yet, most of the Python forecasting packages focus on a specific model family, e.g. generalized additive models or statistical models. Sktime aims to fill the gap between those forecasting tools.
Sktime is an open-source toolbox for time series modeling. It combines functionalities spread across many Python libraries. It also adds its own unique features for forecasting. It allows us to train, fine-tune and evaluate models for time series. It is compatible with scikit-learn. The framework also enables, e.g. time series classification, feature extraction and time series clustering. For a complete list of features check out sktimeβs documentation. This article focuses on forecasting and how sktime makes the whole process easier. It is a practical walk-through of sktimeβs functionalities for forecasting. But first, letβs take a quick look at the data used in this article.
All code examples are based on a public dataset from the statsmodels library. It contains USA quarterly macroeconomic data between 1959 and 2009. A full description of the dataset is available here. We will focus on predicting real gross domestic product (realgdp).
Sktime puts certain constraints on the data structure used to store the time series. You can find the macroeconomic data import and transformations below.
But to the point...
Sktime brings together functionalities from many forecasting libraries. Upon that, it provides a unified API, compatible with scikit-learn.
What are the advantages of a unified API in that case? Here are some of the main reasons:
It allows users to easily implement, analyze and compare new models.
It helps to avoid confusion in choosing an appropriate algorithm thanks to a clear classification of forecasters.
It makes the workflow readable and understandable as all forecasters share a common interface. They are implemented in separate classes, as in other toolboxes, including scikit-learn.
It enables altering forecasters in a workflow. This saves us from adjusting the structure of our code each time we change our model.
Sktimeβs forecasters share crucial scikit-learnβs methods, such as fit() and predict(). The code below shows a basic forecasting workflow.
Output:2002Q2 11477.868
The code above generates a one-step-ahead forecast. That is why we assigned one to the forecasting horizon. Letβs now focus on different possibilities of specifying the horizon.
The forecasting horizon can be an array of relative or absolute values. Absolute values are specific data points for which we want to generate forecasts. Relative values include a list of steps for which predictions will be made. The relative forecasting horizon is especially useful if we make rolling predictions using the update_predict() method. It saves us from updating the absolute horizon each time we generate predictions. The relative horizon stays constant as we add new data.
We can also convert relative horizons to absolute horizons and vice versa. Converting from absolute to relative values is especially worth mentioning. It does not simply produce a list of step numbers. Those values relate to the last date of the training series. This means that if the values are negative, they are in-sample forecasts. This feature is important as forecasters can fit different parameters to each step. The code below shows the differences between forecasting horizons.
Output:Absolute FH: ForecastingHorizon(['2002Q2', '2002Q3', '2002Q4', '2003Q1', '2003Q2', '2003Q3','2003Q4', '2004Q1', '2004Q2', '2004Q3', '2004Q4', '2005Q1', '2005Q2', '2005Q3', '2005Q4', '2006Q1', '2006Q2', '2006Q3', '2006Q4', '2007Q1', '2007Q2', '2007Q3', '2007Q4', '2008Q1', '2008Q2', '2008Q3', '2008Q4', '2009Q1', '2009Q2', '2009Q3'], dtype='period[Q-DEC]', name='date', is_relative=False)Relative FH ahead: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]Relative FH in-sample: [-29, -28, -27, -26, -25, -24, -23, -22, -21, -20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0]
Letβs now dive into some common interface functionalities that sktime provides. First of all, the process of specifying and training the model is split into separate steps. We specify the forecasterβs parameters before fitting the model. In the case of univariate time series, the fit() method takes in the training series. For some forecasters, e.g. DirectTabularRegressionForecaster or DirectTimeSeriesRegressionForecaster, it also takes in the forecasting horizon. For others, the forecasting horizon can be interchangeably passed in the predict() method. Below is an example of forecasting a univariate time series using AutoARIMA.
Sktime also allows forecasting with exogenous variables. With multivariate exogenous time series, the range of fitting parameters is broader. It includes both a training series and a data frame with exogenous variables. As with univariate time series, some forecasters require the forecasting horizon in the parameters. In the code below weβre forecasting values of realgdp, using lagged values of an exogenous variable β realinv.
Apart from fitting, sktime also enables updating forecasters with new data. This allows us to automatically update the cutoff for predictions, so we donβt need to change the horizon ourselves each time we add new data. The cutoff is set to the last data point in the new training series. This method allows us to update the fitted parameters of the forecaster.
A common interface applies to all families of models. Sktime includes a wide range of easy-to-use, well-integrated forecasters. Here is a list of forecasters currently implemented in sktime:
Holt-Winterβs Exponential Smoothing, Theta forecaster, and ETS (from statsmodels),
ARIMA and AutoARIMA (from pmdarima),
BATS and TBATS (from tbats),
Prophet forecaster (from fbprophet),
Polynomial Trend forecaster,
Crostonβs method.
Sktime also allows the use of scikit-learnβs machine learning models for modeling time series. This leads us to the next great advantage of sktime.
As I mentioned earlier, sktimeβs API is compatible with scikit-learn. This implies the possibility to adapt lots of scikit-learnβs functionalities. Sktime allows us to solve forecasting problems using machine learning models from scikit-learn.
But why canβt we use standard regression models available in scikit-learn? In fact, we can, but the process requires lots of handwritten code and is prone to mistakes. The main reason is the conceptual difference between those two learning tasks.
In tabular regression, we have two types of variables β target and feature variables. We predict the target variable based on feature variables. In other words, the model learns from a set of columns to predict the value of a different column. The rows are interchangeable as they are independent of each other.
In forecasting, we only need to have a single variable. We predict its future values based on its past values. That is β the model predicts new rows of the same column. The rows are not interchangeable as future values depend on past values. So even if we forecast with an exogenous variable it is still not a regression problem.
The difference between those two problems is pretty clear. But what are the risks of using regression models in forecasting problems? Here are some of the reasons why:
It generates problems with evaluating forecasting models. Using scikit-learnβs train test split can cause data leakage. In forecasting problems, rows depend on each other so we cannot shuffle them at random.
The process of transforming data for forecasting is prone to mistakes. In forecasting tasks, we often aggregate data from multiple data points or create lagged variables. This transformation requires lots of hand-written code.
The time-series parameters are hard to tune. Values like lag size or window length are not exposed as parameters of scikit-learnβs estimators. This means we need to write extra code to adjust them to fit our problem.
Generating multi-step predictions is tricky. Letβs consider generating forecasts for the next 14 days. Regressors from scikit-learn make 14 predictions based on the last observed value. That is not what we want to do. We expect our forecaster to update the last known value every time we generate a forecast. That is, each prediction should be based on a different data point.
Sktime allows the use of regression models as components within forecasters. That is possible due to the reduction.
Reduction is the concept of using an algorithm to solve a learning task that it was not designed for. It is the process of going from a complex learning task to a simpler one.
We can use reduction to transform a forecasting task into a tabular regression problem. This means we can solve a forecasting task using scikit-learnβs estimators, e.g. Random Forest.
The key steps that take place in the reduction process are:
Using a sliding window approach to split the training set into fixed-length windows.
To give you an example β if the window length is equal to 11, the process looks as follows: the 1st window contains data from days 0β10 (where days 0β9 become feature variables and day 10 becomes the target variable). The 2nd window contains data from days 1β11 (where days 1β10 become feature variables and day 11 becomes the target variable), etc.
Arranging those windows on top of each other. This gives us data in tabular form, with clear distinction between feature and target variables.
Using one of the following strategies β recursive, direct, or multi-output, for generating forecasts.
Letβs now look at some code, performing forecasting with a regressor component.
In our example sktimeβs method make_reduction() creates a forecaster based on reduction, using a scikit-learnβs model. It takes in a regressor, the name of the strategy for forecasting and window length. It outputs a forecaster which can be fitted like any other forecaster. You can alternatively use the DirectTabularRegressionForecaster object to reduce a forecasting problem to a tabular regression task. However, this forecaster uses the direct strategy for reduction.
Whatβs worth mentioning, the reductionβs parameters can be tuned like any other hyperparameter. This brings us to the next advantage of sktime, which is evaluating models.
Evaluating forecasting models is not a simple task. It requires tracking different metrics than in the case of standard regression problems. They are not always easy to implement, e.g. mean absolute scaled error (MASE). Validation of those models can also be tricky, as we cannot divide our data into random subsets. And finally, tuning forecastersβ parameters, e.g. window length requires lots of hand-written code and is error-prone. Sktime addresses those three main issues connected to evaluating forecasting models.
Sktime allows the evaluation of forecasters through back-testing. This process includes splitting our data into temporal training and test sets. Whatβs important, the test set contains data points ahead of the training set. The rest of the process is what we know from scikit-learn. We generate predictions on the test set and calculate the metric. Then we compare forecasts with the actual values.
Sktime provides several performance metrics specific for forecasting models. They include, e.g. mean absolute scaled error (MASE) or mean absolute percentage error (MAPE). You can invoke those metrics in two ways β either by calling a function, or a class. Using the class interface provides more flexibility. It allows you e.g. to change the parameters of the metrics. What is great, sktime also offers easy implementation of custom scorers using the make_forecasting_scorer() function. An example of defining a custom metric and evaluating a model is shown below.
Output:custom MAPE: 0.05751249071487726custom MAPE per row:date2002Q2 0.0010202002Q3 0.0039182002Q4 0.0020542003Q1 0.0040202003Q2 0.009772Freq: Q-DEC, dtype: float64
Evaluating our model on the test set is not always an optimal solution. Is there a way to adapt cross-validation for forecasting problems? The answer is yes, and sktime does it pretty well. It provides time-based cross-validation.
It enables the usage of two methods of splitting the data for cross-validation. They include Expanding Window and Sliding Window. In Expanding Window we extend the training set by a fixed number of data points in each run. This way we create multiple train-test subsets. The process takes place until the training set reaches a specified maximum size. In Sliding Window we keep a fixed size of the training set and move it across the data.
We can specify the temporal cross-validation splitter in the evaluate() method. Besides selecting the type of window, we can also specify the strategy for adding new data. We can do this either by refitting our model or updating it. Below is an example of performing cross-validation using an expanding window.
Finally, sktime provides several ways to tune modelsβ hyperparameters. It also enables tuning parameters specific to time series. For now, sktime provides two tuning meta-forecasters: ForecastingGridSearch and ForecastingRandomizedSearch. Like in scikit-learn, they work by training and evaluating a specified model with a different set of parameters. ForecastingGridSearch evaluates all combinations of hyperparameters. ForecastingRandomizedSearch tests only a fixed-size random subsample of them. Sktime provides parameter tuning for all kinds of forecasters. That also includes forecasters with regressor components.
What is great, we can also tune the parameters of nested components. It works exactly like in scikit-learnβs Pipeline. We do this by accessing keys in the dictionary generated by the get_params() method. It contains specific key-value pairs connected to forecastersβ hyperparameters. The key names are made of two elements, joined by a double underscore, e.g. `estimator__max_depth`. The first part is the name of the component. The second part is the name of the parameter.
In the example below, we tune Random Forest Regressorβs parameters using ForecastingRandomizedSearchCV.
Output:{'window_length': 2, 'estimator__max_depth': 14}0.014131551041160335
Tuning nested parameters is one of the complex use cases offered by sktime. Letβs now dive into other complicated problems that sktime addresses.
Complex forecasting problems are also supported by sktime. It offers a wide range of transformers, which can alter our time series before fitting the model. It also allows us to build pipelines, connecting transformers and forecasters. Additionally, it provides automated model selection. It compares whole model families and types of transformations. Lastly, it enables ensemble forecasting.
Weβll now focus on each of the functionalities separately. Letβs start with transformers. Why do we even need transformations in forecasting? First of all, the main goal is to remove the complexity observed in the past time series. Also, some of the forecasters, especially statistical models, require specific transformations before fitting. One example is the ARIMA model which requires time series to be stationary. Sktime provides a wide range of transformers. Some of them are:
Detrender β removing trend from time series,
Deseasonalizer β removing seasonal patterns from time series,
BoxCoxTransformer β transforming time series to resemble a normal distribution,
HampelFilter β detecting outliers in time series,
TabularToSeriesAdaptor β adapting tabular transformations to series (e.g. adapting preprocessing functionalities from scikit-learn).
Make sure to check out all of them, as the list of available transformers is still growing. Sktime provides similar methods to those available in scikit-learn. They include fit(), transform() and fit_transform(). Some of the transformers also share the inverse_transform() method. It enables accessing predictions on the same scale as the initial time series.
The code below shows an example of transforming time series and reversing the operation.
Sktime allows chaining transformers with forecasters to get a single forecaster object. That can be done using pipelines. Sktime offers a TransformedTargetForecaster class. It is a pipeline object designed to combine any number of transformers and a forecaster. It enables reducing multi-step operations to a single step. You can use any type of forecaster in a pipeline.
Sktime also allows building pipelines for time series with exogenous variables. It provides another pipeline object, ForecastingPipeline. This pipeline enables transformations of both exogenous variables and the target time series.
Below you can find an example of building a pipeline with exogenous data.
Now that you have several transformations and forecasters to test, you may wonder which of them are the best fit for your problem. Sktime provides an easy way to answer this question. It enables autoML, meaning automated model selection. This can be done using the MultiplexForecaster class. An object of this class takes in a list of forecasters as an argument. You can use it to find a forecaster with the best performance. It works with both ForecastingGridSearch and ForecastingRandomizedSearch. You can find an example of it below.
Output:{'selected_forecaster': 'ets'}
Sktime also enables the automated selection of transformations used in the pipeline. It provides an OptionalPassthrough transformer. It takes in another transformer object as an argument. That enables us to validate whether a selected transformation boosts the modelβs performance. The OptionalPassthrough object is then passed as a step in a pipeline. We can now add those passthrough hyperparameters to the grid and apply cross-validation techniques. We can also evaluate the transformerβs parameters.
Finally, sktime supports ensemble forecasting. You can pass a list of forecasters to EnsembleForecaster and then use all of them for generating predictions. This feature is especially useful if you choose models from different families. Forecasters are fit parallelly. Each of them generates its predictions. Afterwards, they are averaged by default. You can change the technique of aggregation by specifying the aggfunc parameter.
Below you can find an example of an ensemble forecaster.
Output:[TBATS(), AutoARIMA()]
The list of complex functionalities is still growing. This leads us to the last advantage that I would like to mention.
What is important for maturing libraries, a diverse community has been actively working on this project. The newest release (v. 0.7.0) took place in July 2021. It introduced features such as pipelines with exogenous variables or Crostonβs method. Forecasting is currently marked as a stable functionality. But there is still a list of future steps. They include prediction intervals and probabilistic forecasting. Also, multivariate forecasting will be added in the future. There are plans to include testing for significant differences between modelsβ performances, too.
Sktime is easily extendable. It provides extension templates to simplify the process of adding new functionalities. There is also an extension template for forecasters. It makes local implementation of new forecasters and contributions to sktime easy. If you are interested in participating in the project, you are more than welcome to do so. You can find all of the information about the contributions here.
In my opinion, sktime is a comprehensive toolkit that largely improves the experience of forecasting in Python. It simplifies the process of training models, generating predictions, and evaluating forecasters. It also enables resolving complex forecasting problems. Whatβs more, it adapts scikit-learn interface patterns to forecasting problems. The package is still in development, but even right now it is a great choice for forecasting.
Example notebook
LoΜning, M., KiraΜly, F. (2020) Forecasting with sktime: Designing sktimeβs New Forecasting API and Applying It to Replicate and Extend the M4 Study
sktimeβs documentation
sktimeβs github
sktimeβs tutorial β forecasting
sktimeβs tutorial β forecasting with sklearn and its downsides
Hyndman, R.J., Athanasopoulos, G. (2021) Forecasting: principles and practice, 3rd edition, OTexts: Melbourne, Australia. OTexts.com/fpp3. Accessed on 20.07.2021.
Thank you for reading! I would really appreciate your feedback about the article β you can connect with me on Linkedin. Also, feel free to play around with sktimeβs features using my example notebook linked in the resources.
|
[
{
"code": null,
"e": 824,
"s": 172,
"text": "One of the challenges faced by business owners is predicting future market conditions. Forecasts help to make informed decisions and form realistic expectations of results. This demand for predictions leads to the ongoing development of forecasting tools. They enable predicting future events by grasping useful information from past observations. Some of the recent forecasting frameworks include Facebookβs Prophet, Uberβs Orbit, or Linkedinβs Greykite. Yet, most of the Python forecasting packages focus on a specific model family, e.g. generalized additive models or statistical models. Sktime aims to fill the gap between those forecasting tools."
},
{
"code": null,
"e": 1510,
"s": 824,
"text": "Sktime is an open-source toolbox for time series modeling. It combines functionalities spread across many Python libraries. It also adds its own unique features for forecasting. It allows us to train, fine-tune and evaluate models for time series. It is compatible with scikit-learn. The framework also enables, e.g. time series classification, feature extraction and time series clustering. For a complete list of features check out sktimeβs documentation. This article focuses on forecasting and how sktime makes the whole process easier. It is a practical walk-through of sktimeβs functionalities for forecasting. But first, letβs take a quick look at the data used in this article."
},
{
"code": null,
"e": 1776,
"s": 1510,
"text": "All code examples are based on a public dataset from the statsmodels library. It contains USA quarterly macroeconomic data between 1959 and 2009. A full description of the dataset is available here. We will focus on predicting real gross domestic product (realgdp)."
},
{
"code": null,
"e": 1931,
"s": 1776,
"text": "Sktime puts certain constraints on the data structure used to store the time series. You can find the macroeconomic data import and transformations below."
},
{
"code": null,
"e": 1951,
"s": 1931,
"text": "But to the point..."
},
{
"code": null,
"e": 2091,
"s": 1951,
"text": "Sktime brings together functionalities from many forecasting libraries. Upon that, it provides a unified API, compatible with scikit-learn."
},
{
"code": null,
"e": 2181,
"s": 2091,
"text": "What are the advantages of a unified API in that case? Here are some of the main reasons:"
},
{
"code": null,
"e": 2250,
"s": 2181,
"text": "It allows users to easily implement, analyze and compare new models."
},
{
"code": null,
"e": 2364,
"s": 2250,
"text": "It helps to avoid confusion in choosing an appropriate algorithm thanks to a clear classification of forecasters."
},
{
"code": null,
"e": 2548,
"s": 2364,
"text": "It makes the workflow readable and understandable as all forecasters share a common interface. They are implemented in separate classes, as in other toolboxes, including scikit-learn."
},
{
"code": null,
"e": 2681,
"s": 2548,
"text": "It enables altering forecasters in a workflow. This saves us from adjusting the structure of our code each time we change our model."
},
{
"code": null,
"e": 2820,
"s": 2681,
"text": "Sktimeβs forecasters share crucial scikit-learnβs methods, such as fit() and predict(). The code below shows a basic forecasting workflow."
},
{
"code": null,
"e": 2847,
"s": 2820,
"text": "Output:2002Q2 11477.868"
},
{
"code": null,
"e": 3025,
"s": 2847,
"text": "The code above generates a one-step-ahead forecast. That is why we assigned one to the forecasting horizon. Letβs now focus on different possibilities of specifying the horizon."
},
{
"code": null,
"e": 3513,
"s": 3025,
"text": "The forecasting horizon can be an array of relative or absolute values. Absolute values are specific data points for which we want to generate forecasts. Relative values include a list of steps for which predictions will be made. The relative forecasting horizon is especially useful if we make rolling predictions using the update_predict() method. It saves us from updating the absolute horizon each time we generate predictions. The relative horizon stays constant as we add new data."
},
{
"code": null,
"e": 4001,
"s": 3513,
"text": "We can also convert relative horizons to absolute horizons and vice versa. Converting from absolute to relative values is especially worth mentioning. It does not simply produce a list of step numbers. Those values relate to the last date of the training series. This means that if the values are negative, they are in-sample forecasts. This feature is important as forecasters can fit different parameters to each step. The code below shows the differences between forecasting horizons."
},
{
"code": null,
"e": 4688,
"s": 4001,
"text": "Output:Absolute FH: ForecastingHorizon(['2002Q2', '2002Q3', '2002Q4', '2003Q1', '2003Q2', '2003Q3','2003Q4', '2004Q1', '2004Q2', '2004Q3', '2004Q4', '2005Q1', '2005Q2', '2005Q3', '2005Q4', '2006Q1', '2006Q2', '2006Q3', '2006Q4', '2007Q1', '2007Q2', '2007Q3', '2007Q4', '2008Q1', '2008Q2', '2008Q3', '2008Q4', '2009Q1', '2009Q2', '2009Q3'], dtype='period[Q-DEC]', name='date', is_relative=False)Relative FH ahead: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]Relative FH in-sample: [-29, -28, -27, -26, -25, -24, -23, -22, -21, -20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0]"
},
{
"code": null,
"e": 5324,
"s": 4688,
"text": "Letβs now dive into some common interface functionalities that sktime provides. First of all, the process of specifying and training the model is split into separate steps. We specify the forecasterβs parameters before fitting the model. In the case of univariate time series, the fit() method takes in the training series. For some forecasters, e.g. DirectTabularRegressionForecaster or DirectTimeSeriesRegressionForecaster, it also takes in the forecasting horizon. For others, the forecasting horizon can be interchangeably passed in the predict() method. Below is an example of forecasting a univariate time series using AutoARIMA."
},
{
"code": null,
"e": 5755,
"s": 5324,
"text": "Sktime also allows forecasting with exogenous variables. With multivariate exogenous time series, the range of fitting parameters is broader. It includes both a training series and a data frame with exogenous variables. As with univariate time series, some forecasters require the forecasting horizon in the parameters. In the code below weβre forecasting values of realgdp, using lagged values of an exogenous variable β realinv."
},
{
"code": null,
"e": 6116,
"s": 5755,
"text": "Apart from fitting, sktime also enables updating forecasters with new data. This allows us to automatically update the cutoff for predictions, so we donβt need to change the horizon ourselves each time we add new data. The cutoff is set to the last data point in the new training series. This method allows us to update the fitted parameters of the forecaster."
},
{
"code": null,
"e": 6307,
"s": 6116,
"text": "A common interface applies to all families of models. Sktime includes a wide range of easy-to-use, well-integrated forecasters. Here is a list of forecasters currently implemented in sktime:"
},
{
"code": null,
"e": 6390,
"s": 6307,
"text": "Holt-Winterβs Exponential Smoothing, Theta forecaster, and ETS (from statsmodels),"
},
{
"code": null,
"e": 6427,
"s": 6390,
"text": "ARIMA and AutoARIMA (from pmdarima),"
},
{
"code": null,
"e": 6456,
"s": 6427,
"text": "BATS and TBATS (from tbats),"
},
{
"code": null,
"e": 6493,
"s": 6456,
"text": "Prophet forecaster (from fbprophet),"
},
{
"code": null,
"e": 6522,
"s": 6493,
"text": "Polynomial Trend forecaster,"
},
{
"code": null,
"e": 6540,
"s": 6522,
"text": "Crostonβs method."
},
{
"code": null,
"e": 6688,
"s": 6540,
"text": "Sktime also allows the use of scikit-learnβs machine learning models for modeling time series. This leads us to the next great advantage of sktime."
},
{
"code": null,
"e": 6932,
"s": 6688,
"text": "As I mentioned earlier, sktimeβs API is compatible with scikit-learn. This implies the possibility to adapt lots of scikit-learnβs functionalities. Sktime allows us to solve forecasting problems using machine learning models from scikit-learn."
},
{
"code": null,
"e": 7179,
"s": 6932,
"text": "But why canβt we use standard regression models available in scikit-learn? In fact, we can, but the process requires lots of handwritten code and is prone to mistakes. The main reason is the conceptual difference between those two learning tasks."
},
{
"code": null,
"e": 7491,
"s": 7179,
"text": "In tabular regression, we have two types of variables β target and feature variables. We predict the target variable based on feature variables. In other words, the model learns from a set of columns to predict the value of a different column. The rows are interchangeable as they are independent of each other."
},
{
"code": null,
"e": 7821,
"s": 7491,
"text": "In forecasting, we only need to have a single variable. We predict its future values based on its past values. That is β the model predicts new rows of the same column. The rows are not interchangeable as future values depend on past values. So even if we forecast with an exogenous variable it is still not a regression problem."
},
{
"code": null,
"e": 7989,
"s": 7821,
"text": "The difference between those two problems is pretty clear. But what are the risks of using regression models in forecasting problems? Here are some of the reasons why:"
},
{
"code": null,
"e": 8197,
"s": 7989,
"text": "It generates problems with evaluating forecasting models. Using scikit-learnβs train test split can cause data leakage. In forecasting problems, rows depend on each other so we cannot shuffle them at random."
},
{
"code": null,
"e": 8424,
"s": 8197,
"text": "The process of transforming data for forecasting is prone to mistakes. In forecasting tasks, we often aggregate data from multiple data points or create lagged variables. This transformation requires lots of hand-written code."
},
{
"code": null,
"e": 8641,
"s": 8424,
"text": "The time-series parameters are hard to tune. Values like lag size or window length are not exposed as parameters of scikit-learnβs estimators. This means we need to write extra code to adjust them to fit our problem."
},
{
"code": null,
"e": 9018,
"s": 8641,
"text": "Generating multi-step predictions is tricky. Letβs consider generating forecasts for the next 14 days. Regressors from scikit-learn make 14 predictions based on the last observed value. That is not what we want to do. We expect our forecaster to update the last known value every time we generate a forecast. That is, each prediction should be based on a different data point."
},
{
"code": null,
"e": 9134,
"s": 9018,
"text": "Sktime allows the use of regression models as components within forecasters. That is possible due to the reduction."
},
{
"code": null,
"e": 9310,
"s": 9134,
"text": "Reduction is the concept of using an algorithm to solve a learning task that it was not designed for. It is the process of going from a complex learning task to a simpler one."
},
{
"code": null,
"e": 9494,
"s": 9310,
"text": "We can use reduction to transform a forecasting task into a tabular regression problem. This means we can solve a forecasting task using scikit-learnβs estimators, e.g. Random Forest."
},
{
"code": null,
"e": 9554,
"s": 9494,
"text": "The key steps that take place in the reduction process are:"
},
{
"code": null,
"e": 9639,
"s": 9554,
"text": "Using a sliding window approach to split the training set into fixed-length windows."
},
{
"code": null,
"e": 9989,
"s": 9639,
"text": "To give you an example β if the window length is equal to 11, the process looks as follows: the 1st window contains data from days 0β10 (where days 0β9 become feature variables and day 10 becomes the target variable). The 2nd window contains data from days 1β11 (where days 1β10 become feature variables and day 11 becomes the target variable), etc."
},
{
"code": null,
"e": 10132,
"s": 9989,
"text": "Arranging those windows on top of each other. This gives us data in tabular form, with clear distinction between feature and target variables."
},
{
"code": null,
"e": 10234,
"s": 10132,
"text": "Using one of the following strategies β recursive, direct, or multi-output, for generating forecasts."
},
{
"code": null,
"e": 10314,
"s": 10234,
"text": "Letβs now look at some code, performing forecasting with a regressor component."
},
{
"code": null,
"e": 10787,
"s": 10314,
"text": "In our example sktimeβs method make_reduction() creates a forecaster based on reduction, using a scikit-learnβs model. It takes in a regressor, the name of the strategy for forecasting and window length. It outputs a forecaster which can be fitted like any other forecaster. You can alternatively use the DirectTabularRegressionForecaster object to reduce a forecasting problem to a tabular regression task. However, this forecaster uses the direct strategy for reduction."
},
{
"code": null,
"e": 10959,
"s": 10787,
"text": "Whatβs worth mentioning, the reductionβs parameters can be tuned like any other hyperparameter. This brings us to the next advantage of sktime, which is evaluating models."
},
{
"code": null,
"e": 11480,
"s": 10959,
"text": "Evaluating forecasting models is not a simple task. It requires tracking different metrics than in the case of standard regression problems. They are not always easy to implement, e.g. mean absolute scaled error (MASE). Validation of those models can also be tricky, as we cannot divide our data into random subsets. And finally, tuning forecastersβ parameters, e.g. window length requires lots of hand-written code and is error-prone. Sktime addresses those three main issues connected to evaluating forecasting models."
},
{
"code": null,
"e": 11879,
"s": 11480,
"text": "Sktime allows the evaluation of forecasters through back-testing. This process includes splitting our data into temporal training and test sets. Whatβs important, the test set contains data points ahead of the training set. The rest of the process is what we know from scikit-learn. We generate predictions on the test set and calculate the metric. Then we compare forecasts with the actual values."
},
{
"code": null,
"e": 12445,
"s": 11879,
"text": "Sktime provides several performance metrics specific for forecasting models. They include, e.g. mean absolute scaled error (MASE) or mean absolute percentage error (MAPE). You can invoke those metrics in two ways β either by calling a function, or a class. Using the class interface provides more flexibility. It allows you e.g. to change the parameters of the metrics. What is great, sktime also offers easy implementation of custom scorers using the make_forecasting_scorer() function. An example of defining a custom metric and evaluating a model is shown below."
},
{
"code": null,
"e": 12626,
"s": 12445,
"text": "Output:custom MAPE: 0.05751249071487726custom MAPE per row:date2002Q2 0.0010202002Q3 0.0039182002Q4 0.0020542003Q1 0.0040202003Q2 0.009772Freq: Q-DEC, dtype: float64"
},
{
"code": null,
"e": 12857,
"s": 12626,
"text": "Evaluating our model on the test set is not always an optimal solution. Is there a way to adapt cross-validation for forecasting problems? The answer is yes, and sktime does it pretty well. It provides time-based cross-validation."
},
{
"code": null,
"e": 13297,
"s": 12857,
"text": "It enables the usage of two methods of splitting the data for cross-validation. They include Expanding Window and Sliding Window. In Expanding Window we extend the training set by a fixed number of data points in each run. This way we create multiple train-test subsets. The process takes place until the training set reaches a specified maximum size. In Sliding Window we keep a fixed size of the training set and move it across the data."
},
{
"code": null,
"e": 13608,
"s": 13297,
"text": "We can specify the temporal cross-validation splitter in the evaluate() method. Besides selecting the type of window, we can also specify the strategy for adding new data. We can do this either by refitting our model or updating it. Below is an example of performing cross-validation using an expanding window."
},
{
"code": null,
"e": 14228,
"s": 13608,
"text": "Finally, sktime provides several ways to tune modelsβ hyperparameters. It also enables tuning parameters specific to time series. For now, sktime provides two tuning meta-forecasters: ForecastingGridSearch and ForecastingRandomizedSearch. Like in scikit-learn, they work by training and evaluating a specified model with a different set of parameters. ForecastingGridSearch evaluates all combinations of hyperparameters. ForecastingRandomizedSearch tests only a fixed-size random subsample of them. Sktime provides parameter tuning for all kinds of forecasters. That also includes forecasters with regressor components."
},
{
"code": null,
"e": 14703,
"s": 14228,
"text": "What is great, we can also tune the parameters of nested components. It works exactly like in scikit-learnβs Pipeline. We do this by accessing keys in the dictionary generated by the get_params() method. It contains specific key-value pairs connected to forecastersβ hyperparameters. The key names are made of two elements, joined by a double underscore, e.g. `estimator__max_depth`. The first part is the name of the component. The second part is the name of the parameter."
},
{
"code": null,
"e": 14807,
"s": 14703,
"text": "In the example below, we tune Random Forest Regressorβs parameters using ForecastingRandomizedSearchCV."
},
{
"code": null,
"e": 14883,
"s": 14807,
"text": "Output:{'window_length': 2, 'estimator__max_depth': 14}0.014131551041160335"
},
{
"code": null,
"e": 15029,
"s": 14883,
"text": "Tuning nested parameters is one of the complex use cases offered by sktime. Letβs now dive into other complicated problems that sktime addresses."
},
{
"code": null,
"e": 15422,
"s": 15029,
"text": "Complex forecasting problems are also supported by sktime. It offers a wide range of transformers, which can alter our time series before fitting the model. It also allows us to build pipelines, connecting transformers and forecasters. Additionally, it provides automated model selection. It compares whole model families and types of transformations. Lastly, it enables ensemble forecasting."
},
{
"code": null,
"e": 15905,
"s": 15422,
"text": "Weβll now focus on each of the functionalities separately. Letβs start with transformers. Why do we even need transformations in forecasting? First of all, the main goal is to remove the complexity observed in the past time series. Also, some of the forecasters, especially statistical models, require specific transformations before fitting. One example is the ARIMA model which requires time series to be stationary. Sktime provides a wide range of transformers. Some of them are:"
},
{
"code": null,
"e": 15950,
"s": 15905,
"text": "Detrender β removing trend from time series,"
},
{
"code": null,
"e": 16012,
"s": 15950,
"text": "Deseasonalizer β removing seasonal patterns from time series,"
},
{
"code": null,
"e": 16092,
"s": 16012,
"text": "BoxCoxTransformer β transforming time series to resemble a normal distribution,"
},
{
"code": null,
"e": 16142,
"s": 16092,
"text": "HampelFilter β detecting outliers in time series,"
},
{
"code": null,
"e": 16275,
"s": 16142,
"text": "TabularToSeriesAdaptor β adapting tabular transformations to series (e.g. adapting preprocessing functionalities from scikit-learn)."
},
{
"code": null,
"e": 16635,
"s": 16275,
"text": "Make sure to check out all of them, as the list of available transformers is still growing. Sktime provides similar methods to those available in scikit-learn. They include fit(), transform() and fit_transform(). Some of the transformers also share the inverse_transform() method. It enables accessing predictions on the same scale as the initial time series."
},
{
"code": null,
"e": 16724,
"s": 16635,
"text": "The code below shows an example of transforming time series and reversing the operation."
},
{
"code": null,
"e": 17096,
"s": 16724,
"text": "Sktime allows chaining transformers with forecasters to get a single forecaster object. That can be done using pipelines. Sktime offers a TransformedTargetForecaster class. It is a pipeline object designed to combine any number of transformers and a forecaster. It enables reducing multi-step operations to a single step. You can use any type of forecaster in a pipeline."
},
{
"code": null,
"e": 17328,
"s": 17096,
"text": "Sktime also allows building pipelines for time series with exogenous variables. It provides another pipeline object, ForecastingPipeline. This pipeline enables transformations of both exogenous variables and the target time series."
},
{
"code": null,
"e": 17402,
"s": 17328,
"text": "Below you can find an example of building a pipeline with exogenous data."
},
{
"code": null,
"e": 17939,
"s": 17402,
"text": "Now that you have several transformations and forecasters to test, you may wonder which of them are the best fit for your problem. Sktime provides an easy way to answer this question. It enables autoML, meaning automated model selection. This can be done using the MultiplexForecaster class. An object of this class takes in a list of forecasters as an argument. You can use it to find a forecaster with the best performance. It works with both ForecastingGridSearch and ForecastingRandomizedSearch. You can find an example of it below."
},
{
"code": null,
"e": 17977,
"s": 17939,
"text": "Output:{'selected_forecaster': 'ets'}"
},
{
"code": null,
"e": 18481,
"s": 17977,
"text": "Sktime also enables the automated selection of transformations used in the pipeline. It provides an OptionalPassthrough transformer. It takes in another transformer object as an argument. That enables us to validate whether a selected transformation boosts the modelβs performance. The OptionalPassthrough object is then passed as a step in a pipeline. We can now add those passthrough hyperparameters to the grid and apply cross-validation techniques. We can also evaluate the transformerβs parameters."
},
{
"code": null,
"e": 18913,
"s": 18481,
"text": "Finally, sktime supports ensemble forecasting. You can pass a list of forecasters to EnsembleForecaster and then use all of them for generating predictions. This feature is especially useful if you choose models from different families. Forecasters are fit parallelly. Each of them generates its predictions. Afterwards, they are averaged by default. You can change the technique of aggregation by specifying the aggfunc parameter."
},
{
"code": null,
"e": 18970,
"s": 18913,
"text": "Below you can find an example of an ensemble forecaster."
},
{
"code": null,
"e": 19000,
"s": 18970,
"text": "Output:[TBATS(), AutoARIMA()]"
},
{
"code": null,
"e": 19120,
"s": 19000,
"text": "The list of complex functionalities is still growing. This leads us to the last advantage that I would like to mention."
},
{
"code": null,
"e": 19692,
"s": 19120,
"text": "What is important for maturing libraries, a diverse community has been actively working on this project. The newest release (v. 0.7.0) took place in July 2021. It introduced features such as pipelines with exogenous variables or Crostonβs method. Forecasting is currently marked as a stable functionality. But there is still a list of future steps. They include prediction intervals and probabilistic forecasting. Also, multivariate forecasting will be added in the future. There are plans to include testing for significant differences between modelsβ performances, too."
},
{
"code": null,
"e": 20101,
"s": 19692,
"text": "Sktime is easily extendable. It provides extension templates to simplify the process of adding new functionalities. There is also an extension template for forecasters. It makes local implementation of new forecasters and contributions to sktime easy. If you are interested in participating in the project, you are more than welcome to do so. You can find all of the information about the contributions here."
},
{
"code": null,
"e": 20541,
"s": 20101,
"text": "In my opinion, sktime is a comprehensive toolkit that largely improves the experience of forecasting in Python. It simplifies the process of training models, generating predictions, and evaluating forecasters. It also enables resolving complex forecasting problems. Whatβs more, it adapts scikit-learn interface patterns to forecasting problems. The package is still in development, but even right now it is a great choice for forecasting."
},
{
"code": null,
"e": 20558,
"s": 20541,
"text": "Example notebook"
},
{
"code": null,
"e": 20707,
"s": 20558,
"text": "LoΜning, M., KiraΜly, F. (2020) Forecasting with sktime: Designing sktimeβs New Forecasting API and Applying It to Replicate and Extend the M4 Study"
},
{
"code": null,
"e": 20730,
"s": 20707,
"text": "sktimeβs documentation"
},
{
"code": null,
"e": 20746,
"s": 20730,
"text": "sktimeβs github"
},
{
"code": null,
"e": 20778,
"s": 20746,
"text": "sktimeβs tutorial β forecasting"
},
{
"code": null,
"e": 20841,
"s": 20778,
"text": "sktimeβs tutorial β forecasting with sklearn and its downsides"
},
{
"code": null,
"e": 21004,
"s": 20841,
"text": "Hyndman, R.J., Athanasopoulos, G. (2021) Forecasting: principles and practice, 3rd edition, OTexts: Melbourne, Australia. OTexts.com/fpp3. Accessed on 20.07.2021."
}
] |
Checkbox/Table cell detection using OpenCV-Python | by Sreekiran A R | Towards Data Science
|
In this age of Digital Transformation, Information Extraction is one of the key areas of Business interest, where we need to extract relevant information from unstructured data sources like scanned invoices, bills, etc into structured data, using Computer Vision and Natural Language Processing. Here, the primary steps we are dependent on are Optical Character Recognition and Document Layout Analysis.
Optical Character Recognition (OCR) is for detecting the text from the image, and Document Layout Analysis(DLA) is where we try to get additional metadata from the documents like identifying headers, paragraphs, lines, words, tables, key-value pairs, etc.
In this article, we are focusing on solving one problem in DLA, detecting boxes in an image, which can be a checkbox or a Table cell. I am taking you through the journey of solving this problem with three examples
Create a Version0 Solution for Digital documents with checkboxes.Test the solution on a low-quality scanned document with checkboxes, find the corner cases, and finetune the algorithm to create a Version1.Test the Version1 solution on a low-quality scanned document with a table and see how it works out.
Create a Version0 Solution for Digital documents with checkboxes.
Test the solution on a low-quality scanned document with checkboxes, find the corner cases, and finetune the algorithm to create a Version1.
Test the Version1 solution on a low-quality scanned document with a table and see how it works out.
The term Born-Digital refers to materials that originated in digital form. The advantage of a Born-digital document is that it is the purest form of data. We are trying to solve this ideal scenario first. In reality, most of the documents we will be dealing with are scanned documents, where issues like poor quality, noise, skewness & orientation issues, etc are to be taken into consideration to arrive at a solution.
But letβs focus on our first solution, as Homer Simpson would say
Thatβs a problem for future Me! Man I donβt envy that guy :P
This is the sample image we are using for solving our problem.
import osimport cv2import numpy as npimage_path='digital.jpg'image=cv2.imread(image_path)
For a lot of Image Processing problems that you will encounter in the future, Binarisation will be the primary step.
Why?
The original image we get will have 3 channels and each channel will represent the Blue, Green, and Red values of each pixel of the image. But, for a lot of processes, we do not need that much information.
So we convert the image to grayscale, Where the original 3 channel image is reduced to a single-channel image and each pixel value is between 0 and 255, 0 being black and 255 being white.
Still, to reduce the complexity further, we do the Thresholding. It is nothing but making all the pixels either ON or OFF based on a threshold on the pixel values. Hence, the term Binarisation.
Now, we have a simple image with all the pixels either 0 or 255. As Steve Jobs said, sometimes
Simplicity is the Ultimate Sophistication!
gray_scale=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)th1,img_bin = cv2.threshold(gray_scale,150,225,cv2.THRESH_BINARY)img_bin=~img_bin
After binarisation, the image looks like this.
When solving Image processing problems, Morphological Transformation is a term that you will come across a lot of times.
We need to know these four terms; Dilation, Erosion, Opening, Closing.
In simple terms,Dilation: Makes the image thicker β Used to join broken partsErosion: Makes the image thinner β Used to remove noise, separate nearby componentsOpening: Erosion then Dilation β Used in Noise removalClosing: Dilation then Erosion β Filling small holes
You can read more about it from here.
Now, we create two kernels; for detecting horizontal and vertical lines.
Assumption 1: we are assuming a checkbox will be at least 15x15 size.
Why?
To avoid boxes in text getting detected as False positives. Why did I choose 15 pixels? Just a value to get started. You might need to change it later depending on our data, or we can set the line_min_width as a function of the image size.
### selecting min size as 15 pixelsline_min_width = 15kernal_h = np.ones((1,line_min_width), np.uint8)kernal_v = np.ones((line_min_width,1), np.uint8)
Applying Horizontal Kernel on the image
img_bin_h = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, kernal_h)
Applying Vertical Kernel on the image
img_bin_v = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, kernal_v)
Merging Horizontal and Vertical Images
img_bin_final=img_bin_h|img_bin_v
Now, as you can see from the above image, we can filter most of the text as noise, we do a Connected Component Analysis on the image to get the Bounding Boxes of the checkboxes.
Basically, what it does is simply what the Bucket icon in our childhood hero, Microsoft Paint does!
_, labels, stats,_ = cv2.connectedComponentsWithStats(~img_bin_final, connectivity=8, ltype=cv2.CV_32S)
So, after calling the function, we are making use of two outputs; labels and stats.
labels is a GrayScale image with each connected Component getting assigned to a different value from its neighbour.
stats is a tuple of lists with each tuple having (x,y,w,h,area) of the detected bounding boxes.
Visualizing Connected Component Image
As you can see from the above image, all the checkboxes are identified. Now Letβs use the stats to draw the detected boxes on the input image.
for x,y,w,h,area in stats[2:]: cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),2)
If you noticed, I have skipped the first 2 values of stats. Why?
They are the background and residue pixel bounding boxes, which we do not require in this case. You can try to plot the stats values to get a better idea.
Voila!! we have our Version0 Solution!
Now that we have Version 0, Letβs test it on a low-quality document and see how it performs..!
This is our input image:
Current Algorithm output:
Whoaa..! Almost, we missed two boxes...Letβs see our CC image to see why this happened.
As you can see, there is a slight gap in the boxes that we could not detect, resulting in the overflow.
So, what technique do we apply for joining broken parts? Yes, you guessed it Right! We are going to apply a layer of Dilation to the image to sort it. Before, calling the Connected Components function, we add
final_kernel = np.ones((3,3), np.uint8)img_bin_final=cv2.dilate(img_bin_final,final_kernel,iterations=1)
Now, let's see the output!
As you can see, we have detected all the bounding boxes correctly.
So, we have successfully solved a corner case and created version 1.
Letβs see the complete code now. I created it as a function.
def detect_box(image,line_min_width=15): gray_scale=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) th1,img_bin=cv2.threshold(gray_scale,150,225,cv2.THRESH_BINARY) kernal_h=np.ones((1,line_min_width), np.uint8) kernal_v=np.ones((line_min_width,1), np.uint8) img_bin_h=cv2.morphologyEx(~img_bin, cv2.MORPH_OPEN, kernal_h) img_bin_v=cv2.morphologyEx(~img_bin, cv2.MORPH_OPEN, kernal_v) img_bin_final=img_bin_h|img_bin_v final_kernel=np.ones((3,3), np.uint8) img_bin_final=cv2.dilate(img_bin_final,final_kernel,iterations=1) ret, labels, stats,centroids = cv2.connectedComponentsWithStats(~img_bin_final, connectivity=8, ltype=cv2.CV_32S) return stats,labels
It took less than 15 lines of code to solve this problem. Isnβt OpenCV amazing!?
Now, letβs test our algorithm on a low-quality document for table detection.
Input Image:
Output Images:
Looks rather beautiful ainβt it?
There it is!! We were able to extract all the boxes from an image. Notice that here Iβm not skipping any stats we detected. So, Iβm getting the entire image as a bounding box, and also the full table itself as a bounding box.
Now that we can detect checkboxes and table cells from an image, Letβs check how can we make use of the information.
Here, we were able to identify all the table cells. But, if itβs a table, a client would like to extract it into a structured format like CSV or Excel Sheet.
How can we achieve that?
As I said above, the stats variable will give the Bounding Box and area of all the table cells and the table itself.
Now, it's just a matter of Coordinate Geometry.
As most Math teachers would say,
Most of those were covered in your previous year, I wonβt be covering them :P
Usually, the use case associated with a checkbox will be mostly,
Whether itβs checked or not β Check if a bounding box is empty or notWhat is the text content inside the box (cross or tick usually)?
Whether itβs checked or not β Check if a bounding box is empty or not
What is the text content inside the box (cross or tick usually)?
As most Math teachers would say,
Most of those will be covered in next year, So I am skipping them :P
Thanks for spending your valuable time, hope you had fun learning!
Please find the full code explained in this GitHub repo. You can also check out my StackOverflow answer for the same.
Please connect with me on LinkedIn for feedback and suggestions.
As always,
Happy Coding :D
|
[
{
"code": null,
"e": 576,
"s": 172,
"text": "In this age of Digital Transformation, Information Extraction is one of the key areas of Business interest, where we need to extract relevant information from unstructured data sources like scanned invoices, bills, etc into structured data, using Computer Vision and Natural Language Processing. Here, the primary steps we are dependent on are Optical Character Recognition and Document Layout Analysis."
},
{
"code": null,
"e": 832,
"s": 576,
"text": "Optical Character Recognition (OCR) is for detecting the text from the image, and Document Layout Analysis(DLA) is where we try to get additional metadata from the documents like identifying headers, paragraphs, lines, words, tables, key-value pairs, etc."
},
{
"code": null,
"e": 1046,
"s": 832,
"text": "In this article, we are focusing on solving one problem in DLA, detecting boxes in an image, which can be a checkbox or a Table cell. I am taking you through the journey of solving this problem with three examples"
},
{
"code": null,
"e": 1351,
"s": 1046,
"text": "Create a Version0 Solution for Digital documents with checkboxes.Test the solution on a low-quality scanned document with checkboxes, find the corner cases, and finetune the algorithm to create a Version1.Test the Version1 solution on a low-quality scanned document with a table and see how it works out."
},
{
"code": null,
"e": 1417,
"s": 1351,
"text": "Create a Version0 Solution for Digital documents with checkboxes."
},
{
"code": null,
"e": 1558,
"s": 1417,
"text": "Test the solution on a low-quality scanned document with checkboxes, find the corner cases, and finetune the algorithm to create a Version1."
},
{
"code": null,
"e": 1658,
"s": 1558,
"text": "Test the Version1 solution on a low-quality scanned document with a table and see how it works out."
},
{
"code": null,
"e": 2078,
"s": 1658,
"text": "The term Born-Digital refers to materials that originated in digital form. The advantage of a Born-digital document is that it is the purest form of data. We are trying to solve this ideal scenario first. In reality, most of the documents we will be dealing with are scanned documents, where issues like poor quality, noise, skewness & orientation issues, etc are to be taken into consideration to arrive at a solution."
},
{
"code": null,
"e": 2144,
"s": 2078,
"text": "But letβs focus on our first solution, as Homer Simpson would say"
},
{
"code": null,
"e": 2205,
"s": 2144,
"text": "Thatβs a problem for future Me! Man I donβt envy that guy :P"
},
{
"code": null,
"e": 2268,
"s": 2205,
"text": "This is the sample image we are using for solving our problem."
},
{
"code": null,
"e": 2358,
"s": 2268,
"text": "import osimport cv2import numpy as npimage_path='digital.jpg'image=cv2.imread(image_path)"
},
{
"code": null,
"e": 2475,
"s": 2358,
"text": "For a lot of Image Processing problems that you will encounter in the future, Binarisation will be the primary step."
},
{
"code": null,
"e": 2480,
"s": 2475,
"text": "Why?"
},
{
"code": null,
"e": 2686,
"s": 2480,
"text": "The original image we get will have 3 channels and each channel will represent the Blue, Green, and Red values of each pixel of the image. But, for a lot of processes, we do not need that much information."
},
{
"code": null,
"e": 2874,
"s": 2686,
"text": "So we convert the image to grayscale, Where the original 3 channel image is reduced to a single-channel image and each pixel value is between 0 and 255, 0 being black and 255 being white."
},
{
"code": null,
"e": 3068,
"s": 2874,
"text": "Still, to reduce the complexity further, we do the Thresholding. It is nothing but making all the pixels either ON or OFF based on a threshold on the pixel values. Hence, the term Binarisation."
},
{
"code": null,
"e": 3163,
"s": 3068,
"text": "Now, we have a simple image with all the pixels either 0 or 255. As Steve Jobs said, sometimes"
},
{
"code": null,
"e": 3206,
"s": 3163,
"text": "Simplicity is the Ultimate Sophistication!"
},
{
"code": null,
"e": 3337,
"s": 3206,
"text": "gray_scale=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)th1,img_bin = cv2.threshold(gray_scale,150,225,cv2.THRESH_BINARY)img_bin=~img_bin"
},
{
"code": null,
"e": 3384,
"s": 3337,
"text": "After binarisation, the image looks like this."
},
{
"code": null,
"e": 3505,
"s": 3384,
"text": "When solving Image processing problems, Morphological Transformation is a term that you will come across a lot of times."
},
{
"code": null,
"e": 3576,
"s": 3505,
"text": "We need to know these four terms; Dilation, Erosion, Opening, Closing."
},
{
"code": null,
"e": 3843,
"s": 3576,
"text": "In simple terms,Dilation: Makes the image thicker β Used to join broken partsErosion: Makes the image thinner β Used to remove noise, separate nearby componentsOpening: Erosion then Dilation β Used in Noise removalClosing: Dilation then Erosion β Filling small holes"
},
{
"code": null,
"e": 3881,
"s": 3843,
"text": "You can read more about it from here."
},
{
"code": null,
"e": 3954,
"s": 3881,
"text": "Now, we create two kernels; for detecting horizontal and vertical lines."
},
{
"code": null,
"e": 4024,
"s": 3954,
"text": "Assumption 1: we are assuming a checkbox will be at least 15x15 size."
},
{
"code": null,
"e": 4029,
"s": 4024,
"text": "Why?"
},
{
"code": null,
"e": 4269,
"s": 4029,
"text": "To avoid boxes in text getting detected as False positives. Why did I choose 15 pixels? Just a value to get started. You might need to change it later depending on our data, or we can set the line_min_width as a function of the image size."
},
{
"code": null,
"e": 4420,
"s": 4269,
"text": "### selecting min size as 15 pixelsline_min_width = 15kernal_h = np.ones((1,line_min_width), np.uint8)kernal_v = np.ones((line_min_width,1), np.uint8)"
},
{
"code": null,
"e": 4460,
"s": 4420,
"text": "Applying Horizontal Kernel on the image"
},
{
"code": null,
"e": 4524,
"s": 4460,
"text": "img_bin_h = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, kernal_h)"
},
{
"code": null,
"e": 4562,
"s": 4524,
"text": "Applying Vertical Kernel on the image"
},
{
"code": null,
"e": 4626,
"s": 4562,
"text": "img_bin_v = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, kernal_v)"
},
{
"code": null,
"e": 4665,
"s": 4626,
"text": "Merging Horizontal and Vertical Images"
},
{
"code": null,
"e": 4699,
"s": 4665,
"text": "img_bin_final=img_bin_h|img_bin_v"
},
{
"code": null,
"e": 4877,
"s": 4699,
"text": "Now, as you can see from the above image, we can filter most of the text as noise, we do a Connected Component Analysis on the image to get the Bounding Boxes of the checkboxes."
},
{
"code": null,
"e": 4977,
"s": 4877,
"text": "Basically, what it does is simply what the Bucket icon in our childhood hero, Microsoft Paint does!"
},
{
"code": null,
"e": 5081,
"s": 4977,
"text": "_, labels, stats,_ = cv2.connectedComponentsWithStats(~img_bin_final, connectivity=8, ltype=cv2.CV_32S)"
},
{
"code": null,
"e": 5165,
"s": 5081,
"text": "So, after calling the function, we are making use of two outputs; labels and stats."
},
{
"code": null,
"e": 5281,
"s": 5165,
"text": "labels is a GrayScale image with each connected Component getting assigned to a different value from its neighbour."
},
{
"code": null,
"e": 5377,
"s": 5281,
"text": "stats is a tuple of lists with each tuple having (x,y,w,h,area) of the detected bounding boxes."
},
{
"code": null,
"e": 5415,
"s": 5377,
"text": "Visualizing Connected Component Image"
},
{
"code": null,
"e": 5558,
"s": 5415,
"text": "As you can see from the above image, all the checkboxes are identified. Now Letβs use the stats to draw the detected boxes on the input image."
},
{
"code": null,
"e": 5641,
"s": 5558,
"text": "for x,y,w,h,area in stats[2:]: cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),2)"
},
{
"code": null,
"e": 5706,
"s": 5641,
"text": "If you noticed, I have skipped the first 2 values of stats. Why?"
},
{
"code": null,
"e": 5861,
"s": 5706,
"text": "They are the background and residue pixel bounding boxes, which we do not require in this case. You can try to plot the stats values to get a better idea."
},
{
"code": null,
"e": 5900,
"s": 5861,
"text": "Voila!! we have our Version0 Solution!"
},
{
"code": null,
"e": 5995,
"s": 5900,
"text": "Now that we have Version 0, Letβs test it on a low-quality document and see how it performs..!"
},
{
"code": null,
"e": 6020,
"s": 5995,
"text": "This is our input image:"
},
{
"code": null,
"e": 6046,
"s": 6020,
"text": "Current Algorithm output:"
},
{
"code": null,
"e": 6134,
"s": 6046,
"text": "Whoaa..! Almost, we missed two boxes...Letβs see our CC image to see why this happened."
},
{
"code": null,
"e": 6238,
"s": 6134,
"text": "As you can see, there is a slight gap in the boxes that we could not detect, resulting in the overflow."
},
{
"code": null,
"e": 6447,
"s": 6238,
"text": "So, what technique do we apply for joining broken parts? Yes, you guessed it Right! We are going to apply a layer of Dilation to the image to sort it. Before, calling the Connected Components function, we add"
},
{
"code": null,
"e": 6552,
"s": 6447,
"text": "final_kernel = np.ones((3,3), np.uint8)img_bin_final=cv2.dilate(img_bin_final,final_kernel,iterations=1)"
},
{
"code": null,
"e": 6579,
"s": 6552,
"text": "Now, let's see the output!"
},
{
"code": null,
"e": 6646,
"s": 6579,
"text": "As you can see, we have detected all the bounding boxes correctly."
},
{
"code": null,
"e": 6715,
"s": 6646,
"text": "So, we have successfully solved a corner case and created version 1."
},
{
"code": null,
"e": 6776,
"s": 6715,
"text": "Letβs see the complete code now. I created it as a function."
},
{
"code": null,
"e": 7455,
"s": 6776,
"text": "def detect_box(image,line_min_width=15): gray_scale=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) th1,img_bin=cv2.threshold(gray_scale,150,225,cv2.THRESH_BINARY) kernal_h=np.ones((1,line_min_width), np.uint8) kernal_v=np.ones((line_min_width,1), np.uint8) img_bin_h=cv2.morphologyEx(~img_bin, cv2.MORPH_OPEN, kernal_h) img_bin_v=cv2.morphologyEx(~img_bin, cv2.MORPH_OPEN, kernal_v) img_bin_final=img_bin_h|img_bin_v final_kernel=np.ones((3,3), np.uint8) img_bin_final=cv2.dilate(img_bin_final,final_kernel,iterations=1) ret, labels, stats,centroids = cv2.connectedComponentsWithStats(~img_bin_final, connectivity=8, ltype=cv2.CV_32S) return stats,labels"
},
{
"code": null,
"e": 7536,
"s": 7455,
"text": "It took less than 15 lines of code to solve this problem. Isnβt OpenCV amazing!?"
},
{
"code": null,
"e": 7613,
"s": 7536,
"text": "Now, letβs test our algorithm on a low-quality document for table detection."
},
{
"code": null,
"e": 7626,
"s": 7613,
"text": "Input Image:"
},
{
"code": null,
"e": 7641,
"s": 7626,
"text": "Output Images:"
},
{
"code": null,
"e": 7674,
"s": 7641,
"text": "Looks rather beautiful ainβt it?"
},
{
"code": null,
"e": 7900,
"s": 7674,
"text": "There it is!! We were able to extract all the boxes from an image. Notice that here Iβm not skipping any stats we detected. So, Iβm getting the entire image as a bounding box, and also the full table itself as a bounding box."
},
{
"code": null,
"e": 8017,
"s": 7900,
"text": "Now that we can detect checkboxes and table cells from an image, Letβs check how can we make use of the information."
},
{
"code": null,
"e": 8175,
"s": 8017,
"text": "Here, we were able to identify all the table cells. But, if itβs a table, a client would like to extract it into a structured format like CSV or Excel Sheet."
},
{
"code": null,
"e": 8200,
"s": 8175,
"text": "How can we achieve that?"
},
{
"code": null,
"e": 8317,
"s": 8200,
"text": "As I said above, the stats variable will give the Bounding Box and area of all the table cells and the table itself."
},
{
"code": null,
"e": 8365,
"s": 8317,
"text": "Now, it's just a matter of Coordinate Geometry."
},
{
"code": null,
"e": 8398,
"s": 8365,
"text": "As most Math teachers would say,"
},
{
"code": null,
"e": 8476,
"s": 8398,
"text": "Most of those were covered in your previous year, I wonβt be covering them :P"
},
{
"code": null,
"e": 8541,
"s": 8476,
"text": "Usually, the use case associated with a checkbox will be mostly,"
},
{
"code": null,
"e": 8675,
"s": 8541,
"text": "Whether itβs checked or not β Check if a bounding box is empty or notWhat is the text content inside the box (cross or tick usually)?"
},
{
"code": null,
"e": 8745,
"s": 8675,
"text": "Whether itβs checked or not β Check if a bounding box is empty or not"
},
{
"code": null,
"e": 8810,
"s": 8745,
"text": "What is the text content inside the box (cross or tick usually)?"
},
{
"code": null,
"e": 8843,
"s": 8810,
"text": "As most Math teachers would say,"
},
{
"code": null,
"e": 8912,
"s": 8843,
"text": "Most of those will be covered in next year, So I am skipping them :P"
},
{
"code": null,
"e": 8979,
"s": 8912,
"text": "Thanks for spending your valuable time, hope you had fun learning!"
},
{
"code": null,
"e": 9097,
"s": 8979,
"text": "Please find the full code explained in this GitHub repo. You can also check out my StackOverflow answer for the same."
},
{
"code": null,
"e": 9162,
"s": 9097,
"text": "Please connect with me on LinkedIn for feedback and suggestions."
},
{
"code": null,
"e": 9173,
"s": 9162,
"text": "As always,"
}
] |
Transforming Skewed Data | by Corey Wade | Towards Data Science
|
Note: The following code is written in Python and excerpted from various Jupyter Notebook. Inline comments have been eliminated to make the article more readable.
Skewed data is cumbersome and common. Itβs often desirable to transform skewed data and to convert it into values between 0 and 1.
Standard functions used for such conversions include Normalization, the Sigmoid, Log, Cube Root and the Hyperbolic Tangent. It all depends on what one is trying to accomplish.
Hereβs an example of a skewed column that I generated from an 8.9 million row Amazon Books Review Dataset (Julian McAuley, UCSD). df.Helpful_Votes gives the total number of helpful votes (as opposed to unhelpful) that each book review received.
IN df.Helpful_Votes.describe()OUTcount 4.756338e+06mean 5.625667e+00std 2.663631e+01min 0.000000e+0025% 1.000000e+0050% 2.000000e+0075% 4.000000e+00max 2.331100e+04
0, 1, 2, 4, 23311. Thatβs quite a jump!
Removing outliers is an option, but not one that I want to use here. My end goal is to build a machine learning algorithm to predict whether a given review is helpful, so reviews with the most helpful votes are indispensable.
I will use the functions listed above to transform the data, explaining pros and cons along the way. As with most data science, there is no correct function. It depends on the data, and the goal of the analyst.
Normalization converts all data points to decimals between 0 and 1. If the min is 0, simply divide each point by the max.
If the min is not 0, subtract the min from each point, and then divide by the min-max difference.
The following function includes both cases.
INdef normalize(column): upper = column.max() lower = column.min() y = (column - lower)/(upper-lower) return yhelpful_normalized = normalize(df.Helpful_Votes)helpful_normalized.describe()OUTcount 4.756338e+06mean 2.413310e-04std 1.142650e-03min 0.000000e+0025% 4.289820e-0550% 8.579641e-0575% 1.715928e-04max 1.000000e+00
After normalization, the data is just as skewed as before. If the goal is simply to convert the data to points between 0 and 1, normalization is the way to go. Otherwise, normalization should be used in conjunction with other functions.
Next, the Sigmoid function. Itβs worth looking at a visual if you have not seen the Sigmoid before.
Itβs a beautifully smooth curve that guarantees a 0 to 1 range. Letβs see how it performs on df.Helpful_Votes.
INdef sigmoid(x): e = np.exp(1) y = 1/(1+e**(-x)) return yhelpful_sigmoid = sigmoid(df.Helpful_Votes)helpful_sigmoid.describe()OUTcount 4.756338e+06mean 8.237590e-01std 1.598215e-01min 5.000000e-0125% 7.310586e-0150% 8.807971e-0175% 9.820138e-01max 1.000000e+00
A definite improvement. The new data is between 0 and 1 as expected, but the min is 0.5. This makes sense when looking at the graph as there are no negative values when tallying votes.
Another point of consideration is the spread. Here, the 75th percentile is within 0.2 of the 100th percentile, comparable to other quartiles. But in the original data, the 75th percentile more than 20,000 away from the 100th percentile, not remotely close to other quartiles. In this case, the data has been distorted.
The sigmoid function can be tweaked to improve results, but for now, letβs explore other options.
Next up, logarithms. An excellent choice for making data less skewed. When using log with Python, the default base is usually e.
INhelpful_log = np.log(df.Helpful_Votes)helpful_log.describe()OUTRuntimeWarning: divide by zero encountered in log
Whoops! Division by zero! How did this happen? Perhaps a visual will clarify matters.
Ah, yes. The domain for log is strictly greater than 0. Thatβs a vertical asymptote heading down the y-axis. As x approaches 0, y approaches negative infinity. In other words, 0 is excluded from the domain.
Many of my data points are 0 because many reviews received no helpful votes. For a quick fix, I can add 1 to each data point. This works well since the log of 1 is 0. Furthermore, the same spread is retained since all points are increased by 1.
INhelpful_log = np.log(df.Helpful_Votes + 1)helpful_log.describe()OUTcount 4.756338e+06mean 1.230977e+00std 9.189495e-01min 0.000000e+0025% 6.931472e-0150% 1.098612e+0075% 1.609438e+00max 1.005672e+01Name: Helpful_Votes, dtype: float64
Excellent. The new range is from 0 to 10, and the quartiles are reflective of the original data.
Time to normalize.
INhelpful_log_normalized = normalize(helpful_log)helpful_log_normalized.describe()OUTcount 4.756338e+06mean 1.224034e-01std 9.137663e-02min 0.000000e+0025% 6.892376e-0250% 1.092416e-0175% 1.600360e-01max 1.000000e+00Name: Helpful_Votes, dtype: float64
This looks very reasonable. The log function plus normalization is an excellent way to transform skewed data if the results can still be skewed. There is, however, one major drawback in this case.
Why transform data to values between 0 and 1 in the first place? Itβs usually so percentages and probability can play a role. In my case, I want the median at around 50%. After normalizing here, the median is at 0.1.
When numbers are too large, one can try fractional exponents as a means of transformation. Consider the cube root.
INhelpful_cube_root = df.Helpful_Votes**(1/3)helpful_cube_root.describe()OUTcount 4.756338e+06mean 1.321149e+00std 8.024150e-01min 0.000000e+0025% 1.000000e+0050% 1.259921e+0075% 1.587401e+00max 2.856628e+01
This is very similar to log, but the range here is larger, from 0 to 28.
INhelpful_cube_root_normalized = normalize(helpful_cube_root)helpful_cube_root_normalized.describe()OUTcount 4.756338e+06mean 4.624857e-02std 2.808959e-02min 0.000000e+0025% 3.500631e-0250% 4.410519e-0275% 5.556906e-02max 1.000000e+00
As expected, the new data is more problematic after normalizing. Now the median is at 0.04, a far cry from 50%.
I like to play around with numbers, so I experimented with a few powers. Interesting results came from 1/log_max. I define log_max as the log of the maximum value. (The log of 23,311 is 10.06.)
INlog_max = np.log(df.Helpful_Votes.max())helpful_log_max_root = df.Helpful_Votes**(1/log_max)helpful_log_max_root.describe()OUTcount 4.756338e+06mean 9.824853e-01std 3.712224e-01min 0.000000e+0025% 1.000000e+0050% 1.071355e+0075% 1.147801e+00max 2.718282e+00
A range from 0 to 2.7 is very appealing.
Log Max Root Normalized
INhelpful_log_max_root_normalized = normalize(helpful_log_max_root)helpful_log_max_root_normalized.describe()OUTcount 4.756338e+06mean 3.614362e-01std 1.365651e-01min 0.000000e+0025% 3.678794e-0150% 3.941294e-0175% 4.222525e-01max 1.000000e+00
This looks good, but the dataβs very clustered in the 25β75% range, a cluster that likely extends much further. So although the overall spread is more desirable, itβs not quite sufficient here.
Itβs time for our last standard function, the hyperbolic tangent. Letβs start with a graph.
This looks very similar to the sigmoid. One primary difference is the range. The hyperbolic tangent has a range from -1 to 1, whereas the sigmoid has a range from 0 to 1.
In my data, since df.Helpful_Votes are all non-negative, my output will be from 0 to 1.
INhelpful_hyperbolic_tangent = np.tanh(df.Helpful_Votes)helpful_hyperbolic_tangent.describe()OUTcount 4.756338e+06mean 7.953343e-01std 3.033794e-01min 0.000000e+0025% 7.615942e-0150% 9.640276e-0175% 9.993293e-01max 1.000000e+00
Thereβs no need to normalize, but thereβs on glaring issue.
The hyperbolic tangent distorts the data more than the sigmoid. Thereβs a difference of 0.001 between the 75th and 100th percentiles, much closer than any other quartile. In the original data, that difference is 23,307, 1,000 times greater than the difference between other quartiles.
Itβs not even close.
Percentiles provide yet another option. Each data point can be ranked according to its percentile, and pandas provides a nice built-in method, .rank, for dealing with this.
The general idea is that each point receives the value of itβs percentile. In my case, since there are many data points with a low number of helpful votes, there are different ways for choosing these percentiles. I like the βminβ method, where all data points receive the percentile given to the first member of the group. The default method is βaverage,β where all data points with the same value take the mean percentile in that group.
INsize = len(df.Helpful_Votes)-1helpful_percentile_linearization = df.Helpful_Votes.rank(method=βminβ).apply(lambda x: (x-1)/size)helpful_percentile_linearization.describe()OUTcount 4.756338e+06mean 4.111921e-01std 3.351097e-01min 0.000000e+0025% 1.133505e-0150% 4.719447e-0175% 7.059382e-01max 1.000000e+00
Intriguing. Percentile linearization is basically the same as a ranking system. If the difference between the 1st data point and the 2nd should be the same as all data points that are one unit part, percentile linearization is the way to go.
On the downside, Percentile Linearization erases critical signs of skewness. This data appears slightly skewed because there are hundreds of thousands of reviews with 1 and 2 votes, not because there are few reviews with an insanely high number of votes.
Since I am dealing primarily with a ranking system, I combined percentile linearization with my own piecewise linearization function. Logs also played a role.
Whatever your choice or style, never limit yourself to the standard options. Mathematical functions are extremely rich, and their intersection with data science deserves more recognition and flexibility.
I would love to hear about other functions that people use for transforming skewed data. I have heard about the boxcox function, though I have yet to explore it in detail.
More details on Wadeβs Amazon Book Review project can be viewed on his Github page, Helpful_Reviews.
|
[
{
"code": null,
"e": 335,
"s": 172,
"text": "Note: The following code is written in Python and excerpted from various Jupyter Notebook. Inline comments have been eliminated to make the article more readable."
},
{
"code": null,
"e": 466,
"s": 335,
"text": "Skewed data is cumbersome and common. Itβs often desirable to transform skewed data and to convert it into values between 0 and 1."
},
{
"code": null,
"e": 642,
"s": 466,
"text": "Standard functions used for such conversions include Normalization, the Sigmoid, Log, Cube Root and the Hyperbolic Tangent. It all depends on what one is trying to accomplish."
},
{
"code": null,
"e": 887,
"s": 642,
"text": "Hereβs an example of a skewed column that I generated from an 8.9 million row Amazon Books Review Dataset (Julian McAuley, UCSD). df.Helpful_Votes gives the total number of helpful votes (as opposed to unhelpful) that each book review received."
},
{
"code": null,
"e": 1089,
"s": 887,
"text": "IN df.Helpful_Votes.describe()OUTcount 4.756338e+06mean 5.625667e+00std 2.663631e+01min 0.000000e+0025% 1.000000e+0050% 2.000000e+0075% 4.000000e+00max 2.331100e+04"
},
{
"code": null,
"e": 1129,
"s": 1089,
"text": "0, 1, 2, 4, 23311. Thatβs quite a jump!"
},
{
"code": null,
"e": 1355,
"s": 1129,
"text": "Removing outliers is an option, but not one that I want to use here. My end goal is to build a machine learning algorithm to predict whether a given review is helpful, so reviews with the most helpful votes are indispensable."
},
{
"code": null,
"e": 1566,
"s": 1355,
"text": "I will use the functions listed above to transform the data, explaining pros and cons along the way. As with most data science, there is no correct function. It depends on the data, and the goal of the analyst."
},
{
"code": null,
"e": 1688,
"s": 1566,
"text": "Normalization converts all data points to decimals between 0 and 1. If the min is 0, simply divide each point by the max."
},
{
"code": null,
"e": 1786,
"s": 1688,
"text": "If the min is not 0, subtract the min from each point, and then divide by the min-max difference."
},
{
"code": null,
"e": 1830,
"s": 1786,
"text": "The following function includes both cases."
},
{
"code": null,
"e": 2201,
"s": 1830,
"text": "INdef normalize(column): upper = column.max() lower = column.min() y = (column - lower)/(upper-lower) return yhelpful_normalized = normalize(df.Helpful_Votes)helpful_normalized.describe()OUTcount 4.756338e+06mean 2.413310e-04std 1.142650e-03min 0.000000e+0025% 4.289820e-0550% 8.579641e-0575% 1.715928e-04max 1.000000e+00"
},
{
"code": null,
"e": 2438,
"s": 2201,
"text": "After normalization, the data is just as skewed as before. If the goal is simply to convert the data to points between 0 and 1, normalization is the way to go. Otherwise, normalization should be used in conjunction with other functions."
},
{
"code": null,
"e": 2538,
"s": 2438,
"text": "Next, the Sigmoid function. Itβs worth looking at a visual if you have not seen the Sigmoid before."
},
{
"code": null,
"e": 2649,
"s": 2538,
"text": "Itβs a beautifully smooth curve that guarantees a 0 to 1 range. Letβs see how it performs on df.Helpful_Votes."
},
{
"code": null,
"e": 2957,
"s": 2649,
"text": "INdef sigmoid(x): e = np.exp(1) y = 1/(1+e**(-x)) return yhelpful_sigmoid = sigmoid(df.Helpful_Votes)helpful_sigmoid.describe()OUTcount 4.756338e+06mean 8.237590e-01std 1.598215e-01min 5.000000e-0125% 7.310586e-0150% 8.807971e-0175% 9.820138e-01max 1.000000e+00"
},
{
"code": null,
"e": 3142,
"s": 2957,
"text": "A definite improvement. The new data is between 0 and 1 as expected, but the min is 0.5. This makes sense when looking at the graph as there are no negative values when tallying votes."
},
{
"code": null,
"e": 3461,
"s": 3142,
"text": "Another point of consideration is the spread. Here, the 75th percentile is within 0.2 of the 100th percentile, comparable to other quartiles. But in the original data, the 75th percentile more than 20,000 away from the 100th percentile, not remotely close to other quartiles. In this case, the data has been distorted."
},
{
"code": null,
"e": 3559,
"s": 3461,
"text": "The sigmoid function can be tweaked to improve results, but for now, letβs explore other options."
},
{
"code": null,
"e": 3688,
"s": 3559,
"text": "Next up, logarithms. An excellent choice for making data less skewed. When using log with Python, the default base is usually e."
},
{
"code": null,
"e": 3803,
"s": 3688,
"text": "INhelpful_log = np.log(df.Helpful_Votes)helpful_log.describe()OUTRuntimeWarning: divide by zero encountered in log"
},
{
"code": null,
"e": 3889,
"s": 3803,
"text": "Whoops! Division by zero! How did this happen? Perhaps a visual will clarify matters."
},
{
"code": null,
"e": 4096,
"s": 3889,
"text": "Ah, yes. The domain for log is strictly greater than 0. Thatβs a vertical asymptote heading down the y-axis. As x approaches 0, y approaches negative infinity. In other words, 0 is excluded from the domain."
},
{
"code": null,
"e": 4341,
"s": 4096,
"text": "Many of my data points are 0 because many reviews received no helpful votes. For a quick fix, I can add 1 to each data point. This works well since the log of 1 is 0. Furthermore, the same spread is retained since all points are increased by 1."
},
{
"code": null,
"e": 4614,
"s": 4341,
"text": "INhelpful_log = np.log(df.Helpful_Votes + 1)helpful_log.describe()OUTcount 4.756338e+06mean 1.230977e+00std 9.189495e-01min 0.000000e+0025% 6.931472e-0150% 1.098612e+0075% 1.609438e+00max 1.005672e+01Name: Helpful_Votes, dtype: float64"
},
{
"code": null,
"e": 4711,
"s": 4614,
"text": "Excellent. The new range is from 0 to 10, and the quartiles are reflective of the original data."
},
{
"code": null,
"e": 4730,
"s": 4711,
"text": "Time to normalize."
},
{
"code": null,
"e": 5019,
"s": 4730,
"text": "INhelpful_log_normalized = normalize(helpful_log)helpful_log_normalized.describe()OUTcount 4.756338e+06mean 1.224034e-01std 9.137663e-02min 0.000000e+0025% 6.892376e-0250% 1.092416e-0175% 1.600360e-01max 1.000000e+00Name: Helpful_Votes, dtype: float64"
},
{
"code": null,
"e": 5216,
"s": 5019,
"text": "This looks very reasonable. The log function plus normalization is an excellent way to transform skewed data if the results can still be skewed. There is, however, one major drawback in this case."
},
{
"code": null,
"e": 5433,
"s": 5216,
"text": "Why transform data to values between 0 and 1 in the first place? Itβs usually so percentages and probability can play a role. In my case, I want the median at around 50%. After normalizing here, the median is at 0.1."
},
{
"code": null,
"e": 5548,
"s": 5433,
"text": "When numbers are too large, one can try fractional exponents as a means of transformation. Consider the cube root."
},
{
"code": null,
"e": 5793,
"s": 5548,
"text": "INhelpful_cube_root = df.Helpful_Votes**(1/3)helpful_cube_root.describe()OUTcount 4.756338e+06mean 1.321149e+00std 8.024150e-01min 0.000000e+0025% 1.000000e+0050% 1.259921e+0075% 1.587401e+00max 2.856628e+01"
},
{
"code": null,
"e": 5866,
"s": 5793,
"text": "This is very similar to log, but the range here is larger, from 0 to 28."
},
{
"code": null,
"e": 6138,
"s": 5866,
"text": "INhelpful_cube_root_normalized = normalize(helpful_cube_root)helpful_cube_root_normalized.describe()OUTcount 4.756338e+06mean 4.624857e-02std 2.808959e-02min 0.000000e+0025% 3.500631e-0250% 4.410519e-0275% 5.556906e-02max 1.000000e+00"
},
{
"code": null,
"e": 6250,
"s": 6138,
"text": "As expected, the new data is more problematic after normalizing. Now the median is at 0.04, a far cry from 50%."
},
{
"code": null,
"e": 6444,
"s": 6250,
"text": "I like to play around with numbers, so I experimented with a few powers. Interesting results came from 1/log_max. I define log_max as the log of the maximum value. (The log of 23,311 is 10.06.)"
},
{
"code": null,
"e": 6741,
"s": 6444,
"text": "INlog_max = np.log(df.Helpful_Votes.max())helpful_log_max_root = df.Helpful_Votes**(1/log_max)helpful_log_max_root.describe()OUTcount 4.756338e+06mean 9.824853e-01std 3.712224e-01min 0.000000e+0025% 1.000000e+0050% 1.071355e+0075% 1.147801e+00max 2.718282e+00"
},
{
"code": null,
"e": 6782,
"s": 6741,
"text": "A range from 0 to 2.7 is very appealing."
},
{
"code": null,
"e": 6806,
"s": 6782,
"text": "Log Max Root Normalized"
},
{
"code": null,
"e": 7087,
"s": 6806,
"text": "INhelpful_log_max_root_normalized = normalize(helpful_log_max_root)helpful_log_max_root_normalized.describe()OUTcount 4.756338e+06mean 3.614362e-01std 1.365651e-01min 0.000000e+0025% 3.678794e-0150% 3.941294e-0175% 4.222525e-01max 1.000000e+00"
},
{
"code": null,
"e": 7281,
"s": 7087,
"text": "This looks good, but the dataβs very clustered in the 25β75% range, a cluster that likely extends much further. So although the overall spread is more desirable, itβs not quite sufficient here."
},
{
"code": null,
"e": 7373,
"s": 7281,
"text": "Itβs time for our last standard function, the hyperbolic tangent. Letβs start with a graph."
},
{
"code": null,
"e": 7544,
"s": 7373,
"text": "This looks very similar to the sigmoid. One primary difference is the range. The hyperbolic tangent has a range from -1 to 1, whereas the sigmoid has a range from 0 to 1."
},
{
"code": null,
"e": 7632,
"s": 7544,
"text": "In my data, since df.Helpful_Votes are all non-negative, my output will be from 0 to 1."
},
{
"code": null,
"e": 7897,
"s": 7632,
"text": "INhelpful_hyperbolic_tangent = np.tanh(df.Helpful_Votes)helpful_hyperbolic_tangent.describe()OUTcount 4.756338e+06mean 7.953343e-01std 3.033794e-01min 0.000000e+0025% 7.615942e-0150% 9.640276e-0175% 9.993293e-01max 1.000000e+00"
},
{
"code": null,
"e": 7957,
"s": 7897,
"text": "Thereβs no need to normalize, but thereβs on glaring issue."
},
{
"code": null,
"e": 8242,
"s": 7957,
"text": "The hyperbolic tangent distorts the data more than the sigmoid. Thereβs a difference of 0.001 between the 75th and 100th percentiles, much closer than any other quartile. In the original data, that difference is 23,307, 1,000 times greater than the difference between other quartiles."
},
{
"code": null,
"e": 8263,
"s": 8242,
"text": "Itβs not even close."
},
{
"code": null,
"e": 8436,
"s": 8263,
"text": "Percentiles provide yet another option. Each data point can be ranked according to its percentile, and pandas provides a nice built-in method, .rank, for dealing with this."
},
{
"code": null,
"e": 8874,
"s": 8436,
"text": "The general idea is that each point receives the value of itβs percentile. In my case, since there are many data points with a low number of helpful votes, there are different ways for choosing these percentiles. I like the βminβ method, where all data points receive the percentile given to the first member of the group. The default method is βaverage,β where all data points with the same value take the mean percentile in that group."
},
{
"code": null,
"e": 9219,
"s": 8874,
"text": "INsize = len(df.Helpful_Votes)-1helpful_percentile_linearization = df.Helpful_Votes.rank(method=βminβ).apply(lambda x: (x-1)/size)helpful_percentile_linearization.describe()OUTcount 4.756338e+06mean 4.111921e-01std 3.351097e-01min 0.000000e+0025% 1.133505e-0150% 4.719447e-0175% 7.059382e-01max 1.000000e+00"
},
{
"code": null,
"e": 9461,
"s": 9219,
"text": "Intriguing. Percentile linearization is basically the same as a ranking system. If the difference between the 1st data point and the 2nd should be the same as all data points that are one unit part, percentile linearization is the way to go."
},
{
"code": null,
"e": 9716,
"s": 9461,
"text": "On the downside, Percentile Linearization erases critical signs of skewness. This data appears slightly skewed because there are hundreds of thousands of reviews with 1 and 2 votes, not because there are few reviews with an insanely high number of votes."
},
{
"code": null,
"e": 9875,
"s": 9716,
"text": "Since I am dealing primarily with a ranking system, I combined percentile linearization with my own piecewise linearization function. Logs also played a role."
},
{
"code": null,
"e": 10079,
"s": 9875,
"text": "Whatever your choice or style, never limit yourself to the standard options. Mathematical functions are extremely rich, and their intersection with data science deserves more recognition and flexibility."
},
{
"code": null,
"e": 10251,
"s": 10079,
"text": "I would love to hear about other functions that people use for transforming skewed data. I have heard about the boxcox function, though I have yet to explore it in detail."
}
] |
Bootstrap 4 - Jumbotron
|
Jumbotron component increases the size of headings and add a lot of margin for landing page content. By default, jumbotron display with light grey box to show the important information.
Create a jumbotron by adding .jumbotron class to <div> element as shown in the example below β
<html lang = "en">
<head>
<!-- Meta tags -->
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
<!-- Bootstrap CSS -->
<link rel = "stylesheet"
href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin = "anonymous">
<title>Bootstrap 4 Example</title>
</head>
<body>
<div class = "container">
<h2>Jumbotron</h2>
<div class = "jumbotron">
<h2>Welcome To Tutorials Point!</h2>
<p class = "lead">
Our mission is to deliver Simply Easy Learning with clear, crisp, and
to-the-point content on a wide range of technical and non-technical
subjects without any preconditions and impediments.
</p>
<hr class = "my-4">
<p>20 million readers read 50 million pages every month.</p>
<a class = "btn btn-info btn-sm" href = "#" role = "button">Read more</a>
</div>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin = "anonymous">
</script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin = "anonymous">
</script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
crossorigin = "anonymous">
</script>
</body>
</html>
It will produce the following result β
Our mission is to deliver Simply Easy Learning with clear, crisp, and
to-the-point content on a wide range of technical and non-technical
subjects without any preconditions and impediments.
20 million readers read 50 million pages every month.
Create a full width jumbotron without rounded corners by using .jumbotron-fluid class and add .container or .container-fluid class inside the jumbotron as shown in the following example β
<html lang = "en">
<head>
<!-- Meta tags -->
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
<!-- Bootstrap CSS -->
<link rel = "stylesheet"
href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin = "anonymous">
<title>Bootstrap 4 Example</title>
</head>
<body>
<div class = "jumbotron jumbotron-fluid">
<div class = "container">
<h2>Fluid jumbotron</h2>
<p class = "lead">This occupies the entire horizontal space.</p>
</div>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin = "anonymous">
</script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin = "anonymous">
</script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
crossorigin = "anonymous">
</script>
</body>
</html>
It will produce the following result β
This occupies the entire horizontal space.
26 Lectures
2 hours
Anadi Sharma
54 Lectures
4.5 hours
Frahaan Hussain
161 Lectures
14.5 hours
Eduonix Learning Solutions
20 Lectures
4 hours
Azaz Patel
15 Lectures
1.5 hours
Muhammad Ismail
62 Lectures
8 hours
Yossef Ayman Zedan
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2002,
"s": 1816,
"text": "Jumbotron component increases the size of headings and add a lot of margin for landing page content. By default, jumbotron display with light grey box to show the important information."
},
{
"code": null,
"e": 2097,
"s": 2002,
"text": "Create a jumbotron by adding .jumbotron class to <div> element as shown in the example below β"
},
{
"code": null,
"e": 4129,
"s": 2097,
"text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n \n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Jumbotron</h2>\n <div class = \"jumbotron\">\n <h2>Welcome To Tutorials Point!</h2>\n <p class = \"lead\">\n Our mission is to deliver Simply Easy Learning with clear, crisp, and \n to-the-point content on a wide range of technical and non-technical \n subjects without any preconditions and impediments.\n </p>\n \n <hr class = \"my-4\">\n <p>20 million readers read 50 million pages every month.</p>\n <a class = \"btn btn-info btn-sm\" href = \"#\" role = \"button\">Read more</a>\n </div>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 4168,
"s": 4129,
"text": "It will produce the following result β"
},
{
"code": null,
"e": 4419,
"s": 4168,
"text": "\n Our mission is to deliver Simply Easy Learning with clear, crisp, and \n to-the-point content on a wide range of technical and non-technical \n subjects without any preconditions and impediments.\n "
},
{
"code": null,
"e": 4473,
"s": 4419,
"text": "20 million readers read 50 million pages every month."
},
{
"code": null,
"e": 4661,
"s": 4473,
"text": "Create a full width jumbotron without rounded corners by using .jumbotron-fluid class and add .container or .container-fluid class inside the jumbotron as shown in the following example β"
},
{
"code": null,
"e": 6257,
"s": 4661,
"text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n \n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"jumbotron jumbotron-fluid\">\n <div class = \"container\">\n <h2>Fluid jumbotron</h2>\n <p class = \"lead\">This occupies the entire horizontal space.</p>\n </div>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 6296,
"s": 6257,
"text": "It will produce the following result β"
},
{
"code": null,
"e": 6339,
"s": 6296,
"text": "This occupies the entire horizontal space."
},
{
"code": null,
"e": 6372,
"s": 6339,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6386,
"s": 6372,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6421,
"s": 6386,
"text": "\n 54 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6438,
"s": 6421,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6475,
"s": 6438,
"text": "\n 161 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 6503,
"s": 6475,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 6536,
"s": 6503,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6548,
"s": 6536,
"text": " Azaz Patel"
},
{
"code": null,
"e": 6583,
"s": 6548,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6600,
"s": 6583,
"text": " Muhammad Ismail"
},
{
"code": null,
"e": 6633,
"s": 6600,
"text": "\n 62 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 6653,
"s": 6633,
"text": " Yossef Ayman Zedan"
},
{
"code": null,
"e": 6660,
"s": 6653,
"text": " Print"
},
{
"code": null,
"e": 6671,
"s": 6660,
"text": " Add Notes"
}
] |
std::basic_istream::getline in C++ with Examples - GeeksforGeeks
|
06 Jan, 2022
The std::basic_istream::getline is used to extract the characters from stream until end of line or the extracted character is the delimiting character. The delimiting character is the new line character i.e β\nβ. This function will also stop extracting characters if the end-of-file is reached if input is taken using file.Header File:
#include <iostream>
Syntax:
basic_istream& getline (char_type* a,
streamsize n )
basic_istream& getline (char_type* a,
streamsize n,
char_type delim);
Parameters: It accepts the following parameters:
N: It represent maximum number of character pointed by a.
a: It is the pointer to string to store the characters.
stream: It is an explicit delimiting character.
Return Value: It returns the basic_istream object.Below are the program to demonstrate basic_istream::getline():Program 1:
CPP
// C++ program to demonstrate// basic_istream::getline #include <iostream>using namespace std; // Driver Codeint main(){ // Given string istringstream gfg("123|aef|5h"); // Array to store the above string // after streaming vector<array<char, 4> > v; // Use function getline() to stream // the given string with delimiter '|' for (array<char, 4> a; gfg.getline(&a[0], 4, '|');) { v.push_back(a); } // Print the strings after streaming for (auto& it : v) { cout << &it[0] << endl; } return 0;}
123
aef
5h
Program 2:
CPP
// C++ program to demonstrate// basic_istream::getline #include <iostream>using namespace std; // Driver Codeint main(){ // Given string istringstream gfg("GeeksforGeeks, " " A, Computer, Science, " "Portal, For, Geeks"); // Array to store the above string // after streaming vector<array<char, 40> > v; // Use function getline() to stream // the given string with delimiter ', ' for (array<char, 40> a; gfg.getline(&a[0], 40, ', ');) { v.push_back(a); } // Print the strings after streaming for (auto& it : v) { cout << &it[0] << endl; } return 0;}
GeeksforGeeks
A
Computer
Science
Portal
For
Geeks
Reference: http://www.cplusplus.com/reference/istream/basic_istream/getline/
akshaysingh98088
adnanirshad158
CPP-Functions
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Iterators in C++ STL
Friend class and function in C++
Polymorphism in C++
Sorting a vector in C++
Convert string to char array in C++
List in C++ Standard Template Library (STL)
Inline Functions in C++
std::string class in C++
Destructors in C++
|
[
{
"code": null,
"e": 24018,
"s": 23990,
"text": "\n06 Jan, 2022"
},
{
"code": null,
"e": 24355,
"s": 24018,
"text": "The std::basic_istream::getline is used to extract the characters from stream until end of line or the extracted character is the delimiting character. The delimiting character is the new line character i.e β\\nβ. This function will also stop extracting characters if the end-of-file is reached if input is taken using file.Header File: "
},
{
"code": null,
"e": 24375,
"s": 24355,
"text": "#include <iostream>"
},
{
"code": null,
"e": 24384,
"s": 24375,
"text": "Syntax: "
},
{
"code": null,
"e": 24596,
"s": 24384,
"text": "basic_istream& getline (char_type* a, \n streamsize n )\n\nbasic_istream& getline (char_type* a, \n streamsize n, \n char_type delim);"
},
{
"code": null,
"e": 24647,
"s": 24596,
"text": "Parameters: It accepts the following parameters: "
},
{
"code": null,
"e": 24705,
"s": 24647,
"text": "N: It represent maximum number of character pointed by a."
},
{
"code": null,
"e": 24761,
"s": 24705,
"text": "a: It is the pointer to string to store the characters."
},
{
"code": null,
"e": 24809,
"s": 24761,
"text": "stream: It is an explicit delimiting character."
},
{
"code": null,
"e": 24933,
"s": 24809,
"text": "Return Value: It returns the basic_istream object.Below are the program to demonstrate basic_istream::getline():Program 1: "
},
{
"code": null,
"e": 24937,
"s": 24933,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate// basic_istream::getline #include <iostream>using namespace std; // Driver Codeint main(){ // Given string istringstream gfg(\"123|aef|5h\"); // Array to store the above string // after streaming vector<array<char, 4> > v; // Use function getline() to stream // the given string with delimiter '|' for (array<char, 4> a; gfg.getline(&a[0], 4, '|');) { v.push_back(a); } // Print the strings after streaming for (auto& it : v) { cout << &it[0] << endl; } return 0;}",
"e": 25495,
"s": 24937,
"text": null
},
{
"code": null,
"e": 25506,
"s": 25495,
"text": "123\naef\n5h"
},
{
"code": null,
"e": 25520,
"s": 25508,
"text": "Program 2: "
},
{
"code": null,
"e": 25524,
"s": 25520,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate// basic_istream::getline #include <iostream>using namespace std; // Driver Codeint main(){ // Given string istringstream gfg(\"GeeksforGeeks, \" \" A, Computer, Science, \" \"Portal, For, Geeks\"); // Array to store the above string // after streaming vector<array<char, 40> > v; // Use function getline() to stream // the given string with delimiter ', ' for (array<char, 40> a; gfg.getline(&a[0], 40, ', ');) { v.push_back(a); } // Print the strings after streaming for (auto& it : v) { cout << &it[0] << endl; } return 0;}",
"e": 26181,
"s": 25524,
"text": null
},
{
"code": null,
"e": 26231,
"s": 26181,
"text": "GeeksforGeeks\nA\nComputer\nScience\nPortal\nFor\nGeeks"
},
{
"code": null,
"e": 26310,
"s": 26233,
"text": "Reference: http://www.cplusplus.com/reference/istream/basic_istream/getline/"
},
{
"code": null,
"e": 26327,
"s": 26310,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 26342,
"s": 26327,
"text": "adnanirshad158"
},
{
"code": null,
"e": 26356,
"s": 26342,
"text": "CPP-Functions"
},
{
"code": null,
"e": 26360,
"s": 26356,
"text": "C++"
},
{
"code": null,
"e": 26364,
"s": 26360,
"text": "CPP"
},
{
"code": null,
"e": 26462,
"s": 26364,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26471,
"s": 26462,
"text": "Comments"
},
{
"code": null,
"e": 26484,
"s": 26471,
"text": "Old Comments"
},
{
"code": null,
"e": 26512,
"s": 26484,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 26533,
"s": 26512,
"text": "Iterators in C++ STL"
},
{
"code": null,
"e": 26566,
"s": 26533,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 26586,
"s": 26566,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 26610,
"s": 26586,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 26646,
"s": 26610,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 26690,
"s": 26646,
"text": "List in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 26714,
"s": 26690,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 26739,
"s": 26714,
"text": "std::string class in C++"
}
] |
How to store a 2d Array in another 2d Array in java?
|
Create an array to which you want to store the existing array with the same length. A 2d array is an array of one dimensional arrays therefore, to copy (or, to perform any operation on) the elements of the 2d array you need two loops one nested within the other. Where, the outer loop is to traverse through the array of one dimensional arrays and, the inner loop is to traverse through the elements of a particular one dimensional array.
public class Copying2DArray {
public static void main(String args[]) {
int[][] myArray = {{41, 52, 63}, {74, 85, 96}, {93, 82, 71} };
int[][] copyArray =new int[myArray.length][];
for (int i = 0; i < copyArray.length; ++i) {
copyArray[i] = new int[myArray[i].length];
for (int j = 0; j < copyArray[i].length; ++j) {
copyArray[i][j] = myArray[i][j];
}
}
System.out.println(Arrays.deepToString(copyArray));
}
}
[[41, 52, 63], [74, 85, 96], [93, 82, 71]]
|
[
{
"code": null,
"e": 1501,
"s": 1062,
"text": "Create an array to which you want to store the existing array with the same length. A 2d array is an array of one dimensional arrays therefore, to copy (or, to perform any operation on) the elements of the 2d array you need two loops one nested within the other. Where, the outer loop is to traverse through the array of one dimensional arrays and, the inner loop is to traverse through the elements of a particular one dimensional array."
},
{
"code": null,
"e": 1985,
"s": 1501,
"text": "public class Copying2DArray {\n public static void main(String args[]) {\n int[][] myArray = {{41, 52, 63}, {74, 85, 96}, {93, 82, 71} };\n int[][] copyArray =new int[myArray.length][];\n for (int i = 0; i < copyArray.length; ++i) {\n copyArray[i] = new int[myArray[i].length];\n for (int j = 0; j < copyArray[i].length; ++j) {\n copyArray[i][j] = myArray[i][j];\n }\n }\n System.out.println(Arrays.deepToString(copyArray));\n }\n}"
},
{
"code": null,
"e": 2028,
"s": 1985,
"text": "[[41, 52, 63], [74, 85, 96], [93, 82, 71]]"
}
] |
PyQt5 QSpinBox - Checking if the character is UTF-32 format - GeeksforGeeks
|
26 May, 2020
In this article we will see how we can check if the given character in the font of the spin box is in UTF-32 format. UTF-32 is a fixed-length encoding used to encode Unicode code points that uses exactly 32 bits per code point. UTF-32 is a fixed-length encoding, in contrast to all other Unicode transformation formats, which are variable-length encodings.
In order to do this we use inFontUcs4 method with the spin boxβs QFontMetrics object.
Syntax : font_metrics.inFontUcs4(unit_character)
Argument : It takes integer as argument
Return : It returns bool.
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating spin box self.spin = QSpinBox(self) # setting geometry to spin box self.spin.setGeometry(100, 100, 250, 40) # setting range to the spin box self.spin.setRange(0, 999999) # setting prefix to spin self.spin.setPrefix("PREFIX ") # setting suffix to spin self.spin.setSuffix(" SUFFIX") # creating a label label = QLabel(self) # making label multi line label.setWordWrap(True) # setting geometry to the label label.setGeometry(100, 200, 300, 60) # getting font metrics f_metrics = self.spin.fontMetrics() # checking if the character is in the font check = f_metrics.inFontUcs4(1) # setting text to the label label.setText(" UTF Format : " + str(check)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python PyQt-SpinBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Python String | replace()
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 24966,
"s": 24938,
"text": "\n26 May, 2020"
},
{
"code": null,
"e": 25323,
"s": 24966,
"text": "In this article we will see how we can check if the given character in the font of the spin box is in UTF-32 format. UTF-32 is a fixed-length encoding used to encode Unicode code points that uses exactly 32 bits per code point. UTF-32 is a fixed-length encoding, in contrast to all other Unicode transformation formats, which are variable-length encodings."
},
{
"code": null,
"e": 25409,
"s": 25323,
"text": "In order to do this we use inFontUcs4 method with the spin boxβs QFontMetrics object."
},
{
"code": null,
"e": 25458,
"s": 25409,
"text": "Syntax : font_metrics.inFontUcs4(unit_character)"
},
{
"code": null,
"e": 25498,
"s": 25458,
"text": "Argument : It takes integer as argument"
},
{
"code": null,
"e": 25524,
"s": 25498,
"text": "Return : It returns bool."
},
{
"code": null,
"e": 25552,
"s": 25524,
"text": "Below is the implementation"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating spin box self.spin = QSpinBox(self) # setting geometry to spin box self.spin.setGeometry(100, 100, 250, 40) # setting range to the spin box self.spin.setRange(0, 999999) # setting prefix to spin self.spin.setPrefix(\"PREFIX \") # setting suffix to spin self.spin.setSuffix(\" SUFFIX\") # creating a label label = QLabel(self) # making label multi line label.setWordWrap(True) # setting geometry to the label label.setGeometry(100, 200, 300, 60) # getting font metrics f_metrics = self.spin.fontMetrics() # checking if the character is in the font check = f_metrics.inFontUcs4(1) # setting text to the label label.setText(\" UTF Format : \" + str(check)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 27053,
"s": 25552,
"text": null
},
{
"code": null,
"e": 27062,
"s": 27053,
"text": "Output :"
},
{
"code": null,
"e": 27082,
"s": 27062,
"text": "Python PyQt-SpinBox"
},
{
"code": null,
"e": 27093,
"s": 27082,
"text": "Python-gui"
},
{
"code": null,
"e": 27105,
"s": 27093,
"text": "Python-PyQt"
},
{
"code": null,
"e": 27112,
"s": 27105,
"text": "Python"
},
{
"code": null,
"e": 27210,
"s": 27112,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27219,
"s": 27210,
"text": "Comments"
},
{
"code": null,
"e": 27232,
"s": 27219,
"text": "Old Comments"
},
{
"code": null,
"e": 27250,
"s": 27232,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27282,
"s": 27250,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27317,
"s": 27282,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27339,
"s": 27317,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27369,
"s": 27339,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27411,
"s": 27369,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27454,
"s": 27411,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27491,
"s": 27454,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27517,
"s": 27491,
"text": "Python String | replace()"
}
] |
Convert string to a number in Java
|
To convert a string to a number in Java, use the Integer.parseInt() method. First, let use create a String and set value.
String str = "45";
Now, take an Integer and use the Integer.parseInt() method.
Integer i = Integer.parseInt(str);
Let us see the complete example.
Live Demo
public class Demo {
public static void main( String args[] ) {
String str = "45";
Integer i = Integer.parseInt(str);
System.out.println("Num: " + i);
}
}
Num: 45
|
[
{
"code": null,
"e": 1184,
"s": 1062,
"text": "To convert a string to a number in Java, use the Integer.parseInt() method. First, let use create a String and set value."
},
{
"code": null,
"e": 1203,
"s": 1184,
"text": "String str = \"45\";"
},
{
"code": null,
"e": 1263,
"s": 1203,
"text": "Now, take an Integer and use the Integer.parseInt() method."
},
{
"code": null,
"e": 1298,
"s": 1263,
"text": "Integer i = Integer.parseInt(str);"
},
{
"code": null,
"e": 1331,
"s": 1298,
"text": "Let us see the complete example."
},
{
"code": null,
"e": 1342,
"s": 1331,
"text": " Live Demo"
},
{
"code": null,
"e": 1520,
"s": 1342,
"text": "public class Demo {\n public static void main( String args[] ) {\n String str = \"45\";\n Integer i = Integer.parseInt(str);\n System.out.println(\"Num: \" + i);\n }\n}"
},
{
"code": null,
"e": 1528,
"s": 1520,
"text": "Num: 45"
}
] |
File.WriteAllLines(String, IEnumerable<String>, Encoding) Method in C# with Examples - GeeksforGeeks
|
01 Jun, 2020
File.WriteAllLines(String, IEnumerable<String>, Encoding) is an inbuilt File class method that is used to create a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file.
Syntax:
public static void WriteAllLines (string path, System.Collections.Generic.IEnumerable<String> contents, System.Text.Encoding encoding);
Parameter: This function accepts three parameters which are illustrated below:
path: This is the specified file where collection of strings are going to be written.
contents: This is the specified lines to write to the file.
encoding: This is the specified character encoding to use.
Exceptions:
ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters defined by the GetInvalidPathChars() method.
ArgumentNullException: Either path, contents, or encoding is null.
DirectoryNotFoundException: The path is invalid.
IOException: An I/O error occurred while opening the file.
PathTooLongException: The path exceeds the system-defined maximum length.
NotSupportedException: The path is in an invalid format.
SecurityException: The caller does not have the required permission.
UnauthorizedAccessException: The path specified a file that is read-only. OR the path specified a file that is hidden. OR this operation is not supported on the current platform. OR the path is a directory. OR the caller does not have the required permission.
Below are the programs to illustrate the File.WriteAllLines(String, IEnumerable, Encoding) method.
Program 1: Before running the below code, a file file.txt is created whose contents are going to be filtered that are shown below-
Below code, itself creates a new file gfg.txt which contains the filtered strings.
// C# program to illustrate the usage// of File.WriteAllLines(String, // IEnumerable<String>, Encoding) method // Using System, System.IO,// System.Linq and System.Text namespacesusing System;using System.IO;using System.Linq;using System.Text; class GFG { // Specifying a file from where // some contents are going to be filtered static string Path = @"file.txt"; static void Main(string[] args) { // Reading content of file.txt var da = from line in File.ReadLines(Path) // Selecting lines started with "G" where(line.StartsWith("G")) select line; // Creating a new file gfg.txt with the // filtered contents File.WriteAllLines(@"gfg.txt", da, Encoding.UTF8); Console.WriteLine("Writing the filtered collection "+ "of strings to the file has been done."); }}
Output:
Writing the filtered collection of strings to the file has been done.
After running the above code, the above output is shown, and a new file gfg.txt is created shown below-
Program 2: Before running the below code, two files file.txt and gfg.txt are created with some contents shown below-
Below code overwrites the file gfg.txt with the selected contents of the file file.txt.
// C# program to illustrate the usage// of File.WriteAllLines(String, // IEnumerable<String>, Encoding) method // Using System, System.IO,// System.Linq and System.Text namespacesusing System;using System.IO;using System.Linq;using System.Text; class GFG { // Specifying a file from where // some contents are going to be filtered static string Path = @"file.txt"; static void Main(string[] args) { // Reading the contents of file.txt var da = from line in File.ReadLines(Path) // Selecting lines started with "g" where(line.StartsWith("g")) select line; // Overwriting the file gfg.txt with the // selected string of the file file.txt File.WriteAllLines(@"gfg.txt", da, Encoding.UTF8); Console.WriteLine("Overwriting the selected collection"+ " of strings to the file has been done."); }}
Output:
Overwriting the selected collection of strings to the file has been done.
After running the above code, the above output is shown, and the file gfg.txt contents became like shown below-
CSharp-File-Handling
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 C# Interview Questions & Answers
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
Convert String to Character Array in C#
Linked List Implementation in C#
C# | How to insert an element in an Array?
C# | List Class
Difference between Hashtable and Dictionary in C#
|
[
{
"code": null,
"e": 23911,
"s": 23883,
"text": "\n01 Jun, 2020"
},
{
"code": null,
"e": 24138,
"s": 23911,
"text": "File.WriteAllLines(String, IEnumerable<String>, Encoding) is an inbuilt File class method that is used to create a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file."
},
{
"code": null,
"e": 24146,
"s": 24138,
"text": "Syntax:"
},
{
"code": null,
"e": 24282,
"s": 24146,
"text": "public static void WriteAllLines (string path, System.Collections.Generic.IEnumerable<String> contents, System.Text.Encoding encoding);"
},
{
"code": null,
"e": 24361,
"s": 24282,
"text": "Parameter: This function accepts three parameters which are illustrated below:"
},
{
"code": null,
"e": 24447,
"s": 24361,
"text": "path: This is the specified file where collection of strings are going to be written."
},
{
"code": null,
"e": 24507,
"s": 24447,
"text": "contents: This is the specified lines to write to the file."
},
{
"code": null,
"e": 24566,
"s": 24507,
"text": "encoding: This is the specified character encoding to use."
},
{
"code": null,
"e": 24578,
"s": 24566,
"text": "Exceptions:"
},
{
"code": null,
"e": 24737,
"s": 24578,
"text": "ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters defined by the GetInvalidPathChars() method."
},
{
"code": null,
"e": 24804,
"s": 24737,
"text": "ArgumentNullException: Either path, contents, or encoding is null."
},
{
"code": null,
"e": 24853,
"s": 24804,
"text": "DirectoryNotFoundException: The path is invalid."
},
{
"code": null,
"e": 24912,
"s": 24853,
"text": "IOException: An I/O error occurred while opening the file."
},
{
"code": null,
"e": 24986,
"s": 24912,
"text": "PathTooLongException: The path exceeds the system-defined maximum length."
},
{
"code": null,
"e": 25043,
"s": 24986,
"text": "NotSupportedException: The path is in an invalid format."
},
{
"code": null,
"e": 25112,
"s": 25043,
"text": "SecurityException: The caller does not have the required permission."
},
{
"code": null,
"e": 25372,
"s": 25112,
"text": "UnauthorizedAccessException: The path specified a file that is read-only. OR the path specified a file that is hidden. OR this operation is not supported on the current platform. OR the path is a directory. OR the caller does not have the required permission."
},
{
"code": null,
"e": 25471,
"s": 25372,
"text": "Below are the programs to illustrate the File.WriteAllLines(String, IEnumerable, Encoding) method."
},
{
"code": null,
"e": 25602,
"s": 25471,
"text": "Program 1: Before running the below code, a file file.txt is created whose contents are going to be filtered that are shown below-"
},
{
"code": null,
"e": 25685,
"s": 25602,
"text": "Below code, itself creates a new file gfg.txt which contains the filtered strings."
},
{
"code": "// C# program to illustrate the usage// of File.WriteAllLines(String, // IEnumerable<String>, Encoding) method // Using System, System.IO,// System.Linq and System.Text namespacesusing System;using System.IO;using System.Linq;using System.Text; class GFG { // Specifying a file from where // some contents are going to be filtered static string Path = @\"file.txt\"; static void Main(string[] args) { // Reading content of file.txt var da = from line in File.ReadLines(Path) // Selecting lines started with \"G\" where(line.StartsWith(\"G\")) select line; // Creating a new file gfg.txt with the // filtered contents File.WriteAllLines(@\"gfg.txt\", da, Encoding.UTF8); Console.WriteLine(\"Writing the filtered collection \"+ \"of strings to the file has been done.\"); }}",
"e": 26586,
"s": 25685,
"text": null
},
{
"code": null,
"e": 26594,
"s": 26586,
"text": "Output:"
},
{
"code": null,
"e": 26665,
"s": 26594,
"text": "Writing the filtered collection of strings to the file has been done.\n"
},
{
"code": null,
"e": 26769,
"s": 26665,
"text": "After running the above code, the above output is shown, and a new file gfg.txt is created shown below-"
},
{
"code": null,
"e": 26886,
"s": 26769,
"text": "Program 2: Before running the below code, two files file.txt and gfg.txt are created with some contents shown below-"
},
{
"code": null,
"e": 26974,
"s": 26886,
"text": "Below code overwrites the file gfg.txt with the selected contents of the file file.txt."
},
{
"code": "// C# program to illustrate the usage// of File.WriteAllLines(String, // IEnumerable<String>, Encoding) method // Using System, System.IO,// System.Linq and System.Text namespacesusing System;using System.IO;using System.Linq;using System.Text; class GFG { // Specifying a file from where // some contents are going to be filtered static string Path = @\"file.txt\"; static void Main(string[] args) { // Reading the contents of file.txt var da = from line in File.ReadLines(Path) // Selecting lines started with \"g\" where(line.StartsWith(\"g\")) select line; // Overwriting the file gfg.txt with the // selected string of the file file.txt File.WriteAllLines(@\"gfg.txt\", da, Encoding.UTF8); Console.WriteLine(\"Overwriting the selected collection\"+ \" of strings to the file has been done.\"); }}",
"e": 27906,
"s": 26974,
"text": null
},
{
"code": null,
"e": 27914,
"s": 27906,
"text": "Output:"
},
{
"code": null,
"e": 27989,
"s": 27914,
"text": "Overwriting the selected collection of strings to the file has been done.\n"
},
{
"code": null,
"e": 28101,
"s": 27989,
"text": "After running the above code, the above output is shown, and the file gfg.txt contents became like shown below-"
},
{
"code": null,
"e": 28122,
"s": 28101,
"text": "CSharp-File-Handling"
},
{
"code": null,
"e": 28125,
"s": 28122,
"text": "C#"
},
{
"code": null,
"e": 28223,
"s": 28125,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28232,
"s": 28223,
"text": "Comments"
},
{
"code": null,
"e": 28245,
"s": 28232,
"text": "Old Comments"
},
{
"code": null,
"e": 28285,
"s": 28245,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 28308,
"s": 28285,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28336,
"s": 28308,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 28353,
"s": 28336,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 28375,
"s": 28353,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 28415,
"s": 28375,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 28448,
"s": 28415,
"text": "Linked List Implementation in C#"
},
{
"code": null,
"e": 28491,
"s": 28448,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 28507,
"s": 28491,
"text": "C# | List Class"
}
] |
Largest subsequence such that its prefix sum never gets negative - GeeksforGeeks
|
27 Jan, 2022
Given an array arr[] containing integers. The task is to find the largest subsequence such that at any point in time prefix sum of that subsequence is not negative.
Examples:
Input: arr[] = {-3, -3, -7, -7, -1, -7, 3, 3, -2, -1, 0, -7}Output: 3 3 -2 -1 0Explanation: Adding -3 makes sum negative so it canβt be included, Similarly -3, -7, -7, -1, -7, -7 canβt be included. Only 3, 3, -2, -1, 0 can be included.
Input: arr[] = {3, 4, -8, 6, -7, 5}Output: 3 4 6 -7 5Explanation: 3, 4 can be added as they make sum positive but when -8 is added the sum becomes negative so it canβt be included rest all numbers can be included.
Approach: This problem can be solved by using Min Heap. Follow the steps below to solve the given problem.
At first Initialize variables βsβ=0 and βcβ=0, to store the sum of array elements and count of elements respectively.
Take a min priority queue, to store the negative elements.
Now start from the leftmost element take the sum of the current element, push it to vector, and increase the count.
If the current element is less than zero push it in the min priority queue.
If the sum becomes less than zero then subtract the largest negative number(or smallest number ) of priority queue from sum and pop that element from the priority queue and also decrease the count of the element, as well as delete that element from the vector.
After traversing the whole array we get the desired subsequence in vector.
Below is the implementation of the above approach.
C++
Python3
// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Function to find the largest subsequence// satisfying given conditionsvoid FindMaxSubsequence(int* a, int n){ // Min priority queue priority_queue<int, vector<int>, greater<int> > v; int c = 0, s = 0; vector<int> v1; vector<int>::iterator it; for (int i = 0; i < n; i++) { // Current sum s += a[i]; // Push the subsequence v1.push_back(a[i]); // Current count c++; // Storing negative elements // in priority queue if (a[i] < 0) v.push(a[i]); // If sum is less than zero // than subtract largest // negative number from left // and decrease the count if (s < 0) { s -= v.top(); it = find(v1.begin(), v1.end(), v.top()); // Erase the added vector v1.erase(it); v.pop(); c--; } } // Largest subsequence for (auto i : v1) { cout << i << " "; }} // Driver Codeint main(){ int arr[] = { -3, -3, -7, -7, -1, -7, 3, 3, -2, -1, 0, -7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call FindMaxSubsequence(arr, N); return 0;}
# Python code for the above approachfrom queue import PriorityQueue # Function to find the largest subsequence# satisfying given conditionsdef FindMaxSubsequence(a, n): # Min priority queue v = PriorityQueue() c = 0 s = 0 v1 = [] for i in range(n): # Current sum s += a[i] # Push the subsequence v1.append(a[i]) # Current count c = c + 1 # Storing negative elements # in priority queue if a[i] < 0: v.put(a[i]) # If sum is less than zero # than subtract largest # negative number from left # and decrease the count if (s < 0): t = v.get() s = s-t # Erase the added vector v1.remove(t) c = c - 1 # Largest subsequence for i in range(len(v1)): print(v1[i], end = " ") # Driver Codearr = [-3, -3, -7, -7, -1, -7, 3, 3, -2, -1, 0, -7] N = len(arr) # Function CallFindMaxSubsequence(arr, N) # This code is contributed by Potta Lokesh
3 3 -2 -1 0
Time Complexity: O(N logN) Auxiliary Space: O(N)
lokeshpotta20
sumitgumber28
prefix
subsequence
Arrays
Greedy
Arrays
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Next Greater Element
Window Sliding Technique
Count pairs with given sum
Program to find sum of elements in a given array
Reversal algorithm for array rotation
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
Huffman Coding | Greedy Algo-3
Write a program to print all permutations of a given string
|
[
{
"code": null,
"e": 24405,
"s": 24377,
"text": "\n27 Jan, 2022"
},
{
"code": null,
"e": 24570,
"s": 24405,
"text": "Given an array arr[] containing integers. The task is to find the largest subsequence such that at any point in time prefix sum of that subsequence is not negative."
},
{
"code": null,
"e": 24580,
"s": 24570,
"text": "Examples:"
},
{
"code": null,
"e": 24816,
"s": 24580,
"text": "Input: arr[] = {-3, -3, -7, -7, -1, -7, 3, 3, -2, -1, 0, -7}Output: 3 3 -2 -1 0Explanation: Adding -3 makes sum negative so it canβt be included, Similarly -3, -7, -7, -1, -7, -7 canβt be included. Only 3, 3, -2, -1, 0 can be included."
},
{
"code": null,
"e": 25030,
"s": 24816,
"text": "Input: arr[] = {3, 4, -8, 6, -7, 5}Output: 3 4 6 -7 5Explanation: 3, 4 can be added as they make sum positive but when -8 is added the sum becomes negative so it canβt be included rest all numbers can be included."
},
{
"code": null,
"e": 25138,
"s": 25030,
"text": "Approach: This problem can be solved by using Min Heap. Follow the steps below to solve the given problem. "
},
{
"code": null,
"e": 25256,
"s": 25138,
"text": "At first Initialize variables βsβ=0 and βcβ=0, to store the sum of array elements and count of elements respectively."
},
{
"code": null,
"e": 25315,
"s": 25256,
"text": "Take a min priority queue, to store the negative elements."
},
{
"code": null,
"e": 25431,
"s": 25315,
"text": "Now start from the leftmost element take the sum of the current element, push it to vector, and increase the count."
},
{
"code": null,
"e": 25507,
"s": 25431,
"text": "If the current element is less than zero push it in the min priority queue."
},
{
"code": null,
"e": 25768,
"s": 25507,
"text": "If the sum becomes less than zero then subtract the largest negative number(or smallest number ) of priority queue from sum and pop that element from the priority queue and also decrease the count of the element, as well as delete that element from the vector."
},
{
"code": null,
"e": 25843,
"s": 25768,
"text": "After traversing the whole array we get the desired subsequence in vector."
},
{
"code": null,
"e": 25894,
"s": 25843,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 25898,
"s": 25894,
"text": "C++"
},
{
"code": null,
"e": 25906,
"s": 25898,
"text": "Python3"
},
{
"code": "// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Function to find the largest subsequence// satisfying given conditionsvoid FindMaxSubsequence(int* a, int n){ // Min priority queue priority_queue<int, vector<int>, greater<int> > v; int c = 0, s = 0; vector<int> v1; vector<int>::iterator it; for (int i = 0; i < n; i++) { // Current sum s += a[i]; // Push the subsequence v1.push_back(a[i]); // Current count c++; // Storing negative elements // in priority queue if (a[i] < 0) v.push(a[i]); // If sum is less than zero // than subtract largest // negative number from left // and decrease the count if (s < 0) { s -= v.top(); it = find(v1.begin(), v1.end(), v.top()); // Erase the added vector v1.erase(it); v.pop(); c--; } } // Largest subsequence for (auto i : v1) { cout << i << \" \"; }} // Driver Codeint main(){ int arr[] = { -3, -3, -7, -7, -1, -7, 3, 3, -2, -1, 0, -7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call FindMaxSubsequence(arr, N); return 0;}",
"e": 27198,
"s": 25906,
"text": null
},
{
"code": "# Python code for the above approachfrom queue import PriorityQueue # Function to find the largest subsequence# satisfying given conditionsdef FindMaxSubsequence(a, n): # Min priority queue v = PriorityQueue() c = 0 s = 0 v1 = [] for i in range(n): # Current sum s += a[i] # Push the subsequence v1.append(a[i]) # Current count c = c + 1 # Storing negative elements # in priority queue if a[i] < 0: v.put(a[i]) # If sum is less than zero # than subtract largest # negative number from left # and decrease the count if (s < 0): t = v.get() s = s-t # Erase the added vector v1.remove(t) c = c - 1 # Largest subsequence for i in range(len(v1)): print(v1[i], end = \" \") # Driver Codearr = [-3, -3, -7, -7, -1, -7, 3, 3, -2, -1, 0, -7] N = len(arr) # Function CallFindMaxSubsequence(arr, N) # This code is contributed by Potta Lokesh",
"e": 28237,
"s": 27198,
"text": null
},
{
"code": null,
"e": 28253,
"s": 28240,
"text": "3 3 -2 -1 0 "
},
{
"code": null,
"e": 28304,
"s": 28255,
"text": "Time Complexity: O(N logN) Auxiliary Space: O(N)"
},
{
"code": null,
"e": 28320,
"s": 28306,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 28334,
"s": 28320,
"text": "sumitgumber28"
},
{
"code": null,
"e": 28341,
"s": 28334,
"text": "prefix"
},
{
"code": null,
"e": 28353,
"s": 28341,
"text": "subsequence"
},
{
"code": null,
"e": 28360,
"s": 28353,
"text": "Arrays"
},
{
"code": null,
"e": 28367,
"s": 28360,
"text": "Greedy"
},
{
"code": null,
"e": 28374,
"s": 28367,
"text": "Arrays"
},
{
"code": null,
"e": 28381,
"s": 28374,
"text": "Greedy"
},
{
"code": null,
"e": 28479,
"s": 28381,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28488,
"s": 28479,
"text": "Comments"
},
{
"code": null,
"e": 28501,
"s": 28488,
"text": "Old Comments"
},
{
"code": null,
"e": 28522,
"s": 28501,
"text": "Next Greater Element"
},
{
"code": null,
"e": 28547,
"s": 28522,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 28574,
"s": 28547,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 28623,
"s": 28574,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 28661,
"s": 28623,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 28712,
"s": 28661,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 28763,
"s": 28712,
"text": "Primβs Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 28821,
"s": 28763,
"text": "Kruskalβs Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 28852,
"s": 28821,
"text": "Huffman Coding | Greedy Algo-3"
}
] |
cout in C++ - GeeksforGeeks
|
27 Aug, 2021
The cout object in C++ is an object of class ostream. It is defined in iostream header file. It is used to display the output to the standard output device i.e. monitor. It is associated with the standard C output stream stdout. The data needed to be displayed on the screen is inserted in the standard output stream (cout) using the insertion operator(<<).
Program 1:
Below is the C++ program to implement cout object:
C++
// C++ program to illustrate the use// of cout object#include <iostream>using namespace std; // Driver Codeint main(){ // Print standard output // on the screen cout << "Welcome to GFG"; return 0;}
Welcome to GFG
Note: More than one variable can be printed using the insertion operator(<<) with cout.
Program 2:
Below is the C++ program to implement the above approach:
C++
// C++ program to illustrate printing// of more than one statement in a// single cout statement#include <iostream>using namespace std; // Driver Codeint main(){ string name = "Akshay"; int age = 18; // Print multiple variable on // screen using cout cout << "Name : " << name << endl << "Age : " << age << endl; return 0;}
Name : Akshay
Age : 18
The cout statement can also be used with some member functions:
cout.write(char *str, int n): Print the first N character reading from str.
cout.put(char &ch): Print the character stored in character ch.
cout.precision(int n): Sets the decimal precision to N, when using float values.
Program 3:
Below is the implementation of the member functions of the cout.write() and cout.put():
C++
// C++ program to illustrate the use// of cout.write() and cout.put()#include <iostream>using namespace std; // Driver Codeint main(){ char gfg[] = "Welcome at GFG"; char ch = 'e'; // Print first 6 characters cout.write(gfg, 6); // Print the character ch cout.put(ch); return 0;}
Welcome
Program 4:
Below is the C++ program to illustrate the use of cout.precision():
C++
// C++ program toillustrate the use// of cout.precision()#include <iostream>using namespace std; // Driver Codeint main(){ double pi = 3.14159783; // Set precision to 5 cout.precision(5); // Print pi cout << pi << endl; // Set precision to 7 cout.precision(7); // Print pi cout << pi << endl; return 0;}
3.1416
3.141598
Code_Mech
anikaseth98
cpp-input-output
Input and Output
Input Output Systems
Picked
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Iterators in C++ STL
Socket Programming in C/C++
Operator Overloading in C++
Constructors in C++
C++ Classes and Objects
Header files in C/C++ and its uses
C++ Program for QuickSort
How to return multiple values from a function in C or C++?
C++ program for hashing with chaining
cin in C++
|
[
{
"code": null,
"e": 24328,
"s": 24300,
"text": "\n27 Aug, 2021"
},
{
"code": null,
"e": 24686,
"s": 24328,
"text": "The cout object in C++ is an object of class ostream. It is defined in iostream header file. It is used to display the output to the standard output device i.e. monitor. It is associated with the standard C output stream stdout. The data needed to be displayed on the screen is inserted in the standard output stream (cout) using the insertion operator(<<)."
},
{
"code": null,
"e": 24697,
"s": 24686,
"text": "Program 1:"
},
{
"code": null,
"e": 24748,
"s": 24697,
"text": "Below is the C++ program to implement cout object:"
},
{
"code": null,
"e": 24752,
"s": 24748,
"text": "C++"
},
{
"code": "// C++ program to illustrate the use// of cout object#include <iostream>using namespace std; // Driver Codeint main(){ // Print standard output // on the screen cout << \"Welcome to GFG\"; return 0;}",
"e": 24963,
"s": 24752,
"text": null
},
{
"code": null,
"e": 24978,
"s": 24963,
"text": "Welcome to GFG"
},
{
"code": null,
"e": 25068,
"s": 24980,
"text": "Note: More than one variable can be printed using the insertion operator(<<) with cout."
},
{
"code": null,
"e": 25079,
"s": 25068,
"text": "Program 2:"
},
{
"code": null,
"e": 25137,
"s": 25079,
"text": "Below is the C++ program to implement the above approach:"
},
{
"code": null,
"e": 25141,
"s": 25137,
"text": "C++"
},
{
"code": "// C++ program to illustrate printing// of more than one statement in a// single cout statement#include <iostream>using namespace std; // Driver Codeint main(){ string name = \"Akshay\"; int age = 18; // Print multiple variable on // screen using cout cout << \"Name : \" << name << endl << \"Age : \" << age << endl; return 0;}",
"e": 25492,
"s": 25141,
"text": null
},
{
"code": null,
"e": 25515,
"s": 25492,
"text": "Name : Akshay\nAge : 18"
},
{
"code": null,
"e": 25581,
"s": 25517,
"text": "The cout statement can also be used with some member functions:"
},
{
"code": null,
"e": 25657,
"s": 25581,
"text": "cout.write(char *str, int n): Print the first N character reading from str."
},
{
"code": null,
"e": 25721,
"s": 25657,
"text": "cout.put(char &ch): Print the character stored in character ch."
},
{
"code": null,
"e": 25802,
"s": 25721,
"text": "cout.precision(int n): Sets the decimal precision to N, when using float values."
},
{
"code": null,
"e": 25813,
"s": 25802,
"text": "Program 3:"
},
{
"code": null,
"e": 25901,
"s": 25813,
"text": "Below is the implementation of the member functions of the cout.write() and cout.put():"
},
{
"code": null,
"e": 25905,
"s": 25901,
"text": "C++"
},
{
"code": "// C++ program to illustrate the use// of cout.write() and cout.put()#include <iostream>using namespace std; // Driver Codeint main(){ char gfg[] = \"Welcome at GFG\"; char ch = 'e'; // Print first 6 characters cout.write(gfg, 6); // Print the character ch cout.put(ch); return 0;}",
"e": 26208,
"s": 25905,
"text": null
},
{
"code": null,
"e": 26216,
"s": 26208,
"text": "Welcome"
},
{
"code": null,
"e": 26229,
"s": 26218,
"text": "Program 4:"
},
{
"code": null,
"e": 26297,
"s": 26229,
"text": "Below is the C++ program to illustrate the use of cout.precision():"
},
{
"code": null,
"e": 26301,
"s": 26297,
"text": "C++"
},
{
"code": "// C++ program toillustrate the use// of cout.precision()#include <iostream>using namespace std; // Driver Codeint main(){ double pi = 3.14159783; // Set precision to 5 cout.precision(5); // Print pi cout << pi << endl; // Set precision to 7 cout.precision(7); // Print pi cout << pi << endl; return 0;}",
"e": 26640,
"s": 26301,
"text": null
},
{
"code": null,
"e": 26656,
"s": 26640,
"text": "3.1416\n3.141598"
},
{
"code": null,
"e": 26668,
"s": 26658,
"text": "Code_Mech"
},
{
"code": null,
"e": 26680,
"s": 26668,
"text": "anikaseth98"
},
{
"code": null,
"e": 26697,
"s": 26680,
"text": "cpp-input-output"
},
{
"code": null,
"e": 26714,
"s": 26697,
"text": "Input and Output"
},
{
"code": null,
"e": 26735,
"s": 26714,
"text": "Input Output Systems"
},
{
"code": null,
"e": 26742,
"s": 26735,
"text": "Picked"
},
{
"code": null,
"e": 26746,
"s": 26742,
"text": "C++"
},
{
"code": null,
"e": 26759,
"s": 26746,
"text": "C++ Programs"
},
{
"code": null,
"e": 26763,
"s": 26759,
"text": "CPP"
},
{
"code": null,
"e": 26861,
"s": 26763,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26870,
"s": 26861,
"text": "Comments"
},
{
"code": null,
"e": 26883,
"s": 26870,
"text": "Old Comments"
},
{
"code": null,
"e": 26904,
"s": 26883,
"text": "Iterators in C++ STL"
},
{
"code": null,
"e": 26932,
"s": 26904,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 26960,
"s": 26932,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 26980,
"s": 26960,
"text": "Constructors in C++"
},
{
"code": null,
"e": 27004,
"s": 26980,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 27039,
"s": 27004,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 27065,
"s": 27039,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 27124,
"s": 27065,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 27162,
"s": 27124,
"text": "C++ program for hashing with chaining"
}
] |
Is finally block always get executed in Java?
|
Yes, the finally block is always get executed unless there is an abnormal program termination either resulting from a JVM crash or from a call to System.exit().
A finally block is always get executed whether the exception has occurred or not.
If an exception occurs like closing a file or DB connection, then the finally block is used to clean up the code.
We cannot say the finally block is always executes because sometimes if any statement like System.exit() or some similar code is written into try block then program will automatically terminate and the finally block will not be executed in this case.
A finally block will not execute due to other conditions like when JVM runs out of memory when our java process is killed forcefully from task manager or console when our machine shuts down due to power failure and deadlock condition in our try block.
public class FinallyBlock {
public static void main(String args[]){
try {
int a=10,b=30;
int c = b/a;
System.out.println(c);
} catch(ArithmeticException ae){
System.out.println(ae);
} finally {
System.out.println("finally block is always executed");
}
}
}
In the above example, the finally block always get executed if the exception has occurred or not.
3
finally block is always executed
public class FinallyBlock {
public static void main(String args[]) {
try {
System.out.println("I am in try block");
System.exit(1);
} catch(Exception ex){
ex.printStackTrace();
} finally {
System.out.println("I am in finally block");
}
}
}
In the above example, the finally block will not execute due to the System.exit(1) condition in the try block.
I am in try block
|
[
{
"code": null,
"e": 1223,
"s": 1062,
"text": "Yes, the finally block is always get executed unless there is an abnormal program termination either resulting from a JVM crash or from a call to System.exit()."
},
{
"code": null,
"e": 1305,
"s": 1223,
"text": "A finally block is always get executed whether the exception has occurred or not."
},
{
"code": null,
"e": 1419,
"s": 1305,
"text": "If an exception occurs like closing a file or DB connection, then the finally block is used to clean up the code."
},
{
"code": null,
"e": 1670,
"s": 1419,
"text": "We cannot say the finally block is always executes because sometimes if any statement like System.exit() or some similar code is written into try block then program will automatically terminate and the finally block will not be executed in this case."
},
{
"code": null,
"e": 1922,
"s": 1670,
"text": "A finally block will not execute due to other conditions like when JVM runs out of memory when our java process is killed forcefully from task manager or console when our machine shuts down due to power failure and deadlock condition in our try block."
},
{
"code": null,
"e": 2253,
"s": 1922,
"text": "public class FinallyBlock {\n public static void main(String args[]){\n try {\n int a=10,b=30;\n int c = b/a;\n System.out.println(c);\n } catch(ArithmeticException ae){\n System.out.println(ae);\n } finally {\n System.out.println(\"finally block is always executed\");\n }\n }\n}"
},
{
"code": null,
"e": 2351,
"s": 2253,
"text": "In the above example, the finally block always get executed if the exception has occurred or not."
},
{
"code": null,
"e": 2386,
"s": 2351,
"text": "3\nfinally block is always executed"
},
{
"code": null,
"e": 2692,
"s": 2386,
"text": "public class FinallyBlock {\n public static void main(String args[]) {\n try {\n System.out.println(\"I am in try block\");\n System.exit(1);\n } catch(Exception ex){\n ex.printStackTrace();\n } finally {\n System.out.println(\"I am in finally block\");\n }\n }\n}"
},
{
"code": null,
"e": 2803,
"s": 2692,
"text": "In the above example, the finally block will not execute due to the System.exit(1) condition in the try block."
},
{
"code": null,
"e": 2821,
"s": 2803,
"text": "I am in try block"
}
] |
How to print a one-month calendar of user choice using for loop in C?
|
The logic to print a one-month calendar is as follows β
for(i=1;i<first;i++)
printf(" ");
for(i=1;i<=noofdays;i++){
printf("%3d",i);
if((first+i-1)%7==0)
printf("\n");
}
Live Demo
Following example accepts number of days and first day in a month from the user and prints the calendar of a month accordingly β
#include<stdio.h>
int main(){
int i,noofdays;
int first;
printf("enter no of days in a month:\n");
scanf("%d",&noofdays);
printf("enter first day in a month:\n");
scanf("%d",&first);
for(i=1;i<first;i++)
printf(" ");
for(i=1;i<=noofdays;i++){
printf("%3d",i);
if((first+i-1)%7==0)
printf("\n");
}
return 0;
}
enter no of days in a month:
30
enter first day in a month:
4
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30
|
[
{
"code": null,
"e": 1118,
"s": 1062,
"text": "The logic to print a one-month calendar is as follows β"
},
{
"code": null,
"e": 1247,
"s": 1118,
"text": "for(i=1;i<first;i++)\n printf(\" \");\nfor(i=1;i<=noofdays;i++){\n printf(\"%3d\",i);\n if((first+i-1)%7==0)\n printf(\"\\n\");\n}"
},
{
"code": null,
"e": 1258,
"s": 1247,
"text": " Live Demo"
},
{
"code": null,
"e": 1387,
"s": 1258,
"text": "Following example accepts number of days and first day in a month from the user and prints the calendar of a month accordingly β"
},
{
"code": null,
"e": 1753,
"s": 1387,
"text": "#include<stdio.h>\nint main(){\n int i,noofdays;\n int first;\n printf(\"enter no of days in a month:\\n\");\n scanf(\"%d\",&noofdays);\n printf(\"enter first day in a month:\\n\");\n scanf(\"%d\",&first);\n for(i=1;i<first;i++)\n printf(\" \");\n for(i=1;i<=noofdays;i++){\n printf(\"%3d\",i);\n if((first+i-1)%7==0)\n printf(\"\\n\");\n }\n return 0;\n}"
},
{
"code": null,
"e": 1914,
"s": 1753,
"text": "enter no of days in a month:\n30\nenter first day in a month:\n4\n 1 2 3 4\n 5 6 7 8 9 10 11\n12 13 14 15 16 17 18\n19 20 21 22 23 24 25\n26 27 28 29 30"
}
] |
Converting string to MORSE code in JavaScript
|
Morse code is a method used in telecommunications to encode text characters as standardized sequences of two different signal durations, called dots and dashes.
To have a function that converts a particular string to Morse code, we will need an object that
maps all the characters (English alphabets) to Morse code equivalents. Once we have that we
can simply iterate over the string and construct a new string.
Here is the object that maps alphabets to Morse codes β
Morse Code Map
const morseCode = {
"A": ".-",
"B": "-...",
"C": "-.-.",
"D": "-..",
"E": ".",
"F": "..-.",
"G": "--.",
"H": "....",
"I": "..",
"J": ".---",
"K": "-.-",
"L": ".-..",
"M": "--",
"N": "-.",
"O": "---",
"P": ".--.",
"Q": "--.-",
"R": ".-.",
"S": "...",
"T": "-",
"U": "..-",
"W": ".--",
"X": "-..-",
"Y": "-.--",
"Z": "--.."
}
Now the function that converts string to Morse code will be β
const morseCode = {
"A": ".-",
"B": "-...",
"C": "-.-.",
"D": "-..",
"E": ".",
"F": "..-.",
"G": "--.",
"H": "....",
"I": "..",
"J": ".---",
"K": "-.-",
"L": ".-..",
"M": "--",
"N": "-.",
"O": "---",
"P": ".--.",
"Q": "--.-",
"R": ".-.",
"S": "...",
"T": "-",
"U": "..-",
"W": ".--",
"X": "-..-",
"Y": "-.--",
"Z": "--.."
}
const convertToMorse = (str) => {
return str.toUpperCase().split("").map(el => {
return morseCode[el] ? morseCode[el] : el;
}).join("");
};
console.log(convertToMorse('Disaster management'));
console.log(convertToMorse('hey there!'));
The output in the console will be β
-........-...-..-. --.--..---..--.-.-
.....-.-- -......-..!
|
[
{
"code": null,
"e": 1223,
"s": 1062,
"text": "Morse code is a method used in telecommunications to encode text characters as standardized sequences of two different signal durations, called dots and dashes."
},
{
"code": null,
"e": 1474,
"s": 1223,
"text": "To have a function that converts a particular string to Morse code, we will need an object that\nmaps all the characters (English alphabets) to Morse code equivalents. Once we have that we\ncan simply iterate over the string and construct a new string."
},
{
"code": null,
"e": 1530,
"s": 1474,
"text": "Here is the object that maps alphabets to Morse codes β"
},
{
"code": null,
"e": 1545,
"s": 1530,
"text": "Morse Code Map"
},
{
"code": null,
"e": 1944,
"s": 1545,
"text": "const morseCode = {\n \"A\": \".-\",\n \"B\": \"-...\",\n \"C\": \"-.-.\",\n \"D\": \"-..\",\n \"E\": \".\",\n \"F\": \"..-.\",\n \"G\": \"--.\",\n \"H\": \"....\",\n \"I\": \"..\",\n \"J\": \".---\",\n \"K\": \"-.-\",\n \"L\": \".-..\",\n \"M\": \"--\",\n \"N\": \"-.\",\n \"O\": \"---\",\n \"P\": \".--.\",\n \"Q\": \"--.-\",\n \"R\": \".-.\",\n \"S\": \"...\",\n \"T\": \"-\",\n \"U\": \"..-\",\n \"W\": \".--\",\n \"X\": \"-..-\",\n \"Y\": \"-.--\",\n \"Z\": \"--..\"\n}"
},
{
"code": null,
"e": 2006,
"s": 1944,
"text": "Now the function that converts string to Morse code will be β"
},
{
"code": null,
"e": 2652,
"s": 2006,
"text": "const morseCode = {\n \"A\": \".-\",\n \"B\": \"-...\",\n \"C\": \"-.-.\",\n \"D\": \"-..\",\n \"E\": \".\",\n \"F\": \"..-.\",\n \"G\": \"--.\",\n \"H\": \"....\",\n \"I\": \"..\",\n \"J\": \".---\",\n \"K\": \"-.-\",\n \"L\": \".-..\",\n \"M\": \"--\",\n \"N\": \"-.\",\n \"O\": \"---\",\n \"P\": \".--.\",\n \"Q\": \"--.-\",\n \"R\": \".-.\",\n \"S\": \"...\",\n \"T\": \"-\",\n \"U\": \"..-\",\n \"W\": \".--\",\n \"X\": \"-..-\",\n \"Y\": \"-.--\",\n \"Z\": \"--..\"\n}\nconst convertToMorse = (str) => {\n return str.toUpperCase().split(\"\").map(el => {\n return morseCode[el] ? morseCode[el] : el;\n }).join(\"\");\n};\nconsole.log(convertToMorse('Disaster management'));\nconsole.log(convertToMorse('hey there!'));"
},
{
"code": null,
"e": 2688,
"s": 2652,
"text": "The output in the console will be β"
},
{
"code": null,
"e": 2748,
"s": 2688,
"text": "-........-...-..-. --.--..---..--.-.-\n.....-.-- -......-..!"
}
] |
MODIS Vegetation Indices: a GEE Approach | by Willy Hagi | Towards Data Science
|
The Moderate Resolution Imaging Spectroradiometer (MODIS) is one of the key sensors used in Earth Observation ever since it was first launched into orbit in 1999. Several reasons can be appointed for its success: the high revisit-time of 1 to 2 days, the global coverage, the wide range of applicability and its derived products. Just to name a few.
In this tutorial, youβll focus on the MOD13Q1 product, which consists of both the Normalized Difference Vegetation Index (NDVI) and the Enhanced Vegetation Index (EVI) in a global scale at a 16 days frequency. You might already know the NDVI from the Introduction to GEE, but here youβll also explore the usefulness of EVI for environmental analysis.
From the GEE Introduction, you already know how to sign up and use gee, install folium for interactive visualization and geehydro to interact with the code in a similar way to the native Javascript API. If youβre interested in climate modeling and read the Introduction to CMIP6, then you must know Proplot as well. The novel package for this tutorial is ipygee, which works in a similar way as geehydro to allow the use of some functions that are only available within the GEE code editor.
To install ipygee, just use Pip:
pip install ipygee
Then you can proceed to import all the tools youβll need in this tutorial:
import eeimport folium import geehydroimport numpy as np # yes, numpy!import pandas as pd # yes, pandas!import proplot as plot import matplotlib.pyplot as plt from ipygee import*from pandas.plotting import register_matplotlib_converters
As you know, to use gee you must always trigger the authentication and initialize the library, especially if you are interested in running the code in Google Colab.
# Trigger the authentication flow.>>> ee.Authenticate()# Initialize the library.>>> ee.Initialize()
The World Database on Protected Areas (WDPA) is the greatest database of marine and terrestrial protected areas and itβs easily available in GEE. It provides comprehensive geographic information and the boundaries of any area in the world. Here youβll use it to get the shape of the Xingu Indigenous Park in Brazil, known as one of the first and greatest protected areas in the world.
With the EE snippet, you can load the polygon database of the WDPA and filter the area of the Xingu Park:
wdpa_polygon = ee.FeatureCollection('WCMC/WDPA/current/polygons')# select the Xingu Indigenous Park shapefilexingu = wdpa_polygon.filter(ee.Filter.eq('NAME', 'Parque do Xingu'))
As you already know, Folium and geehydro allow visualization of GEE data. In this case, you can plot the area of the Xingu Park and interact with it:
Map = folium.Map(location=[-12., -52.5], zoom_start=8)>>> Map.addLayer(xingu)>>> Map
The Xingu Park is a special place for its rich history and diversity. Before the boundaries were defined to make the Park official in 1961, the Villas-Boas brothers first went there almost by accident as part of the Roncador-Xingu expedition. As most of the country (and the government at the time) thought the region was deserted, they quickly found it was filled with hundreds of different indigenous tribes. Those encounters defined the beginning of the history of indigenous rights in Brazil.
To load the MODIS product, simply use ee.ImageColletion() with the snippet you need. To make the analysis a bit easier, youβll filter the data for the last 3 years.
# MODIS MOD13Q1modis = ee.ImageCollection('MODIS/006/MOD13Q1')modis = modis.filterDate(ee.DateRange('2016-01-01','2019-12-01'))
The MOD13Q1 product has both the NDVI and EVI available, so you can easily select them and attribute the data to different variables:
# select EVI and NDVIevi = modis.select('EVI')ndvi = modis.select('NDVI')
A minor issue with MODIS data is that you need to apply a scale factor according to the product youβre using to make sense of it. According to this User Guide (RTFM), the scale factor for the MOD13Q1 product is simply 0.0001. That means youβll have to multiply each dataset by this scale factor to start using it properly.
You probably already figured out that youβll need to write a small function to do it. In GEE dialect that means youβll have to .map() over an ImageCollection. No unnecessary for-loops here, please. When in Rome, do as the Romans do.
Please, insert your Monty Python joke here.
def scale_factor(image):# scale factor for the MODIS MOD13Q1 productreturn image.multiply(0.0001).copyProperties(image, ['system:time_start'])# mapping function to multiply by the scale factorscaled_evi = evi.map(scale_factor)scaled_ndvi = ndvi.map(scale_factor)
With the datasets properly scaled, you can finally use them within the WDPA boundaries of the Xingu Park and start your analysis. A good way to start is to plot the mean NDVI on the interactive Map.
# mean NDVI in the Xingu Park>>> Map.addLayer(scaled_ndvi.mean().clip(xingu), vis_params={'min': 0, 'max': 1, 'palette': ['red', 'yellow','green']})>>> Map
The same code goes for the mean EVI. Thanks to Folium and geehydro itβs simple as that. While an interactive Map is cool, any python enthusiast would be interested to get a time series and squeeze out some cool information from it with data science. GEE has a native way to make time-series plotting but, unfortunately, thatβs only available in the Code Editor. Thatβs exactly where ipygee comes in handy, as it mimics the native javascript-based ui.Chart.image.series(). Without it, we would be in trouble.
It works just the same way with the same arguments, and it even allows you to make a small widget from it when you plot.
# Xingu MOD13Q1 NDVI time seriesxingu_ndvi = chart.Image.series(**{'imageCollection': scaled_ndvi, 'region': xingu, 'reducer': ee.Reducer.mean(), 'scale': 1000, 'xProperty': 'system:time_start'})xingu_ndvi.renderWidget(width='50%')
That could get a way better, you could probably be thinking. The amazing part from that is that ipygee also permits you to work with this time series as any Dataframe you might be familiar with. Thatβs where Pandas gets in the pitch. Donβt believe it?
>>> type(xingu_ndvi.dataframe)pandas.core.frame.DataFrame
From then on, you can go from GEE to our usual Python ecosystem at ease. Think about Pandas, Seaborn or any related package you know to study time series. Thanks to ipygee you can go from both points any time you want.
That means you can plot it in the way you like it. Try it out with Proplot:
fig, ax = plot.subplots(figsize=(7, 3), tight=True)ax.plot(xingu_ndvi.dataframe.index, xingu_ndvi.dataframe['NDVI'], color='forest green', marker='o')plot.show()
Again, the same can be done with the EVI time series just waiting around the corner. With a bit of Pandas, we can transform these 16-day sampled time series in a monthly time series with .groupby(). That could make them behave a bit less wildly.
# monthly averagingxingu_evi_monthly = xingu_evi.dataframe.groupby(pd.Grouper(freq="M")).mean()xingu_ndvi_monthly = xingu_ndvi.dataframe.groupby(pd.Grouper(freq="M")).mean()
To compare the two time series, youβll go back to the standard Matplotlib as there are some issues about sharing axis in Proplot for the time. Unfortunately, or not, youβll have to stick with a little less elegant solution until they fix this minor problem.
# time indextime = xingu_evi_monthly.index# plotfig, ax1 = plt.subplots(figsize=(7, 3))ax2 = ax1.twinx()# EVIax1.plot(time, xingu_evi_monthly, label='EVI', color='muddy brown', marker='+')# NDVIax2.plot(time, xingu_ndvi_monthly, label='NDVI', color='forest green', marker='o')ax1.set_xlabel('Time')ax1.set_ylabel('EVI')ax2.set_ylabel('NDVI')ax1.set_yticks(np.arange(0.3, 1.1, 0.1))ax2.set_yticks(np.arange(0.3, 1.1, 0.1))plt.legend()plt.tight_layout()plt.show()
Notice the difference in magnitude but the same behavior in both time series. Itβs likely that the more complex algorithm of EVI makes it resistant to atmospheric effects and allows it to reflect more robust vegetation changes. The vegetation in the Xingu Park is dominated by the Cerrado biome, which is less dense than the standard Amazon rainforest. Perhaps thatβs why EVI is lower than NDVI, but thatβs a guess.
MODIS-related products are fantastic datasets that allow a wide range of environmental applications. The global, high-frequency and high-resolution MOD13Q1 dataset is extraordinarily useful to study vegetation behavior and changes. With the Python API, you can have access to many of these products in GEE and, hopefully, you learned how to explore them with this tutorial.
As usual, the interactive Jupyter Notebook with all of the code above is freely available in my Climate Data Science repository.
|
[
{
"code": null,
"e": 522,
"s": 172,
"text": "The Moderate Resolution Imaging Spectroradiometer (MODIS) is one of the key sensors used in Earth Observation ever since it was first launched into orbit in 1999. Several reasons can be appointed for its success: the high revisit-time of 1 to 2 days, the global coverage, the wide range of applicability and its derived products. Just to name a few."
},
{
"code": null,
"e": 873,
"s": 522,
"text": "In this tutorial, youβll focus on the MOD13Q1 product, which consists of both the Normalized Difference Vegetation Index (NDVI) and the Enhanced Vegetation Index (EVI) in a global scale at a 16 days frequency. You might already know the NDVI from the Introduction to GEE, but here youβll also explore the usefulness of EVI for environmental analysis."
},
{
"code": null,
"e": 1364,
"s": 873,
"text": "From the GEE Introduction, you already know how to sign up and use gee, install folium for interactive visualization and geehydro to interact with the code in a similar way to the native Javascript API. If youβre interested in climate modeling and read the Introduction to CMIP6, then you must know Proplot as well. The novel package for this tutorial is ipygee, which works in a similar way as geehydro to allow the use of some functions that are only available within the GEE code editor."
},
{
"code": null,
"e": 1397,
"s": 1364,
"text": "To install ipygee, just use Pip:"
},
{
"code": null,
"e": 1416,
"s": 1397,
"text": "pip install ipygee"
},
{
"code": null,
"e": 1491,
"s": 1416,
"text": "Then you can proceed to import all the tools youβll need in this tutorial:"
},
{
"code": null,
"e": 1728,
"s": 1491,
"text": "import eeimport folium import geehydroimport numpy as np # yes, numpy!import pandas as pd # yes, pandas!import proplot as plot import matplotlib.pyplot as plt from ipygee import*from pandas.plotting import register_matplotlib_converters"
},
{
"code": null,
"e": 1893,
"s": 1728,
"text": "As you know, to use gee you must always trigger the authentication and initialize the library, especially if you are interested in running the code in Google Colab."
},
{
"code": null,
"e": 1993,
"s": 1893,
"text": "# Trigger the authentication flow.>>> ee.Authenticate()# Initialize the library.>>> ee.Initialize()"
},
{
"code": null,
"e": 2378,
"s": 1993,
"text": "The World Database on Protected Areas (WDPA) is the greatest database of marine and terrestrial protected areas and itβs easily available in GEE. It provides comprehensive geographic information and the boundaries of any area in the world. Here youβll use it to get the shape of the Xingu Indigenous Park in Brazil, known as one of the first and greatest protected areas in the world."
},
{
"code": null,
"e": 2484,
"s": 2378,
"text": "With the EE snippet, you can load the polygon database of the WDPA and filter the area of the Xingu Park:"
},
{
"code": null,
"e": 2662,
"s": 2484,
"text": "wdpa_polygon = ee.FeatureCollection('WCMC/WDPA/current/polygons')# select the Xingu Indigenous Park shapefilexingu = wdpa_polygon.filter(ee.Filter.eq('NAME', 'Parque do Xingu'))"
},
{
"code": null,
"e": 2812,
"s": 2662,
"text": "As you already know, Folium and geehydro allow visualization of GEE data. In this case, you can plot the area of the Xingu Park and interact with it:"
},
{
"code": null,
"e": 2897,
"s": 2812,
"text": "Map = folium.Map(location=[-12., -52.5], zoom_start=8)>>> Map.addLayer(xingu)>>> Map"
},
{
"code": null,
"e": 3394,
"s": 2897,
"text": "The Xingu Park is a special place for its rich history and diversity. Before the boundaries were defined to make the Park official in 1961, the Villas-Boas brothers first went there almost by accident as part of the Roncador-Xingu expedition. As most of the country (and the government at the time) thought the region was deserted, they quickly found it was filled with hundreds of different indigenous tribes. Those encounters defined the beginning of the history of indigenous rights in Brazil."
},
{
"code": null,
"e": 3559,
"s": 3394,
"text": "To load the MODIS product, simply use ee.ImageColletion() with the snippet you need. To make the analysis a bit easier, youβll filter the data for the last 3 years."
},
{
"code": null,
"e": 3687,
"s": 3559,
"text": "# MODIS MOD13Q1modis = ee.ImageCollection('MODIS/006/MOD13Q1')modis = modis.filterDate(ee.DateRange('2016-01-01','2019-12-01'))"
},
{
"code": null,
"e": 3821,
"s": 3687,
"text": "The MOD13Q1 product has both the NDVI and EVI available, so you can easily select them and attribute the data to different variables:"
},
{
"code": null,
"e": 3895,
"s": 3821,
"text": "# select EVI and NDVIevi = modis.select('EVI')ndvi = modis.select('NDVI')"
},
{
"code": null,
"e": 4218,
"s": 3895,
"text": "A minor issue with MODIS data is that you need to apply a scale factor according to the product youβre using to make sense of it. According to this User Guide (RTFM), the scale factor for the MOD13Q1 product is simply 0.0001. That means youβll have to multiply each dataset by this scale factor to start using it properly."
},
{
"code": null,
"e": 4451,
"s": 4218,
"text": "You probably already figured out that youβll need to write a small function to do it. In GEE dialect that means youβll have to .map() over an ImageCollection. No unnecessary for-loops here, please. When in Rome, do as the Romans do."
},
{
"code": null,
"e": 4495,
"s": 4451,
"text": "Please, insert your Monty Python joke here."
},
{
"code": null,
"e": 4803,
"s": 4495,
"text": "def scale_factor(image):# scale factor for the MODIS MOD13Q1 productreturn image.multiply(0.0001).copyProperties(image, ['system:time_start'])# mapping function to multiply by the scale factorscaled_evi = evi.map(scale_factor)scaled_ndvi = ndvi.map(scale_factor)"
},
{
"code": null,
"e": 5002,
"s": 4803,
"text": "With the datasets properly scaled, you can finally use them within the WDPA boundaries of the Xingu Park and start your analysis. A good way to start is to plot the mean NDVI on the interactive Map."
},
{
"code": null,
"e": 5233,
"s": 5002,
"text": "# mean NDVI in the Xingu Park>>> Map.addLayer(scaled_ndvi.mean().clip(xingu), vis_params={'min': 0, 'max': 1, 'palette': ['red', 'yellow','green']})>>> Map"
},
{
"code": null,
"e": 5741,
"s": 5233,
"text": "The same code goes for the mean EVI. Thanks to Folium and geehydro itβs simple as that. While an interactive Map is cool, any python enthusiast would be interested to get a time series and squeeze out some cool information from it with data science. GEE has a native way to make time-series plotting but, unfortunately, thatβs only available in the Code Editor. Thatβs exactly where ipygee comes in handy, as it mimics the native javascript-based ui.Chart.image.series(). Without it, we would be in trouble."
},
{
"code": null,
"e": 5862,
"s": 5741,
"text": "It works just the same way with the same arguments, and it even allows you to make a small widget from it when you plot."
},
{
"code": null,
"e": 6230,
"s": 5862,
"text": "# Xingu MOD13Q1 NDVI time seriesxingu_ndvi = chart.Image.series(**{'imageCollection': scaled_ndvi, 'region': xingu, 'reducer': ee.Reducer.mean(), 'scale': 1000, 'xProperty': 'system:time_start'})xingu_ndvi.renderWidget(width='50%')"
},
{
"code": null,
"e": 6482,
"s": 6230,
"text": "That could get a way better, you could probably be thinking. The amazing part from that is that ipygee also permits you to work with this time series as any Dataframe you might be familiar with. Thatβs where Pandas gets in the pitch. Donβt believe it?"
},
{
"code": null,
"e": 6540,
"s": 6482,
"text": ">>> type(xingu_ndvi.dataframe)pandas.core.frame.DataFrame"
},
{
"code": null,
"e": 6759,
"s": 6540,
"text": "From then on, you can go from GEE to our usual Python ecosystem at ease. Think about Pandas, Seaborn or any related package you know to study time series. Thanks to ipygee you can go from both points any time you want."
},
{
"code": null,
"e": 6835,
"s": 6759,
"text": "That means you can plot it in the way you like it. Try it out with Proplot:"
},
{
"code": null,
"e": 7004,
"s": 6835,
"text": "fig, ax = plot.subplots(figsize=(7, 3), tight=True)ax.plot(xingu_ndvi.dataframe.index, xingu_ndvi.dataframe['NDVI'], color='forest green', marker='o')plot.show()"
},
{
"code": null,
"e": 7250,
"s": 7004,
"text": "Again, the same can be done with the EVI time series just waiting around the corner. With a bit of Pandas, we can transform these 16-day sampled time series in a monthly time series with .groupby(). That could make them behave a bit less wildly."
},
{
"code": null,
"e": 7424,
"s": 7250,
"text": "# monthly averagingxingu_evi_monthly = xingu_evi.dataframe.groupby(pd.Grouper(freq=\"M\")).mean()xingu_ndvi_monthly = xingu_ndvi.dataframe.groupby(pd.Grouper(freq=\"M\")).mean()"
},
{
"code": null,
"e": 7682,
"s": 7424,
"text": "To compare the two time series, youβll go back to the standard Matplotlib as there are some issues about sharing axis in Proplot for the time. Unfortunately, or not, youβll have to stick with a little less elegant solution until they fix this minor problem."
},
{
"code": null,
"e": 8160,
"s": 7682,
"text": "# time indextime = xingu_evi_monthly.index# plotfig, ax1 = plt.subplots(figsize=(7, 3))ax2 = ax1.twinx()# EVIax1.plot(time, xingu_evi_monthly, label='EVI', color='muddy brown', marker='+')# NDVIax2.plot(time, xingu_ndvi_monthly, label='NDVI', color='forest green', marker='o')ax1.set_xlabel('Time')ax1.set_ylabel('EVI')ax2.set_ylabel('NDVI')ax1.set_yticks(np.arange(0.3, 1.1, 0.1))ax2.set_yticks(np.arange(0.3, 1.1, 0.1))plt.legend()plt.tight_layout()plt.show()"
},
{
"code": null,
"e": 8576,
"s": 8160,
"text": "Notice the difference in magnitude but the same behavior in both time series. Itβs likely that the more complex algorithm of EVI makes it resistant to atmospheric effects and allows it to reflect more robust vegetation changes. The vegetation in the Xingu Park is dominated by the Cerrado biome, which is less dense than the standard Amazon rainforest. Perhaps thatβs why EVI is lower than NDVI, but thatβs a guess."
},
{
"code": null,
"e": 8950,
"s": 8576,
"text": "MODIS-related products are fantastic datasets that allow a wide range of environmental applications. The global, high-frequency and high-resolution MOD13Q1 dataset is extraordinarily useful to study vegetation behavior and changes. With the Python API, you can have access to many of these products in GEE and, hopefully, you learned how to explore them with this tutorial."
}
] |
Classic Probability Problem #2: The Coupon Problem | by Andrew Rothman | Towards Data Science
|
This is my second entry on classic toy problems in probability theory. βThe Coupon Problemβ is great problem to be aware of; it shows up in a number of applied situations. From a technical interviewing perspective, by adding a small computational component at the end it can serve as a solid test of general probability & coding knowledge. The question is as follows:
There is a brand of cereal that comes with a single coupon with the purchase of each box. There are a 5 different types of coupons. The probability of getting any one of the 5 coupons with each cereal box purchase is uniform. The objective is to collect all 5 unique coupon types.
Now the questions begs, what is the expected number of boxes of cereal you will need to purchase to collect all 5 unique coupons?
We will first solve this problem analytically, and then simulate the problem computationally to verify our findings.
Letβs start with a few observations:
Each cereal box purchased is independent of the last box (or boxes) purchased.The probability of getting any of the 5 coupon types in a given box is the same.
Each cereal box purchased is independent of the last box (or boxes) purchased.
The probability of getting any of the 5 coupon types in a given box is the same.
We need someway of mathematically bounding this problem. Perhaps there are some parametric tools we can use? Letβs take a quick detour and discuss geometric random variables.
A Geometric random variable is a discrete random variable with a one-parameter distribution as detailed below:
Note, that we can view our coupon collecting problem as the sum of the expected value of five geometric random variables, each with different success parameters p:
Note, that the expected value of a geometric random variable is 1/p:
For those interested in derivations of the expected value of a Geometric random variable, below I have included two derivations (one directly using the PMF and another using the MGF). If these proofs are not of interest to you, feel free to skip this section:
Now we simply sum the expected values of our five specified random variables:
Therefore, rounding up to the nearest integer, the expected number of boxes we will need to purchase to collect all 5 unique coupons is 12 boxes.
Letβs now simulate this scenario in python computationally over 10,000 iterations to confirm our analytical results above:
import numpy as npimport pandas as pdimport matplotlib.pyplot as plt## specify number of coupons, and the probability of getting a couponnum_coupons=5expected_number_of_trials = 0for i in range(num_coupons, 0, -1): expected_number_of_trials = expected_number_of_trials + (1/(i/num_coupons))iterations = 10000df = pd.DataFrame()df['iteration'] = range(1,iterations+1)df['average_num_trials_required'] = Nonefor i in range(0, iterations): full_set = set(range(0,num_coupons)) current_set = set([]) total_number_of_coupons_collected = 0 while(current_set != full_set): total_number_of_coupons_collected = total_number_of_coupons_collected+1 random_coupon = np.asscalar(np.random.randint(low=0, high=num_coupons, size=1)) update_set = list(current_set) update_set.append(random_coupon) current_set = set(update_set) del random_coupon, update_set if(i+1 == 1): df.loc[df['iteration']==i+1, 'average_num_trials_required'] = total_number_of_coupons_collected else: df.loc[df['iteration']==i+1, 'average_num_trials_required'] = float(((df.loc[df['iteration']==i, 'average_num_trials_required']*i) + total_number_of_coupons_collected)/(i+1))print(df['average_num_trials_required'][i])
As shown above, over 10,000 iterations of this scenario, the sample average of the number of boxes needed to be purchased to collect all 5 unique coupons was approximately 11.431. This result coincides with our analytical solution above.
As with most well-known toy problems in technical fields, this βCoupon Problemβ and silly child-like scenario about cereal and coupon collecting serves an important purpose. This problem (and slight variants of it) shows up in applied practice constantly; problems concerning the expected value of discrete waiting times, or the number of events that likely need to occur before something happens. These are problems that can often be reduced to some variant of the Coupon Problem. Therefore having good fundamentals and grounded knowledge in theory about toy problems such as the one discussed here can very much assist you in applied practice.
Additionally, itβs worth mentioning we solved this problem for 5 unique coupons. But we could have chosen any arbitrary constant n unique coupons greater than zero. The methodology used here still applies.
Lastly, I would like to leave you with a lingering question. In our problem above, letβs say youβve already collected 4 of the unique coupons, and now working on collecting that 5th and last unique coupon. Post your 4th unique coupon collected, youβve already purchased 50 more cereal boxes, but all have contained more of the 4 unique coupons you already have. From that point forward, what is the expected number of boxes you will need to purchase to get that 5th coupon? I will give you a hint, the Geometric distribution is the discrete counterpart of the Exponential distribution, which has a particular unique property regarding waiting times. Feel free to add in the comments your thoughts, and possible answers to my riddle above.
I hope the above is insightful. As Iβve mentioned in some of my previous pieces, itβs my opinion not enough folks take the time to go through these types of exercises. For me, this type of theory-based insight leaves me more comfortable using methods in practice. A personal goal of mine is to encourage others in the field to take a similar approach. Iβm planning on writing based pieces in the future, so feel free to connect with me on LinkedIn, and follow me here on Medium for updates!
|
[
{
"code": null,
"e": 540,
"s": 172,
"text": "This is my second entry on classic toy problems in probability theory. βThe Coupon Problemβ is great problem to be aware of; it shows up in a number of applied situations. From a technical interviewing perspective, by adding a small computational component at the end it can serve as a solid test of general probability & coding knowledge. The question is as follows:"
},
{
"code": null,
"e": 821,
"s": 540,
"text": "There is a brand of cereal that comes with a single coupon with the purchase of each box. There are a 5 different types of coupons. The probability of getting any one of the 5 coupons with each cereal box purchase is uniform. The objective is to collect all 5 unique coupon types."
},
{
"code": null,
"e": 951,
"s": 821,
"text": "Now the questions begs, what is the expected number of boxes of cereal you will need to purchase to collect all 5 unique coupons?"
},
{
"code": null,
"e": 1068,
"s": 951,
"text": "We will first solve this problem analytically, and then simulate the problem computationally to verify our findings."
},
{
"code": null,
"e": 1105,
"s": 1068,
"text": "Letβs start with a few observations:"
},
{
"code": null,
"e": 1264,
"s": 1105,
"text": "Each cereal box purchased is independent of the last box (or boxes) purchased.The probability of getting any of the 5 coupon types in a given box is the same."
},
{
"code": null,
"e": 1343,
"s": 1264,
"text": "Each cereal box purchased is independent of the last box (or boxes) purchased."
},
{
"code": null,
"e": 1424,
"s": 1343,
"text": "The probability of getting any of the 5 coupon types in a given box is the same."
},
{
"code": null,
"e": 1599,
"s": 1424,
"text": "We need someway of mathematically bounding this problem. Perhaps there are some parametric tools we can use? Letβs take a quick detour and discuss geometric random variables."
},
{
"code": null,
"e": 1710,
"s": 1599,
"text": "A Geometric random variable is a discrete random variable with a one-parameter distribution as detailed below:"
},
{
"code": null,
"e": 1874,
"s": 1710,
"text": "Note, that we can view our coupon collecting problem as the sum of the expected value of five geometric random variables, each with different success parameters p:"
},
{
"code": null,
"e": 1943,
"s": 1874,
"text": "Note, that the expected value of a geometric random variable is 1/p:"
},
{
"code": null,
"e": 2203,
"s": 1943,
"text": "For those interested in derivations of the expected value of a Geometric random variable, below I have included two derivations (one directly using the PMF and another using the MGF). If these proofs are not of interest to you, feel free to skip this section:"
},
{
"code": null,
"e": 2281,
"s": 2203,
"text": "Now we simply sum the expected values of our five specified random variables:"
},
{
"code": null,
"e": 2427,
"s": 2281,
"text": "Therefore, rounding up to the nearest integer, the expected number of boxes we will need to purchase to collect all 5 unique coupons is 12 boxes."
},
{
"code": null,
"e": 2550,
"s": 2427,
"text": "Letβs now simulate this scenario in python computationally over 10,000 iterations to confirm our analytical results above:"
},
{
"code": null,
"e": 3807,
"s": 2550,
"text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as plt## specify number of coupons, and the probability of getting a couponnum_coupons=5expected_number_of_trials = 0for i in range(num_coupons, 0, -1): expected_number_of_trials = expected_number_of_trials + (1/(i/num_coupons))iterations = 10000df = pd.DataFrame()df['iteration'] = range(1,iterations+1)df['average_num_trials_required'] = Nonefor i in range(0, iterations): full_set = set(range(0,num_coupons)) current_set = set([]) total_number_of_coupons_collected = 0 while(current_set != full_set): total_number_of_coupons_collected = total_number_of_coupons_collected+1 random_coupon = np.asscalar(np.random.randint(low=0, high=num_coupons, size=1)) update_set = list(current_set) update_set.append(random_coupon) current_set = set(update_set) del random_coupon, update_set if(i+1 == 1): df.loc[df['iteration']==i+1, 'average_num_trials_required'] = total_number_of_coupons_collected else: df.loc[df['iteration']==i+1, 'average_num_trials_required'] = float(((df.loc[df['iteration']==i, 'average_num_trials_required']*i) + total_number_of_coupons_collected)/(i+1))print(df['average_num_trials_required'][i])"
},
{
"code": null,
"e": 4045,
"s": 3807,
"text": "As shown above, over 10,000 iterations of this scenario, the sample average of the number of boxes needed to be purchased to collect all 5 unique coupons was approximately 11.431. This result coincides with our analytical solution above."
},
{
"code": null,
"e": 4691,
"s": 4045,
"text": "As with most well-known toy problems in technical fields, this βCoupon Problemβ and silly child-like scenario about cereal and coupon collecting serves an important purpose. This problem (and slight variants of it) shows up in applied practice constantly; problems concerning the expected value of discrete waiting times, or the number of events that likely need to occur before something happens. These are problems that can often be reduced to some variant of the Coupon Problem. Therefore having good fundamentals and grounded knowledge in theory about toy problems such as the one discussed here can very much assist you in applied practice."
},
{
"code": null,
"e": 4897,
"s": 4691,
"text": "Additionally, itβs worth mentioning we solved this problem for 5 unique coupons. But we could have chosen any arbitrary constant n unique coupons greater than zero. The methodology used here still applies."
},
{
"code": null,
"e": 5636,
"s": 4897,
"text": "Lastly, I would like to leave you with a lingering question. In our problem above, letβs say youβve already collected 4 of the unique coupons, and now working on collecting that 5th and last unique coupon. Post your 4th unique coupon collected, youβve already purchased 50 more cereal boxes, but all have contained more of the 4 unique coupons you already have. From that point forward, what is the expected number of boxes you will need to purchase to get that 5th coupon? I will give you a hint, the Geometric distribution is the discrete counterpart of the Exponential distribution, which has a particular unique property regarding waiting times. Feel free to add in the comments your thoughts, and possible answers to my riddle above."
}
] |
How to compare two text files in python? - GeeksforGeeks
|
24 Jan, 2021
Python has provided the methods to manipulate files that too in a very concise manner. In this article we are going to discuss one of the applications of the Pythonβs file handling features i.e. the comparison of files.
Files in use:
Text File 1
Text File 2
Python supports a module called filecmp with a method filecmp.cmp() that returns three list containing matched files, mismatched files and errors regarding those files which could not be compared. This method can operate in two modes :
shallow mode: where only metadata of the files are compared like the size, date modified, etc.
deep mode: where the content of the files are compared.
Syntax:
cmp(a, b)
Parameters:
a and b are the two numbers in which the comparison is being done.
Returns:
-1 if a<b
0 if a=b
1 if a>b
Program:
Python3
import filecmp f1 = "C:/Users/user/Documents/intro.txt"f2 = "C:/Users/user/Desktop/intro1.txt" # shallow comparisonresult = filecmp.cmp(f1, f2)print(result)# deep comparisonresult = filecmp.cmp(f1, f2, shallow=False)print(result)
Output:
False
False
The drawback in the above approach is that we can not retrieve the lines where the files differ. Though this is an optional requirement we often want to watch out for the lines where files differ and then manipulate that to our advantage. The basic approach to implement this is to store each line of every file in separate lists one for each file. These lists are compared against each other two files at a time.
Approach:
Open the files to be compared
Loop through the files and compare each line of the two files.
If lines are identical, output SAME on the output screen.
Else, output the differing lines from both the files on the output screen.
Program:
Python3
# reading filesf1 = open("C:/Users/user/Documents/intro.txt", "r") f2 = open("C:/Users/user/Desktop/intro1.txt", "r") i = 0 for line1 in f1: i += 1 for line2 in f2: # matching line1 from both files if line1 == line2: # print IDENTICAL if similar print("Line ", i, ": IDENTICAL") else: print("Line ", i, ":") # else print that line from both files print("\tFile 1:", line1, end='') print("\tFile 2:", line2, end='') break # closing filesf1.close() f2.close()
Output:
Python supports a module called filecmp with a method filecmp.cmpfiles() that returns three list containing matched files, mismatched files and errors regarding those files which could not be compared. It is similar to first approach but it is used to compare files in two different directories.
Program:
Python3
import filecmp d1 = "C:/Users/user/Documents/"d2 = "C:/Users/user/Desktop/"files = ['intro.txt'] # shallow comparisonmatch, mismatch, errors = filecmp.cmpfiles(d1, d2, files)print('Shallow comparison')print("Match:", match)print("Mismatch:", mismatch)print("Errors:", errors) # deep comparisonmatch, mismatch, errors = filecmp.cmpfiles(d1, d2, files, shallow=False)print('Deep comparison')print("Match:", match)print("Mismatch:", mismatch)print("Errors:", errors)
Output:
Shallow Comparison
Match: [ ]
Mismatch: [ β intro.txt β]
Errors: [ ]
Deep comparison
Match: []
Mismatch: [ β intro.txt β]
Errors: [ ]
Picked
Python file-handling-programs
python-file-handling
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
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()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 24641,
"s": 24613,
"text": "\n24 Jan, 2021"
},
{
"code": null,
"e": 24861,
"s": 24641,
"text": "Python has provided the methods to manipulate files that too in a very concise manner. In this article we are going to discuss one of the applications of the Pythonβs file handling features i.e. the comparison of files."
},
{
"code": null,
"e": 24875,
"s": 24861,
"text": "Files in use:"
},
{
"code": null,
"e": 24887,
"s": 24875,
"text": "Text File 1"
},
{
"code": null,
"e": 24899,
"s": 24887,
"text": "Text File 2"
},
{
"code": null,
"e": 25135,
"s": 24899,
"text": "Python supports a module called filecmp with a method filecmp.cmp() that returns three list containing matched files, mismatched files and errors regarding those files which could not be compared. This method can operate in two modes :"
},
{
"code": null,
"e": 25230,
"s": 25135,
"text": "shallow mode: where only metadata of the files are compared like the size, date modified, etc."
},
{
"code": null,
"e": 25286,
"s": 25230,
"text": "deep mode: where the content of the files are compared."
},
{
"code": null,
"e": 25294,
"s": 25286,
"text": "Syntax:"
},
{
"code": null,
"e": 25304,
"s": 25294,
"text": "cmp(a, b)"
},
{
"code": null,
"e": 25316,
"s": 25304,
"text": "Parameters:"
},
{
"code": null,
"e": 25384,
"s": 25316,
"text": "a and b are the two numbers in which the comparison is being done. "
},
{
"code": null,
"e": 25393,
"s": 25384,
"text": "Returns:"
},
{
"code": null,
"e": 25403,
"s": 25393,
"text": "-1 if a<b"
},
{
"code": null,
"e": 25412,
"s": 25403,
"text": "0 if a=b"
},
{
"code": null,
"e": 25421,
"s": 25412,
"text": "1 if a>b"
},
{
"code": null,
"e": 25430,
"s": 25421,
"text": "Program:"
},
{
"code": null,
"e": 25438,
"s": 25430,
"text": "Python3"
},
{
"code": "import filecmp f1 = \"C:/Users/user/Documents/intro.txt\"f2 = \"C:/Users/user/Desktop/intro1.txt\" # shallow comparisonresult = filecmp.cmp(f1, f2)print(result)# deep comparisonresult = filecmp.cmp(f1, f2, shallow=False)print(result)",
"e": 25670,
"s": 25438,
"text": null
},
{
"code": null,
"e": 25678,
"s": 25670,
"text": "Output:"
},
{
"code": null,
"e": 25684,
"s": 25678,
"text": "False"
},
{
"code": null,
"e": 25690,
"s": 25684,
"text": "False"
},
{
"code": null,
"e": 26104,
"s": 25690,
"text": "The drawback in the above approach is that we can not retrieve the lines where the files differ. Though this is an optional requirement we often want to watch out for the lines where files differ and then manipulate that to our advantage. The basic approach to implement this is to store each line of every file in separate lists one for each file. These lists are compared against each other two files at a time."
},
{
"code": null,
"e": 26116,
"s": 26104,
"text": "Approach: "
},
{
"code": null,
"e": 26146,
"s": 26116,
"text": "Open the files to be compared"
},
{
"code": null,
"e": 26209,
"s": 26146,
"text": "Loop through the files and compare each line of the two files."
},
{
"code": null,
"e": 26267,
"s": 26209,
"text": "If lines are identical, output SAME on the output screen."
},
{
"code": null,
"e": 26342,
"s": 26267,
"text": "Else, output the differing lines from both the files on the output screen."
},
{
"code": null,
"e": 26351,
"s": 26342,
"text": "Program:"
},
{
"code": null,
"e": 26359,
"s": 26351,
"text": "Python3"
},
{
"code": "# reading filesf1 = open(\"C:/Users/user/Documents/intro.txt\", \"r\") f2 = open(\"C:/Users/user/Desktop/intro1.txt\", \"r\") i = 0 for line1 in f1: i += 1 for line2 in f2: # matching line1 from both files if line1 == line2: # print IDENTICAL if similar print(\"Line \", i, \": IDENTICAL\") else: print(\"Line \", i, \":\") # else print that line from both files print(\"\\tFile 1:\", line1, end='') print(\"\\tFile 2:\", line2, end='') break # closing filesf1.close() f2.close() ",
"e": 27024,
"s": 26359,
"text": null
},
{
"code": null,
"e": 27033,
"s": 27024,
"text": "Output: "
},
{
"code": null,
"e": 27330,
"s": 27033,
"text": "Python supports a module called filecmp with a method filecmp.cmpfiles() that returns three list containing matched files, mismatched files and errors regarding those files which could not be compared. It is similar to first approach but it is used to compare files in two different directories. "
},
{
"code": null,
"e": 27339,
"s": 27330,
"text": "Program:"
},
{
"code": null,
"e": 27347,
"s": 27339,
"text": "Python3"
},
{
"code": "import filecmp d1 = \"C:/Users/user/Documents/\"d2 = \"C:/Users/user/Desktop/\"files = ['intro.txt'] # shallow comparisonmatch, mismatch, errors = filecmp.cmpfiles(d1, d2, files)print('Shallow comparison')print(\"Match:\", match)print(\"Mismatch:\", mismatch)print(\"Errors:\", errors) # deep comparisonmatch, mismatch, errors = filecmp.cmpfiles(d1, d2, files, shallow=False)print('Deep comparison')print(\"Match:\", match)print(\"Mismatch:\", mismatch)print(\"Errors:\", errors)",
"e": 27814,
"s": 27347,
"text": null
},
{
"code": null,
"e": 27822,
"s": 27814,
"text": "Output:"
},
{
"code": null,
"e": 27841,
"s": 27822,
"text": "Shallow Comparison"
},
{
"code": null,
"e": 27852,
"s": 27841,
"text": "Match: [ ]"
},
{
"code": null,
"e": 27879,
"s": 27852,
"text": "Mismatch: [ β intro.txt β]"
},
{
"code": null,
"e": 27891,
"s": 27879,
"text": "Errors: [ ]"
},
{
"code": null,
"e": 27907,
"s": 27891,
"text": "Deep comparison"
},
{
"code": null,
"e": 27917,
"s": 27907,
"text": "Match: []"
},
{
"code": null,
"e": 27944,
"s": 27917,
"text": "Mismatch: [ β intro.txt β]"
},
{
"code": null,
"e": 27956,
"s": 27944,
"text": "Errors: [ ]"
},
{
"code": null,
"e": 27963,
"s": 27956,
"text": "Picked"
},
{
"code": null,
"e": 27993,
"s": 27963,
"text": "Python file-handling-programs"
},
{
"code": null,
"e": 28014,
"s": 27993,
"text": "python-file-handling"
},
{
"code": null,
"e": 28038,
"s": 28014,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 28045,
"s": 28038,
"text": "Python"
},
{
"code": null,
"e": 28064,
"s": 28045,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28162,
"s": 28064,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28171,
"s": 28162,
"text": "Comments"
},
{
"code": null,
"e": 28184,
"s": 28171,
"text": "Old Comments"
},
{
"code": null,
"e": 28202,
"s": 28184,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28237,
"s": 28202,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28259,
"s": 28237,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28291,
"s": 28259,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28321,
"s": 28291,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28363,
"s": 28321,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28389,
"s": 28363,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28432,
"s": 28389,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28469,
"s": 28432,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Windows Server 2012 R2 Stuck at "Updating Your Systemβ - GeeksforGeeks
|
11 Dec, 2018
This tutorial describes an unusual problem that may occur during Windows Server 2012 R2 Updates. This issue generally occurs while performing scheduled Windows Updates. Failure of one single update may keep you stuck you at the screen that says Updating your system, but will not move a single inch, even after hours of waiting with no progress. To overcome this challenge you can follow one of the methods popular among the system administrators. Here, we will see one of them.
Troubleshooting:
1. Boot your server from Windows Server 2012 > click on Troubleshoot to enter in recovery mode console.
2. Run the following command to get a list of available drives:
wmic logicaldisk get name
3. The next step is to locate the drive that contains the windows directory. The easiest way to confirm is to check each drive for Windows directory by using βdirβ command. Generally, Windows directory exists in the βC:β drive, however, if itβs located under different drive then simply replace βC:β with respective drive.
4. Navigate D:\Windows\WinSxS directory by using >> βcd Windows\Winsxsβ
5. Check βpending.xmlβ file >> run βdir pending*β command
6. Now rename the βPendingβ files to β_oldβ at the end of the file name >> enter βren Pending.xml Pending_old.xmlβ command
7. Once you rename the βpending.xmlβ >> the next step is to create a new blank βPending.xmlβ file by using: echo > pending.xml
8. Now navigate Windows directory
9. Create a new directory within Windows >> run βmkdir directorynameβ where directory name can be a random choice by you. We will name the directory as scratch.
10. Use DISM (deployment image servicing and management) command. It will remove or revert all pending actions from the damaged image >> run below command:
DISM /Image: D:\ / Cleanup-Image / RevertPendingActions
/ scratchdir: D:\Windows\ scratch
11. Now rename the βSoftwareDistributionβ folder to βSoftwareDistributionOLDβ >> run below command:
Ren SoftwareDistribution SoftwareDistributionOLD
12. Run a system file checker tool to repair missing or corrupt kernel files by using the following command:
sfc /SCANNOW /OFFBOOTDIR=D:\ /OFFWINDIR=D:\Windows
13. Reboot the server
Note: If it is a virtual machine, make sure to take backup of βvhdβ before making any changes on the server.
GBlog
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
12 pip Commands For Python Developers
What is web socket and how it is different from the HTTP?
ML | Underfitting and Overfitting
How to Find the Wi-Fi Password Using CMD in Windows?
Docker - COPY Instruction
How to Run a Python Script using Docker?
Setting up the environment in Java
How to Add External JAR File to an IntelliJ IDEA Project?
|
[
{
"code": null,
"e": 25150,
"s": 25122,
"text": "\n11 Dec, 2018"
},
{
"code": null,
"e": 25629,
"s": 25150,
"text": "This tutorial describes an unusual problem that may occur during Windows Server 2012 R2 Updates. This issue generally occurs while performing scheduled Windows Updates. Failure of one single update may keep you stuck you at the screen that says Updating your system, but will not move a single inch, even after hours of waiting with no progress. To overcome this challenge you can follow one of the methods popular among the system administrators. Here, we will see one of them."
},
{
"code": null,
"e": 25646,
"s": 25629,
"text": "Troubleshooting:"
},
{
"code": null,
"e": 25750,
"s": 25646,
"text": "1. Boot your server from Windows Server 2012 > click on Troubleshoot to enter in recovery mode console."
},
{
"code": null,
"e": 25814,
"s": 25750,
"text": "2. Run the following command to get a list of available drives:"
},
{
"code": null,
"e": 25840,
"s": 25814,
"text": "wmic logicaldisk get name"
},
{
"code": null,
"e": 26163,
"s": 25840,
"text": "3. The next step is to locate the drive that contains the windows directory. The easiest way to confirm is to check each drive for Windows directory by using βdirβ command. Generally, Windows directory exists in the βC:β drive, however, if itβs located under different drive then simply replace βC:β with respective drive."
},
{
"code": null,
"e": 26235,
"s": 26163,
"text": "4. Navigate D:\\Windows\\WinSxS directory by using >> βcd Windows\\Winsxsβ"
},
{
"code": null,
"e": 26293,
"s": 26235,
"text": "5. Check βpending.xmlβ file >> run βdir pending*β command"
},
{
"code": null,
"e": 26416,
"s": 26293,
"text": "6. Now rename the βPendingβ files to β_oldβ at the end of the file name >> enter βren Pending.xml Pending_old.xmlβ command"
},
{
"code": null,
"e": 26543,
"s": 26416,
"text": "7. Once you rename the βpending.xmlβ >> the next step is to create a new blank βPending.xmlβ file by using: echo > pending.xml"
},
{
"code": null,
"e": 26577,
"s": 26543,
"text": "8. Now navigate Windows directory"
},
{
"code": null,
"e": 26738,
"s": 26577,
"text": "9. Create a new directory within Windows >> run βmkdir directorynameβ where directory name can be a random choice by you. We will name the directory as scratch."
},
{
"code": null,
"e": 26894,
"s": 26738,
"text": "10. Use DISM (deployment image servicing and management) command. It will remove or revert all pending actions from the damaged image >> run below command:"
},
{
"code": null,
"e": 27011,
"s": 26894,
"text": "DISM /Image: D:\\ / Cleanup-Image / RevertPendingActions \n / scratchdir: D:\\Windows\\ scratch"
},
{
"code": null,
"e": 27111,
"s": 27011,
"text": "11. Now rename the βSoftwareDistributionβ folder to βSoftwareDistributionOLDβ >> run below command:"
},
{
"code": null,
"e": 27160,
"s": 27111,
"text": "Ren SoftwareDistribution SoftwareDistributionOLD"
},
{
"code": null,
"e": 27269,
"s": 27160,
"text": "12. Run a system file checker tool to repair missing or corrupt kernel files by using the following command:"
},
{
"code": null,
"e": 27321,
"s": 27269,
"text": "sfc /SCANNOW /OFFBOOTDIR=D:\\ /OFFWINDIR=D:\\Windows"
},
{
"code": null,
"e": 27343,
"s": 27321,
"text": "13. Reboot the server"
},
{
"code": null,
"e": 27452,
"s": 27343,
"text": "Note: If it is a virtual machine, make sure to take backup of βvhdβ before making any changes on the server."
},
{
"code": null,
"e": 27458,
"s": 27452,
"text": "GBlog"
},
{
"code": null,
"e": 27467,
"s": 27458,
"text": "TechTips"
},
{
"code": null,
"e": 27565,
"s": 27467,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27590,
"s": 27565,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 27617,
"s": 27590,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 27655,
"s": 27617,
"text": "12 pip Commands For Python Developers"
},
{
"code": null,
"e": 27713,
"s": 27655,
"text": "What is web socket and how it is different from the HTTP?"
},
{
"code": null,
"e": 27747,
"s": 27713,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 27800,
"s": 27747,
"text": "How to Find the Wi-Fi Password Using CMD in Windows?"
},
{
"code": null,
"e": 27826,
"s": 27800,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 27867,
"s": 27826,
"text": "How to Run a Python Script using Docker?"
},
{
"code": null,
"e": 27902,
"s": 27867,
"text": "Setting up the environment in Java"
}
] |
Using Python to find new books to read | Towards Data Science
|
There are tons of books out there, but not all are worth reading. To quote the old Faber in Fahrenheit 451, the best books are the ones that βshow the pores in the face of life.β
So, with an overwhelming number of books out there, how can you find the best ones?
One way is to go to a dedicated book website (such as Amazon or Goodreads). They provide filtering tools to refine search results, and display usersβ reviews and average ratings to help narrow down the choices.
Alternatively, one could ask their friends or acquaintances for recommendations.
These two methods are undeniably effective.
But there is a third way to get great results: Look at the recommendations of well-known people who say the books they read played a significant role in their achievements.
And this is where this amazing website, Mostrecommendedbooks.com, comes into play.
This website shows pretty much all the books recommended by βworld-class peopleβ. Compared to its peers, it is really way ahead of the curve.
So, I decided to retrieve all its book titles1, with two purposes in mind:
Bring all these books together in one DataFrame for my fellow book lovers, andGet some insights into this valuable treasure using Python visualization libraries.
Bring all these books together in one DataFrame for my fellow book lovers, and
Get some insights into this valuable treasure using Python visualization libraries.
I also used Google Books API to get the number of pages, the publication dates, and the categories. I chose Google Books API because:
It offers a wide variety of information about a large pool of books.
The documentation is concise and easy to follow.
There are multiple query parameters (title, author, ISBN, etc.).
Public data, like the one weβd like to access, doesnβt require authorization. You are only required to provide the API key2.
(The code for scraping data and building the dataset is available on my Github. The dataset can also be found in Kaggle)
Before we get started, letβs import the Python libraries weβll be using.
import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as sbimport textwrap%matplotlib inline
books_df = pd.read_csv('books_clean.csv')books_df.head(10)
And this is how our dataset looks like. Letβs see how many books we got here:
books_df.shape
(3003, 8)
As you can see, we have 3003 book titles.
We also have other features such as number of recommendations, category, publication date, and number of pages.
For anyone who might be interested, I also made sure to include Google books IDs to facilitate data scraping of the same books.
Letβs start by plotting the distribution of the number of recommendations/ book:
#Histogram:plt.figure(figsize=[10,5])plt.hist(data=books_df, x='num_recommendations')plt.title('Distribution of the number of recommendations per book', size=18, fontweight='bold')plt.xlabel('Recommendations', size=15)plt.ylabel('Frequency', size=15)
The distribution is right-skewed and many books have less than 2 recommendations.
So, what are the most recommended books within this list?
To answer this question, we cannot plot all 3003 books in descending order, as this will produce an unaesthetic chart that will not convey information concisely.
So, I will (arbitrarily) take the median of the βnum_recommendationsβ unique values as a minimum threshold for the most recommended books:
#Fixing the threshold:threshold=np.median(books_df['num_recommendations'].value_counts().index)#Subset of the dataset based on the threshold:data=books_df.loc[books_df.num_recommendations >= threshold]#Combining titles and authors: data['title_y']=[','.join(i) for i in list(zip(data['title'],data['author']))]#Barplot: plt.figure(figsize = [5,10])color_base = sb.color_palette()[0]sb.barplot(data = data.sort_values(by = 'num_recommendations', ascending = False), x = 'recommender_count', y = 'title_y', color = color_base)plt.title('The Most Recommended Books', size = 18)plt.xlabel('Recommendations', fontweight = 'bold', size = 15)plt.ylabel('Titles', size = 15);
Here, we have 22 books at the absolute pinnacle of our DataFrame.
As you can see, Manβs Search for Meaning (Victor Frankl) tops the list with more than 20 recommendations, followed by Sapiens (Yuval Harari) and then Principles by Ray Dalio.
However, it appears that this plot contains many business and self-help books. We can hardly see a fiction book, let alone philosophy or another specific category.
Digging deeper into the categories within the DataFrame will certainly refine our findings and bring forth meaningful information that would help choose the best books for us.
But first, we need to know the most frequently occurring categories in our dataset.
For the sake of simplicity, I will only plot the top 20:
#Plotting the 20 most frequently occurring categories:plt.figure(figsize = [10,5])color_base = sb.color_palette()[0]sb.barplot(books_df.category.value_counts().head(20).index, books_df.category.value_counts().head(20).values, color=color_base)plt.xticks(rotation = 'vertical')plt.title('The Most Frequently Occurring Categories', fontweight = 'bold', size = 18)plt.xlabel('Categories', size = 15)plt.ylabel('Count', size = 15)
Unsurprisingly, fiction and business books are the most popular with over 400 books in each of them. Biography books are the third in the list, followed by history and science.
Having many books in a given category doesnβt mean this category is the most recommended, nor that the books in said category are the most recommended of all. Thereβs no accounting for taste. Some people prefer fiction, while others are more interested in economics.
For this reason, it would be reasonable to see the distribution of recommendations in each category.
This will give us an idea about the outliers and will help us spot the most recommended books within each category:
cat = books_df.category.value_counts().head(20).indexfig, ax = plt.subplots(figsize = [10,5])sb.swarmplot(data = books_df[books_df.category.isin(cat)], x = 'category', y = 'num_recommendations', palette = 'tab20')ax.set_xticklabels(ax.get_xticklabels(), rotation = 90)ax.set_title('Distribution of Recommendations by Category', fontweight = 'bold', size = 18)ax.set_xlabel('Categories', size = 15)ax.set_ylabel('Recommendations', fontsize = 15)
We see that most categories have books within the 1β5 recommendations range.
Meanwhile, some categories have books recommended by more than 5 people, while others have books recommended by more than 10 people. Biography, business and economics, fiction, psychology, and self-help all have numerous books with many recommendations.
Now, letβs find out the must-read books in each category.
I will only consider 9 categories and plot the top 5 based on the number of recommendations. But please note it is possible to add more categories or widen the list of books using the code below:
#Defining the categories:categories = books_df.category.value_counts().head(9).index.tolist()#Defining a function to select a subset of data:def selection(cat): data = books_df[books_df['category'] == cat].sort_values(by = 'num_recommendations', ascending = False).head() return datafig, ax = plt.subplots(nrows = 3, ncols = 3,figsize = [20,15])plt.suptitle('Top 5 Recommended Books in each Category', size = 30, y = 1.05, fontweight = 'bold')fig.tight_layout(h_pad = 8)fig.text(-0.02, 0.5, 'Recommendations', va = 'center', rotation='vertical', fontweight='bold', fontsize=25)fig.text(0.5, -0.06, 'Titles', va = 'center', ha = 'center', fontweight = 'bold', fontsize=25)ax = ax.flatten()color_base = sb.color_palette()[0]y = sorted(books_df['num_recommendations'].unique())i=0for cat in categories: sb.barplot(data = selection(cat), x='title', y = 'num_recommendations', ax = ax[i], color = color_base) ax[i].set_title(cat, fontweight = 'bold', fontsize = 18, color = 'crimson') ax[i].set_ylabel('') ax[i].set_xlabel('') ax[i].set_xticklabels((textwrap.fill(x.get_text(), width=11) for x in ax[i].get_xticklabels()), fontsize = 14) ax[i].set_yticks(np.arange(0, max(y)+1, 5)) ax[i].set_yticklabels(labels = ax[i].get_yticks(), fontsize =14) i += 1
Now we have a variety of books we can choose from depending on our preferred genre!
Of course, as mentioned earlier, it is possible to plot more than five books. This is just an illustration to show how it can be presented.
Finally, we can go further and look at our dataset from another angle.
An author can have multiple books, and if some books have racked up many likes, some authors may likewise have more fans than others.
In other words, letβs see βwho are the most recommended authorsβ:
#Grouping by 'recommender' and 'author' to get the unique values of #authors per each recommender: data = recommended_books.groupby(['recommender', 'author']).count().reset_index(level=1)#Plotting the 20 most recommended authors: plt.figure(figsize=[10,5])color_base = sb.color_palette()[0]sb.barplot(data['author'].value_counts().head(20).index, data['author'].value_counts().head(20).values, color=color_base)plt.xticks(rotation = 'vertical')plt.title('The Most Recommended Authors', fontweight = 'bold', size = 18)plt.xlabel('Authors', size = 15)plt.ylabel('Count', size = 15)
This is a groovy bar plot with many names that appeared earlier in the first plot.
However, the order is not the same, and some names are new.
In other words, even if some books are highly recommended, letβs not ignore the authors, as they are equally important.
Saying the recommendations from famous personalities are βthe best ones everβ is not what I aimed for. There are certainly many other astonishing books that are unnoticed (or havenβt been translated into English).
Recommendations simply create the social proof that drives our choices. The greater the number of reviews or recommendations a book has, the greater the number of people who will want to read it. And when these reviews or recommendations come from the most successful among us, social proof tends to increase. Recommendations are like a compass that shows us the right direction when we are lost.
1 Iβd like to thank Richard Reis and Anurag Ramdasan, co-founders of mostrecommendedbooks.com for allowing me to use their website as a main source of information.
2 Accessing public data through Google books API can be done even without the API key. Iβve tried with and without the key and it did work in both cases.
|
[
{
"code": null,
"e": 351,
"s": 172,
"text": "There are tons of books out there, but not all are worth reading. To quote the old Faber in Fahrenheit 451, the best books are the ones that βshow the pores in the face of life.β"
},
{
"code": null,
"e": 435,
"s": 351,
"text": "So, with an overwhelming number of books out there, how can you find the best ones?"
},
{
"code": null,
"e": 646,
"s": 435,
"text": "One way is to go to a dedicated book website (such as Amazon or Goodreads). They provide filtering tools to refine search results, and display usersβ reviews and average ratings to help narrow down the choices."
},
{
"code": null,
"e": 727,
"s": 646,
"text": "Alternatively, one could ask their friends or acquaintances for recommendations."
},
{
"code": null,
"e": 771,
"s": 727,
"text": "These two methods are undeniably effective."
},
{
"code": null,
"e": 944,
"s": 771,
"text": "But there is a third way to get great results: Look at the recommendations of well-known people who say the books they read played a significant role in their achievements."
},
{
"code": null,
"e": 1027,
"s": 944,
"text": "And this is where this amazing website, Mostrecommendedbooks.com, comes into play."
},
{
"code": null,
"e": 1169,
"s": 1027,
"text": "This website shows pretty much all the books recommended by βworld-class peopleβ. Compared to its peers, it is really way ahead of the curve."
},
{
"code": null,
"e": 1244,
"s": 1169,
"text": "So, I decided to retrieve all its book titles1, with two purposes in mind:"
},
{
"code": null,
"e": 1406,
"s": 1244,
"text": "Bring all these books together in one DataFrame for my fellow book lovers, andGet some insights into this valuable treasure using Python visualization libraries."
},
{
"code": null,
"e": 1485,
"s": 1406,
"text": "Bring all these books together in one DataFrame for my fellow book lovers, and"
},
{
"code": null,
"e": 1569,
"s": 1485,
"text": "Get some insights into this valuable treasure using Python visualization libraries."
},
{
"code": null,
"e": 1703,
"s": 1569,
"text": "I also used Google Books API to get the number of pages, the publication dates, and the categories. I chose Google Books API because:"
},
{
"code": null,
"e": 1772,
"s": 1703,
"text": "It offers a wide variety of information about a large pool of books."
},
{
"code": null,
"e": 1821,
"s": 1772,
"text": "The documentation is concise and easy to follow."
},
{
"code": null,
"e": 1886,
"s": 1821,
"text": "There are multiple query parameters (title, author, ISBN, etc.)."
},
{
"code": null,
"e": 2011,
"s": 1886,
"text": "Public data, like the one weβd like to access, doesnβt require authorization. You are only required to provide the API key2."
},
{
"code": null,
"e": 2132,
"s": 2011,
"text": "(The code for scraping data and building the dataset is available on my Github. The dataset can also be found in Kaggle)"
},
{
"code": null,
"e": 2205,
"s": 2132,
"text": "Before we get started, letβs import the Python libraries weβll be using."
},
{
"code": null,
"e": 2327,
"s": 2205,
"text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as sbimport textwrap%matplotlib inline"
},
{
"code": null,
"e": 2386,
"s": 2327,
"text": "books_df = pd.read_csv('books_clean.csv')books_df.head(10)"
},
{
"code": null,
"e": 2464,
"s": 2386,
"text": "And this is how our dataset looks like. Letβs see how many books we got here:"
},
{
"code": null,
"e": 2479,
"s": 2464,
"text": "books_df.shape"
},
{
"code": null,
"e": 2489,
"s": 2479,
"text": "(3003, 8)"
},
{
"code": null,
"e": 2531,
"s": 2489,
"text": "As you can see, we have 3003 book titles."
},
{
"code": null,
"e": 2643,
"s": 2531,
"text": "We also have other features such as number of recommendations, category, publication date, and number of pages."
},
{
"code": null,
"e": 2771,
"s": 2643,
"text": "For anyone who might be interested, I also made sure to include Google books IDs to facilitate data scraping of the same books."
},
{
"code": null,
"e": 2852,
"s": 2771,
"text": "Letβs start by plotting the distribution of the number of recommendations/ book:"
},
{
"code": null,
"e": 3103,
"s": 2852,
"text": "#Histogram:plt.figure(figsize=[10,5])plt.hist(data=books_df, x='num_recommendations')plt.title('Distribution of the number of recommendations per book', size=18, fontweight='bold')plt.xlabel('Recommendations', size=15)plt.ylabel('Frequency', size=15)"
},
{
"code": null,
"e": 3185,
"s": 3103,
"text": "The distribution is right-skewed and many books have less than 2 recommendations."
},
{
"code": null,
"e": 3243,
"s": 3185,
"text": "So, what are the most recommended books within this list?"
},
{
"code": null,
"e": 3405,
"s": 3243,
"text": "To answer this question, we cannot plot all 3003 books in descending order, as this will produce an unaesthetic chart that will not convey information concisely."
},
{
"code": null,
"e": 3544,
"s": 3405,
"text": "So, I will (arbitrarily) take the median of the βnum_recommendationsβ unique values as a minimum threshold for the most recommended books:"
},
{
"code": null,
"e": 4212,
"s": 3544,
"text": "#Fixing the threshold:threshold=np.median(books_df['num_recommendations'].value_counts().index)#Subset of the dataset based on the threshold:data=books_df.loc[books_df.num_recommendations >= threshold]#Combining titles and authors: data['title_y']=[','.join(i) for i in list(zip(data['title'],data['author']))]#Barplot: plt.figure(figsize = [5,10])color_base = sb.color_palette()[0]sb.barplot(data = data.sort_values(by = 'num_recommendations', ascending = False), x = 'recommender_count', y = 'title_y', color = color_base)plt.title('The Most Recommended Books', size = 18)plt.xlabel('Recommendations', fontweight = 'bold', size = 15)plt.ylabel('Titles', size = 15);"
},
{
"code": null,
"e": 4278,
"s": 4212,
"text": "Here, we have 22 books at the absolute pinnacle of our DataFrame."
},
{
"code": null,
"e": 4453,
"s": 4278,
"text": "As you can see, Manβs Search for Meaning (Victor Frankl) tops the list with more than 20 recommendations, followed by Sapiens (Yuval Harari) and then Principles by Ray Dalio."
},
{
"code": null,
"e": 4617,
"s": 4453,
"text": "However, it appears that this plot contains many business and self-help books. We can hardly see a fiction book, let alone philosophy or another specific category."
},
{
"code": null,
"e": 4793,
"s": 4617,
"text": "Digging deeper into the categories within the DataFrame will certainly refine our findings and bring forth meaningful information that would help choose the best books for us."
},
{
"code": null,
"e": 4877,
"s": 4793,
"text": "But first, we need to know the most frequently occurring categories in our dataset."
},
{
"code": null,
"e": 4934,
"s": 4877,
"text": "For the sake of simplicity, I will only plot the top 20:"
},
{
"code": null,
"e": 5361,
"s": 4934,
"text": "#Plotting the 20 most frequently occurring categories:plt.figure(figsize = [10,5])color_base = sb.color_palette()[0]sb.barplot(books_df.category.value_counts().head(20).index, books_df.category.value_counts().head(20).values, color=color_base)plt.xticks(rotation = 'vertical')plt.title('The Most Frequently Occurring Categories', fontweight = 'bold', size = 18)plt.xlabel('Categories', size = 15)plt.ylabel('Count', size = 15)"
},
{
"code": null,
"e": 5538,
"s": 5361,
"text": "Unsurprisingly, fiction and business books are the most popular with over 400 books in each of them. Biography books are the third in the list, followed by history and science."
},
{
"code": null,
"e": 5805,
"s": 5538,
"text": "Having many books in a given category doesnβt mean this category is the most recommended, nor that the books in said category are the most recommended of all. Thereβs no accounting for taste. Some people prefer fiction, while others are more interested in economics."
},
{
"code": null,
"e": 5906,
"s": 5805,
"text": "For this reason, it would be reasonable to see the distribution of recommendations in each category."
},
{
"code": null,
"e": 6022,
"s": 5906,
"text": "This will give us an idea about the outliers and will help us spot the most recommended books within each category:"
},
{
"code": null,
"e": 6469,
"s": 6022,
"text": "cat = books_df.category.value_counts().head(20).indexfig, ax = plt.subplots(figsize = [10,5])sb.swarmplot(data = books_df[books_df.category.isin(cat)], x = 'category', y = 'num_recommendations', palette = 'tab20')ax.set_xticklabels(ax.get_xticklabels(), rotation = 90)ax.set_title('Distribution of Recommendations by Category', fontweight = 'bold', size = 18)ax.set_xlabel('Categories', size = 15)ax.set_ylabel('Recommendations', fontsize = 15)"
},
{
"code": null,
"e": 6546,
"s": 6469,
"text": "We see that most categories have books within the 1β5 recommendations range."
},
{
"code": null,
"e": 6800,
"s": 6546,
"text": "Meanwhile, some categories have books recommended by more than 5 people, while others have books recommended by more than 10 people. Biography, business and economics, fiction, psychology, and self-help all have numerous books with many recommendations."
},
{
"code": null,
"e": 6858,
"s": 6800,
"text": "Now, letβs find out the must-read books in each category."
},
{
"code": null,
"e": 7054,
"s": 6858,
"text": "I will only consider 9 categories and plot the top 5 based on the number of recommendations. But please note it is possible to add more categories or widen the list of books using the code below:"
},
{
"code": null,
"e": 8334,
"s": 7054,
"text": "#Defining the categories:categories = books_df.category.value_counts().head(9).index.tolist()#Defining a function to select a subset of data:def selection(cat): data = books_df[books_df['category'] == cat].sort_values(by = 'num_recommendations', ascending = False).head() return datafig, ax = plt.subplots(nrows = 3, ncols = 3,figsize = [20,15])plt.suptitle('Top 5 Recommended Books in each Category', size = 30, y = 1.05, fontweight = 'bold')fig.tight_layout(h_pad = 8)fig.text(-0.02, 0.5, 'Recommendations', va = 'center', rotation='vertical', fontweight='bold', fontsize=25)fig.text(0.5, -0.06, 'Titles', va = 'center', ha = 'center', fontweight = 'bold', fontsize=25)ax = ax.flatten()color_base = sb.color_palette()[0]y = sorted(books_df['num_recommendations'].unique())i=0for cat in categories: sb.barplot(data = selection(cat), x='title', y = 'num_recommendations', ax = ax[i], color = color_base) ax[i].set_title(cat, fontweight = 'bold', fontsize = 18, color = 'crimson') ax[i].set_ylabel('') ax[i].set_xlabel('') ax[i].set_xticklabels((textwrap.fill(x.get_text(), width=11) for x in ax[i].get_xticklabels()), fontsize = 14) ax[i].set_yticks(np.arange(0, max(y)+1, 5)) ax[i].set_yticklabels(labels = ax[i].get_yticks(), fontsize =14) i += 1"
},
{
"code": null,
"e": 8418,
"s": 8334,
"text": "Now we have a variety of books we can choose from depending on our preferred genre!"
},
{
"code": null,
"e": 8558,
"s": 8418,
"text": "Of course, as mentioned earlier, it is possible to plot more than five books. This is just an illustration to show how it can be presented."
},
{
"code": null,
"e": 8629,
"s": 8558,
"text": "Finally, we can go further and look at our dataset from another angle."
},
{
"code": null,
"e": 8763,
"s": 8629,
"text": "An author can have multiple books, and if some books have racked up many likes, some authors may likewise have more fans than others."
},
{
"code": null,
"e": 8829,
"s": 8763,
"text": "In other words, letβs see βwho are the most recommended authorsβ:"
},
{
"code": null,
"e": 9409,
"s": 8829,
"text": "#Grouping by 'recommender' and 'author' to get the unique values of #authors per each recommender: data = recommended_books.groupby(['recommender', 'author']).count().reset_index(level=1)#Plotting the 20 most recommended authors: plt.figure(figsize=[10,5])color_base = sb.color_palette()[0]sb.barplot(data['author'].value_counts().head(20).index, data['author'].value_counts().head(20).values, color=color_base)plt.xticks(rotation = 'vertical')plt.title('The Most Recommended Authors', fontweight = 'bold', size = 18)plt.xlabel('Authors', size = 15)plt.ylabel('Count', size = 15)"
},
{
"code": null,
"e": 9492,
"s": 9409,
"text": "This is a groovy bar plot with many names that appeared earlier in the first plot."
},
{
"code": null,
"e": 9552,
"s": 9492,
"text": "However, the order is not the same, and some names are new."
},
{
"code": null,
"e": 9672,
"s": 9552,
"text": "In other words, even if some books are highly recommended, letβs not ignore the authors, as they are equally important."
},
{
"code": null,
"e": 9886,
"s": 9672,
"text": "Saying the recommendations from famous personalities are βthe best ones everβ is not what I aimed for. There are certainly many other astonishing books that are unnoticed (or havenβt been translated into English)."
},
{
"code": null,
"e": 10283,
"s": 9886,
"text": "Recommendations simply create the social proof that drives our choices. The greater the number of reviews or recommendations a book has, the greater the number of people who will want to read it. And when these reviews or recommendations come from the most successful among us, social proof tends to increase. Recommendations are like a compass that shows us the right direction when we are lost."
},
{
"code": null,
"e": 10447,
"s": 10283,
"text": "1 Iβd like to thank Richard Reis and Anurag Ramdasan, co-founders of mostrecommendedbooks.com for allowing me to use their website as a main source of information."
}
] |
The HttpSession Interface in Servlet - GeeksforGeeks
|
25 Apr, 2022
What is a session?
In web terminology, a session is simply the limited interval of time in which two systems communicate with each other. The two systems can share a client-server or a peer-to-peer relationship. However, in Http protocol, the state of the communication is not maintained. Hence, the web applications that work on http protocol use several different technologies that comprise Session Tracking, which means maintaining the state (data) of the user, in order to recognize him/her.
In order to achieve session tracking in servlets, cookies have been one of the most commonly used tech. However, they have the following disadvantages:
They can only keep textual information.
Theyβre browser dependent. Hence, if the client disables them, your web application canβt make use of them
Individual cookie can contain not more than 4kb of information
How to create sessions with a unique session id for each user in java servlet
For this, servlets provide an interface called βHttpSessionβ Interface. The following diagram explains how Http Sessions work in servlets:
Methods in HttpSession Interface
Advantages of Http Sessions in Servlet
Any kind of object can be stored into a session, be it a text, database, dataset etc.
Usage of sessions is not dependent on the clientβs browser.
Sessions are secure and transparent
Disadvantages of Http session
Performance overhead due to session object being stored on server
Overhead due to serialization and de-serialization of data
Example of Session tracking using HttpServlet Interface: In the below example the setAttribute() and getAttribute() methods of the HttpServlet class is used to create an attribute in the session scope of one servlet and fetch that attribute from the session scope of another servlet.
index.html<html><head><body><form action="servlet1"> Name:<input type="text" name="userName"/><br/> <input type="submit" value="submit"/> </form> </body></html>
<html><head><body><form action="servlet1"> Name:<input type="text" name="userName"/><br/> <input type="submit" value="submit"/> </form> </body></html>
First.java// The first servletimport java.io.*;import javax.servlet.*;import javax.servlet.http.*; < div class= "noIdeBtnDiv" > public class First extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { try { /*Declaration of the get method*/ response.setContentType("text/html"); // Setting the content type to text PrintWriter out = response.getWriter(); String n = request.getParameter("userName"); /*Fetching the contents of the userName field from the form*/ out.print("Welcome " + n); // Printing the username HttpSession session = request.getSession(); /* Creating a new session*/ session.setAttribute("uname", n); /*Setting a variable uname containing the value as the fetched username as an attribute of the session which will be shared among different servlets of the application*/ out.print("<a href='servlet2'>visit</a>"); // Link to the second servlet out.close(); } catch (Exception e) { System.out.println(e); } }}
// The first servletimport java.io.*;import javax.servlet.*;import javax.servlet.http.*; < div class= "noIdeBtnDiv" > public class First extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { try { /*Declaration of the get method*/ response.setContentType("text/html"); // Setting the content type to text PrintWriter out = response.getWriter(); String n = request.getParameter("userName"); /*Fetching the contents of the userName field from the form*/ out.print("Welcome " + n); // Printing the username HttpSession session = request.getSession(); /* Creating a new session*/ session.setAttribute("uname", n); /*Setting a variable uname containing the value as the fetched username as an attribute of the session which will be shared among different servlets of the application*/ out.print("<a href='servlet2'>visit</a>"); // Link to the second servlet out.close(); } catch (Exception e) { System.out.println(e); } }}
Second.java// The second servletimport java.io.*;import javax.servlet.*;import javax.servlet.http.*; public class SecondServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) try { /*Declaration of the get method*/ response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(false); /*Resuming the session created in the previous servlet using the same method that was used to create the session. The boolean parameter 'false' has been passed so that a new session is not created since the session already exists*/ String n = (String)session.getAttribute("uname"); out.print("Hello " + n); out.close(); } catch (Exception e) { System.out.println(e); }}}
// The second servletimport java.io.*;import javax.servlet.*;import javax.servlet.http.*; public class SecondServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) try { /*Declaration of the get method*/ response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(false); /*Resuming the session created in the previous servlet using the same method that was used to create the session. The boolean parameter 'false' has been passed so that a new session is not created since the session already exists*/ String n = (String)session.getAttribute("uname"); out.print("Hello " + n); out.close(); } catch (Exception e) { System.out.println(e); }}}
web.xml<web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>First</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <servlet> <servlet-name>s2</servlet-name> <servlet-class>Second</servlet-class> </servlet> <servlet-mapping> <servlet-name>s2</servlet-name> <url-pattern>/servlet2</url-pattern> </servlet-mapping> </web-app>
<web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>First</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <servlet> <servlet-name>s2</servlet-name> <servlet-class>Second</servlet-class> </servlet> <servlet-mapping> <servlet-name>s2</servlet-name> <url-pattern>/servlet2</url-pattern> </servlet-mapping> </web-app>
Output:
index.html :
Servlet1 :
Servlet2 :
advaithkrupanandh
java-servlet
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
Set in Java
Multithreading in Java
Collections in Java
Initializing a List in Java
Constructors in Java
Exceptions in Java
Queue Interface In Java
Functional Interfaces in Java
|
[
{
"code": null,
"e": 25624,
"s": 25596,
"text": "\n25 Apr, 2022"
},
{
"code": null,
"e": 25643,
"s": 25624,
"text": "What is a session?"
},
{
"code": null,
"e": 26120,
"s": 25643,
"text": "In web terminology, a session is simply the limited interval of time in which two systems communicate with each other. The two systems can share a client-server or a peer-to-peer relationship. However, in Http protocol, the state of the communication is not maintained. Hence, the web applications that work on http protocol use several different technologies that comprise Session Tracking, which means maintaining the state (data) of the user, in order to recognize him/her."
},
{
"code": null,
"e": 26272,
"s": 26120,
"text": "In order to achieve session tracking in servlets, cookies have been one of the most commonly used tech. However, they have the following disadvantages:"
},
{
"code": null,
"e": 26312,
"s": 26272,
"text": "They can only keep textual information."
},
{
"code": null,
"e": 26419,
"s": 26312,
"text": "Theyβre browser dependent. Hence, if the client disables them, your web application canβt make use of them"
},
{
"code": null,
"e": 26482,
"s": 26419,
"text": "Individual cookie can contain not more than 4kb of information"
},
{
"code": null,
"e": 26560,
"s": 26482,
"text": "How to create sessions with a unique session id for each user in java servlet"
},
{
"code": null,
"e": 26699,
"s": 26560,
"text": "For this, servlets provide an interface called βHttpSessionβ Interface. The following diagram explains how Http Sessions work in servlets:"
},
{
"code": null,
"e": 26732,
"s": 26699,
"text": "Methods in HttpSession Interface"
},
{
"code": null,
"e": 26771,
"s": 26732,
"text": "Advantages of Http Sessions in Servlet"
},
{
"code": null,
"e": 26857,
"s": 26771,
"text": "Any kind of object can be stored into a session, be it a text, database, dataset etc."
},
{
"code": null,
"e": 26917,
"s": 26857,
"text": "Usage of sessions is not dependent on the clientβs browser."
},
{
"code": null,
"e": 26953,
"s": 26917,
"text": "Sessions are secure and transparent"
},
{
"code": null,
"e": 26983,
"s": 26953,
"text": "Disadvantages of Http session"
},
{
"code": null,
"e": 27049,
"s": 26983,
"text": "Performance overhead due to session object being stored on server"
},
{
"code": null,
"e": 27108,
"s": 27049,
"text": "Overhead due to serialization and de-serialization of data"
},
{
"code": null,
"e": 27392,
"s": 27108,
"text": "Example of Session tracking using HttpServlet Interface: In the below example the setAttribute() and getAttribute() methods of the HttpServlet class is used to create an attribute in the session scope of one servlet and fetch that attribute from the session scope of another servlet."
},
{
"code": null,
"e": 27557,
"s": 27392,
"text": "index.html<html><head><body><form action=\"servlet1\"> Name:<input type=\"text\" name=\"userName\"/><br/> <input type=\"submit\" value=\"submit\"/> </form> </body></html>"
},
{
"code": "<html><head><body><form action=\"servlet1\"> Name:<input type=\"text\" name=\"userName\"/><br/> <input type=\"submit\" value=\"submit\"/> </form> </body></html>",
"e": 27712,
"s": 27557,
"text": null
},
{
"code": null,
"e": 29025,
"s": 27712,
"text": "First.java// The first servletimport java.io.*;import javax.servlet.*;import javax.servlet.http.*; < div class= \"noIdeBtnDiv\" > public class First extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { try { /*Declaration of the get method*/ response.setContentType(\"text/html\"); // Setting the content type to text PrintWriter out = response.getWriter(); String n = request.getParameter(\"userName\"); /*Fetching the contents of the userName field from the form*/ out.print(\"Welcome \" + n); // Printing the username HttpSession session = request.getSession(); /* Creating a new session*/ session.setAttribute(\"uname\", n); /*Setting a variable uname containing the value as the fetched username as an attribute of the session which will be shared among different servlets of the application*/ out.print(\"<a href='servlet2'>visit</a>\"); // Link to the second servlet out.close(); } catch (Exception e) { System.out.println(e); } }}"
},
{
"code": "// The first servletimport java.io.*;import javax.servlet.*;import javax.servlet.http.*; < div class= \"noIdeBtnDiv\" > public class First extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { try { /*Declaration of the get method*/ response.setContentType(\"text/html\"); // Setting the content type to text PrintWriter out = response.getWriter(); String n = request.getParameter(\"userName\"); /*Fetching the contents of the userName field from the form*/ out.print(\"Welcome \" + n); // Printing the username HttpSession session = request.getSession(); /* Creating a new session*/ session.setAttribute(\"uname\", n); /*Setting a variable uname containing the value as the fetched username as an attribute of the session which will be shared among different servlets of the application*/ out.print(\"<a href='servlet2'>visit</a>\"); // Link to the second servlet out.close(); } catch (Exception e) { System.out.println(e); } }}",
"e": 30328,
"s": 29025,
"text": null
},
{
"code": null,
"e": 31452,
"s": 30328,
"text": "Second.java// The second servletimport java.io.*;import javax.servlet.*;import javax.servlet.http.*; public class SecondServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) try { /*Declaration of the get method*/ response.setContentType(\"text/html\"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(false); /*Resuming the session created in the previous servlet using the same method that was used to create the session. The boolean parameter 'false' has been passed so that a new session is not created since the session already exists*/ String n = (String)session.getAttribute(\"uname\"); out.print(\"Hello \" + n); out.close(); } catch (Exception e) { System.out.println(e); }}}"
},
{
"code": "// The second servletimport java.io.*;import javax.servlet.*;import javax.servlet.http.*; public class SecondServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) try { /*Declaration of the get method*/ response.setContentType(\"text/html\"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(false); /*Resuming the session created in the previous servlet using the same method that was used to create the session. The boolean parameter 'false' has been passed so that a new session is not created since the session already exists*/ String n = (String)session.getAttribute(\"uname\"); out.print(\"Hello \" + n); out.close(); } catch (Exception e) { System.out.println(e); }}}",
"e": 32565,
"s": 31452,
"text": null
},
{
"code": null,
"e": 33025,
"s": 32565,
"text": "web.xml<web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>First</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <servlet> <servlet-name>s2</servlet-name> <servlet-class>Second</servlet-class> </servlet> <servlet-mapping> <servlet-name>s2</servlet-name> <url-pattern>/servlet2</url-pattern> </servlet-mapping> </web-app> "
},
{
"code": "<web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>First</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <servlet> <servlet-name>s2</servlet-name> <servlet-class>Second</servlet-class> </servlet> <servlet-mapping> <servlet-name>s2</servlet-name> <url-pattern>/servlet2</url-pattern> </servlet-mapping> </web-app> ",
"e": 33478,
"s": 33025,
"text": null
},
{
"code": null,
"e": 33486,
"s": 33478,
"text": "Output:"
},
{
"code": null,
"e": 33499,
"s": 33486,
"text": "index.html :"
},
{
"code": null,
"e": 33510,
"s": 33499,
"text": "Servlet1 :"
},
{
"code": null,
"e": 33521,
"s": 33510,
"text": "Servlet2 :"
},
{
"code": null,
"e": 33539,
"s": 33521,
"text": "advaithkrupanandh"
},
{
"code": null,
"e": 33552,
"s": 33539,
"text": "java-servlet"
},
{
"code": null,
"e": 33557,
"s": 33552,
"text": "Java"
},
{
"code": null,
"e": 33562,
"s": 33557,
"text": "Java"
},
{
"code": null,
"e": 33660,
"s": 33562,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33675,
"s": 33660,
"text": "Stream In Java"
},
{
"code": null,
"e": 33694,
"s": 33675,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 33706,
"s": 33694,
"text": "Set in Java"
},
{
"code": null,
"e": 33729,
"s": 33706,
"text": "Multithreading in Java"
},
{
"code": null,
"e": 33749,
"s": 33729,
"text": "Collections in Java"
},
{
"code": null,
"e": 33777,
"s": 33749,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 33798,
"s": 33777,
"text": "Constructors in Java"
},
{
"code": null,
"e": 33817,
"s": 33798,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 33841,
"s": 33817,
"text": "Queue Interface In Java"
}
] |
How to merge data frames by row names in R?
|
Mostly, we merge the data frames by columns because column names are considered prominent in data sets but it is also possible to merge two data frames by using rows. Merging by rows is likely to result in more uncleaned data as compared to the merging by columns. This can be done with the help of merge function and its by argument.
Consider the below data frames β
df1<-data.frame(x1=rnorm(10),x2=rpois(10,5))
df1
x1 x2
1 -0.47030794 0
2 0.86338465 8
3 -2.05770293 5
4 1.95479596 9
5 -0.06913421 5
6 0.64897263 5
7 -1.79859382 8
8 0.31247699 6
9 -0.36808285 7
10 -0.79578938 3
df2 <-data.frame(x1=rnorm(10,1.5))
df2
x1
1 -0.01317184
2 0.01687606
3 -0.71685289
4 1.75961121
5 2.49024285
6 2.92183374
7 0.10276216
8 1.39703966
9 1.41001339
10 0.98221783
df3 <-data.frame(x1=rnorm(5,0.5),x2=runif(5,2,3),x3=runif(5,2,5))
df3
x1 x2 x3
1 -0.4926244 2.697937 3.961118
2 1.9863263 2.861944 3.659564
3 -0.2266537 2.383499 3.208741
4 0.5966503 2.511485 3.230795
5 0.7148641 2.362419 4.582841
Merging df1 with df2, df1 with df3, and df2 with df3 β
df_1_2 <-merge(df1,df2,by='row.names',all=TRUE)
df_1_2
Row.names x1.x x2 x1.y
1 1 -0.47030794 0 -0.01317184
2 10 -0.79578938 3 0.98221783
3 2 0.86338465 8 0.01687606
4 3 -2.05770293 5 -0.71685289
5 4 1.95479596 9 1.75961121
6 5 -0.06913421 5 2.49024285
7 6 0.64897263 5 2.92183374
8 7 -1.79859382 8 0.10276216
9 8 0.31247699 6 1.39703966
10 9 -0.36808285 7 1.41001339
df_1_3 <-merge(df1,df3,by='row.names',all=TRUE)
df_1_3
Row.names x1.x x2.x x1.y x2.y x3
1 1 -0.47030794 0 -0.4926244 2.697937 3.961118
2 10 -0.79578938 3 NA NA NA
3 2 0.86338465 8 1.9863263 2.861944 3.659564
4 3 -2.05770293 5 -0.2266537 2.383499 3.208741
5 4 1.95479596 9 0.5966503 2.511485 3.230795
6 5 -0.06913421 5 0.7148641 2.362419 4.582841
7 6 0.64897263 5 NA NA NA
8 7 -1.79859382 8 NA NA NA
9 8 0.31247699 6 NA NA NA
10 9 -0.36808285 7 NA NA NA
df_2_3 <-merge(df2,df3,by='row.names',all=TRUE)
df_2_3
Row.names x1.x x1.y x2 x3
1 1 -0.01317184 -0.4926244 2.697937 3.961118
2 10 0.98221783 NA NA NA
3 2 0.01687606 1.9863263 2.861944 3.659564
4 3 -0.71685289 -0.2266537 2.383499 3.208741
5 4 1.75961121 0.5966503 2.511485 3.230795
6 5 2.49024285 0.7148641 2.362419 4.582841
7 6 2.92183374 NA NA NA
8 7 0.10276216 NA NA NA
9 8 1.39703966 NA NA NA
10 9 1.41001339 NA NA NA
|
[
{
"code": null,
"e": 1397,
"s": 1062,
"text": "Mostly, we merge the data frames by columns because column names are considered prominent in data sets but it is also possible to merge two data frames by using rows. Merging by rows is likely to result in more uncleaned data as compared to the merging by columns. This can be done with the help of merge function and its by argument."
},
{
"code": null,
"e": 1430,
"s": 1397,
"text": "Consider the below data frames β"
},
{
"code": null,
"e": 1479,
"s": 1430,
"text": "df1<-data.frame(x1=rnorm(10),x2=rpois(10,5))\ndf1"
},
{
"code": null,
"e": 1661,
"s": 1479,
"text": " x1 x2\n1 -0.47030794 0\n2 0.86338465 8\n3 -2.05770293 5\n4 1.95479596 9\n5 -0.06913421 5\n6 0.64897263 5\n7 -1.79859382 8\n8 0.31247699 6\n9 -0.36808285 7\n10 -0.79578938 3"
},
{
"code": null,
"e": 1700,
"s": 1661,
"text": "df2 <-data.frame(x1=rnorm(10,1.5))\ndf2"
},
{
"code": null,
"e": 1843,
"s": 1700,
"text": "x1\n1 -0.01317184\n2 0.01687606\n3 -0.71685289\n4 1.75961121\n5 2.49024285\n6 2.92183374\n7 0.10276216\n8 1.39703966\n9 1.41001339\n10 0.98221783"
},
{
"code": null,
"e": 1913,
"s": 1843,
"text": "df3 <-data.frame(x1=rnorm(5,0.5),x2=runif(5,2,3),x3=runif(5,2,5))\ndf3"
},
{
"code": null,
"e": 2095,
"s": 1913,
"text": " x1 x2 x3\n1 -0.4926244 2.697937 3.961118\n2 1.9863263 2.861944 3.659564\n3 -0.2266537 2.383499 3.208741\n4 0.5966503 2.511485 3.230795\n5 0.7148641 2.362419 4.582841"
},
{
"code": null,
"e": 2150,
"s": 2095,
"text": "Merging df1 with df2, df1 with df3, and df2 with df3 β"
},
{
"code": null,
"e": 2205,
"s": 2150,
"text": "df_1_2 <-merge(df1,df2,by='row.names',all=TRUE)\ndf_1_2"
},
{
"code": null,
"e": 2538,
"s": 2205,
"text": "Row.names x1.x x2 x1.y\n1 1 -0.47030794 0 -0.01317184\n2 10 -0.79578938 3 0.98221783\n3 2 0.86338465 8 0.01687606\n4 3 -2.05770293 5 -0.71685289\n5 4 1.95479596 9 1.75961121\n6 5 -0.06913421 5 2.49024285\n7 6 0.64897263 5 2.92183374\n8 7 -1.79859382 8 0.10276216\n9 8 0.31247699 6 1.39703966\n10 9 -0.36808285 7 1.41001339"
},
{
"code": null,
"e": 2593,
"s": 2538,
"text": "df_1_3 <-merge(df1,df3,by='row.names',all=TRUE)\ndf_1_3"
},
{
"code": null,
"e": 2991,
"s": 2593,
"text": "Row.names x1.x x2.x x1.y x2.y x3\n1 1 -0.47030794 0 -0.4926244 2.697937 3.961118\n2 10 -0.79578938 3 NA NA NA\n3 2 0.86338465 8 1.9863263 2.861944 3.659564\n4 3 -2.05770293 5 -0.2266537 2.383499 3.208741\n5 4 1.95479596 9 0.5966503 2.511485 3.230795\n6 5 -0.06913421 5 0.7148641 2.362419 4.582841\n7 6 0.64897263 5 NA NA NA\n8 7 -1.79859382 8 NA NA NA\n9 8 0.31247699 6 NA NA NA\n10 9 -0.36808285 7 NA NA NA"
},
{
"code": null,
"e": 3046,
"s": 2991,
"text": "df_2_3 <-merge(df2,df3,by='row.names',all=TRUE)\ndf_2_3"
},
{
"code": null,
"e": 3413,
"s": 3046,
"text": "Row.names x1.x x1.y x2 x3\n1 1 -0.01317184 -0.4926244 2.697937 3.961118\n2 10 0.98221783 NA NA NA\n3 2 0.01687606 1.9863263 2.861944 3.659564\n4 3 -0.71685289 -0.2266537 2.383499 3.208741\n5 4 1.75961121 0.5966503 2.511485 3.230795\n6 5 2.49024285 0.7148641 2.362419 4.582841\n7 6 2.92183374 NA NA NA\n8 7 0.10276216 NA NA NA\n9 8 1.39703966 NA NA NA\n10 9 1.41001339 NA NA NA"
}
] |
Check if two strings have a common substring - GeeksforGeeks
|
19 Apr, 2022
You are given two strings str1 and str2. You have to check if the two strings share a common substring.Examples :
Input : str1 = "HELLO"
str2 = "WORLD"
Output : YES
Explanation : The substrings "O" and
"L" are common to both str1 and str2
Input : str1 = "HI"
str2 = "ALL"
Output : NO
Explanation : Because str1 and str2
have no common substrings
A basic approach runs in O(n^2), where we compare every character of string 1 with every character of string 2 and replace every matched character with a β_β and set flag variable as true.An efficient approach works in O(n). We basically need to check if there is a common character or not. We create a vector of size 26 for alphabets and initialize them as 0. For every character in string 1 we increment vector index of that character eg: v[s1[i]-βaβ]++, for every character of string 2 we check vector for the common characters if v[s2[i]-βaβ] > 0 then set flag = true and v[s2[i]-βaβ]β such that one character of string 2 is compared with only one character of string 1.
C++
Java
C#
Javascript
// CPP program to check if two strings have// common substring#include <bits/stdc++.h>using namespace std; const int MAX_CHAR = 26; // function to return true if strings have// common substring and no if strings have// no common substringbool twoStrings(string s1, string s2) { // vector for storing character occurrences vector<bool> v(MAX_CHAR, 0); // increment vector index for every // character of str1 for (int i = 0; i < s1.length(); i++) v[s1[i] - 'a'] = true; // checking common substring of str2 in str1 for (int i = 0; i < s2.length(); i++) if (v[s2[i] - 'a']) return true; return false; } // driver programint main() { string str1 = "hello"; string str2 = "world"; if (twoStrings(str1, str2)) cout << "Yes"; else cout << "No"; return 0;}
// Java program to check if two strings have// common substringimport java.util.Arrays; class GFG{ static int MAX_CHAR = 26; // function to return true if strings have // common substring and no if strings have // no common substring static boolean twoStrings(String s1, String s2) { // vector for storing character occurrences boolean v[]=new boolean[MAX_CHAR]; Arrays.fill(v,false); // increment vector index for every // character of str1 for (int i = 0; i < s1.length(); i++) v[s1.charAt(i) - 'a'] = true; // checking common substring of str2 in str1 for (int i = 0; i < s2.length(); i++) if (v[s2.charAt(i) - 'a']) return true; return false; } // Driver code public static void main (String[] args) { String str1 = "hello"; String str2 = "world"; if (twoStrings(str1, str2)) System.out.print("Yes"); else System.out.print("No"); }} // This code is contributed by Anant Agarwal.
Python 3
# Python 3 program to check if two
# strings have common substring
MAX_CHAR = 26
# function to return true if
# strings have common substring
# and no if strings have no
# common substring
def twoStrings(s1, s2) :
# vector for storing character
# occurrences
v = [0] * (MAX_CHAR)
# increment vector index for every
# character of str1
for i in range(len(s1)):
v[ord(s1[i]) - ord('a')] = True
# checking common substring
# of str2 in str1
for i in range(len(s2)) :
if (v[ord(s2[i]) - ord('a')]) :
return True
return False
# Driver Code
if __name__ == "__main__":
str1 = "hello"
str2 = "world"
if (twoStrings(str1, str2)):
print("Yes")
else:
print("No")
# This code is contributed
# by ChitraNayal
// C# program to check if two// strings have common substringusing System; class GFG{ static int MAX_CHAR = 26; // function to return true if strings have // common substring and no if strings have // no common substring static bool twoStrings(String s1, String s2) { // vector for storing character occurrences bool []v = new bool[MAX_CHAR]; // Arrays.fill(v,false); for(int i = 0; i < MAX_CHAR; i++) v[i]=false; // increment vector index for // every character of str1 for (int i = 0; i < s1.Length; i++) v[s1[i] - 'a'] = true; // checking common substring of str2 in str1 for (int i = 0; i < s2.Length; i++) if (v[s2[i] - 'a']) return true; return false; } // Driver code public static void Main () { String str1 = "hello"; String str2 = "world"; if (twoStrings(str1, str2)) Console.Write("Yes"); else Console.Write("No"); }} // This code is contributed by nitin mittal.
<script> // javascript program to check if two strings have// common substring var MAX_CHAR = 26; // function to return true if strings have// common substring and no if strings have// no common substringfunction twoStrings(s1, s2) { // vector for storing character occurrences var v = Array(MAX_CHAR).fill(0); // increment vector index for every // character of str1 for (var i = 0; i < s1.length; i++) v[s1[i] - 'a'] = true; // checking common substring of str2 in str1 for (var i = 0; i < s2.length; i++) if (v[s2[i] - 'a']) return true; return false; } // driver programvar str1 = "hello";var str2 = "world";if (twoStrings(str1, str2)) document.write( "Yes");else document.write("No"); // This code is contributed by rutvik_56.</script>
Output :
Yes
Time Complexity : O(n)
YouTubeGeeksforGeeks507K subscribersCheck if two strings have a common substring | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:07β’Liveβ’<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=ZdRMhgCuk3k" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
nitin mittal
ukasp
rutvik_56
sagartomar9927
cpp-vector
frequency-counting
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Array of Strings in C++ (5 Different Ways to Create)
Different methods to reverse a string in C/C++
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Check whether two strings are anagram of each other
Top 50 String Coding Problems for Interviews
|
[
{
"code": null,
"e": 26150,
"s": 26122,
"text": "\n19 Apr, 2022"
},
{
"code": null,
"e": 26266,
"s": 26150,
"text": "You are given two strings str1 and str2. You have to check if the two strings share a common substring.Examples : "
},
{
"code": null,
"e": 26517,
"s": 26266,
"text": "Input : str1 = \"HELLO\"\n str2 = \"WORLD\"\nOutput : YES\nExplanation : The substrings \"O\" and\n\"L\" are common to both str1 and str2\n\nInput : str1 = \"HI\"\n str2 = \"ALL\"\nOutput : NO\nExplanation : Because str1 and str2 \nhave no common substrings"
},
{
"code": null,
"e": 27195,
"s": 26519,
"text": "A basic approach runs in O(n^2), where we compare every character of string 1 with every character of string 2 and replace every matched character with a β_β and set flag variable as true.An efficient approach works in O(n). We basically need to check if there is a common character or not. We create a vector of size 26 for alphabets and initialize them as 0. For every character in string 1 we increment vector index of that character eg: v[s1[i]-βaβ]++, for every character of string 2 we check vector for the common characters if v[s2[i]-βaβ] > 0 then set flag = true and v[s2[i]-βaβ]β such that one character of string 2 is compared with only one character of string 1. "
},
{
"code": null,
"e": 27199,
"s": 27195,
"text": "C++"
},
{
"code": null,
"e": 27204,
"s": 27199,
"text": "Java"
},
{
"code": null,
"e": 27207,
"s": 27204,
"text": "C#"
},
{
"code": null,
"e": 27218,
"s": 27207,
"text": "Javascript"
},
{
"code": "// CPP program to check if two strings have// common substring#include <bits/stdc++.h>using namespace std; const int MAX_CHAR = 26; // function to return true if strings have// common substring and no if strings have// no common substringbool twoStrings(string s1, string s2) { // vector for storing character occurrences vector<bool> v(MAX_CHAR, 0); // increment vector index for every // character of str1 for (int i = 0; i < s1.length(); i++) v[s1[i] - 'a'] = true; // checking common substring of str2 in str1 for (int i = 0; i < s2.length(); i++) if (v[s2[i] - 'a']) return true; return false; } // driver programint main() { string str1 = \"hello\"; string str2 = \"world\"; if (twoStrings(str1, str2)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 28012,
"s": 27218,
"text": null
},
{
"code": "// Java program to check if two strings have// common substringimport java.util.Arrays; class GFG{ static int MAX_CHAR = 26; // function to return true if strings have // common substring and no if strings have // no common substring static boolean twoStrings(String s1, String s2) { // vector for storing character occurrences boolean v[]=new boolean[MAX_CHAR]; Arrays.fill(v,false); // increment vector index for every // character of str1 for (int i = 0; i < s1.length(); i++) v[s1.charAt(i) - 'a'] = true; // checking common substring of str2 in str1 for (int i = 0; i < s2.length(); i++) if (v[s2.charAt(i) - 'a']) return true; return false; } // Driver code public static void main (String[] args) { String str1 = \"hello\"; String str2 = \"world\"; if (twoStrings(str1, str2)) System.out.print(\"Yes\"); else System.out.print(\"No\"); }} // This code is contributed by Anant Agarwal.",
"e": 29111,
"s": 28012,
"text": null
},
{
"code": null,
"e": 29121,
"s": 29111,
"text": "Python 3 "
},
{
"code": null,
"e": 29944,
"s": 29121,
"text": "\n# Python 3 program to check if two \n# strings have common substring\nMAX_CHAR = 26\n\n# function to return true if \n# strings have common substring \n# and no if strings have no\n# common substring\ndef twoStrings(s1, s2) :\n\n # vector for storing character\n # occurrences\n v = [0] * (MAX_CHAR)\n \n # increment vector index for every\n # character of str1\n for i in range(len(s1)):\n v[ord(s1[i]) - ord('a')] = True\n \n # checking common substring \n # of str2 in str1\n for i in range(len(s2)) :\n if (v[ord(s2[i]) - ord('a')]) :\n return True\n \n return False\n\n# Driver Code\nif __name__ == \"__main__\":\n str1 = \"hello\"\n str2 = \"world\"\n if (twoStrings(str1, str2)):\n print(\"Yes\")\n else:\n print(\"No\")\n\n# This code is contributed \n# by ChitraNayal\n\n"
},
{
"code": "// C# program to check if two// strings have common substringusing System; class GFG{ static int MAX_CHAR = 26; // function to return true if strings have // common substring and no if strings have // no common substring static bool twoStrings(String s1, String s2) { // vector for storing character occurrences bool []v = new bool[MAX_CHAR]; // Arrays.fill(v,false); for(int i = 0; i < MAX_CHAR; i++) v[i]=false; // increment vector index for // every character of str1 for (int i = 0; i < s1.Length; i++) v[s1[i] - 'a'] = true; // checking common substring of str2 in str1 for (int i = 0; i < s2.Length; i++) if (v[s2[i] - 'a']) return true; return false; } // Driver code public static void Main () { String str1 = \"hello\"; String str2 = \"world\"; if (twoStrings(str1, str2)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }} // This code is contributed by nitin mittal.",
"e": 31045,
"s": 29944,
"text": null
},
{
"code": "<script> // javascript program to check if two strings have// common substring var MAX_CHAR = 26; // function to return true if strings have// common substring and no if strings have// no common substringfunction twoStrings(s1, s2) { // vector for storing character occurrences var v = Array(MAX_CHAR).fill(0); // increment vector index for every // character of str1 for (var i = 0; i < s1.length; i++) v[s1[i] - 'a'] = true; // checking common substring of str2 in str1 for (var i = 0; i < s2.length; i++) if (v[s2[i] - 'a']) return true; return false; } // driver programvar str1 = \"hello\";var str2 = \"world\";if (twoStrings(str1, str2)) document.write( \"Yes\");else document.write(\"No\"); // This code is contributed by rutvik_56.</script>",
"e": 31821,
"s": 31045,
"text": null
},
{
"code": null,
"e": 31832,
"s": 31821,
"text": "Output : "
},
{
"code": null,
"e": 31836,
"s": 31832,
"text": "Yes"
},
{
"code": null,
"e": 31861,
"s": 31836,
"text": "Time Complexity : O(n) "
},
{
"code": null,
"e": 32704,
"s": 31861,
"text": "YouTubeGeeksforGeeks507K subscribersCheck if two strings have a common substring | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:07β’Liveβ’<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=ZdRMhgCuk3k\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 32719,
"s": 32706,
"text": "nitin mittal"
},
{
"code": null,
"e": 32725,
"s": 32719,
"text": "ukasp"
},
{
"code": null,
"e": 32735,
"s": 32725,
"text": "rutvik_56"
},
{
"code": null,
"e": 32750,
"s": 32735,
"text": "sagartomar9927"
},
{
"code": null,
"e": 32761,
"s": 32750,
"text": "cpp-vector"
},
{
"code": null,
"e": 32780,
"s": 32761,
"text": "frequency-counting"
},
{
"code": null,
"e": 32788,
"s": 32780,
"text": "Strings"
},
{
"code": null,
"e": 32796,
"s": 32788,
"text": "Strings"
},
{
"code": null,
"e": 32894,
"s": 32796,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32969,
"s": 32894,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 33026,
"s": 32969,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 33062,
"s": 33026,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 33115,
"s": 33062,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 33162,
"s": 33115,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 33198,
"s": 33162,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 33236,
"s": 33198,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 33266,
"s": 33236,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 33318,
"s": 33266,
"text": "Check whether two strings are anagram of each other"
}
] |
which() Function in R - GeeksforGeeks
|
23 Aug, 2021
which() function in R Programming Language is used to return the position of the specified values in the logical vector.
Syntax: which(x, arr.ind, useNames)
Parameters: This function accepts some parameters which are illustrated below:
X: This is the specified input logical vector
Arr.ind: This parameter returns the array indices if x is an array.
useNames: This parameter says the dimension names of an array.
Return value: This function returns the position of the specified values in the logical vector.
In the below example, which() function returns the alphabetical position of the specified letter. For example, a is the first letter in the alphabet sequence thatβs why 1 is returned and z is the last letter in the sequence so 26 is returned.
R
# R program to illustrate# which() function # Calling the which function# to return alphabetical position# of the given alphabetwhich(letters == "a")which(letters == "d")which(letters == "z")which(letters == "p")which(letters == "g")
Output :
[1] 1
[1] 4
[1] 26
[1] 16
[1] 7
In the below example, the position of some elements of the specified vector is being returned which the help of which() function.
R
# R program to illustrate# which() function # Creating a vector of some elementsvector <- c(3, 5, 1, 6, 12, 4) # Getting the position of element 12# in the above vectorwhich(vector == 12) # Getting the position of element 1# in the above vectorwhich(vector == 1) # Getting the position of element 6# in the above vectorwhich(vector == 6) # Getting the position of elements# those are greater than 5which(vector > 5)
Output:
[1] 5
[1] 3
[1] 4
[1] 4 5
In the below example, which() function is used to find the columns in a data frame with numeric values.
An Iris data set is used as a data frame that contains 4 columns for numerical values and 1 column for categorical values i.e., Species. The which() function find the columns name from the data set that contain numeric values.
R
# Considering βIrisβ datasetdata_set <- datasets::iris # Printing the Iris dataset values# along with its 5 columns out of which# 4 columns are numerical and 1 is categorical# (Species)head(data_set) # Calling the which() function over# the above specified data set that # returns the columns with numeric valuesResult <- which(sapply(data_set, is.numeric)) # Printing the columns with numeric valuescolnames(data_set)[Result]
Output:
In the below example, which() function is used to find the position of an element in the specified matrix.
Here the position of value 2 in the specified matrix is being calculated.
R
# Creating a matrix of 3 columns and 4 rowsMatrix <- matrix(rep(c(1, 2, 3), 4), nrow = 4) # Printing the entire matrix with its valuesMatrix # Calling the which() function to find the # position of value 2 in the above matrixwhich(Matrix == 2, arr.ind = T)
Output:
Picked
R-Functions
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to Change Axis Scales in R Plots?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
R - if statement
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
|
[
{
"code": null,
"e": 26597,
"s": 26569,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 26718,
"s": 26597,
"text": "which() function in R Programming Language is used to return the position of the specified values in the logical vector."
},
{
"code": null,
"e": 26754,
"s": 26718,
"text": "Syntax: which(x, arr.ind, useNames)"
},
{
"code": null,
"e": 26833,
"s": 26754,
"text": "Parameters: This function accepts some parameters which are illustrated below:"
},
{
"code": null,
"e": 26879,
"s": 26833,
"text": "X: This is the specified input logical vector"
},
{
"code": null,
"e": 26947,
"s": 26879,
"text": "Arr.ind: This parameter returns the array indices if x is an array."
},
{
"code": null,
"e": 27010,
"s": 26947,
"text": "useNames: This parameter says the dimension names of an array."
},
{
"code": null,
"e": 27106,
"s": 27010,
"text": "Return value: This function returns the position of the specified values in the logical vector."
},
{
"code": null,
"e": 27349,
"s": 27106,
"text": "In the below example, which() function returns the alphabetical position of the specified letter. For example, a is the first letter in the alphabet sequence thatβs why 1 is returned and z is the last letter in the sequence so 26 is returned."
},
{
"code": null,
"e": 27351,
"s": 27349,
"text": "R"
},
{
"code": "# R program to illustrate# which() function # Calling the which function# to return alphabetical position# of the given alphabetwhich(letters == \"a\")which(letters == \"d\")which(letters == \"z\")which(letters == \"p\")which(letters == \"g\")",
"e": 27586,
"s": 27351,
"text": null
},
{
"code": null,
"e": 27595,
"s": 27586,
"text": "Output :"
},
{
"code": null,
"e": 27627,
"s": 27595,
"text": "[1] 1\n[1] 4\n[1] 26\n[1] 16\n[1] 7"
},
{
"code": null,
"e": 27757,
"s": 27627,
"text": "In the below example, the position of some elements of the specified vector is being returned which the help of which() function."
},
{
"code": null,
"e": 27759,
"s": 27757,
"text": "R"
},
{
"code": "# R program to illustrate# which() function # Creating a vector of some elementsvector <- c(3, 5, 1, 6, 12, 4) # Getting the position of element 12# in the above vectorwhich(vector == 12) # Getting the position of element 1# in the above vectorwhich(vector == 1) # Getting the position of element 6# in the above vectorwhich(vector == 6) # Getting the position of elements# those are greater than 5which(vector > 5)",
"e": 28180,
"s": 27759,
"text": null
},
{
"code": null,
"e": 28188,
"s": 28180,
"text": "Output:"
},
{
"code": null,
"e": 28214,
"s": 28188,
"text": "[1] 5\n[1] 3\n[1] 4\n[1] 4 5"
},
{
"code": null,
"e": 28319,
"s": 28214,
"text": " In the below example, which() function is used to find the columns in a data frame with numeric values."
},
{
"code": null,
"e": 28546,
"s": 28319,
"text": "An Iris data set is used as a data frame that contains 4 columns for numerical values and 1 column for categorical values i.e., Species. The which() function find the columns name from the data set that contain numeric values."
},
{
"code": null,
"e": 28548,
"s": 28546,
"text": "R"
},
{
"code": "# Considering βIrisβ datasetdata_set <- datasets::iris # Printing the Iris dataset values# along with its 5 columns out of which# 4 columns are numerical and 1 is categorical# (Species)head(data_set) # Calling the which() function over# the above specified data set that # returns the columns with numeric valuesResult <- which(sapply(data_set, is.numeric)) # Printing the columns with numeric valuescolnames(data_set)[Result]",
"e": 28978,
"s": 28548,
"text": null
},
{
"code": null,
"e": 28986,
"s": 28978,
"text": "Output:"
},
{
"code": null,
"e": 29093,
"s": 28986,
"text": "In the below example, which() function is used to find the position of an element in the specified matrix."
},
{
"code": null,
"e": 29167,
"s": 29093,
"text": "Here the position of value 2 in the specified matrix is being calculated."
},
{
"code": null,
"e": 29169,
"s": 29167,
"text": "R"
},
{
"code": "# Creating a matrix of 3 columns and 4 rowsMatrix <- matrix(rep(c(1, 2, 3), 4), nrow = 4) # Printing the entire matrix with its valuesMatrix # Calling the which() function to find the # position of value 2 in the above matrixwhich(Matrix == 2, arr.ind = T)",
"e": 29428,
"s": 29169,
"text": null
},
{
"code": null,
"e": 29436,
"s": 29428,
"text": "Output:"
},
{
"code": null,
"e": 29443,
"s": 29436,
"text": "Picked"
},
{
"code": null,
"e": 29455,
"s": 29443,
"text": "R-Functions"
},
{
"code": null,
"e": 29466,
"s": 29455,
"text": "R Language"
},
{
"code": null,
"e": 29564,
"s": 29466,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29616,
"s": 29564,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 29651,
"s": 29616,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 29709,
"s": 29651,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 29747,
"s": 29709,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 29790,
"s": 29747,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 29840,
"s": 29790,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 29857,
"s": 29840,
"text": "R - if statement"
},
{
"code": null,
"e": 29906,
"s": 29857,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 29943,
"s": 29906,
"text": "How to import an Excel File into R ?"
}
] |
Display three letter-month value with SimpleDateFormat('MMM') in Java
|
Using the SimpleDateFormat(βMMMβ) to display three-letter month β
Format f = new SimpleDateFormat("MMM");
String strMonth = f.format(new Date());
System.out.println("Month (Three-letter format) = "+strMonth);
Since, we have used the Format and SimpleDateFormat class above, therefore import the following packages. With that, we have also used the Date β
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
The following is an example β
Live Demo
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
public class Demo {
public static void main(String[] args) throws Exception {
// displaying current date and time
Calendar cal = Calendar.getInstance();
SimpleDateFormat simpleformat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
System.out.println("Today's date and time = "+simpleformat.format(cal.getTime()));
// displaying date
Format f = new SimpleDateFormat("dd/MMMM/yyyy");
String strDate = f.format(new Date());
System.out.println("Current Date = "+strDate);
// displaying year
f = new SimpleDateFormat("yyyy");
String strYear = f.format(new Date());
System.out.println("Year = "+strYear);
// displaying three-letter month
f = new SimpleDateFormat("MMM");
String strMonth = f.format(new Date());
System.out.println("Month (Three-letter format) = "+strMonth);
// current time
f = new SimpleDateFormat("HH.mm.ss Z");
String strTime = f.format(new Date());
System.out.println("Current Time = "+strTime);
// displaying hour
f = new SimpleDateFormat("H");
String strHour = f.format(new Date());
System.out.println("Current Hour = "+strHour);
// displaying minutes
f = new SimpleDateFormat("mm");
String strMinute = f.format(new Date());
System.out.println("Current Minutes = "+strMinute);
// displaying seconds
f = new SimpleDateFormat("ss");
String strSeconds = f.format(new Date());
System.out.println("Current Seconds = "+strSeconds);
}
}
Today's date and time = Mon, 26 Nov 2018 09:29:58 +0000
Current Date = 26/November/2018
Year = 2018
Month (Three-letter format) = Nov
Current Time = 09.29.58 +0000
Current Hour = 9
Current Minutes = 29
Current Seconds = 58
|
[
{
"code": null,
"e": 1128,
"s": 1062,
"text": "Using the SimpleDateFormat(βMMMβ) to display three-letter month β"
},
{
"code": null,
"e": 1271,
"s": 1128,
"text": "Format f = new SimpleDateFormat(\"MMM\");\nString strMonth = f.format(new Date());\nSystem.out.println(\"Month (Three-letter format) = \"+strMonth);"
},
{
"code": null,
"e": 1417,
"s": 1271,
"text": "Since, we have used the Format and SimpleDateFormat class above, therefore import the following packages. With that, we have also used the Date β"
},
{
"code": null,
"e": 1500,
"s": 1417,
"text": "import java.text.Format;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;"
},
{
"code": null,
"e": 1530,
"s": 1500,
"text": "The following is an example β"
},
{
"code": null,
"e": 1541,
"s": 1530,
"text": " Live Demo"
},
{
"code": null,
"e": 3200,
"s": 1541,
"text": "import java.text.Format;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.Calendar;\npublic class Demo {\n public static void main(String[] args) throws Exception {\n // displaying current date and time\n Calendar cal = Calendar.getInstance();\n SimpleDateFormat simpleformat = new SimpleDateFormat(\"E, dd MMM yyyy HH:mm:ss Z\");\n System.out.println(\"Today's date and time = \"+simpleformat.format(cal.getTime()));\n // displaying date\n Format f = new SimpleDateFormat(\"dd/MMMM/yyyy\");\n String strDate = f.format(new Date());\n System.out.println(\"Current Date = \"+strDate);\n // displaying year\n f = new SimpleDateFormat(\"yyyy\");\n String strYear = f.format(new Date());\n System.out.println(\"Year = \"+strYear);\n // displaying three-letter month\n f = new SimpleDateFormat(\"MMM\");\n String strMonth = f.format(new Date());\n System.out.println(\"Month (Three-letter format) = \"+strMonth);\n // current time\n f = new SimpleDateFormat(\"HH.mm.ss Z\");\n String strTime = f.format(new Date());\n System.out.println(\"Current Time = \"+strTime);\n // displaying hour\n f = new SimpleDateFormat(\"H\");\n String strHour = f.format(new Date());\n System.out.println(\"Current Hour = \"+strHour);\n // displaying minutes\n f = new SimpleDateFormat(\"mm\");\n String strMinute = f.format(new Date());\n System.out.println(\"Current Minutes = \"+strMinute);\n // displaying seconds\n f = new SimpleDateFormat(\"ss\");\n String strSeconds = f.format(new Date());\n System.out.println(\"Current Seconds = \"+strSeconds);\n }\n}"
},
{
"code": null,
"e": 3423,
"s": 3200,
"text": "Today's date and time = Mon, 26 Nov 2018 09:29:58 +0000\nCurrent Date = 26/November/2018\nYear = 2018\nMonth (Three-letter format) = Nov\nCurrent Time = 09.29.58 +0000\nCurrent Hour = 9\nCurrent Minutes = 29\nCurrent Seconds = 58"
}
] |
Why is NullPointerException in Java?
|
NullPointerException is a runtime exception and it is thrown when the application try to use an object reference which has a null value.
For example, using a method on a null reference.
Object ref = null;
ref.toString(); // this will throw a NullPointerException
|
[
{
"code": null,
"e": 1199,
"s": 1062,
"text": "NullPointerException is a runtime exception and it is thrown when the application try to use an object reference which has a null value."
},
{
"code": null,
"e": 1248,
"s": 1199,
"text": "For example, using a method on a null reference."
},
{
"code": null,
"e": 1325,
"s": 1248,
"text": "Object ref = null;\nref.toString(); // this will throw a NullPointerException"
}
] |
Z algorithm (Linear time pattern searching Algorithm)
|
15 Jun, 2022
This algorithm finds all occurrences of a pattern in a text in linear time. Let length of text be n and of pattern be m, then total time taken is O(m + n) with linear space complexity. Now we can see that both time and space complexity is same as KMP algorithm but this algorithm is Simpler to understand.In this algorithm, we construct a Z array.
What is Z Array? For a string str[0..n-1], Z array is of same length as string. An element Z[i] of Z array stores length of the longest substring starting from str[i] which is also a prefix of str[0..n-1]. The first entry of Z array is meaning less as complete string is always prefix of itself.
Example:
Index 0 1 2 3 4 5 6 7 8 9 10 11
Text a a b c a a b x a a a z
Z values X 1 0 0 3 1 0 0 2 2 1 0
More Examples:
str = "aaaaaa"
Z[] = {x, 5, 4, 3, 2, 1}
str = "aabaacd"
Z[] = {x, 1, 0, 2, 1, 0, 0}
str = "abababab"
Z[] = {x, 0, 6, 0, 4, 0, 2, 0}
How is Z array helpful in Searching Pattern in Linear time? The idea is to concatenate pattern and text, and create a string βP$Tβ where P is pattern, $ is a special character should not be present in pattern and text, and T is text. Build the Z array for concatenated string. In Z array, if Z value at any point is equal to pattern length, then pattern is present at that point.
Example:
Pattern P = "aab", Text T = "baabaa"
The concatenated string is = "aab$baabaa"
Z array for above concatenated string is {x, 1, 0, 0, 0,
3, 1, 0, 2, 1}.
Since length of pattern is 3, the value 3 in Z array
indicates presence of pattern.
How to construct Z array? A Simple Solution is to run two nested loops, the outer loop goes to every index and the inner loop finds length of the longest prefix that matches the substring starting at the current index. The time complexity of this solution is O(n2). We can construct Z array in linear time.
The idea is to maintain an interval [L, R] which is the interval with max R
such that [L,R] is prefix substring (substring which is also prefix).
Steps for maintaining this interval are as follows β
1) If i > R then there is no prefix substring that starts before i and
ends after i, so we reset L and R and compute new [L,R] by comparing
str[0..] to str[i..] and get Z[i] (= R-L+1).
2) If i <= R then let K = i-L, now Z[i] >= min(Z[K], R-i+1) because
str[i..] matches with str[K..] for atleast R-i+1 characters (they are in
[L,R] interval which we know is a prefix substring).
Now two sub cases arise β
a) If Z[K] < R-i+1 then there is no prefix substring starting at
str[i] (otherwise Z[K] would be larger) so Z[i] = Z[K] and
interval [L,R] remains same.
b) If Z[K] >= R-i+1 then it is possible to extend the [L,R] interval
thus we will set L as i and start matching from str[R] onwards and
get new R then we will update interval [L,R] and calculate Z[i] (=R-L+1).
For better understanding of above step by step procedure please check this animation β http://www.utdallas.edu/~besp/demo/John2010/z-algorithm.htmThe algorithm runs in linear time because we never compare character less than R and with matching we increase R by one so there are at most T comparisons. In mismatch case, mismatch happen only once for each i (because of which R stops), thatβs another at most T comparison making overall linear complexity.
Below is the implementation of Z algorithm for pattern searching.
C++
Java
Python3
C#
Javascript
// A C++ program that implements Z algorithm for pattern searching#include<iostream>using namespace std; void getZarr(string str, int Z[]); // prints all occurrences of pattern in text using Z algovoid search(string text, string pattern){ // Create concatenated string "P$T" string concat = pattern + "$" + text; int l = concat.length(); // Construct Z array int Z[l]; getZarr(concat, Z); // now looping through Z array for matching condition for (int i = 0; i < l; ++i) { // if Z[i] (matched region) is equal to pattern // length we got the pattern if (Z[i] == pattern.length()) cout << "Pattern found at index " << i - pattern.length() -1 << endl; }} // Fills Z array for given string str[]void getZarr(string str, int Z[]){ int n = str.length(); int L, R, k; // [L,R] make a window which matches with prefix of s L = R = 0; for (int i = 1; i < n; ++i) { // if i>R nothing matches so we will calculate. // Z[i] using naive way. if (i > R) { L = R = i; // R-L = 0 in starting, so it will start // checking from 0'th index. For example, // for "ababab" and i = 1, the value of R // remains 0 and Z[i] becomes 0. For string // "aaaaaa" and i = 1, Z[i] and R become 5 while (R<n && str[R-L] == str[R]) R++; Z[i] = R-L; R--; } else { // k = i-L so k corresponds to number which // matches in [L,R] interval. k = i-L; // if Z[k] is less than remaining interval // then Z[i] will be equal to Z[k]. // For example, str = "ababab", i = 3, R = 5 // and L = 2 if (Z[k] < R-i+1) Z[i] = Z[k]; // For example str = "aaaaaa" and i = 2, R is 5, // L is 0 else { // else start from R and check manually L = i; while (R<n && str[R-L] == str[R]) R++; Z[i] = R-L; R--; } } }} // Driver programint main(){ string text = "GEEKS FOR GEEKS"; string pattern = "GEEK"; search(text, pattern); return 0;}
// A Java program that implements Z algorithm for pattern// searchingclass GFG { // prints all occurrences of pattern in text using // Z algo public static void search(String text, String pattern) { // Create concatenated string "P$T" String concat = pattern + "$" + text; int l = concat.length(); int Z[] = new int[l]; // Construct Z array getZarr(concat, Z); // now looping through Z array for matching condition for(int i = 0; i < l; ++i){ // if Z[i] (matched region) is equal to pattern // length we got the pattern if(Z[i] == pattern.length()){ System.out.println("Pattern found at index " + (i - pattern.length() - 1)); } } } // Fills Z array for given string str[] private static void getZarr(String str, int[] Z) { int n = str.length(); // [L,R] make a window which matches with // prefix of s int L = 0, R = 0; for(int i = 1; i < n; ++i) { // if i>R nothing matches so we will calculate. // Z[i] using naive way. if(i > R){ L = R = i; // R-L = 0 in starting, so it will start // checking from 0'th index. For example, // for "ababab" and i = 1, the value of R // remains 0 and Z[i] becomes 0. For string // "aaaaaa" and i = 1, Z[i] and R become 5 while(R < n && str.charAt(R - L) == str.charAt(R)) R++; Z[i] = R - L; R--; } else{ // k = i-L so k corresponds to number which // matches in [L,R] interval. int k = i - L; // if Z[k] is less than remaining interval // then Z[i] will be equal to Z[k]. // For example, str = "ababab", i = 3, R = 5 // and L = 2 if(Z[k] < R - i + 1) Z[i] = Z[k]; // For example str = "aaaaaa" and i = 2, R is 5, // L is 0 else{ // else start from R and check manually L = i; while(R < n && str.charAt(R - L) == str.charAt(R)) R++; Z[i] = R - L; R--; } } } } // Driver program public static void main(String[] args) { String text = "GEEKS FOR GEEKS"; String pattern = "GEEK"; search(text, pattern); }} // This code is contributed by PavanKoli.
# Python3 program that implements Z algorithm# for pattern searching # Fills Z array for given string str[]def getZarr(string, z): n = len(string) # [L,R] make a window which matches # with prefix of s l, r, k = 0, 0, 0 for i in range(1, n): # if i>R nothing matches so we will calculate. # Z[i] using naive way. if i > r: l, r = i, i # R-L = 0 in starting, so it will start # checking from 0'th index. For example, # for "ababab" and i = 1, the value of R # remains 0 and Z[i] becomes 0. For string # "aaaaaa" and i = 1, Z[i] and R become 5 while r < n and string[r - l] == string[r]: r += 1 z[i] = r - l r -= 1 else: # k = i-L so k corresponds to number which # matches in [L,R] interval. k = i - l # if Z[k] is less than remaining interval # then Z[i] will be equal to Z[k]. # For example, str = "ababab", i = 3, R = 5 # and L = 2 if z[k] < r - i + 1: z[i] = z[k] # For example str = "aaaaaa" and i = 2, # R is 5, L is 0 else: # else start from R and check manually l = i while r < n and string[r - l] == string[r]: r += 1 z[i] = r - l r -= 1 # prints all occurrences of pattern# in text using Z algodef search(text, pattern): # Create concatenated string "P$T" concat = pattern + "$" + text l = len(concat) # Construct Z array z = [0] * l getZarr(concat, z) # now looping through Z array for matching condition for i in range(l): # if Z[i] (matched region) is equal to pattern # length we got the pattern if z[i] == len(pattern): print("Pattern found at index", i - len(pattern) - 1) # Driver Codeif __name__ == "__main__": text = "GEEKS FOR GEEKS" pattern = "GEEK" search(text, pattern) # This code is contributed by# sanjeev2552
// A C# program that implements Z// algorithm for pattern searchingusing System; class GFG{ // prints all occurrences of// pattern in text using Z algopublic static void search(string text, string pattern){ // Create concatenated string "P$T" string concat = pattern + "$" + text; int l = concat.Length; int[] Z = new int[l]; // Construct Z array getZarr(concat, Z); // now looping through Z array // for matching condition for (int i = 0; i < l; ++i) { // if Z[i] (matched region) is equal // to pattern length we got the pattern if (Z[i] == pattern.Length) { Console.WriteLine("Pattern found at index " + (i - pattern.Length - 1)); } }} // Fills Z array for given string str[]private static void getZarr(string str, int[] Z){ int n = str.Length; // [L,R] make a window which // matches with prefix of s int L = 0, R = 0; for (int i = 1; i < n; ++i) { // if i>R nothing matches so we will // calculate. Z[i] using naive way. if (i > R) { L = R = i; // R-L = 0 in starting, so it will start // checking from 0'th index. For example, // for "ababab" and i = 1, the value of R // remains 0 and Z[i] becomes 0. For string // "aaaaaa" and i = 1, Z[i] and R become 5 while (R < n && str[R - L] == str[R]) { R++; } Z[i] = R - L; R--; } else { // k = i-L so k corresponds to number // which matches in [L,R] interval. int k = i - L; // if Z[k] is less than remaining interval // then Z[i] will be equal to Z[k]. // For example, str = "ababab", i = 3, // R = 5 and L = 2 if (Z[k] < R - i + 1) { Z[i] = Z[k]; } // For example str = "aaaaaa" and // i = 2, R is 5, L is 0 else { // else start from R and // check manually L = i; while (R < n && str[R - L] == str[R]) { R++; } Z[i] = R - L; R--; } } }} // Driver Codepublic static void Main(string[] args){ string text = "GEEKS FOR GEEKS"; string pattern = "GEEK"; search(text, pattern);}} // This code is contributed by Shrikant13
<script> // A JavaScript program that implements Z algorithm for pattern// searching // prints all occurrences of pattern in text using // Z algofunction search(text,pattern){ // Create concatenated string "P$T" let concat = pattern + "$" + text; let l = concat.length; let Z = new Array(l); // Construct Z array getZarr(concat, Z); // now looping through Z array for matching condition for(let i = 0; i < l; ++i){ // if Z[i] (matched region) is equal to pattern // length we got the pattern if(Z[i] == pattern.length){ document.write("Pattern found at index " + (i - pattern.length - 1)+"<br>"); } }} // Fills Z array for given string str[]function getZarr(str,Z){ let n = str.length; // [L,R] make a window which matches with // prefix of s let L = 0, R = 0; for(let i = 1; i < n; ++i) { // if i>R nothing matches so we will calculate. // Z[i] using naive way. if(i > R){ L = R = i; // R-L = 0 in starting, so it will start // checking from 0'th index. For example, // for "ababab" and i = 1, the value of R // remains 0 and Z[i] becomes 0. For string // "aaaaaa" and i = 1, Z[i] and R become 5 while(R < n && str[R - L] == str[R]) R++; Z[i] = R - L; R--; } else{ // k = i-L so k corresponds to number which // matches in [L,R] interval. let k = i - L; // if Z[k] is less than remaining interval // then Z[i] will be equal to Z[k]. // For example, str = "ababab", i = 3, R = 5 // and L = 2 if(Z[k] < R - i + 1) Z[i] = Z[k]; // For example str = "aaaaaa" and i = 2, R is 5, // L is 0 else{ // else start from R and check manually L = i; while(R < n && str[R - L] == str[R]) R++; Z[i] = R - L; R--; } } }} // Driver programlet text = "GEEKS FOR GEEKS";let pattern = "GEEK"; search(text, pattern); // This code is contributed by rag2127 </script>
Output:
Pattern found at index 0
Pattern found at index 10
Time Complexity: O(m+n), where m is length of pattern and n is length of text.
Auxiliary Space: O(m+n)
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
pkoli
shrikanth13
sanjeev2552
surindertarika1234
unknown2108
keshavmalpani01
sanskar84
Pattern Searching
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Jun, 2022"
},
{
"code": null,
"e": 400,
"s": 52,
"text": "This algorithm finds all occurrences of a pattern in a text in linear time. Let length of text be n and of pattern be m, then total time taken is O(m + n) with linear space complexity. Now we can see that both time and space complexity is same as KMP algorithm but this algorithm is Simpler to understand.In this algorithm, we construct a Z array."
},
{
"code": null,
"e": 697,
"s": 400,
"text": "What is Z Array? For a string str[0..n-1], Z array is of same length as string. An element Z[i] of Z array stores length of the longest substring starting from str[i] which is also a prefix of str[0..n-1]. The first entry of Z array is meaning less as complete string is always prefix of itself. "
},
{
"code": null,
"e": 897,
"s": 697,
"text": "Example:\nIndex 0 1 2 3 4 5 6 7 8 9 10 11 \nText a a b c a a b x a a a z\nZ values X 1 0 0 3 1 0 0 2 2 1 0 "
},
{
"code": null,
"e": 1050,
"s": 897,
"text": "More Examples:\nstr = \"aaaaaa\"\nZ[] = {x, 5, 4, 3, 2, 1}\n\nstr = \"aabaacd\"\nZ[] = {x, 1, 0, 2, 1, 0, 0}\n\nstr = \"abababab\"\nZ[] = {x, 0, 6, 0, 4, 0, 2, 0}\n "
},
{
"code": null,
"e": 1431,
"s": 1050,
"text": "How is Z array helpful in Searching Pattern in Linear time? The idea is to concatenate pattern and text, and create a string βP$Tβ where P is pattern, $ is a special character should not be present in pattern and text, and T is text. Build the Z array for concatenated string. In Z array, if Z value at any point is equal to pattern length, then pattern is present at that point. "
},
{
"code": null,
"e": 1724,
"s": 1431,
"text": "Example:\nPattern P = \"aab\", Text T = \"baabaa\"\n\nThe concatenated string is = \"aab$baabaa\"\n\nZ array for above concatenated string is {x, 1, 0, 0, 0, \n 3, 1, 0, 2, 1}.\nSince length of pattern is 3, the value 3 in Z array \nindicates presence of pattern. "
},
{
"code": null,
"e": 2042,
"s": 1724,
"text": "How to construct Z array? A Simple Solution is to run two nested loops, the outer loop goes to every index and the inner loop finds length of the longest prefix that matches the substring starting at the current index. The time complexity of this solution is O(n2). We can construct Z array in linear time. "
},
{
"code": null,
"e": 3096,
"s": 2042,
"text": "The idea is to maintain an interval [L, R] which is the interval with max R\nsuch that [L,R] is prefix substring (substring which is also prefix). \n\nSteps for maintaining this interval are as follows β \n\n1) If i > R then there is no prefix substring that starts before i and \n ends after i, so we reset L and R and compute new [L,R] by comparing \n str[0..] to str[i..] and get Z[i] (= R-L+1).\n\n2) If i <= R then let K = i-L, now Z[i] >= min(Z[K], R-i+1) because \n str[i..] matches with str[K..] for atleast R-i+1 characters (they are in\n [L,R] interval which we know is a prefix substring). \n Now two sub cases arise β \n a) If Z[K] < R-i+1 then there is no prefix substring starting at \n str[i] (otherwise Z[K] would be larger) so Z[i] = Z[K] and \n interval [L,R] remains same.\n b) If Z[K] >= R-i+1 then it is possible to extend the [L,R] interval\n thus we will set L as i and start matching from str[R] onwards and\n get new R then we will update interval [L,R] and calculate Z[i] (=R-L+1)."
},
{
"code": null,
"e": 3551,
"s": 3096,
"text": "For better understanding of above step by step procedure please check this animation β http://www.utdallas.edu/~besp/demo/John2010/z-algorithm.htmThe algorithm runs in linear time because we never compare character less than R and with matching we increase R by one so there are at most T comparisons. In mismatch case, mismatch happen only once for each i (because of which R stops), thatβs another at most T comparison making overall linear complexity."
},
{
"code": null,
"e": 3618,
"s": 3551,
"text": "Below is the implementation of Z algorithm for pattern searching. "
},
{
"code": null,
"e": 3622,
"s": 3618,
"text": "C++"
},
{
"code": null,
"e": 3627,
"s": 3622,
"text": "Java"
},
{
"code": null,
"e": 3635,
"s": 3627,
"text": "Python3"
},
{
"code": null,
"e": 3638,
"s": 3635,
"text": "C#"
},
{
"code": null,
"e": 3649,
"s": 3638,
"text": "Javascript"
},
{
"code": "// A C++ program that implements Z algorithm for pattern searching#include<iostream>using namespace std; void getZarr(string str, int Z[]); // prints all occurrences of pattern in text using Z algovoid search(string text, string pattern){ // Create concatenated string \"P$T\" string concat = pattern + \"$\" + text; int l = concat.length(); // Construct Z array int Z[l]; getZarr(concat, Z); // now looping through Z array for matching condition for (int i = 0; i < l; ++i) { // if Z[i] (matched region) is equal to pattern // length we got the pattern if (Z[i] == pattern.length()) cout << \"Pattern found at index \" << i - pattern.length() -1 << endl; }} // Fills Z array for given string str[]void getZarr(string str, int Z[]){ int n = str.length(); int L, R, k; // [L,R] make a window which matches with prefix of s L = R = 0; for (int i = 1; i < n; ++i) { // if i>R nothing matches so we will calculate. // Z[i] using naive way. if (i > R) { L = R = i; // R-L = 0 in starting, so it will start // checking from 0'th index. For example, // for \"ababab\" and i = 1, the value of R // remains 0 and Z[i] becomes 0. For string // \"aaaaaa\" and i = 1, Z[i] and R become 5 while (R<n && str[R-L] == str[R]) R++; Z[i] = R-L; R--; } else { // k = i-L so k corresponds to number which // matches in [L,R] interval. k = i-L; // if Z[k] is less than remaining interval // then Z[i] will be equal to Z[k]. // For example, str = \"ababab\", i = 3, R = 5 // and L = 2 if (Z[k] < R-i+1) Z[i] = Z[k]; // For example str = \"aaaaaa\" and i = 2, R is 5, // L is 0 else { // else start from R and check manually L = i; while (R<n && str[R-L] == str[R]) R++; Z[i] = R-L; R--; } } }} // Driver programint main(){ string text = \"GEEKS FOR GEEKS\"; string pattern = \"GEEK\"; search(text, pattern); return 0;}",
"e": 5966,
"s": 3649,
"text": null
},
{
"code": "// A Java program that implements Z algorithm for pattern// searchingclass GFG { // prints all occurrences of pattern in text using // Z algo public static void search(String text, String pattern) { // Create concatenated string \"P$T\" String concat = pattern + \"$\" + text; int l = concat.length(); int Z[] = new int[l]; // Construct Z array getZarr(concat, Z); // now looping through Z array for matching condition for(int i = 0; i < l; ++i){ // if Z[i] (matched region) is equal to pattern // length we got the pattern if(Z[i] == pattern.length()){ System.out.println(\"Pattern found at index \" + (i - pattern.length() - 1)); } } } // Fills Z array for given string str[] private static void getZarr(String str, int[] Z) { int n = str.length(); // [L,R] make a window which matches with // prefix of s int L = 0, R = 0; for(int i = 1; i < n; ++i) { // if i>R nothing matches so we will calculate. // Z[i] using naive way. if(i > R){ L = R = i; // R-L = 0 in starting, so it will start // checking from 0'th index. For example, // for \"ababab\" and i = 1, the value of R // remains 0 and Z[i] becomes 0. For string // \"aaaaaa\" and i = 1, Z[i] and R become 5 while(R < n && str.charAt(R - L) == str.charAt(R)) R++; Z[i] = R - L; R--; } else{ // k = i-L so k corresponds to number which // matches in [L,R] interval. int k = i - L; // if Z[k] is less than remaining interval // then Z[i] will be equal to Z[k]. // For example, str = \"ababab\", i = 3, R = 5 // and L = 2 if(Z[k] < R - i + 1) Z[i] = Z[k]; // For example str = \"aaaaaa\" and i = 2, R is 5, // L is 0 else{ // else start from R and check manually L = i; while(R < n && str.charAt(R - L) == str.charAt(R)) R++; Z[i] = R - L; R--; } } } } // Driver program public static void main(String[] args) { String text = \"GEEKS FOR GEEKS\"; String pattern = \"GEEK\"; search(text, pattern); }} // This code is contributed by PavanKoli.",
"e": 8703,
"s": 5966,
"text": null
},
{
"code": "# Python3 program that implements Z algorithm# for pattern searching # Fills Z array for given string str[]def getZarr(string, z): n = len(string) # [L,R] make a window which matches # with prefix of s l, r, k = 0, 0, 0 for i in range(1, n): # if i>R nothing matches so we will calculate. # Z[i] using naive way. if i > r: l, r = i, i # R-L = 0 in starting, so it will start # checking from 0'th index. For example, # for \"ababab\" and i = 1, the value of R # remains 0 and Z[i] becomes 0. For string # \"aaaaaa\" and i = 1, Z[i] and R become 5 while r < n and string[r - l] == string[r]: r += 1 z[i] = r - l r -= 1 else: # k = i-L so k corresponds to number which # matches in [L,R] interval. k = i - l # if Z[k] is less than remaining interval # then Z[i] will be equal to Z[k]. # For example, str = \"ababab\", i = 3, R = 5 # and L = 2 if z[k] < r - i + 1: z[i] = z[k] # For example str = \"aaaaaa\" and i = 2, # R is 5, L is 0 else: # else start from R and check manually l = i while r < n and string[r - l] == string[r]: r += 1 z[i] = r - l r -= 1 # prints all occurrences of pattern# in text using Z algodef search(text, pattern): # Create concatenated string \"P$T\" concat = pattern + \"$\" + text l = len(concat) # Construct Z array z = [0] * l getZarr(concat, z) # now looping through Z array for matching condition for i in range(l): # if Z[i] (matched region) is equal to pattern # length we got the pattern if z[i] == len(pattern): print(\"Pattern found at index\", i - len(pattern) - 1) # Driver Codeif __name__ == \"__main__\": text = \"GEEKS FOR GEEKS\" pattern = \"GEEK\" search(text, pattern) # This code is contributed by# sanjeev2552",
"e": 10822,
"s": 8703,
"text": null
},
{
"code": "// A C# program that implements Z// algorithm for pattern searchingusing System; class GFG{ // prints all occurrences of// pattern in text using Z algopublic static void search(string text, string pattern){ // Create concatenated string \"P$T\" string concat = pattern + \"$\" + text; int l = concat.Length; int[] Z = new int[l]; // Construct Z array getZarr(concat, Z); // now looping through Z array // for matching condition for (int i = 0; i < l; ++i) { // if Z[i] (matched region) is equal // to pattern length we got the pattern if (Z[i] == pattern.Length) { Console.WriteLine(\"Pattern found at index \" + (i - pattern.Length - 1)); } }} // Fills Z array for given string str[]private static void getZarr(string str, int[] Z){ int n = str.Length; // [L,R] make a window which // matches with prefix of s int L = 0, R = 0; for (int i = 1; i < n; ++i) { // if i>R nothing matches so we will // calculate. Z[i] using naive way. if (i > R) { L = R = i; // R-L = 0 in starting, so it will start // checking from 0'th index. For example, // for \"ababab\" and i = 1, the value of R // remains 0 and Z[i] becomes 0. For string // \"aaaaaa\" and i = 1, Z[i] and R become 5 while (R < n && str[R - L] == str[R]) { R++; } Z[i] = R - L; R--; } else { // k = i-L so k corresponds to number // which matches in [L,R] interval. int k = i - L; // if Z[k] is less than remaining interval // then Z[i] will be equal to Z[k]. // For example, str = \"ababab\", i = 3, // R = 5 and L = 2 if (Z[k] < R - i + 1) { Z[i] = Z[k]; } // For example str = \"aaaaaa\" and // i = 2, R is 5, L is 0 else { // else start from R and // check manually L = i; while (R < n && str[R - L] == str[R]) { R++; } Z[i] = R - L; R--; } } }} // Driver Codepublic static void Main(string[] args){ string text = \"GEEKS FOR GEEKS\"; string pattern = \"GEEK\"; search(text, pattern);}} // This code is contributed by Shrikant13",
"e": 13413,
"s": 10822,
"text": null
},
{
"code": "<script> // A JavaScript program that implements Z algorithm for pattern// searching // prints all occurrences of pattern in text using // Z algofunction search(text,pattern){ // Create concatenated string \"P$T\" let concat = pattern + \"$\" + text; let l = concat.length; let Z = new Array(l); // Construct Z array getZarr(concat, Z); // now looping through Z array for matching condition for(let i = 0; i < l; ++i){ // if Z[i] (matched region) is equal to pattern // length we got the pattern if(Z[i] == pattern.length){ document.write(\"Pattern found at index \" + (i - pattern.length - 1)+\"<br>\"); } }} // Fills Z array for given string str[]function getZarr(str,Z){ let n = str.length; // [L,R] make a window which matches with // prefix of s let L = 0, R = 0; for(let i = 1; i < n; ++i) { // if i>R nothing matches so we will calculate. // Z[i] using naive way. if(i > R){ L = R = i; // R-L = 0 in starting, so it will start // checking from 0'th index. For example, // for \"ababab\" and i = 1, the value of R // remains 0 and Z[i] becomes 0. For string // \"aaaaaa\" and i = 1, Z[i] and R become 5 while(R < n && str[R - L] == str[R]) R++; Z[i] = R - L; R--; } else{ // k = i-L so k corresponds to number which // matches in [L,R] interval. let k = i - L; // if Z[k] is less than remaining interval // then Z[i] will be equal to Z[k]. // For example, str = \"ababab\", i = 3, R = 5 // and L = 2 if(Z[k] < R - i + 1) Z[i] = Z[k]; // For example str = \"aaaaaa\" and i = 2, R is 5, // L is 0 else{ // else start from R and check manually L = i; while(R < n && str[R - L] == str[R]) R++; Z[i] = R - L; R--; } } }} // Driver programlet text = \"GEEKS FOR GEEKS\";let pattern = \"GEEK\"; search(text, pattern); // This code is contributed by rag2127 </script>",
"e": 15967,
"s": 13413,
"text": null
},
{
"code": null,
"e": 15976,
"s": 15967,
"text": "Output: "
},
{
"code": null,
"e": 16027,
"s": 15976,
"text": "Pattern found at index 0\nPattern found at index 10"
},
{
"code": null,
"e": 16106,
"s": 16027,
"text": "Time Complexity: O(m+n), where m is length of pattern and n is length of text."
},
{
"code": null,
"e": 16130,
"s": 16106,
"text": "Auxiliary Space: O(m+n)"
},
{
"code": null,
"e": 16303,
"s": 16130,
"text": "This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 16309,
"s": 16303,
"text": "pkoli"
},
{
"code": null,
"e": 16321,
"s": 16309,
"text": "shrikanth13"
},
{
"code": null,
"e": 16333,
"s": 16321,
"text": "sanjeev2552"
},
{
"code": null,
"e": 16352,
"s": 16333,
"text": "surindertarika1234"
},
{
"code": null,
"e": 16364,
"s": 16352,
"text": "unknown2108"
},
{
"code": null,
"e": 16380,
"s": 16364,
"text": "keshavmalpani01"
},
{
"code": null,
"e": 16390,
"s": 16380,
"text": "sanskar84"
},
{
"code": null,
"e": 16408,
"s": 16390,
"text": "Pattern Searching"
},
{
"code": null,
"e": 16426,
"s": 16408,
"text": "Pattern Searching"
}
] |
How to scroll automatically to the Bottom of the Page using jQuery?
|
03 Aug, 2021
To auto scroll a page from top to bottom we can use scrollTop() and height() method in jquery.In this method pass the documentβs height in scrollTop method to scroll.
Example-1: Scroll without animation.
<!DOCTYPE html><html> <head> <title>Scroll Automatically</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function() { $("button").click(function() { $(document).scrollTop($(document).height()); }); }); </script> <style> h1 { color: green; } </style></head> <body> <center> <div> <!-- click on this button and see the change --> <button>Click Here!</button> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> </div> </center></body> </html>
Output:
Before:
After:
Example-2: Scroll with animation.
<!DOCTYPE html><html> <head> <title>Scroll Automatically</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function() { $("button").click(function() { $("html, body").animate({ scrollTop: $( 'html, body').get(0).scrollHeight }, 2000); }); }); </script> <style> h1 { color: green; } </style></head> <body> <center> <div> <!-- click on this button and see the change --> <button>Click Here!</button> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> </div> </center></body> </html>
Output:
Before:
After:
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with itβs philosophy of βWrite less, do moreβ.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
jQuery-Misc
Picked
JQuery
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 221,
"s": 54,
"text": "To auto scroll a page from top to bottom we can use scrollTop() and height() method in jquery.In this method pass the documentβs height in scrollTop method to scroll."
},
{
"code": null,
"e": 258,
"s": 221,
"text": "Example-1: Scroll without animation."
},
{
"code": "<!DOCTYPE html><html> <head> <title>Scroll Automatically</title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function() { $(\"button\").click(function() { $(document).scrollTop($(document).height()); }); }); </script> <style> h1 { color: green; } </style></head> <body> <center> <div> <!-- click on this button and see the change --> <button>Click Here!</button> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> </div> </center></body> </html>",
"e": 1348,
"s": 258,
"text": null
},
{
"code": null,
"e": 1356,
"s": 1348,
"text": "Output:"
},
{
"code": null,
"e": 1364,
"s": 1356,
"text": "Before:"
},
{
"code": null,
"e": 1371,
"s": 1364,
"text": "After:"
},
{
"code": null,
"e": 1405,
"s": 1371,
"text": "Example-2: Scroll with animation."
},
{
"code": "<!DOCTYPE html><html> <head> <title>Scroll Automatically</title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function() { $(\"button\").click(function() { $(\"html, body\").animate({ scrollTop: $( 'html, body').get(0).scrollHeight }, 2000); }); }); </script> <style> h1 { color: green; } </style></head> <body> <center> <div> <!-- click on this button and see the change --> <button>Click Here!</button> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> </div> </center></body> </html>",
"e": 2596,
"s": 1405,
"text": null
},
{
"code": null,
"e": 2604,
"s": 2596,
"text": "Output:"
},
{
"code": null,
"e": 2612,
"s": 2604,
"text": "Before:"
},
{
"code": null,
"e": 2619,
"s": 2612,
"text": "After:"
},
{
"code": null,
"e": 2887,
"s": 2619,
"text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with itβs philosophy of βWrite less, do moreβ.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples."
},
{
"code": null,
"e": 2899,
"s": 2887,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 2906,
"s": 2899,
"text": "Picked"
},
{
"code": null,
"e": 2913,
"s": 2906,
"text": "JQuery"
},
{
"code": null,
"e": 2930,
"s": 2913,
"text": "Web Technologies"
},
{
"code": null,
"e": 2957,
"s": 2930,
"text": "Web technologies Questions"
}
] |
Template Method β Python Design Patterns
|
21 Jul, 2021
The Template method is a Behavioral Design Pattern that defines the skeleton of the operation and leaves the details to be implemented by the child class. Its subclasses can override the method implementations as per need but the invocation is to be in the same way as defined by an abstract class. It is one of the easiest among the Behavioral design pattern to understand and implements. Such methods are highly used in framework development as they allow us to reuse the single piece of code at different places by making certain changes. This leads to avoiding code duplication also.
Imagine you are working on a Chatbot application as a software developer which uses data mining techniques to analyze the data of the corporate documents. Initially, your applications were fine with the pdf version of the data only but later your applications also require to collect and convert data from other formats also such as XML, CSV, and others. After implementing the whole scenario for the other formats also, you noticed that all the classes have lots of similar code. Part of the code like analyzing and processing was identical in almost all classes whereas they differ in dealing with the data.
Problem-Template-Method
Letβs discuss the solution to the above-described problem using the template method. It suggests to break down the code into a series of steps and convert these steps into methods and put series call inside the template_function. Hence we created the template_function separately and create methods such as get_xml, get_pdf and get_csv for dealing with the code separately.
Python3
""" method to get the text of file"""def get_text(): return "plain_text" """ method to get the xml version of file"""def get_xml(): return "xml" """ method to get the pdf version of file"""def get_pdf(): return "pdf" """method to get the csv version of file"""def get_csv(): return "csv" """method used to convert the data into text format"""def convert_to_text(data): print("[CONVERT]") return "{} as text".format(data) """method used to save the data"""def saver(): print("[SAVE]") """helper function named as template_function"""def template_function(getter, converter = False, to_save = False): """input data from getter""" data = getter() print("Got `{}`".format(data)) if len(data) <= 3 and converter: data = converter(data) else: print("Skip conversion") """saves the data only if user want to save it""" if to_save: saver() print("`{}` was processed".format(data)) """main method"""if __name__ == "__main__": template_function(get_text, to_save = True) template_function(get_pdf, converter = convert_to_text) template_function(get_csv, to_save = True) template_function(get_xml, to_save = True)
Got `plain_text`
Skip conversion
[SAVE]
`plain_text` was processed
Got `pdf`
[CONVERT]
`pdf as text` was processed
Got `csv`
Skip conversion
[SAVE]
`csv` was processed
Following is the class diagram for the Template Method
Class-diagram-template-method
Equivalent Content: Itβs easy to consider the duplicate code in the superclass by pulling it there where you want to use it.
Flexibility: It provides vast flexibility such that subclasses are able to decide how to implement the steps of the algorithms.
Possibility of Inheritance: We can reuse our code as the Template Method uses inheritance which provides the ability of code reusability.
Complex Code: The code may become enough complex sometimes while using the template method such that it becomes too much hard to understand the code even by the developers who are writing it.
Limitness: Clients may ask for the extended version because sometimes they feel lack of algorithms in the provided skeleton.
Violation: It might be possible that by using Template method, you may end up with violating the Liskov Substitution Principle which is definitely not the good thing to follow.
Extension by Clients: This method is always preferred to use when you want to let clients extend the algorithm using particular steps but with not the whole structure of the algorithm.
Similar Algorithms: When you have a lot of similar algorithms with minor changes, its always better to use the template design pattern because if some changes occur in the algorithm, then you donβt have to make changes in each algorithm.
Development of Frameworks: It is highly recommended to use the template design pattern while developing a framework because it will help us to avoid the duplicate code as well as reusing the piece of code again and again by making certain changes.
Further Read β Template Method in Java
varshagumber28
gulshankumarar231
python-design-pattern
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Jul, 2021"
},
{
"code": null,
"e": 617,
"s": 28,
"text": "The Template method is a Behavioral Design Pattern that defines the skeleton of the operation and leaves the details to be implemented by the child class. Its subclasses can override the method implementations as per need but the invocation is to be in the same way as defined by an abstract class. It is one of the easiest among the Behavioral design pattern to understand and implements. Such methods are highly used in framework development as they allow us to reuse the single piece of code at different places by making certain changes. This leads to avoiding code duplication also. "
},
{
"code": null,
"e": 1228,
"s": 617,
"text": "Imagine you are working on a Chatbot application as a software developer which uses data mining techniques to analyze the data of the corporate documents. Initially, your applications were fine with the pdf version of the data only but later your applications also require to collect and convert data from other formats also such as XML, CSV, and others. After implementing the whole scenario for the other formats also, you noticed that all the classes have lots of similar code. Part of the code like analyzing and processing was identical in almost all classes whereas they differ in dealing with the data. "
},
{
"code": null,
"e": 1252,
"s": 1228,
"text": "Problem-Template-Method"
},
{
"code": null,
"e": 1629,
"s": 1254,
"text": "Letβs discuss the solution to the above-described problem using the template method. It suggests to break down the code into a series of steps and convert these steps into methods and put series call inside the template_function. Hence we created the template_function separately and create methods such as get_xml, get_pdf and get_csv for dealing with the code separately. "
},
{
"code": null,
"e": 1637,
"s": 1629,
"text": "Python3"
},
{
"code": "\"\"\" method to get the text of file\"\"\"def get_text(): return \"plain_text\" \"\"\" method to get the xml version of file\"\"\"def get_xml(): return \"xml\" \"\"\" method to get the pdf version of file\"\"\"def get_pdf(): return \"pdf\" \"\"\"method to get the csv version of file\"\"\"def get_csv(): return \"csv\" \"\"\"method used to convert the data into text format\"\"\"def convert_to_text(data): print(\"[CONVERT]\") return \"{} as text\".format(data) \"\"\"method used to save the data\"\"\"def saver(): print(\"[SAVE]\") \"\"\"helper function named as template_function\"\"\"def template_function(getter, converter = False, to_save = False): \"\"\"input data from getter\"\"\" data = getter() print(\"Got `{}`\".format(data)) if len(data) <= 3 and converter: data = converter(data) else: print(\"Skip conversion\") \"\"\"saves the data only if user want to save it\"\"\" if to_save: saver() print(\"`{}` was processed\".format(data)) \"\"\"main method\"\"\"if __name__ == \"__main__\": template_function(get_text, to_save = True) template_function(get_pdf, converter = convert_to_text) template_function(get_csv, to_save = True) template_function(get_xml, to_save = True)",
"e": 2861,
"s": 1637,
"text": null
},
{
"code": null,
"e": 3029,
"s": 2861,
"text": "Got `plain_text`\nSkip conversion\n[SAVE]\n`plain_text` was processed\nGot `pdf`\n[CONVERT]\n`pdf as text` was processed\nGot `csv`\nSkip conversion\n[SAVE]\n`csv` was processed"
},
{
"code": null,
"e": 3085,
"s": 3029,
"text": "Following is the class diagram for the Template Method "
},
{
"code": null,
"e": 3115,
"s": 3085,
"text": "Class-diagram-template-method"
},
{
"code": null,
"e": 3244,
"s": 3119,
"text": "Equivalent Content: Itβs easy to consider the duplicate code in the superclass by pulling it there where you want to use it."
},
{
"code": null,
"e": 3372,
"s": 3244,
"text": "Flexibility: It provides vast flexibility such that subclasses are able to decide how to implement the steps of the algorithms."
},
{
"code": null,
"e": 3510,
"s": 3372,
"text": "Possibility of Inheritance: We can reuse our code as the Template Method uses inheritance which provides the ability of code reusability."
},
{
"code": null,
"e": 3706,
"s": 3514,
"text": "Complex Code: The code may become enough complex sometimes while using the template method such that it becomes too much hard to understand the code even by the developers who are writing it."
},
{
"code": null,
"e": 3831,
"s": 3706,
"text": "Limitness: Clients may ask for the extended version because sometimes they feel lack of algorithms in the provided skeleton."
},
{
"code": null,
"e": 4008,
"s": 3831,
"text": "Violation: It might be possible that by using Template method, you may end up with violating the Liskov Substitution Principle which is definitely not the good thing to follow."
},
{
"code": null,
"e": 4197,
"s": 4012,
"text": "Extension by Clients: This method is always preferred to use when you want to let clients extend the algorithm using particular steps but with not the whole structure of the algorithm."
},
{
"code": null,
"e": 4435,
"s": 4197,
"text": "Similar Algorithms: When you have a lot of similar algorithms with minor changes, its always better to use the template design pattern because if some changes occur in the algorithm, then you donβt have to make changes in each algorithm."
},
{
"code": null,
"e": 4683,
"s": 4435,
"text": "Development of Frameworks: It is highly recommended to use the template design pattern while developing a framework because it will help us to avoid the duplicate code as well as reusing the piece of code again and again by making certain changes."
},
{
"code": null,
"e": 4723,
"s": 4683,
"text": "Further Read β Template Method in Java "
},
{
"code": null,
"e": 4738,
"s": 4723,
"text": "varshagumber28"
},
{
"code": null,
"e": 4756,
"s": 4738,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 4778,
"s": 4756,
"text": "python-design-pattern"
},
{
"code": null,
"e": 4785,
"s": 4778,
"text": "Python"
}
] |
How to get multiple rows in a single MySQL query?
|
Let us first create a table β
mysql> create table DemoTable
(
Id int,
Name varchar(100)
);
Query OK, 0 rows affected (0.60 sec)
Insert some records in the table using insert command β
mysql> insert into DemoTable values(100,'Chris');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(110,'David');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(120,'Robert');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(130,'Mike');
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement β
mysql> select *from DemoTable;
This will produce the following output β
+------+--------+
| Id | Name |
+------+--------+
| 100 | Chris |
| 110 | David |
| 120 | Robert |
| 130 | Mike |
+------+--------+
4 rows in set (0.00 sec)
Following is the query to get multiple rows in a single MySQL query β
mysql> select *from DemoTable where Id IN(100,120,130):
This will produce the following output β
+------+--------+
| Id | Name |
+------+--------+
| 100 | Chris |
| 120 | Robert |
| 130 | Mike |
+------+--------+
3 rows in set (0.02 sec)
|
[
{
"code": null,
"e": 1217,
"s": 1187,
"text": "Let us first create a table β"
},
{
"code": null,
"e": 1321,
"s": 1217,
"text": "mysql> create table DemoTable\n(\n Id int,\n Name varchar(100)\n);\nQuery OK, 0 rows affected (0.60 sec)"
},
{
"code": null,
"e": 1377,
"s": 1321,
"text": "Insert some records in the table using insert command β"
},
{
"code": null,
"e": 1721,
"s": 1377,
"text": "mysql> insert into DemoTable values(100,'Chris');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable values(110,'David');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values(120,'Robert');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable values(130,'Mike');\nQuery OK, 1 row affected (0.13 sec)"
},
{
"code": null,
"e": 1781,
"s": 1721,
"text": "Display all records from the table using select statement β"
},
{
"code": null,
"e": 1812,
"s": 1781,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1853,
"s": 1812,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2022,
"s": 1853,
"text": "+------+--------+\n| Id | Name |\n+------+--------+\n| 100 | Chris |\n| 110 | David |\n| 120 | Robert |\n| 130 | Mike |\n+------+--------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2092,
"s": 2022,
"text": "Following is the query to get multiple rows in a single MySQL query β"
},
{
"code": null,
"e": 2148,
"s": 2092,
"text": "mysql> select *from DemoTable where Id IN(100,120,130):"
},
{
"code": null,
"e": 2189,
"s": 2148,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2340,
"s": 2189,
"text": "+------+--------+\n| Id | Name |\n+------+--------+\n| 100 | Chris |\n| 120 | Robert |\n| 130 | Mike |\n+------+--------+\n3 rows in set (0.02 sec)"
}
] |
Python - Multithreaded Programming
|
Running several threads is similar to running several different programs concurrently, but with the following benefits β
Multiple threads within a process share the same data space with the main thread and can therefore share information or communicate with each other more easily than if they were separate processes.
Multiple threads within a process share the same data space with the main thread and can therefore share information or communicate with each other more easily than if they were separate processes.
Threads sometimes called light-weight processes and they do not require much memory overhead; they are cheaper than processes.
Threads sometimes called light-weight processes and they do not require much memory overhead; they are cheaper than processes.
A thread has a beginning, an execution sequence, and a conclusion. It has an instruction pointer that keeps track of where within its context it is currently running.
It can be pre-empted (interrupted)
It can be pre-empted (interrupted)
It can temporarily be put on hold (also known as sleeping) while other threads are running - this is called yielding.
It can temporarily be put on hold (also known as sleeping) while other threads are running - this is called yielding.
To spawn another thread, you need to call following method available in thread module β
thread.start_new_thread ( function, args[, kwargs] )
This method call enables a fast and efficient way to create new threads in both Linux and Windows.
The method call returns immediately and the child thread starts and calls function with the passed list of args. When function returns, the thread terminates.
Here, args is a tuple of arguments; use an empty tuple to call function without passing any arguments. kwargs is an optional dictionary of keyword arguments.
#!/usr/bin/python
import thread
import time
# Define a function for the thread
def print_time( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print "%s: %s" % ( threadName, time.ctime(time.time()) )
# Create two threads as follows
try:
thread.start_new_thread( print_time, ("Thread-1", 2, ) )
thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
print "Error: unable to start thread"
while 1:
pass
When the above code is executed, it produces the following result β
Thread-1: Thu Jan 22 15:42:17 2009
Thread-1: Thu Jan 22 15:42:19 2009
Thread-2: Thu Jan 22 15:42:19 2009
Thread-1: Thu Jan 22 15:42:21 2009
Thread-2: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:25 2009
Thread-2: Thu Jan 22 15:42:27 2009
Thread-2: Thu Jan 22 15:42:31 2009
Thread-2: Thu Jan 22 15:42:35 2009
Although it is very effective for low-level threading, but the thread module is very limited compared to the newer threading module.
The newer threading module included with Python 2.4 provides much more powerful, high-level support for threads than the thread module discussed in the previous section.
The threading module exposes all the methods of the thread module and provides some additional methods β
threading.activeCount() β Returns the number of thread objects that are active.
threading.activeCount() β Returns the number of thread objects that are active.
threading.currentThread() β Returns the number of thread objects in the caller's thread control.
threading.currentThread() β Returns the number of thread objects in the caller's thread control.
threading.enumerate() β Returns a list of all thread objects that are currently active.
threading.enumerate() β Returns a list of all thread objects that are currently active.
In addition to the methods, the threading module has the Thread class that implements threading. The methods provided by the Thread class are as follows β
run() β The run() method is the entry point for a thread.
run() β The run() method is the entry point for a thread.
start() β The start() method starts a thread by calling the run method.
start() β The start() method starts a thread by calling the run method.
join([time]) β The join() waits for threads to terminate.
join([time]) β The join() waits for threads to terminate.
isAlive() β The isAlive() method checks whether a thread is still executing.
isAlive() β The isAlive() method checks whether a thread is still executing.
getName() β The getName() method returns the name of a thread.
getName() β The getName() method returns the name of a thread.
setName() β The setName() method sets the name of a thread.
setName() β The setName() method sets the name of a thread.
To implement a new thread using the threading module, you have to do the following β
Define a new subclass of the Thread class.
Define a new subclass of the Thread class.
Override the __init__(self [,args]) method to add additional arguments.
Override the __init__(self [,args]) method to add additional arguments.
Then, override the run(self [,args]) method to implement what the thread should do when started.
Then, override the run(self [,args]) method to implement what the thread should do when started.
Once you have created the new Thread subclass, you can create an instance of it and then start a new thread by invoking the start(), which in turn calls run() method.
#!/usr/bin/python
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
print_time(self.name, 5, self.counter)
print "Exiting " + self.name
def print_time(threadName, counter, delay):
while counter:
if exitFlag:
threadName.exit()
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
print "Exiting Main Thread"
When the above code is executed, it produces the following result β
Starting Thread-1
Starting Thread-2
Exiting Main Thread
Thread-1: Thu Mar 21 09:10:03 2013
Thread-1: Thu Mar 21 09:10:04 2013
Thread-2: Thu Mar 21 09:10:04 2013
Thread-1: Thu Mar 21 09:10:05 2013
Thread-1: Thu Mar 21 09:10:06 2013
Thread-2: Thu Mar 21 09:10:06 2013
Thread-1: Thu Mar 21 09:10:07 2013
Exiting Thread-1
Thread-2: Thu Mar 21 09:10:08 2013
Thread-2: Thu Mar 21 09:10:10 2013
Thread-2: Thu Mar 21 09:10:12 2013
Exiting Thread-2
The threading module provided with Python includes a simple-to-implement locking mechanism that allows you to synchronize threads. A new lock is created by calling the Lock() method, which returns the new lock.
The acquire(blocking) method of the new lock object is used to force threads to run synchronously. The optional blocking parameter enables you to control whether the thread waits to acquire the lock.
If blocking is set to 0, the thread returns immediately with a 0 value if the lock cannot be acquired and with a 1 if the lock was acquired. If blocking is set to 1, the thread blocks and wait for the lock to be released.
The release() method of the new lock object is used to release the lock when it is no longer required.
#!/usr/bin/python
import threading
import time
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
# Get lock to synchronize threads
threadLock.acquire()
print_time(self.name, self.counter, 3)
# Free lock to release next thread
threadLock.release()
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1
threadLock = threading.Lock()
threads = []
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
# Add threads to thread list
threads.append(thread1)
threads.append(thread2)
# Wait for all threads to complete
for t in threads:
t.join()
print "Exiting Main Thread"
When the above code is executed, it produces the following result β
Starting Thread-1
Starting Thread-2
Thread-1: Thu Mar 21 09:11:28 2013
Thread-1: Thu Mar 21 09:11:29 2013
Thread-1: Thu Mar 21 09:11:30 2013
Thread-2: Thu Mar 21 09:11:32 2013
Thread-2: Thu Mar 21 09:11:34 2013
Thread-2: Thu Mar 21 09:11:36 2013
Exiting Main Thread
The Queue module allows you to create a new queue object that can hold a specific number of items. There are following methods to control the Queue β
get() β The get() removes and returns an item from the queue.
get() β The get() removes and returns an item from the queue.
put() β The put adds item to a queue.
put() β The put adds item to a queue.
qsize() β The qsize() returns the number of items that are currently in the queue.
qsize() β The qsize() returns the number of items that are currently in the queue.
empty() β The empty( ) returns True if queue is empty; otherwise, False.
empty() β The empty( ) returns True if queue is empty; otherwise, False.
full() β the full() returns True if queue is full; otherwise, False.
full() β the full() returns True if queue is full; otherwise, False.
#!/usr/bin/python
import Queue
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, q):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.q = q
def run(self):
print "Starting " + self.name
process_data(self.name, self.q)
print "Exiting " + self.name
def process_data(threadName, q):
while not exitFlag:
queueLock.acquire()
if not workQueue.empty():
data = q.get()
queueLock.release()
print "%s processing %s" % (threadName, data)
else:
queueLock.release()
time.sleep(1)
threadList = ["Thread-1", "Thread-2", "Thread-3"]
nameList = ["One", "Two", "Three", "Four", "Five"]
queueLock = threading.Lock()
workQueue = Queue.Queue(10)
threads = []
threadID = 1
# Create new threads
for tName in threadList:
thread = myThread(threadID, tName, workQueue)
thread.start()
threads.append(thread)
threadID += 1
# Fill the queue
queueLock.acquire()
for word in nameList:
workQueue.put(word)
queueLock.release()
# Wait for queue to empty
while not workQueue.empty():
pass
# Notify threads it's time to exit
exitFlag = 1
# Wait for all threads to complete
for t in threads:
t.join()
print "Exiting Main Thread"
When the above code is executed, it produces the following result β
Starting Thread-1
Starting Thread-2
Starting Thread-3
Thread-1 processing One
Thread-2 processing Two
Thread-3 processing Three
Thread-1 processing Four
Thread-2 processing Five
Exiting Thread-3
Exiting Thread-1
Exiting Thread-2
Exiting Main Thread
|
[
{
"code": null,
"e": 2499,
"s": 2378,
"text": "Running several threads is similar to running several different programs concurrently, but with the following benefits β"
},
{
"code": null,
"e": 2697,
"s": 2499,
"text": "Multiple threads within a process share the same data space with the main thread and can therefore share information or communicate with each other more easily than if they were separate processes."
},
{
"code": null,
"e": 2895,
"s": 2697,
"text": "Multiple threads within a process share the same data space with the main thread and can therefore share information or communicate with each other more easily than if they were separate processes."
},
{
"code": null,
"e": 3022,
"s": 2895,
"text": "Threads sometimes called light-weight processes and they do not require much memory overhead; they are cheaper than processes."
},
{
"code": null,
"e": 3149,
"s": 3022,
"text": "Threads sometimes called light-weight processes and they do not require much memory overhead; they are cheaper than processes."
},
{
"code": null,
"e": 3316,
"s": 3149,
"text": "A thread has a beginning, an execution sequence, and a conclusion. It has an instruction pointer that keeps track of where within its context it is currently running."
},
{
"code": null,
"e": 3351,
"s": 3316,
"text": "It can be pre-empted (interrupted)"
},
{
"code": null,
"e": 3386,
"s": 3351,
"text": "It can be pre-empted (interrupted)"
},
{
"code": null,
"e": 3504,
"s": 3386,
"text": "It can temporarily be put on hold (also known as sleeping) while other threads are running - this is called yielding."
},
{
"code": null,
"e": 3622,
"s": 3504,
"text": "It can temporarily be put on hold (also known as sleeping) while other threads are running - this is called yielding."
},
{
"code": null,
"e": 3710,
"s": 3622,
"text": "To spawn another thread, you need to call following method available in thread module β"
},
{
"code": null,
"e": 3764,
"s": 3710,
"text": "thread.start_new_thread ( function, args[, kwargs] )\n"
},
{
"code": null,
"e": 3863,
"s": 3764,
"text": "This method call enables a fast and efficient way to create new threads in both Linux and Windows."
},
{
"code": null,
"e": 4022,
"s": 3863,
"text": "The method call returns immediately and the child thread starts and calls function with the passed list of args. When function returns, the thread terminates."
},
{
"code": null,
"e": 4180,
"s": 4022,
"text": "Here, args is a tuple of arguments; use an empty tuple to call function without passing any arguments. kwargs is an optional dictionary of keyword arguments."
},
{
"code": null,
"e": 4659,
"s": 4180,
"text": "#!/usr/bin/python\n\nimport thread\nimport time\n\n# Define a function for the thread\ndef print_time( threadName, delay):\n count = 0\n while count < 5:\n time.sleep(delay)\n count += 1\n print \"%s: %s\" % ( threadName, time.ctime(time.time()) )\n\n# Create two threads as follows\ntry:\n thread.start_new_thread( print_time, (\"Thread-1\", 2, ) )\n thread.start_new_thread( print_time, (\"Thread-2\", 4, ) )\nexcept:\n print \"Error: unable to start thread\"\n\nwhile 1:\n pass"
},
{
"code": null,
"e": 4728,
"s": 4659,
"text": "When the above code is executed, it produces the following result β"
},
{
"code": null,
"e": 5079,
"s": 4728,
"text": "Thread-1: Thu Jan 22 15:42:17 2009\nThread-1: Thu Jan 22 15:42:19 2009\nThread-2: Thu Jan 22 15:42:19 2009\nThread-1: Thu Jan 22 15:42:21 2009\nThread-2: Thu Jan 22 15:42:23 2009\nThread-1: Thu Jan 22 15:42:23 2009\nThread-1: Thu Jan 22 15:42:25 2009\nThread-2: Thu Jan 22 15:42:27 2009\nThread-2: Thu Jan 22 15:42:31 2009\nThread-2: Thu Jan 22 15:42:35 2009\n"
},
{
"code": null,
"e": 5212,
"s": 5079,
"text": "Although it is very effective for low-level threading, but the thread module is very limited compared to the newer threading module."
},
{
"code": null,
"e": 5382,
"s": 5212,
"text": "The newer threading module included with Python 2.4 provides much more powerful, high-level support for threads than the thread module discussed in the previous section."
},
{
"code": null,
"e": 5487,
"s": 5382,
"text": "The threading module exposes all the methods of the thread module and provides some additional methods β"
},
{
"code": null,
"e": 5567,
"s": 5487,
"text": "threading.activeCount() β Returns the number of thread objects that are active."
},
{
"code": null,
"e": 5647,
"s": 5567,
"text": "threading.activeCount() β Returns the number of thread objects that are active."
},
{
"code": null,
"e": 5744,
"s": 5647,
"text": "threading.currentThread() β Returns the number of thread objects in the caller's thread control."
},
{
"code": null,
"e": 5841,
"s": 5744,
"text": "threading.currentThread() β Returns the number of thread objects in the caller's thread control."
},
{
"code": null,
"e": 5929,
"s": 5841,
"text": "threading.enumerate() β Returns a list of all thread objects that are currently active."
},
{
"code": null,
"e": 6017,
"s": 5929,
"text": "threading.enumerate() β Returns a list of all thread objects that are currently active."
},
{
"code": null,
"e": 6172,
"s": 6017,
"text": "In addition to the methods, the threading module has the Thread class that implements threading. The methods provided by the Thread class are as follows β"
},
{
"code": null,
"e": 6230,
"s": 6172,
"text": "run() β The run() method is the entry point for a thread."
},
{
"code": null,
"e": 6288,
"s": 6230,
"text": "run() β The run() method is the entry point for a thread."
},
{
"code": null,
"e": 6360,
"s": 6288,
"text": "start() β The start() method starts a thread by calling the run method."
},
{
"code": null,
"e": 6432,
"s": 6360,
"text": "start() β The start() method starts a thread by calling the run method."
},
{
"code": null,
"e": 6491,
"s": 6432,
"text": " join([time]) β The join() waits for threads to terminate."
},
{
"code": null,
"e": 6550,
"s": 6491,
"text": " join([time]) β The join() waits for threads to terminate."
},
{
"code": null,
"e": 6628,
"s": 6550,
"text": " isAlive() β The isAlive() method checks whether a thread is still executing."
},
{
"code": null,
"e": 6706,
"s": 6628,
"text": " isAlive() β The isAlive() method checks whether a thread is still executing."
},
{
"code": null,
"e": 6770,
"s": 6706,
"text": " getName() β The getName() method returns the name of a thread."
},
{
"code": null,
"e": 6834,
"s": 6770,
"text": " getName() β The getName() method returns the name of a thread."
},
{
"code": null,
"e": 6895,
"s": 6834,
"text": " setName() β The setName() method sets the name of a thread."
},
{
"code": null,
"e": 6956,
"s": 6895,
"text": " setName() β The setName() method sets the name of a thread."
},
{
"code": null,
"e": 7041,
"s": 6956,
"text": "To implement a new thread using the threading module, you have to do the following β"
},
{
"code": null,
"e": 7084,
"s": 7041,
"text": "Define a new subclass of the Thread class."
},
{
"code": null,
"e": 7127,
"s": 7084,
"text": "Define a new subclass of the Thread class."
},
{
"code": null,
"e": 7199,
"s": 7127,
"text": "Override the __init__(self [,args]) method to add additional arguments."
},
{
"code": null,
"e": 7271,
"s": 7199,
"text": "Override the __init__(self [,args]) method to add additional arguments."
},
{
"code": null,
"e": 7368,
"s": 7271,
"text": "Then, override the run(self [,args]) method to implement what the thread should do when started."
},
{
"code": null,
"e": 7465,
"s": 7368,
"text": "Then, override the run(self [,args]) method to implement what the thread should do when started."
},
{
"code": null,
"e": 7632,
"s": 7465,
"text": "Once you have created the new Thread subclass, you can create an instance of it and then start a new thread by invoking the start(), which in turn calls run() method."
},
{
"code": null,
"e": 8424,
"s": 7632,
"text": "#!/usr/bin/python\n\nimport threading\nimport time\n\nexitFlag = 0\n\nclass myThread (threading.Thread):\n def __init__(self, threadID, name, counter):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.name = name\n self.counter = counter\n def run(self):\n print \"Starting \" + self.name\n print_time(self.name, 5, self.counter)\n print \"Exiting \" + self.name\n\ndef print_time(threadName, counter, delay):\n while counter:\n if exitFlag:\n threadName.exit()\n time.sleep(delay)\n print \"%s: %s\" % (threadName, time.ctime(time.time()))\n counter -= 1\n\n# Create new threads\nthread1 = myThread(1, \"Thread-1\", 1)\nthread2 = myThread(2, \"Thread-2\", 2)\n\n# Start new Threads\nthread1.start()\nthread2.start()\n\nprint \"Exiting Main Thread\""
},
{
"code": null,
"e": 8493,
"s": 8424,
"text": "When the above code is executed, it produces the following result β"
},
{
"code": null,
"e": 8934,
"s": 8493,
"text": "Starting Thread-1\nStarting Thread-2\nExiting Main Thread\nThread-1: Thu Mar 21 09:10:03 2013\nThread-1: Thu Mar 21 09:10:04 2013\nThread-2: Thu Mar 21 09:10:04 2013\nThread-1: Thu Mar 21 09:10:05 2013\nThread-1: Thu Mar 21 09:10:06 2013\nThread-2: Thu Mar 21 09:10:06 2013\nThread-1: Thu Mar 21 09:10:07 2013\nExiting Thread-1\nThread-2: Thu Mar 21 09:10:08 2013\nThread-2: Thu Mar 21 09:10:10 2013\nThread-2: Thu Mar 21 09:10:12 2013\nExiting Thread-2\n"
},
{
"code": null,
"e": 9145,
"s": 8934,
"text": "The threading module provided with Python includes a simple-to-implement locking mechanism that allows you to synchronize threads. A new lock is created by calling the Lock() method, which returns the new lock."
},
{
"code": null,
"e": 9345,
"s": 9145,
"text": "The acquire(blocking) method of the new lock object is used to force threads to run synchronously. The optional blocking parameter enables you to control whether the thread waits to acquire the lock."
},
{
"code": null,
"e": 9567,
"s": 9345,
"text": "If blocking is set to 0, the thread returns immediately with a 0 value if the lock cannot be acquired and with a 1 if the lock was acquired. If blocking is set to 1, the thread blocks and wait for the lock to be released."
},
{
"code": null,
"e": 9670,
"s": 9567,
"text": "The release() method of the new lock object is used to release the lock when it is no longer required."
},
{
"code": null,
"e": 10690,
"s": 9670,
"text": "#!/usr/bin/python\n\nimport threading\nimport time\n\nclass myThread (threading.Thread):\n def __init__(self, threadID, name, counter):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.name = name\n self.counter = counter\n def run(self):\n print \"Starting \" + self.name\n # Get lock to synchronize threads\n threadLock.acquire()\n print_time(self.name, self.counter, 3)\n # Free lock to release next thread\n threadLock.release()\n\ndef print_time(threadName, delay, counter):\n while counter:\n time.sleep(delay)\n print \"%s: %s\" % (threadName, time.ctime(time.time()))\n counter -= 1\n\nthreadLock = threading.Lock()\nthreads = []\n\n# Create new threads\nthread1 = myThread(1, \"Thread-1\", 1)\nthread2 = myThread(2, \"Thread-2\", 2)\n\n# Start new Threads\nthread1.start()\nthread2.start()\n\n# Add threads to thread list\nthreads.append(thread1)\nthreads.append(thread2)\n\n# Wait for all threads to complete\nfor t in threads:\n t.join()\nprint \"Exiting Main Thread\""
},
{
"code": null,
"e": 10759,
"s": 10690,
"text": "When the above code is executed, it produces the following result β"
},
{
"code": null,
"e": 11026,
"s": 10759,
"text": "Starting Thread-1\nStarting Thread-2\nThread-1: Thu Mar 21 09:11:28 2013\nThread-1: Thu Mar 21 09:11:29 2013\nThread-1: Thu Mar 21 09:11:30 2013\nThread-2: Thu Mar 21 09:11:32 2013\nThread-2: Thu Mar 21 09:11:34 2013\nThread-2: Thu Mar 21 09:11:36 2013\nExiting Main Thread\n"
},
{
"code": null,
"e": 11176,
"s": 11026,
"text": "The Queue module allows you to create a new queue object that can hold a specific number of items. There are following methods to control the Queue β"
},
{
"code": null,
"e": 11238,
"s": 11176,
"text": "get() β The get() removes and returns an item from the queue."
},
{
"code": null,
"e": 11300,
"s": 11238,
"text": "get() β The get() removes and returns an item from the queue."
},
{
"code": null,
"e": 11338,
"s": 11300,
"text": "put() β The put adds item to a queue."
},
{
"code": null,
"e": 11376,
"s": 11338,
"text": "put() β The put adds item to a queue."
},
{
"code": null,
"e": 11459,
"s": 11376,
"text": "qsize() β The qsize() returns the number of items that are currently in the queue."
},
{
"code": null,
"e": 11542,
"s": 11459,
"text": "qsize() β The qsize() returns the number of items that are currently in the queue."
},
{
"code": null,
"e": 11615,
"s": 11542,
"text": "empty() β The empty( ) returns True if queue is empty; otherwise, False."
},
{
"code": null,
"e": 11688,
"s": 11615,
"text": "empty() β The empty( ) returns True if queue is empty; otherwise, False."
},
{
"code": null,
"e": 11757,
"s": 11688,
"text": "full() β the full() returns True if queue is full; otherwise, False."
},
{
"code": null,
"e": 11826,
"s": 11757,
"text": "full() β the full() returns True if queue is full; otherwise, False."
},
{
"code": null,
"e": 13172,
"s": 11826,
"text": "#!/usr/bin/python\n\nimport Queue\nimport threading\nimport time\n\nexitFlag = 0\n\nclass myThread (threading.Thread):\n def __init__(self, threadID, name, q):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.name = name\n self.q = q\n def run(self):\n print \"Starting \" + self.name\n process_data(self.name, self.q)\n print \"Exiting \" + self.name\n\ndef process_data(threadName, q):\n while not exitFlag:\n queueLock.acquire()\n if not workQueue.empty():\n data = q.get()\n queueLock.release()\n print \"%s processing %s\" % (threadName, data)\n else:\n queueLock.release()\n time.sleep(1)\n\nthreadList = [\"Thread-1\", \"Thread-2\", \"Thread-3\"]\nnameList = [\"One\", \"Two\", \"Three\", \"Four\", \"Five\"]\nqueueLock = threading.Lock()\nworkQueue = Queue.Queue(10)\nthreads = []\nthreadID = 1\n\n# Create new threads\nfor tName in threadList:\n thread = myThread(threadID, tName, workQueue)\n thread.start()\n threads.append(thread)\n threadID += 1\n\n# Fill the queue\nqueueLock.acquire()\nfor word in nameList:\n workQueue.put(word)\nqueueLock.release()\n\n# Wait for queue to empty\nwhile not workQueue.empty():\n pass\n\n# Notify threads it's time to exit\nexitFlag = 1\n\n# Wait for all threads to complete\nfor t in threads:\n t.join()\nprint \"Exiting Main Thread\""
},
{
"code": null,
"e": 13241,
"s": 13172,
"text": "When the above code is executed, it produces the following result β"
}
] |
How to Prevent Screenshot Or Screen Recorder in Android?
|
23 Sep, 2021
In some situations, we donβt want to allow to take screenshots or screen recordings of our android application. Here we are going to explain how to prevent Android from taking a screenshot or screen recording when the app goes to the background. Generally, when we take a screenshot, we will see a Screen Capture notification in the notification bar and you can see that screenshot in the Gallery app if you click that notification. And some of the android application we canβt take a screenshot of the visible screen because of the screen secured by the developer. In this situation, weβll see the message in the notification bar or in the Toast over the screen. Some of the payment transfer apps or course-containing apps have this feature. In this article, weβre going to create a simple project to demonstrate how this feature works. A sample GIF 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: 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. We will create a simple TextView inside the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Preventing App from Taking Screenshot" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" android:textStyle="bold" android:textSize="18sp" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
In the MainActivity.java file simply add the following code and it will prevent taking Screenshot in Android App.
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE);
Below is the complete code for the MainActivity.java file.
Java
import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.view.WindowManager; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Adding this line will prevent taking screenshot in your app getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE); }}
Method 1 is only appropriate for a single activity but whatβs the solution for block screenshot for all the activities. We are going to discuss this in method 2. First of all, make a Custom Application class and add a registerActivityLifecycleCallbacks. Then register it in your manifest.
Step 1: Here write the given code in the MyApplicationContext.java file
Java
import android.app.Activity;import android.app.Application;import android.content.Context;import android.os.Bundle;import android.view.WindowManager; public class MyApplicationContext extends Application { private Context context; public void onCreate() { super.onCreate(); context = getApplicationContext(); setupActivityListener(); } private void setupActivityListener() { registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() { @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE); } @Override public void onActivityStarted(Activity activity) { } @Override public void onActivityResumed(Activity activity) { } @Override public void onActivityPaused(Activity activity) { } @Override public void onActivityStopped(Activity activity) { } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { } @Override public void onActivityDestroyed(Activity activity) { } }); }}
Step 2: Register it in the manifest file like the following
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:name=".MyApplicationContext"
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>
Here you can see it clearly it neither allows taking screenshots nor screen recordings as when we try to take screen recordings it turns black.
anikakapoor
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Sep, 2021"
},
{
"code": null,
"e": 1055,
"s": 52,
"text": "In some situations, we donβt want to allow to take screenshots or screen recordings of our android application. Here we are going to explain how to prevent Android from taking a screenshot or screen recording when the app goes to the background. Generally, when we take a screenshot, we will see a Screen Capture notification in the notification bar and you can see that screenshot in the Gallery app if you click that notification. And some of the android application we canβt take a screenshot of the visible screen because of the screen secured by the developer. In this situation, weβll see the message in the notification bar or in the Toast over the screen. Some of the payment transfer apps or course-containing apps have this feature. In this article, weβre going to create a simple project to demonstrate how this feature works. A sample GIF 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": 1084,
"s": 1055,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 1246,
"s": 1084,
"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": 1294,
"s": 1246,
"text": "Step 2: Working with the activity_main.xml file"
},
{
"code": null,
"e": 1504,
"s": 1294,
"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. We will create a simple TextView inside the activity_main.xml file."
},
{
"code": null,
"e": 1508,
"s": 1504,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Preventing App from Taking Screenshot\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" android:textStyle=\"bold\" android:textSize=\"18sp\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 2365,
"s": 1508,
"text": null
},
{
"code": null,
"e": 2484,
"s": 2370,
"text": "In the MainActivity.java file simply add the following code and it will prevent taking Screenshot in Android App."
},
{
"code": null,
"e": 2547,
"s": 2486,
"text": "getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,"
},
{
"code": null,
"e": 2622,
"s": 2547,
"text": " WindowManager.LayoutParams.FLAG_SECURE);"
},
{
"code": null,
"e": 2683,
"s": 2624,
"text": "Below is the complete code for the MainActivity.java file."
},
{
"code": null,
"e": 2690,
"s": 2685,
"text": "Java"
},
{
"code": "import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.view.WindowManager; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Adding this line will prevent taking screenshot in your app getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE); }}",
"e": 3235,
"s": 2690,
"text": null
},
{
"code": null,
"e": 3529,
"s": 3240,
"text": "Method 1 is only appropriate for a single activity but whatβs the solution for block screenshot for all the activities. We are going to discuss this in method 2. First of all, make a Custom Application class and add a registerActivityLifecycleCallbacks. Then register it in your manifest."
},
{
"code": null,
"e": 3603,
"s": 3531,
"text": "Step 1: Here write the given code in the MyApplicationContext.java file"
},
{
"code": null,
"e": 3610,
"s": 3605,
"text": "Java"
},
{
"code": "import android.app.Activity;import android.app.Application;import android.content.Context;import android.os.Bundle;import android.view.WindowManager; public class MyApplicationContext extends Application { private Context context; public void onCreate() { super.onCreate(); context = getApplicationContext(); setupActivityListener(); } private void setupActivityListener() { registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() { @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE); } @Override public void onActivityStarted(Activity activity) { } @Override public void onActivityResumed(Activity activity) { } @Override public void onActivityPaused(Activity activity) { } @Override public void onActivityStopped(Activity activity) { } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { } @Override public void onActivityDestroyed(Activity activity) { } }); }}",
"e": 4968,
"s": 3610,
"text": null
},
{
"code": null,
"e": 5032,
"s": 4972,
"text": "Step 2: Register it in the manifest file like the following"
},
{
"code": null,
"e": 5632,
"s": 5034,
"text": "<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:name=\".MyApplicationContext\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>"
},
{
"code": null,
"e": 5778,
"s": 5634,
"text": "Here you can see it clearly it neither allows taking screenshots nor screen recordings as when we try to take screen recordings it turns black."
},
{
"code": null,
"e": 5794,
"s": 5782,
"text": "anikakapoor"
},
{
"code": null,
"e": 5818,
"s": 5794,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 5826,
"s": 5818,
"text": "Android"
},
{
"code": null,
"e": 5831,
"s": 5826,
"text": "Java"
},
{
"code": null,
"e": 5850,
"s": 5831,
"text": "Technical Scripter"
},
{
"code": null,
"e": 5855,
"s": 5850,
"text": "Java"
},
{
"code": null,
"e": 5863,
"s": 5855,
"text": "Android"
}
] |
Count the frequency of a variable per column in R Dataframe
|
30 May, 2021
A data frame may contain repeated or missing values. Each column may contain any number of duplicate or repeated instances of the same variable. Data statistics and analysis mostly rely on the task of computing the frequency or count of the number of instances a particular variable contains within each column. In this article, we are going to see how to find the frequency of a variable per column in Dataframe in R Programming Language.
Method 1: Using plyr package
The plyr package is used preferably to experiment with the data, that is, create, modify and delete the columns of the data frame, subjecting them to multiple conditions and user-defined functions. It can be downloaded and loaded into the workspace using the following command:
install.packages("lpyr")
The ldply() method of this package is used to apply a pre-defined function over each element of a list and then combine the results into a data frame. This method can be used to calculate the frequency of the variable belonging to integer, character, or factor type class.
Syntax: ldply(data, fun = NULL)
Arguments :
data β The data over which to apply
fun β The function to be applied
In this method, the sum() function is applied as a function over the elements of each column belonging to the data frame. The function results in the summation of the number of times a particular specified value occurs within the column. The function is applied individually over each column. The output returned is in the form of a data frame where the first column gives the column names assigned to the data frame and the second column displays the total number of occurrences of the specified variable in that column.
Code:
R
library ('plyr')set.seed(1) # creating a data framedata_table <- data.frame(col1 = sample(letters[1:3], 8, replace = TRUE) , col2 = sample(letters[1:3], 8, replace = TRUE), col3 = sample(letters[1:3], 8, replace = TRUE), col4 = sample(letters[1:3], 8, replace = TRUE)) print ("Original DataFrame")print (data_table)print ("Count of value per column") # count number of c in each columnldply(data_table, function(c) sum(c =="a"))
Output:
[1] "Original DataFrame"
col1 col2 col3 col4
1 a b b a
2 c c b b
3 a c c a
4 b a a a
5 a a c b
6 c a a b
7 c b a b
8 b b a a
[1] "Count of value per column"
.id V1
1 col1 3
2 col2 3
3 col3 4
4 col4 4
The method can also be used to calculate the frequency of a vector of values. The function is defined in such a way that it validates the occurrence of an element inside a vector using the %in% operator. The summation of TRUE occurrences within each column is then returned as the counts.
val %in% vec
Code:
R
library ('plyr') set.seed(1) # creating a data framedata_table <- data.frame(col1 = sample(letters[1:3], 8, replace = TRUE) , col2 = sample(letters[1:3], 8, replace = TRUE), col3 = sample(letters[1:3], 8, replace = TRUE), col4 = sample(letters[1:3], 8, replace = TRUE)) print ("Original DataFrame")print (data_table)print ("Count of value per column")ldply(data_table, function(c) sum(c %in% vec))
Output:
[1] "Original DataFrame"
col1 col2 col3 col4
1 a b b a
2 c c b b
3 a c c a
4 b a a a
5 a a c b
6 c a a b
7 c b a b
8 b b a a
[1] "Count of value per column"
.id V1
1 col1 5
2 col2 6
3 col3 6
4 col4 8
Method 2: Using sapply() method
The sapply() method, which is used to compute the frequency of the occurrences of a variable within each column of the data frame. The sapply() method is used to apply functions over vectors or lists, and return outputs based on these computations.
sapply (df , FUN)
In this case, the FUN is a user-defined function that initially computed the number of levels within the entire data frame cells. This is done by the application of the unlist() methods which are used to convert a data frame into a nested list. This is followed by the application of unique() which extracts only the unique variable values contained in the data frame.
unique (list)
The vector obtained as an output of the unique() method is explicitly converted to a factor type object by the factor() method, where the levels are the unique values encountered. All the components are thus mapped to levels within this vector.
factor (vec)
In the end, the table() method is then applied. The table() method takes the cross-classifying factors belonging in a vector to build a contingency table of the counts at each combination of factor levels. A contingency table is basically a tabulation of the counts and/or percentages for multiple variables. It excludes the counting of any missing values from the factor variable supplied to the method. The output returned is in the form of a table. This method can be used to cross-tabulation and statistical analysis.
table (fac-vec, .. )
The output is a data frame with row headings as the unique values of the data frame and the column headings as the column names of the original data frame, where each cell value indicates the number of occurrences of that row heading variable in the respective column.
Code:
R
set.seed(1) # creating a data framedata_table <- data.frame(col1 = sample(letters[1:3], 8, replace = TRUE) , col2 = sample(letters[1:3], 8, replace = TRUE), col3 = sample(letters[1:3], 8, replace = TRUE), col4 = sample(letters[1:3], 8, replace = TRUE)) print ("Original DataFrame")print (data_table) # compute unique levels in data framelvls <- unique(unlist(data_table)) # apply the summation per value freq <- sapply(data_table, function(x) table(factor(x, levels = lvls, ordered = TRUE)))print ("Count of variables per column")print (freq)
Output:
[1] "Original DataFrame"
col1 col2 col3 col4
1 a b b a
2 c c b b
3 a c c a
4 b a a a
5 a a c b
6 c a a b
7 c b a b
8 b b a a
[1] "Count of variables per column"
col1 col2 col3 col4
a 3 3 4 4
c 3 2 2 0
b 2 3 2 4
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to change Row Names of DataFrame in R ?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Remove rows with NA in one column of R DataFrame
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 May, 2021"
},
{
"code": null,
"e": 468,
"s": 28,
"text": "A data frame may contain repeated or missing values. Each column may contain any number of duplicate or repeated instances of the same variable. Data statistics and analysis mostly rely on the task of computing the frequency or count of the number of instances a particular variable contains within each column. In this article, we are going to see how to find the frequency of a variable per column in Dataframe in R Programming Language."
},
{
"code": null,
"e": 497,
"s": 468,
"text": "Method 1: Using plyr package"
},
{
"code": null,
"e": 776,
"s": 497,
"text": "The plyr package is used preferably to experiment with the data, that is, create, modify and delete the columns of the data frame, subjecting them to multiple conditions and user-defined functions. It can be downloaded and loaded into the workspace using the following command: "
},
{
"code": null,
"e": 801,
"s": 776,
"text": "install.packages(\"lpyr\")"
},
{
"code": null,
"e": 1075,
"s": 801,
"text": "The ldply() method of this package is used to apply a pre-defined function over each element of a list and then combine the results into a data frame. This method can be used to calculate the frequency of the variable belonging to integer, character, or factor type class. "
},
{
"code": null,
"e": 1107,
"s": 1075,
"text": "Syntax: ldply(data, fun = NULL)"
},
{
"code": null,
"e": 1120,
"s": 1107,
"text": "Arguments : "
},
{
"code": null,
"e": 1157,
"s": 1120,
"text": "data β The data over which to apply "
},
{
"code": null,
"e": 1190,
"s": 1157,
"text": "fun β The function to be applied"
},
{
"code": null,
"e": 1714,
"s": 1190,
"text": "In this method, the sum() function is applied as a function over the elements of each column belonging to the data frame. The function results in the summation of the number of times a particular specified value occurs within the column. The function is applied individually over each column. The output returned is in the form of a data frame where the first column gives the column names assigned to the data frame and the second column displays the total number of occurrences of the specified variable in that column. "
},
{
"code": null,
"e": 1720,
"s": 1714,
"text": "Code:"
},
{
"code": null,
"e": 1722,
"s": 1720,
"text": "R"
},
{
"code": "library ('plyr')set.seed(1) # creating a data framedata_table <- data.frame(col1 = sample(letters[1:3], 8, replace = TRUE) , col2 = sample(letters[1:3], 8, replace = TRUE), col3 = sample(letters[1:3], 8, replace = TRUE), col4 = sample(letters[1:3], 8, replace = TRUE)) print (\"Original DataFrame\")print (data_table)print (\"Count of value per column\") # count number of c in each columnldply(data_table, function(c) sum(c ==\"a\"))",
"e": 2382,
"s": 1722,
"text": null
},
{
"code": null,
"e": 2390,
"s": 2382,
"text": "Output:"
},
{
"code": null,
"e": 2712,
"s": 2390,
"text": "[1] \"Original DataFrame\" \n col1 col2 col3 col4 \n1 a b b a \n2 c c b b \n3 a c c a \n4 b a a a \n5 a a c b \n6 c a a b \n7 c b a b \n8 b b a a \n[1] \"Count of value per column\"\n .id V1 \n1 col1 3 \n2 col2 3 \n3 col3 4 \n4 col4 4"
},
{
"code": null,
"e": 3002,
"s": 2712,
"text": "The method can also be used to calculate the frequency of a vector of values. The function is defined in such a way that it validates the occurrence of an element inside a vector using the %in% operator. The summation of TRUE occurrences within each column is then returned as the counts. "
},
{
"code": null,
"e": 3015,
"s": 3002,
"text": "val %in% vec"
},
{
"code": null,
"e": 3021,
"s": 3015,
"text": "Code:"
},
{
"code": null,
"e": 3023,
"s": 3021,
"text": "R"
},
{
"code": "library ('plyr') set.seed(1) # creating a data framedata_table <- data.frame(col1 = sample(letters[1:3], 8, replace = TRUE) , col2 = sample(letters[1:3], 8, replace = TRUE), col3 = sample(letters[1:3], 8, replace = TRUE), col4 = sample(letters[1:3], 8, replace = TRUE)) print (\"Original DataFrame\")print (data_table)print (\"Count of value per column\")ldply(data_table, function(c) sum(c %in% vec))",
"e": 3654,
"s": 3023,
"text": null
},
{
"code": null,
"e": 3662,
"s": 3654,
"text": "Output:"
},
{
"code": null,
"e": 3971,
"s": 3662,
"text": "[1] \"Original DataFrame\"\n col1 col2 col3 col4\n1 a b b a\n2 c c b b\n3 a c c a\n4 b a a a\n5 a a c b\n6 c a a b\n7 c b a b\n8 b b a a \n[1] \"Count of value per column\"\n .id V1\n1 col1 5\n2 col2 6\n3 col3 6\n4 col4 8"
},
{
"code": null,
"e": 4003,
"s": 3971,
"text": "Method 2: Using sapply() method"
},
{
"code": null,
"e": 4253,
"s": 4003,
"text": "The sapply() method, which is used to compute the frequency of the occurrences of a variable within each column of the data frame. The sapply() method is used to apply functions over vectors or lists, and return outputs based on these computations. "
},
{
"code": null,
"e": 4271,
"s": 4253,
"text": "sapply (df , FUN)"
},
{
"code": null,
"e": 4641,
"s": 4271,
"text": "In this case, the FUN is a user-defined function that initially computed the number of levels within the entire data frame cells. This is done by the application of the unlist() methods which are used to convert a data frame into a nested list. This is followed by the application of unique() which extracts only the unique variable values contained in the data frame. "
},
{
"code": null,
"e": 4655,
"s": 4641,
"text": "unique (list)"
},
{
"code": null,
"e": 4901,
"s": 4655,
"text": "The vector obtained as an output of the unique() method is explicitly converted to a factor type object by the factor() method, where the levels are the unique values encountered. All the components are thus mapped to levels within this vector. "
},
{
"code": null,
"e": 4914,
"s": 4901,
"text": "factor (vec)"
},
{
"code": null,
"e": 5436,
"s": 4914,
"text": "In the end, the table() method is then applied. The table() method takes the cross-classifying factors belonging in a vector to build a contingency table of the counts at each combination of factor levels. A contingency table is basically a tabulation of the counts and/or percentages for multiple variables. It excludes the counting of any missing values from the factor variable supplied to the method. The output returned is in the form of a table. This method can be used to cross-tabulation and statistical analysis."
},
{
"code": null,
"e": 5457,
"s": 5436,
"text": "table (fac-vec, .. )"
},
{
"code": null,
"e": 5727,
"s": 5457,
"text": "The output is a data frame with row headings as the unique values of the data frame and the column headings as the column names of the original data frame, where each cell value indicates the number of occurrences of that row heading variable in the respective column. "
},
{
"code": null,
"e": 5733,
"s": 5727,
"text": "Code:"
},
{
"code": null,
"e": 5735,
"s": 5733,
"text": "R"
},
{
"code": "set.seed(1) # creating a data framedata_table <- data.frame(col1 = sample(letters[1:3], 8, replace = TRUE) , col2 = sample(letters[1:3], 8, replace = TRUE), col3 = sample(letters[1:3], 8, replace = TRUE), col4 = sample(letters[1:3], 8, replace = TRUE)) print (\"Original DataFrame\")print (data_table) # compute unique levels in data framelvls <- unique(unlist(data_table)) # apply the summation per value freq <- sapply(data_table, function(x) table(factor(x, levels = lvls, ordered = TRUE)))print (\"Count of variables per column\")print (freq)",
"e": 6565,
"s": 5735,
"text": null
},
{
"code": null,
"e": 6573,
"s": 6565,
"text": "Output:"
},
{
"code": null,
"e": 6925,
"s": 6573,
"text": "[1] \"Original DataFrame\"\n col1 col2 col3 col4\n1 a b b a\n2 c c b b\n3 a c c a\n4 b a a a\n5 a a c b\n6 c a a b\n7 c b a b\n8 b b a a \n[1] \"Count of variables per column\" \n col1 col2 col3 col4 \na 3 3 4 4 \nc 3 2 2 0 \nb 2 3 2 4"
},
{
"code": null,
"e": 6932,
"s": 6925,
"text": "Picked"
},
{
"code": null,
"e": 6953,
"s": 6932,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 6965,
"s": 6953,
"text": "R-DataFrame"
},
{
"code": null,
"e": 6976,
"s": 6965,
"text": "R Language"
},
{
"code": null,
"e": 6987,
"s": 6976,
"text": "R Programs"
},
{
"code": null,
"e": 7085,
"s": 6987,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7137,
"s": 7085,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 7189,
"s": 7137,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 7247,
"s": 7189,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 7279,
"s": 7247,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 7314,
"s": 7279,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 7372,
"s": 7314,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 7416,
"s": 7372,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 7465,
"s": 7416,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 7508,
"s": 7465,
"text": "Replace Specific Characters in String in R"
}
] |
Shorβs Factorization Algorithm
|
05 Feb, 2021
Shorβs Factorization Algorithm:
Shorβs Factorization Algorithm is proposed by Peter Shor.
It suggests that quantum mechanics allows the factorization to be performed in polynomial time, rather than exponential time achieved after using classical algorithms.
This could have a drastic impact on the field of data security, a concept based on the prime factorization of large numbers.
Many polynomial-time algorithms for integer multiplication (e.g., Euclidβs Algorithm) do exist, but no polynomial-time algorithm for factorization exists.
So, Shor came up with an algorithm i.e. Shorβs Factorization Algorithm, an algorithm for factorizing non-prime integers N of L bits.
Quantum algorithms are far much better than classical algorithms because they are based on Quantum Fourier Transform.
Run time on the classical computer is O[exp (L1/3(log L)2/3)] but that on the quantum computer is O(L3).
So, Shorβs Algorithm in principle, shows that a quantum computer is capable of factoring very large numbers in polynomial time.
Shorβs Algorithm depends on:
Modular Arithmetic
Quantum Parallelism
Quantum Fourier Transformation
The Algorithm stands as:
Given an odd composite number N, find an integer d, strictly between 1 and N, that divides N.
Shorβs Algorithm consists of the following two parts:
Conversion of the problem of factorizing to the problem of finding the period. This part can be implemented with classical means.
Finding the period or Quantum period finding using the Quantum Fourier Transform, and is responsible for quantum speedup, and utilizes quantum parallelism.
In Shorβs Algorithm, the Input is Non-prime number N and the Output is Non-trivial factor of N
INPUT (N) β> SHORβS ALGORITHM β> OUTPUT (Non-trivial factor of N)
Algorithm: It contains a few steps, at only step 2 the use of quantum computers is required.
Choose any random number let say r, such that r < N so that they are co-primes of each other.A quantum computer is used to determine the unknown period p of the function fr, N (x) = rx mod N.If p is an odd integer, then go back to Step 1. Else move to the next step.Since p is an even integer so, (rp/2 β 1)(rp/2 + 1) = rp β 1 = 0 mod N.Now, if the value of rp/2 + 1 = 0 mod N, go back to Step 1.If the value of rp/2 + 1 != 0 mod N, Else move to the next step.Compute d = gcd(rp/2-1, N).The answer required is βdβ.
Choose any random number let say r, such that r < N so that they are co-primes of each other.
A quantum computer is used to determine the unknown period p of the function fr, N (x) = rx mod N.
If p is an odd integer, then go back to Step 1. Else move to the next step.
Since p is an even integer so, (rp/2 β 1)(rp/2 + 1) = rp β 1 = 0 mod N.
Now, if the value of rp/2 + 1 = 0 mod N, go back to Step 1.
If the value of rp/2 + 1 != 0 mod N, Else move to the next step.
Compute d = gcd(rp/2-1, N).
The answer required is βdβ.
Classical part (The order finding problem):This is the classical part of order finding problem. Given that x and N, such that x<N and gcd(x, N) = 1. The order of x is the least positive integer, y such that xy = 1(mod N).
A random number n is picked, such that n < N. Compute gcd(n, N).This can be done using the Euclid Algorithm.If gcd(n, N) != 1, then there is a non-trivial factor of N.If (x+p) = nx + p mod N = nxmod N = f(x).If r is odd, then go back to Step 1.If np/2 = -1(mod N), then go back to Step 1.The gcd(np/2 +/- 1, N) is a non-trivial factor of N.
A random number n is picked, such that n < N. Compute gcd(n, N).
This can be done using the Euclid Algorithm.
If gcd(n, N) != 1, then there is a non-trivial factor of N.If (x+p) = nx + p mod N = nxmod N = f(x).
If r is odd, then go back to Step 1.
If np/2 = -1(mod N), then go back to Step 1.
The gcd(np/2 +/- 1, N) is a non-trivial factor of N.
Quantum part:
This is the quantum order finding part. Choose a power of 2, thenQ = 2L such that N2 <= Q <= 2N2
And consider f = {0, 1, 2, ..., Q-1}
Where, f(y)=1/(Q)1/2 βx=0Q-1I f(x) I wxy and w = exp(2Ο i/Q), i.e. Qth root of unity.
Letβs perform Shorβs Algorithm using an example: To factor an odd integer N (let N = 17).
Choose an integer Q such that N2 <= Q β€ 2 N2 ( lets Q = 324).
Then, randomly choose any integer n such that gcd(n, N)=1, (let us choose the integer be n=7).
Then create two quantum registers (these registers should be entangled so that the collapse of the input registered corresponds to the collapse of the output register)Input Register: must be containing enough qubits to represent numbers as large as Q-1.(i.e., up to 323, so we need 9 qubits).Output Register: must be containing enough qubits to represent numbers as large as (N β 1). (i.e., up to 16, so we require 4 qubits).
Input Register: must be containing enough qubits to represent numbers as large as Q-1.(i.e., up to 323, so we need 9 qubits).
Output Register: must be containing enough qubits to represent numbers as large as (N β 1). (i.e., up to 16, so we require 4 qubits).
Code :
Python
from qiskit import IBMQfrom qiskit.aqua import QuantumInstancefrom qiskit.aqua.algorithms import Shor # Enter your API token hereIBMQ.enable_account('ENTER API TOKEN HERE') provider = IBMQ.get_provider(hub='ibm-q') # Specifies the quantum devicebackend = provider.get_backend('ibmq_qasm_simulator') print('\n Shors Algorithm')print('--------------------')print('\nExecuting...\n') # Function to run Shor's algorithm# where 21 is the integer to be factoredfactors = Shor(35) result_dict = factors.run(QuantumInstance( backend, shots=1, skip_qobj_validation=False)) # Get factors from resultsresult = result_dict['factors'] print(result)print('\nPress any key to close')input()
Output :
Shors Algorithm
- - - - - - - - - - - - -
Executing...
[[5,7]]
Press any key to close
Output for the code above showing the factors 5 and 7 for N=35.
jyoti369
Technical Scripter 2020
Algorithms
Articles
Technical Scripter
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Feb, 2021"
},
{
"code": null,
"e": 84,
"s": 52,
"text": "Shorβs Factorization Algorithm:"
},
{
"code": null,
"e": 142,
"s": 84,
"text": "Shorβs Factorization Algorithm is proposed by Peter Shor."
},
{
"code": null,
"e": 310,
"s": 142,
"text": "It suggests that quantum mechanics allows the factorization to be performed in polynomial time, rather than exponential time achieved after using classical algorithms."
},
{
"code": null,
"e": 435,
"s": 310,
"text": "This could have a drastic impact on the field of data security, a concept based on the prime factorization of large numbers."
},
{
"code": null,
"e": 590,
"s": 435,
"text": "Many polynomial-time algorithms for integer multiplication (e.g., Euclidβs Algorithm) do exist, but no polynomial-time algorithm for factorization exists."
},
{
"code": null,
"e": 723,
"s": 590,
"text": "So, Shor came up with an algorithm i.e. Shorβs Factorization Algorithm, an algorithm for factorizing non-prime integers N of L bits."
},
{
"code": null,
"e": 841,
"s": 723,
"text": "Quantum algorithms are far much better than classical algorithms because they are based on Quantum Fourier Transform."
},
{
"code": null,
"e": 946,
"s": 841,
"text": "Run time on the classical computer is O[exp (L1/3(log L)2/3)] but that on the quantum computer is O(L3)."
},
{
"code": null,
"e": 1074,
"s": 946,
"text": "So, Shorβs Algorithm in principle, shows that a quantum computer is capable of factoring very large numbers in polynomial time."
},
{
"code": null,
"e": 1103,
"s": 1074,
"text": "Shorβs Algorithm depends on:"
},
{
"code": null,
"e": 1122,
"s": 1103,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 1142,
"s": 1122,
"text": "Quantum Parallelism"
},
{
"code": null,
"e": 1173,
"s": 1142,
"text": "Quantum Fourier Transformation"
},
{
"code": null,
"e": 1198,
"s": 1173,
"text": "The Algorithm stands as:"
},
{
"code": null,
"e": 1292,
"s": 1198,
"text": "Given an odd composite number N, find an integer d, strictly between 1 and N, that divides N."
},
{
"code": null,
"e": 1346,
"s": 1292,
"text": "Shorβs Algorithm consists of the following two parts:"
},
{
"code": null,
"e": 1476,
"s": 1346,
"text": "Conversion of the problem of factorizing to the problem of finding the period. This part can be implemented with classical means."
},
{
"code": null,
"e": 1632,
"s": 1476,
"text": "Finding the period or Quantum period finding using the Quantum Fourier Transform, and is responsible for quantum speedup, and utilizes quantum parallelism."
},
{
"code": null,
"e": 1727,
"s": 1632,
"text": "In Shorβs Algorithm, the Input is Non-prime number N and the Output is Non-trivial factor of N"
},
{
"code": null,
"e": 1793,
"s": 1727,
"text": "INPUT (N) β> SHORβS ALGORITHM β> OUTPUT (Non-trivial factor of N)"
},
{
"code": null,
"e": 1886,
"s": 1793,
"text": "Algorithm: It contains a few steps, at only step 2 the use of quantum computers is required."
},
{
"code": null,
"e": 2401,
"s": 1886,
"text": "Choose any random number let say r, such that r < N so that they are co-primes of each other.A quantum computer is used to determine the unknown period p of the function fr, N (x) = rx mod N.If p is an odd integer, then go back to Step 1. Else move to the next step.Since p is an even integer so, (rp/2 β 1)(rp/2 + 1) = rp β 1 = 0 mod N.Now, if the value of rp/2 + 1 = 0 mod N, go back to Step 1.If the value of rp/2 + 1 != 0 mod N, Else move to the next step.Compute d = gcd(rp/2-1, N).The answer required is βdβ."
},
{
"code": null,
"e": 2495,
"s": 2401,
"text": "Choose any random number let say r, such that r < N so that they are co-primes of each other."
},
{
"code": null,
"e": 2594,
"s": 2495,
"text": "A quantum computer is used to determine the unknown period p of the function fr, N (x) = rx mod N."
},
{
"code": null,
"e": 2670,
"s": 2594,
"text": "If p is an odd integer, then go back to Step 1. Else move to the next step."
},
{
"code": null,
"e": 2742,
"s": 2670,
"text": "Since p is an even integer so, (rp/2 β 1)(rp/2 + 1) = rp β 1 = 0 mod N."
},
{
"code": null,
"e": 2802,
"s": 2742,
"text": "Now, if the value of rp/2 + 1 = 0 mod N, go back to Step 1."
},
{
"code": null,
"e": 2867,
"s": 2802,
"text": "If the value of rp/2 + 1 != 0 mod N, Else move to the next step."
},
{
"code": null,
"e": 2895,
"s": 2867,
"text": "Compute d = gcd(rp/2-1, N)."
},
{
"code": null,
"e": 2923,
"s": 2895,
"text": "The answer required is βdβ."
},
{
"code": null,
"e": 3145,
"s": 2923,
"text": "Classical part (The order finding problem):This is the classical part of order finding problem. Given that x and N, such that x<N and gcd(x, N) = 1. The order of x is the least positive integer, y such that xy = 1(mod N)."
},
{
"code": null,
"e": 3486,
"s": 3145,
"text": "A random number n is picked, such that n < N. Compute gcd(n, N).This can be done using the Euclid Algorithm.If gcd(n, N) != 1, then there is a non-trivial factor of N.If (x+p) = nx + p mod N = nxmod N = f(x).If r is odd, then go back to Step 1.If np/2 = -1(mod N), then go back to Step 1.The gcd(np/2 +/- 1, N) is a non-trivial factor of N."
},
{
"code": null,
"e": 3551,
"s": 3486,
"text": "A random number n is picked, such that n < N. Compute gcd(n, N)."
},
{
"code": null,
"e": 3596,
"s": 3551,
"text": "This can be done using the Euclid Algorithm."
},
{
"code": null,
"e": 3697,
"s": 3596,
"text": "If gcd(n, N) != 1, then there is a non-trivial factor of N.If (x+p) = nx + p mod N = nxmod N = f(x)."
},
{
"code": null,
"e": 3734,
"s": 3697,
"text": "If r is odd, then go back to Step 1."
},
{
"code": null,
"e": 3779,
"s": 3734,
"text": "If np/2 = -1(mod N), then go back to Step 1."
},
{
"code": null,
"e": 3832,
"s": 3779,
"text": "The gcd(np/2 +/- 1, N) is a non-trivial factor of N."
},
{
"code": null,
"e": 3846,
"s": 3832,
"text": "Quantum part:"
},
{
"code": null,
"e": 3943,
"s": 3846,
"text": "This is the quantum order finding part. Choose a power of 2, thenQ = 2L such that N2 <= Q <= 2N2"
},
{
"code": null,
"e": 3980,
"s": 3943,
"text": "And consider f = {0, 1, 2, ..., Q-1}"
},
{
"code": null,
"e": 4066,
"s": 3980,
"text": "Where, f(y)=1/(Q)1/2 βx=0Q-1I f(x) I wxy and w = exp(2Ο i/Q), i.e. Qth root of unity."
},
{
"code": null,
"e": 4156,
"s": 4066,
"text": "Letβs perform Shorβs Algorithm using an example: To factor an odd integer N (let N = 17)."
},
{
"code": null,
"e": 4218,
"s": 4156,
"text": "Choose an integer Q such that N2 <= Q β€ 2 N2 ( lets Q = 324)."
},
{
"code": null,
"e": 4313,
"s": 4218,
"text": "Then, randomly choose any integer n such that gcd(n, N)=1, (let us choose the integer be n=7)."
},
{
"code": null,
"e": 4739,
"s": 4313,
"text": "Then create two quantum registers (these registers should be entangled so that the collapse of the input registered corresponds to the collapse of the output register)Input Register: must be containing enough qubits to represent numbers as large as Q-1.(i.e., up to 323, so we need 9 qubits).Output Register: must be containing enough qubits to represent numbers as large as (N β 1). (i.e., up to 16, so we require 4 qubits)."
},
{
"code": null,
"e": 4865,
"s": 4739,
"text": "Input Register: must be containing enough qubits to represent numbers as large as Q-1.(i.e., up to 323, so we need 9 qubits)."
},
{
"code": null,
"e": 4999,
"s": 4865,
"text": "Output Register: must be containing enough qubits to represent numbers as large as (N β 1). (i.e., up to 16, so we require 4 qubits)."
},
{
"code": null,
"e": 5006,
"s": 4999,
"text": "Code :"
},
{
"code": null,
"e": 5013,
"s": 5006,
"text": "Python"
},
{
"code": "from qiskit import IBMQfrom qiskit.aqua import QuantumInstancefrom qiskit.aqua.algorithms import Shor # Enter your API token hereIBMQ.enable_account('ENTER API TOKEN HERE') provider = IBMQ.get_provider(hub='ibm-q') # Specifies the quantum devicebackend = provider.get_backend('ibmq_qasm_simulator') print('\\n Shors Algorithm')print('--------------------')print('\\nExecuting...\\n') # Function to run Shor's algorithm# where 21 is the integer to be factoredfactors = Shor(35) result_dict = factors.run(QuantumInstance( backend, shots=1, skip_qobj_validation=False)) # Get factors from resultsresult = result_dict['factors'] print(result)print('\\nPress any key to close')input()",
"e": 5693,
"s": 5013,
"text": null
},
{
"code": null,
"e": 5702,
"s": 5693,
"text": "Output :"
},
{
"code": null,
"e": 5788,
"s": 5702,
"text": "Shors Algorithm\n- - - - - - - - - - - - -\nExecuting...\n[[5,7]]\nPress any key to close"
},
{
"code": null,
"e": 5852,
"s": 5788,
"text": "Output for the code above showing the factors 5 and 7 for N=35."
},
{
"code": null,
"e": 5861,
"s": 5852,
"text": "jyoti369"
},
{
"code": null,
"e": 5885,
"s": 5861,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 5896,
"s": 5885,
"text": "Algorithms"
},
{
"code": null,
"e": 5905,
"s": 5896,
"text": "Articles"
},
{
"code": null,
"e": 5924,
"s": 5905,
"text": "Technical Scripter"
},
{
"code": null,
"e": 5935,
"s": 5924,
"text": "Algorithms"
}
] |
Difference Between Forward List and List in C++
|
08 Dec, 2021
Forward List is a sequence container that allows unidirectional sequential access to its data. It contains data of the same type. In STL, it has been implemented using Singly Linked List, which requires constant time for insertion and deletion. Elements of the forward list are scattered in the memory and the ordering is maintained by associating every element of the list by the next element of the list via a link. Thus, it makes efficient use of memory. It has been introduced from the C++11 version.
Implementation of Forward List:
C++
// CPP Program to demonstrate forward list#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declaring forward list forward_list<int> flist1; // Assigning values using assign() flist1.assign({ 10, 12, 13, 15 }); // Displaying forward list cout << "The elements of forward list are : "; for (auto a : flist1) cout << a << " "; return 0;}
The elements of forward list are : 10 12 13 15
List is also a sequence container that allows bidirectional sequential access to its data. It contains data of the same type. In STL, it has been implemented using Doubly Linked List and it requires constant time for insertion and deletion. It allows non-contiguous memory allocation. Each element of the list is associated with a link to the element following it and preceding it. It is extensively used in sorting algorithm because of its constant insertion and deletion time and bidirectional sequential access.
Implementation of List:
C++
// CPP Program to demonstrate list#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declaring a list list<int> list1; // Assigning values using assign() list1.assign({ 1, 2, 10, 15 }); // Displaying list cout << "The elements of list are : "; for (auto a : list1) cout << a << " "; return 0;}
The elements of list are : 1 2 10 15
Forward List
List
sooda367
anshikajain26
CPP-forward-list
cpp-list
C++
Difference Between
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Pair in C++ Standard Template Library (STL)
Friend class and function in C++
std::string class in C++
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Dec, 2021"
},
{
"code": null,
"e": 557,
"s": 52,
"text": "Forward List is a sequence container that allows unidirectional sequential access to its data. It contains data of the same type. In STL, it has been implemented using Singly Linked List, which requires constant time for insertion and deletion. Elements of the forward list are scattered in the memory and the ordering is maintained by associating every element of the list by the next element of the list via a link. Thus, it makes efficient use of memory. It has been introduced from the C++11 version."
},
{
"code": null,
"e": 590,
"s": 557,
"text": "Implementation of Forward List: "
},
{
"code": null,
"e": 594,
"s": 590,
"text": "C++"
},
{
"code": "// CPP Program to demonstrate forward list#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declaring forward list forward_list<int> flist1; // Assigning values using assign() flist1.assign({ 10, 12, 13, 15 }); // Displaying forward list cout << \"The elements of forward list are : \"; for (auto a : flist1) cout << a << \" \"; return 0;}",
"e": 987,
"s": 594,
"text": null
},
{
"code": null,
"e": 1034,
"s": 987,
"text": "The elements of forward list are : 10 12 13 15"
},
{
"code": null,
"e": 1551,
"s": 1036,
"text": "List is also a sequence container that allows bidirectional sequential access to its data. It contains data of the same type. In STL, it has been implemented using Doubly Linked List and it requires constant time for insertion and deletion. It allows non-contiguous memory allocation. Each element of the list is associated with a link to the element following it and preceding it. It is extensively used in sorting algorithm because of its constant insertion and deletion time and bidirectional sequential access."
},
{
"code": null,
"e": 1577,
"s": 1551,
"text": "Implementation of List: "
},
{
"code": null,
"e": 1581,
"s": 1577,
"text": "C++"
},
{
"code": "// CPP Program to demonstrate list#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declaring a list list<int> list1; // Assigning values using assign() list1.assign({ 1, 2, 10, 15 }); // Displaying list cout << \"The elements of list are : \"; for (auto a : list1) cout << a << \" \"; return 0;}",
"e": 1931,
"s": 1581,
"text": null
},
{
"code": null,
"e": 1968,
"s": 1931,
"text": "The elements of list are : 1 2 10 15"
},
{
"code": null,
"e": 1983,
"s": 1970,
"text": "Forward List"
},
{
"code": null,
"e": 1988,
"s": 1983,
"text": "List"
},
{
"code": null,
"e": 1997,
"s": 1988,
"text": "sooda367"
},
{
"code": null,
"e": 2011,
"s": 1997,
"text": "anshikajain26"
},
{
"code": null,
"e": 2028,
"s": 2011,
"text": "CPP-forward-list"
},
{
"code": null,
"e": 2037,
"s": 2028,
"text": "cpp-list"
},
{
"code": null,
"e": 2041,
"s": 2037,
"text": "C++"
},
{
"code": null,
"e": 2060,
"s": 2041,
"text": "Difference Between"
},
{
"code": null,
"e": 2064,
"s": 2060,
"text": "CPP"
},
{
"code": null,
"e": 2162,
"s": 2064,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2186,
"s": 2162,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 2206,
"s": 2186,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 2250,
"s": 2206,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2283,
"s": 2250,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 2308,
"s": 2283,
"text": "std::string class in C++"
},
{
"code": null,
"e": 2348,
"s": 2308,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 2379,
"s": 2348,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 2440,
"s": 2379,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2508,
"s": 2440,
"text": "Difference Between Method Overloading and Method Overriding in Java"
}
] |
How to Upload Excel Sheet Data to Firebase Realtime Database in Android?
|
10 Feb, 2022
Firebase Realtime Database is the backend service which is provided by Google for handling backend tasks for your Android apps, IOS apps as well as your websites. It provides so many services such as storage, database, and many more. The feature for which Firebase is famous for its Firebase Realtime Database. By using Firebase Realtime Database in your app you can give live data updates to your users without actually refreshing your app. In this article, we will be uploading Excel Sheet Data into the firebase real-time database. This can be useful when you are creating a quiz app where you have to upload a lot of question. In that case, you can upload your data using an excel sheet.
We will be building a simple application in which we will be uploading data into the firebase real-time database using excel Sheet. Firstly we will be selecting an excel file and then it will be uploaded to firebase by taking the total number of rows and columns and then a random id will be generated in which row-wise data will be stored. 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: Working with the AndroidManifest.xml file
For adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml and Inside that file add the below permissions to it.
<uses-permission android:name=βandroid.permission.INTERNETβ />
<uses-permission android:name=βandroid.permission.WRITE_EXTERNAL_STORAGEβ />
<uses-permission android:name=βandroid.permission.READ_EXTERNAL_STORAGEβ />
Step 3: Working with the build.gradle(app) file
Add these implementations into it
implementation fileTree(dir: βlibsβ, include: [β*.jarβ])
implementation βcom.google.firebase:firebase-database:16.0.4β
implementation files(βlibs/poi-3.12-android-a.jarβ)
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"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" tools:context=".MainActivity"> <Button android:id="@+id/excel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click Here to upload excel Sheet" /> </LinearLayout>
Step 5: Working with the MainActivity.java file
Open the MainActivity.java file there within the class, first of all, create the object of the Button class.
public static final int cellCount=2;
Button excel;
Secondly, inside the onCreate() method, we have to link those objects with their respective IDs that we have given in .XML file.
excel = findViewById(R.id.excel);
Checking for permission to excel file from phone storage
if(requestCode == 101){
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
// if permission granted them select file
selectfile();
} else {
Toast.makeText(MainActivity.this, "Permission Not granted",Toast.LENGTH_LONG).show();
}
}
Selecting excel file from phone
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
// file is selected now start activity function to proceed
startActivityForResult(Intent.createChooser(intent, "Select File"),102);
Getting an excel sheet and check for total rows and columns and will add those values to the database.
XSSFSheet sheet=workbook.getSheetAt(0);
FormulaEvaluator formulaEvaluator=workbook.getCreationHelper().createFormulaEvaluator();
int rowscount=sheet.getPhysicalNumberOfRows();
if(rowscount > 0){
// check row wise data
for (int r=0;r<rowscount;r++){
Row row=sheet.getRow(r);
if(row.getPhysicalNumberOfCells()==cellCount) {
// get cell data
String A = getCellData(row,0,formulaEvaluator);
String B = getCellData(row,1,formulaEvaluator);
}
else {
Toast.makeText(MainActivity.this,"row no. "+(r+1)+" has incorrect data",Toast.LENGTH_LONG).show();
return;
}
}
Java
import android.Manifest;import android.app.ProgressDialog;import android.content.Intent;import android.content.pm.PackageManager;import android.net.Uri;import android.os.AsyncTask;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import androidx.core.app.ActivityCompat; import com.google.android.gms.tasks.OnCompleteListener;import com.google.android.gms.tasks.Task;import com.google.firebase.database.FirebaseDatabase; import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.FormulaEvaluator;import org.apache.poi.ss.usermodel.Row;import org.apache.poi.xssf.usermodel.XSSFSheet;import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.util.HashMap;import java.util.UUID; public class MainActivity extends AppCompatActivity { // initialising the cell count as 2 public static final int cellCount = 2; Button excel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); excel = findViewById(R.id.excel); // click on excel to select a file excel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { selectfile(); } else { ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 101); } } }); } // request for storage permission if not given @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == 101) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { selectfile(); } else { Toast.makeText(MainActivity.this, "Permission Not granted", Toast.LENGTH_LONG).show(); } } } private void selectfile() { // select the file from the file storage Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.setType("*/*"); intent.addCategory(Intent.CATEGORY_OPENABLE); startActivityForResult(Intent.createChooser(intent, "Select File"), 102); } protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 102) { if (resultCode == RESULT_OK) { String filepath = data.getData().getPath(); // If excel file then only select the file if (filepath.endsWith(".xlsx") || filepath.endsWith(".xls")) { readfile(data.getData()); } // else show the error else { Toast.makeText(this, "Please Select an Excel file to upload", Toast.LENGTH_LONG).show(); } } } } ProgressDialog dialog; private void readfile(final Uri file) { dialog = new ProgressDialog(this); dialog.setMessage("Uploading"); dialog.setCanceledOnTouchOutside(false); dialog.show(); AsyncTask.execute(new Runnable() { @Override public void run() { final HashMap<String, Object> parentmap = new HashMap<>(); try { XSSFWorkbook workbook; // check for the input from the excel file try (InputStream inputStream = getContentResolver().openInputStream(file)) { workbook = new XSSFWorkbook(inputStream); } final String timestamp = "" + System.currentTimeMillis(); XSSFSheet sheet = workbook.getSheetAt(0); FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator(); int rowscount = sheet.getPhysicalNumberOfRows(); if (rowscount > 0) { // check row wise data for (int r = 0; r < rowscount; r++) { Row row = sheet.getRow(r); if (row.getPhysicalNumberOfCells() == cellCount) { // get cell data String A = getCellData(row, 0, formulaEvaluator); String B = getCellData(row, 1, formulaEvaluator); // initialise the hash map and put value of a and b into it HashMap<String, Object> quetionmap = new HashMap<>(); quetionmap.put("A", A); quetionmap.put("B", B); String id = UUID.randomUUID().toString(); parentmap.put(id, quetionmap); } else { dialog.dismiss(); Toast.makeText(MainActivity.this, "row no. " + (r + 1) + " has incorrect data", Toast.LENGTH_LONG).show(); return; } } // add the data in firebase if everything is correct runOnUiThread(new Runnable() { @Override public void run() { // add the data according to timestamp FirebaseDatabase.getInstance().getReference().child("Data"). child(timestamp).updateChildren(parentmap).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { dialog.dismiss(); Toast.makeText(MainActivity.this, "Uploaded Successfully", Toast.LENGTH_LONG).show(); } else { dialog.dismiss(); Toast.makeText(MainActivity.this, "Something went wrong", Toast.LENGTH_LONG).show(); } } }); } }); } // show the error if file is empty else { runOnUiThread(new Runnable() { @Override public void run() { dialog.dismiss(); Toast.makeText(MainActivity.this, "File is empty", Toast.LENGTH_LONG).show(); } }); return; } } // show the error message if failed // due to file not found catch (final FileNotFoundException e) { e.printStackTrace(); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show(); } }); } // show the error message if there // is error in input output catch (final IOException e) { e.printStackTrace(); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show(); } }); } } }); } private String getCellData(Row row, int cellposition, FormulaEvaluator formulaEvaluator) { String value = ""; // get cell from excel sheet Cell cell = row.getCell(cellposition); switch (cell.getCellType()) { case Cell.CELL_TYPE_BOOLEAN: return value + cell.getBooleanCellValue(); case Cell.CELL_TYPE_NUMERIC: return value + cell.getNumericCellValue(); case Cell.CELL_TYPE_STRING: return value + cell.getStringCellValue(); default: return value; } }}
Output:
Data saved in Database in this way
GitHub link: https://github.com/Anni1123/UploadDataExcelSheet
sagar0719kumar
Firebase
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
How to Communicate Between Fragments in Android?
Retrofit with Kotlin Coroutine in Android
Arrays in Java
Arrays.sort() in Java with examples
Split() String method in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 Feb, 2022"
},
{
"code": null,
"e": 744,
"s": 52,
"text": "Firebase Realtime Database is the backend service which is provided by Google for handling backend tasks for your Android apps, IOS apps as well as your websites. It provides so many services such as storage, database, and many more. The feature for which Firebase is famous for its Firebase Realtime Database. By using Firebase Realtime Database in your app you can give live data updates to your users without actually refreshing your app. In this article, we will be uploading Excel Sheet Data into the firebase real-time database. This can be useful when you are creating a quiz app where you have to upload a lot of question. In that case, you can upload your data using an excel sheet."
},
{
"code": null,
"e": 1159,
"s": 744,
"text": "We will be building a simple application in which we will be uploading data into the firebase real-time database using excel Sheet. Firstly we will be selecting an excel file and then it will be uploaded to firebase by taking the total number of rows and columns and then a random id will be generated in which row-wise data will be stored. Note that we are going to implement this project using the Java language."
},
{
"code": null,
"e": 1188,
"s": 1159,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 1350,
"s": 1188,
"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": 1400,
"s": 1350,
"text": "Step 2: Working with the AndroidManifest.xml file"
},
{
"code": null,
"e": 1618,
"s": 1400,
"text": "For adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml and Inside that file add the below permissions to it. "
},
{
"code": null,
"e": 1681,
"s": 1618,
"text": "<uses-permission android:name=βandroid.permission.INTERNETβ />"
},
{
"code": null,
"e": 1758,
"s": 1681,
"text": "<uses-permission android:name=βandroid.permission.WRITE_EXTERNAL_STORAGEβ />"
},
{
"code": null,
"e": 1834,
"s": 1758,
"text": "<uses-permission android:name=βandroid.permission.READ_EXTERNAL_STORAGEβ />"
},
{
"code": null,
"e": 1882,
"s": 1834,
"text": "Step 3: Working with the build.gradle(app) file"
},
{
"code": null,
"e": 1916,
"s": 1882,
"text": "Add these implementations into it"
},
{
"code": null,
"e": 1973,
"s": 1916,
"text": "implementation fileTree(dir: βlibsβ, include: [β*.jarβ])"
},
{
"code": null,
"e": 2035,
"s": 1973,
"text": "implementation βcom.google.firebase:firebase-database:16.0.4β"
},
{
"code": null,
"e": 2087,
"s": 2035,
"text": "implementation files(βlibs/poi-3.12-android-a.jarβ)"
},
{
"code": null,
"e": 2135,
"s": 2087,
"text": "Step 4: Working with the activity_main.xml file"
},
{
"code": null,
"e": 2278,
"s": 2135,
"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": 2282,
"s": 2278,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/excel\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Click Here to upload excel Sheet\" /> </LinearLayout>",
"e": 2791,
"s": 2282,
"text": null
},
{
"code": null,
"e": 2843,
"s": 2795,
"text": "Step 5: Working with the MainActivity.java file"
},
{
"code": null,
"e": 2954,
"s": 2845,
"text": "Open the MainActivity.java file there within the class, first of all, create the object of the Button class."
},
{
"code": null,
"e": 3007,
"s": 2956,
"text": "public static final int cellCount=2;\nButton excel;"
},
{
"code": null,
"e": 3138,
"s": 3009,
"text": "Secondly, inside the onCreate() method, we have to link those objects with their respective IDs that we have given in .XML file."
},
{
"code": null,
"e": 3174,
"s": 3140,
"text": "excel = findViewById(R.id.excel);"
},
{
"code": null,
"e": 3233,
"s": 3176,
"text": "Checking for permission to excel file from phone storage"
},
{
"code": null,
"e": 3552,
"s": 3235,
"text": "if(requestCode == 101){\n if(grantResults[0] == PackageManager.PERMISSION_GRANTED){\n // if permission granted them select file\n selectfile();\n } else {\n Toast.makeText(MainActivity.this, \"Permission Not granted\",Toast.LENGTH_LONG).show();\n }\n }"
},
{
"code": null,
"e": 3586,
"s": 3554,
"text": "Selecting excel file from phone"
},
{
"code": null,
"e": 3887,
"s": 3588,
"text": "Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);\n intent.setType(\"*/*\");\n intent.addCategory(Intent.CATEGORY_OPENABLE);\n \n // file is selected now start activity function to proceed\n startActivityForResult(Intent.createChooser(intent, \"Select File\"),102);"
},
{
"code": null,
"e": 3992,
"s": 3889,
"text": "Getting an excel sheet and check for total rows and columns and will add those values to the database."
},
{
"code": null,
"e": 4888,
"s": 3994,
"text": "XSSFSheet sheet=workbook.getSheetAt(0);\nFormulaEvaluator formulaEvaluator=workbook.getCreationHelper().createFormulaEvaluator();\nint rowscount=sheet.getPhysicalNumberOfRows();\nif(rowscount > 0){ \n // check row wise data\n for (int r=0;r<rowscount;r++){ \n Row row=sheet.getRow(r);\n if(row.getPhysicalNumberOfCells()==cellCount) {\n // get cell data\n String A = getCellData(row,0,formulaEvaluator);\n String B = getCellData(row,1,formulaEvaluator); \n }\n else {\n Toast.makeText(MainActivity.this,\"row no. \"+(r+1)+\" has incorrect data\",Toast.LENGTH_LONG).show();\n return; \n }\n} "
},
{
"code": null,
"e": 4895,
"s": 4890,
"text": "Java"
},
{
"code": "import android.Manifest;import android.app.ProgressDialog;import android.content.Intent;import android.content.pm.PackageManager;import android.net.Uri;import android.os.AsyncTask;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import androidx.core.app.ActivityCompat; import com.google.android.gms.tasks.OnCompleteListener;import com.google.android.gms.tasks.Task;import com.google.firebase.database.FirebaseDatabase; import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.FormulaEvaluator;import org.apache.poi.ss.usermodel.Row;import org.apache.poi.xssf.usermodel.XSSFSheet;import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.util.HashMap;import java.util.UUID; public class MainActivity extends AppCompatActivity { // initialising the cell count as 2 public static final int cellCount = 2; Button excel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); excel = findViewById(R.id.excel); // click on excel to select a file excel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { selectfile(); } else { ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 101); } } }); } // request for storage permission if not given @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == 101) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { selectfile(); } else { Toast.makeText(MainActivity.this, \"Permission Not granted\", Toast.LENGTH_LONG).show(); } } } private void selectfile() { // select the file from the file storage Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.setType(\"*/*\"); intent.addCategory(Intent.CATEGORY_OPENABLE); startActivityForResult(Intent.createChooser(intent, \"Select File\"), 102); } protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 102) { if (resultCode == RESULT_OK) { String filepath = data.getData().getPath(); // If excel file then only select the file if (filepath.endsWith(\".xlsx\") || filepath.endsWith(\".xls\")) { readfile(data.getData()); } // else show the error else { Toast.makeText(this, \"Please Select an Excel file to upload\", Toast.LENGTH_LONG).show(); } } } } ProgressDialog dialog; private void readfile(final Uri file) { dialog = new ProgressDialog(this); dialog.setMessage(\"Uploading\"); dialog.setCanceledOnTouchOutside(false); dialog.show(); AsyncTask.execute(new Runnable() { @Override public void run() { final HashMap<String, Object> parentmap = new HashMap<>(); try { XSSFWorkbook workbook; // check for the input from the excel file try (InputStream inputStream = getContentResolver().openInputStream(file)) { workbook = new XSSFWorkbook(inputStream); } final String timestamp = \"\" + System.currentTimeMillis(); XSSFSheet sheet = workbook.getSheetAt(0); FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator(); int rowscount = sheet.getPhysicalNumberOfRows(); if (rowscount > 0) { // check row wise data for (int r = 0; r < rowscount; r++) { Row row = sheet.getRow(r); if (row.getPhysicalNumberOfCells() == cellCount) { // get cell data String A = getCellData(row, 0, formulaEvaluator); String B = getCellData(row, 1, formulaEvaluator); // initialise the hash map and put value of a and b into it HashMap<String, Object> quetionmap = new HashMap<>(); quetionmap.put(\"A\", A); quetionmap.put(\"B\", B); String id = UUID.randomUUID().toString(); parentmap.put(id, quetionmap); } else { dialog.dismiss(); Toast.makeText(MainActivity.this, \"row no. \" + (r + 1) + \" has incorrect data\", Toast.LENGTH_LONG).show(); return; } } // add the data in firebase if everything is correct runOnUiThread(new Runnable() { @Override public void run() { // add the data according to timestamp FirebaseDatabase.getInstance().getReference().child(\"Data\"). child(timestamp).updateChildren(parentmap).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { dialog.dismiss(); Toast.makeText(MainActivity.this, \"Uploaded Successfully\", Toast.LENGTH_LONG).show(); } else { dialog.dismiss(); Toast.makeText(MainActivity.this, \"Something went wrong\", Toast.LENGTH_LONG).show(); } } }); } }); } // show the error if file is empty else { runOnUiThread(new Runnable() { @Override public void run() { dialog.dismiss(); Toast.makeText(MainActivity.this, \"File is empty\", Toast.LENGTH_LONG).show(); } }); return; } } // show the error message if failed // due to file not found catch (final FileNotFoundException e) { e.printStackTrace(); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show(); } }); } // show the error message if there // is error in input output catch (final IOException e) { e.printStackTrace(); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show(); } }); } } }); } private String getCellData(Row row, int cellposition, FormulaEvaluator formulaEvaluator) { String value = \"\"; // get cell from excel sheet Cell cell = row.getCell(cellposition); switch (cell.getCellType()) { case Cell.CELL_TYPE_BOOLEAN: return value + cell.getBooleanCellValue(); case Cell.CELL_TYPE_NUMERIC: return value + cell.getNumericCellValue(); case Cell.CELL_TYPE_STRING: return value + cell.getStringCellValue(); default: return value; } }}",
"e": 14101,
"s": 4895,
"text": null
},
{
"code": null,
"e": 14113,
"s": 14105,
"text": "Output:"
},
{
"code": null,
"e": 14152,
"s": 14117,
"text": "Data saved in Database in this way"
},
{
"code": null,
"e": 14218,
"s": 14156,
"text": "GitHub link: https://github.com/Anni1123/UploadDataExcelSheet"
},
{
"code": null,
"e": 14235,
"s": 14220,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 14244,
"s": 14235,
"text": "Firebase"
},
{
"code": null,
"e": 14252,
"s": 14244,
"text": "Android"
},
{
"code": null,
"e": 14257,
"s": 14252,
"text": "Java"
},
{
"code": null,
"e": 14262,
"s": 14257,
"text": "Java"
},
{
"code": null,
"e": 14270,
"s": 14262,
"text": "Android"
},
{
"code": null,
"e": 14368,
"s": 14270,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14437,
"s": 14368,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 14469,
"s": 14437,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 14508,
"s": 14469,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 14557,
"s": 14508,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 14599,
"s": 14557,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 14614,
"s": 14599,
"text": "Arrays in Java"
},
{
"code": null,
"e": 14650,
"s": 14614,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 14694,
"s": 14650,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 14719,
"s": 14694,
"text": "Reverse a string in Java"
}
] |
Shell Script to Display the Exit Status Using Grep Command
|
27 Dec, 2021
Linux provides users a great cool feature of the command-line tool along with a graphical user interface where they can perform tasks via ruining command. All of this command returns a status according to their execution. Its execution value can be used for showing errors or take some other action in a shell script.
Exit status is following according to their execution
Command was successfully executed: 0 ( value of exit status)
Command was a failure: 1 β 255 ( value of exit status will be b/w 1 to 255)
Exit status: Every Linux command has exit status after execution. Its value can get by calling $? ( shell variable ). It gives the value of previous executed command.
Note: Command for printing exit status for privious command: echo $?
Here in this article, a shell script will be written to display the exit status using the grep command. It will show an example of shell scripts to display the exit status.
Approach:
To write the script code for this follow the below steps
Use the touch command to create the database which is a text file named gfg.txt.Now get the key from the user if he wants to insert it in the database or check that the book is present in a database or not( means the book has read or not ).Now according to the chosen key make the if-else block and read the book Name from the user.In the first condition check the availability of the book using the grep command and get the exit status value and check if 0 or not. And the second condition simply gets the book name and adds the name to the database.Now, print the status of the book read according to the value of the exit status of the previous command.
Use the touch command to create the database which is a text file named gfg.txt.
Now get the key from the user if he wants to insert it in the database or check that the book is present in a database or not( means the book has read or not ).
Now according to the chosen key make the if-else block and read the book Name from the user.
In the first condition check the availability of the book using the grep command and get the exit status value and check if 0 or not. And the second condition simply gets the book name and adds the name to the database.
Now, print the status of the book read according to the value of the exit status of the previous command.
Shell Script Code:
# shell script for display exit status by using grep command
# make an file gfg.txt to contain the book name of user that he has read
touch gfg.txt
# now print user to tell him the scenario
echo "Please, enter the some of your book name that you
have read or a book name that you want to know read status of that book"
echo
# print the key to ask user find the book or write the book name
echo "Please enter a key like following"
echo "Enter 1 to know the book read status"
echo "Enter 2 to write the book name in book database ( gfg.txt )"
# read the entered key
read key
echo
# check the condition using if-else statement
if [[ $key == 1 ]]
then
# loop to get the name of book continuously
while [ 1 ]
do
# print the initial statement
echo "Enter book name about that you want to know read status or -1 for exit"
# read the book name and find in gfg.text using grep command
read bookName
# check condition to break the loop
if [[ $bookName == -1 ]]
then
break
else
# now find the book in gfg.text
count=$(grep -c "$bookName" gfg.txt)
# get the exit status of the previous command
exitStatus=$?
# check the value of exitStatus and print output according that
if [[ $exitStatus == 0 ]]
then
# give the msg to user that he have read that book
echo "Your previous command exit status is $exitStatus"
echo "You have read the $bookName book."
echo
else
# give the msg to user that he didn't read that book yet.
echo "Your previous command exit status is $exitStatus"
echo "You didn't read $bookName book yet."
echo
fi
fi
done
else
# loop to get the name of books continuously
while [ 1 ]
do
echo "Enter book name that you want write in database (gfg.txt) or -1 for exit"
# read the name of book
read bookName
# check the condition to break the loop
if [[ $bookName != -1 ]]
then
# write the book name in text file
echo $bookName >> gfg.txt
else
break
fi
echo
done
fi
In the first example will show the inserting book name in the database ( gfg.text).
In the second example will know about the check the book read status ( internal checking using grep command and exit status):
simmytarika5
surindertarika1234
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Dec, 2021"
},
{
"code": null,
"e": 347,
"s": 28,
"text": "Linux provides users a great cool feature of the command-line tool along with a graphical user interface where they can perform tasks via ruining command. All of this command returns a status according to their execution. Its execution value can be used for showing errors or take some other action in a shell script. "
},
{
"code": null,
"e": 402,
"s": 347,
"text": "Exit status is following according to their execution "
},
{
"code": null,
"e": 464,
"s": 402,
"text": "Command was successfully executed: 0 ( value of exit status)"
},
{
"code": null,
"e": 541,
"s": 464,
"text": "Command was a failure: 1 β 255 ( value of exit status will be b/w 1 to 255)"
},
{
"code": null,
"e": 709,
"s": 541,
"text": "Exit status: Every Linux command has exit status after execution. Its value can get by calling $? ( shell variable ). It gives the value of previous executed command. "
},
{
"code": null,
"e": 780,
"s": 709,
"text": "Note: Command for printing exit status for privious command: echo $? "
},
{
"code": null,
"e": 954,
"s": 780,
"text": "Here in this article, a shell script will be written to display the exit status using the grep command. It will show an example of shell scripts to display the exit status. "
},
{
"code": null,
"e": 964,
"s": 954,
"text": "Approach:"
},
{
"code": null,
"e": 1021,
"s": 964,
"text": "To write the script code for this follow the below steps"
},
{
"code": null,
"e": 1678,
"s": 1021,
"text": "Use the touch command to create the database which is a text file named gfg.txt.Now get the key from the user if he wants to insert it in the database or check that the book is present in a database or not( means the book has read or not ).Now according to the chosen key make the if-else block and read the book Name from the user.In the first condition check the availability of the book using the grep command and get the exit status value and check if 0 or not. And the second condition simply gets the book name and adds the name to the database.Now, print the status of the book read according to the value of the exit status of the previous command."
},
{
"code": null,
"e": 1759,
"s": 1678,
"text": "Use the touch command to create the database which is a text file named gfg.txt."
},
{
"code": null,
"e": 1920,
"s": 1759,
"text": "Now get the key from the user if he wants to insert it in the database or check that the book is present in a database or not( means the book has read or not )."
},
{
"code": null,
"e": 2013,
"s": 1920,
"text": "Now according to the chosen key make the if-else block and read the book Name from the user."
},
{
"code": null,
"e": 2233,
"s": 2013,
"text": "In the first condition check the availability of the book using the grep command and get the exit status value and check if 0 or not. And the second condition simply gets the book name and adds the name to the database."
},
{
"code": null,
"e": 2339,
"s": 2233,
"text": "Now, print the status of the book read according to the value of the exit status of the previous command."
},
{
"code": null,
"e": 2359,
"s": 2339,
"text": "Shell Script Code: "
},
{
"code": null,
"e": 4811,
"s": 2359,
"text": "# shell script for display exit status by using grep command\n\n# make an file gfg.txt to contain the book name of user that he has read \ntouch gfg.txt \n\n# now print user to tell him the scenario \necho \"Please, enter the some of your book name that you \n have read or a book name that you want to know read status of that book\"\necho\n\n# print the key to ask user find the book or write the book name\necho \"Please enter a key like following\"\necho \"Enter 1 to know the book read status\" \necho \"Enter 2 to write the book name in book database ( gfg.txt )\"\n\n# read the entered key\nread key\necho\n\n# check the condition using if-else statement\nif [[ $key == 1 ]]\nthen \n # loop to get the name of book continuously \n while [ 1 ]\n do\n # print the initial statement\n echo \"Enter book name about that you want to know read status or -1 for exit\"\n \n # read the book name and find in gfg.text using grep command\n read bookName\n \n # check condition to break the loop\n if [[ $bookName == -1 ]]\n then\n break\n else\n \n # now find the book in gfg.text\n count=$(grep -c \"$bookName\" gfg.txt)\n \n # get the exit status of the previous command \n exitStatus=$?\n \n # check the value of exitStatus and print output according that \n if [[ $exitStatus == 0 ]]\n then \n # give the msg to user that he have read that book \n echo \"Your previous command exit status is $exitStatus\"\n echo \"You have read the $bookName book.\"\n echo \n else\n # give the msg to user that he didn't read that book yet.\n echo \"Your previous command exit status is $exitStatus\"\n echo \"You didn't read $bookName book yet.\"\n echo\n fi\n \n fi\n done\n \n \nelse\n # loop to get the name of books continuously \n while [ 1 ]\n do\n echo \"Enter book name that you want write in database (gfg.txt) or -1 for exit\"\n \n # read the name of book\n read bookName\n \n # check the condition to break the loop\n if [[ $bookName != -1 ]]\n then\n # write the book name in text file\n echo $bookName >> gfg.txt\n else\n break\n fi\n echo\n done\nfi\n "
},
{
"code": null,
"e": 4896,
"s": 4811,
"text": "In the first example will show the inserting book name in the database ( gfg.text). "
},
{
"code": null,
"e": 5022,
"s": 4896,
"text": "In the second example will know about the check the book read status ( internal checking using grep command and exit status):"
},
{
"code": null,
"e": 5035,
"s": 5022,
"text": "simmytarika5"
},
{
"code": null,
"e": 5054,
"s": 5035,
"text": "surindertarika1234"
},
{
"code": null,
"e": 5061,
"s": 5054,
"text": "Picked"
},
{
"code": null,
"e": 5074,
"s": 5061,
"text": "Shell Script"
},
{
"code": null,
"e": 5085,
"s": 5074,
"text": "Linux-Unix"
}
] |
Find all possible ways to Split the given string into Primes
|
17 May, 2021
Given string str that represents a number. The task is to find all possible ways to split the given string such that each segment is a prime number in the range of 1 to 106.Examples:
Input: str = β3175β Output: [317, 5] [31, 7, 5] [3, 17, 5]Explanation: There can be 8 possible ways to split: [3175] [317, 5] β All primes [31, 75] [31, 7, 5] β All primes [3, 175] [3, 17, 5] β All primes [3, 1, 75] [3, 1, 7, 5]Input: str = β11373β Output: [113, 73] [113, 7, 3] [11, 373] [11, 37, 3] [11, 3, 73] [11, 3, 7, 3]
Approach:
The idea is to generate all possible splits of a string of size N by counting binary numbers from 0 to 2(N β 1) β 1. Where every 1 indicates that the string should split at that point.For example:
S = "3175"
0 0 0 3175
0 0 1 317, 5
0 1 0 31, 75
0 1 1 31, 7, 5
1 0 0 3, 175
1 0 1 3, 17, 5
1 1 0 3, 1, 75
1 1 1 3, 1, 7, 5
To check the prime number efficiently we will pre-process prime number in a boolean array using Sieve of Eratosthenes.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program to Find all the// ways to split the given string// into Primes.#include<bits/stdc++.h>using namespace std; bool primes[1000000];const int maxn = 1000000; // Sieve of Eratosthenesvoid sieve(){ memset(primes,true,sizeof(primes)); primes[0] = primes[1] = 0; for(int i = 2; i * i <= maxn; i++) { if(primes[i]) { for(int j = i * i ; j <= maxn ; j += i) primes[j] = false; } }} // Function Convert integer// to binary stringstring toBinary(int n){ string r = ""; while(n != 0) { r = (n % 2 == 0 ?"0":"1") + r; n /= 2; } return (r == "")?"0":r;} // Function print all the all the// ways to split the given string// into Primes.void PrimeSplit(string str){ string temp; int cnt=0; // To store all possible strings vector<string> ans; int bt = 1<<(str.size()-1); int n = str.size(); // Exponetnital complexity n*(2^(n-1)) // for bit for(int i = 0 ; i < bt ; i++) { temp = toBinary(i) + "0"; int j = 0, x = n - temp.size(), y; while(j < x) { temp = "0" + temp; j++; } j = 0; x = 0; y = -1; string sp = "", tp = ""; bool flag = 0; while(j < n) { sp += str[j]; if(temp[j] == '1') { tp += sp + ','; y = stoi(sp); // Pruning step if(!primes[y]) { flag = 1; break; } sp = ""; } j++; } tp += sp; if(sp != "") { y = stoi(sp); if(!primes[y]) flag = 1; } if(!flag) ans.push_back(tp); } if(ans.size() == 0) { cout << -1 << endl; } for(auto i:ans) { cout << i << endl; }} // Driver codeint main(){ string str = "11373"; sieve(); PrimeSplit(str); return 0;}
// Java program to Find all the // ways to split the given string// into Primes.import java.util.*;import java.lang.*; class GFG{ static boolean[] primes = new boolean[1000001];static int maxn = 1000000; // Sieve of Eratosthenesstatic void sieve(){ Arrays.fill(primes, true); primes[0] = false; primes[1] = false; for(int i = 2; i * i <= maxn; i++) { if (primes[i]) { for(int j = i * i; j <= maxn; j += i) primes[j] = false; } }} // Function Convert integer// to binary stringstatic String toBinary(int n){ String r = ""; while(n != 0) { r = (n % 2 == 0 ? "0" : "1") + r; n /= 2; } return (r == "") ? "0" : r;} // Function print all the all the// ways to split the given string// into Primes.static void PrimeSplit(String str){ String temp; int cnt = 0; // To store all possible strings ArrayList<String> ans = new ArrayList<>(); int bt = 1 << (str.length() - 1); int n = str.length(); // Exponetnital complexity n*(2^(n-1)) // for bit for(int i = 0; i < bt; i++) { temp = toBinary(i) + "0"; int j = 0, x = n - temp.length(), y; while(j < x) { temp = "0" + temp; j++; } j = 0; x = 0; y = -1; String sp = "", tp = ""; boolean flag = false; while(j < n) { sp += str.charAt(j); if (temp.charAt(j) == '1') { tp += sp + ','; y = Integer.parseInt(sp); // Pruning step if (!primes[y]) { flag = true; break; } sp = ""; } j++; } tp += sp; if (sp != "") { y = Integer.parseInt(sp); if (!primes[y]) flag = true; } if (!flag) ans.add(tp); } if (ans.size() == 0) { System.out.println(-1); } for(String i : ans) { System.out.println(i); }} // Driver Codepublic static void main (String[] args){ String str = "11373"; sieve(); PrimeSplit(str);}} // This code is contributed by offbeat
# Python 3 program to Find all the# ways to split the given string# into Primes.primes = [True] * 1000001maxn = 1000000 # Sieve of Eratosthenesdef sieve(): primes[0] = primes[1] = 0 i = 2 while i * i <= maxn: if(primes[i]): for j in range(i * i, maxn + 1, i): primes[j] = False i += 1 # Function Convert integer# to binary stringdef toBinary(n): r = "" while(n != 0): if(n % 2 == 0 ): r = "0" + r else: r = "1" + r n //= 2 if (r == ""): return "0" return r # Function print all the all the# ways to split the given string# into Primes.def PrimeSplit(st): cnt = 0 # To store all # possible strings ans = [] bt = 1 << (len(st) - 1) n = len(st) # Exponetnital complexity # n*(2^(n-1)) for bit for i in range(bt): temp = toBinary(i) + "0" j = 0 x = n - len(temp) while(j < x): temp = "0" + temp j += 1 j = 0 x = 0 y = -1 sp = "" tp = "" flag = 0 while(j < n): sp += st[j] if(temp[j] == '1'): tp += sp + ',' y = int(sp) # Pruning step if(not primes[y]): flag = 1 break sp = "" j += 1 tp += sp if(sp != ""): y = int(sp) if(not primes[y]): flag = 1 if(not flag): ans.append(tp) if(len(ans) == 0): print (-1) for i in ans: print (i) # Driver codeif __name__ == "__main__": st = "11373" sieve() PrimeSplit(st) # This code is contributed by Chitranayal
// C# program to Find all the // ways to split the given string// into Primes.using System;using System.Collections.Generic;class GFG{ static bool[] primes = new bool[1000001];static int maxn = 1000000; // Sieve of Eratosthenesstatic void sieve(){ for(int i = 0; i < primes.Length; i++) { primes[i] = true; } primes[0] = false; primes[1] = false; for(int i = 2; i * i <= maxn; i++) { if (primes[i]) { for(int j = i * i; j <= maxn; j += i) primes[j] = false; } }} // Function Convert integer// to binary stringstatic String toBinary(int n){ String r = ""; while(n != 0) { r = (n % 2 == 0 ? "0" : "1") + r; n /= 2; } return (r == "") ? "0" : r;} // Function print all the all the// ways to split the given string// into Primes.static void PrimeSplit(String str){ String temp; // To store all possible strings List<String> ans = new List<String>(); int bt = 1 << (str.Length - 1); int n = str.Length; // Exponetnital complexity // n*(2^(n-1)) for bit for(int i = 0; i < bt; i++) { temp = toBinary(i) + "0"; int j = 0, x = n - temp.Length, y; while(j < x) { temp = "0" + temp; j++; } j = 0; x = 0; y = -1; String sp = "", tp = ""; bool flag = false; while(j < n) { sp += str[j]; if (temp[j] == '1') { tp += sp + ','; y = Int32.Parse(sp); // Pruning step if (!primes[y]) { flag = true; break; } sp = ""; } j++; } tp += sp; if (sp != "") { y = Int32.Parse(sp); if (!primes[y]) flag = true; } if (!flag) ans.Add(tp); } if (ans.Count == 0) { Console.WriteLine(-1); } foreach(String i in ans) { Console.WriteLine(i); }} // Driver Codepublic static void Main(String[] args){ String str = "11373"; sieve(); PrimeSplit(str);}} // This code is contributed by Rajput-Ji
<script>// Javascript program to Find all the// ways to split the given string// into Primes. let primes = new Array(1000000);const maxn = 1000000; // Sieve of Eratosthenesfunction sieve(){ primes.fill(true) primes[0] = primes[1] = 0; for(let i = 2; i * i <= maxn; i++) { if(primes[i]) { for(let j = i * i ; j <= maxn ; j += i) primes[j] = false; } }} // Function Convert integer// to binary stringfunction toBinary(n){ let r = ""; while(n != 0) { r = (n % 2 == 0 ?"0":"1") + r; n = Math.floor(n / 2); } return (r == "")?"0":r;} // Function print all the all the// ways to split the given string// into Primes.function PrimeSplit(str){ let temp; let cnt=0; // To store all possible strings let ans = new Array(); let bt = 1 << (str.length-1); let n = str.length; // Exponetnital complexity n*(2^(n-1)) // for bit for(let i = 0 ; i < bt ; i++) { temp = toBinary(i) + "0"; let j = 0, x = n - temp.length, y; while(j < x) { temp = "0" + temp; j++; } j = 0; x = 0; y = -1; let sp = "", tp = ""; let flag = 0; while(j < n) { sp += str[j]; if(temp[j] == '1') { tp += sp + ','; y = parseInt(sp); // Pruning step if(!primes[y]) { flag = 1; break; } sp = ""; } j++; } tp += sp; if(sp != "") { y = parseInt(sp); if(!primes[y]) flag = 1; } if(!flag) ans.push(tp); } if(ans.length == 0) { document.write(-1 + "<br>"); } for(let i of ans) { document.write(i + "<br>"); }} // Driver code let str = "11373";sieve(); PrimeSplit(str); // This code is contributed by _saurabh_jaiswal</script>
113,73
113,7,3
11,373
11,37,3
11,3,73
11,3,7,3
offbeat
Rajput-Ji
ukasp
_saurabh_jaiswal
digit-DP
number-digits
Prime Number
sieve
Bit Magic
Combinatorial
Dynamic Programming
Mathematical
Strings
Strings
Dynamic Programming
Mathematical
Bit Magic
Prime Number
sieve
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Little and Big Endian Mystery
Bits manipulation (Important tactics)
Find a number X such that (X XOR A) is minimum and the count of set bits in X and B are equal
Josephus problem | Set 1 (A O(n) Solution)
Equal Sum and XOR of three Numbers
Write a program to print all permutations of a given string
Permutation and Combination in Python
Program to calculate value of nCr
Factorial of a large number
itertools.combinations() module in Python to print all possible combinations
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 May, 2021"
},
{
"code": null,
"e": 235,
"s": 52,
"text": "Given string str that represents a number. The task is to find all possible ways to split the given string such that each segment is a prime number in the range of 1 to 106.Examples:"
},
{
"code": null,
"e": 562,
"s": 235,
"text": "Input: str = β3175β Output: [317, 5] [31, 7, 5] [3, 17, 5]Explanation: There can be 8 possible ways to split: [3175] [317, 5] β All primes [31, 75] [31, 7, 5] β All primes [3, 175] [3, 17, 5] β All primes [3, 1, 75] [3, 1, 7, 5]Input: str = β11373β Output: [113, 73] [113, 7, 3] [11, 373] [11, 37, 3] [11, 3, 73] [11, 3, 7, 3]"
},
{
"code": null,
"e": 572,
"s": 562,
"text": "Approach:"
},
{
"code": null,
"e": 770,
"s": 572,
"text": "The idea is to generate all possible splits of a string of size N by counting binary numbers from 0 to 2(N β 1) β 1. Where every 1 indicates that the string should split at that point.For example: "
},
{
"code": null,
"e": 918,
"s": 770,
"text": " S = \"3175\"\n 0 0 0 3175\n 0 0 1 317, 5\n 0 1 0 31, 75\n 0 1 1 31, 7, 5\n 1 0 0 3, 175\n 1 0 1 3, 17, 5\n 1 1 0 3, 1, 75\n 1 1 1 3, 1, 7, 5"
},
{
"code": null,
"e": 1037,
"s": 918,
"text": "To check the prime number efficiently we will pre-process prime number in a boolean array using Sieve of Eratosthenes."
},
{
"code": null,
"e": 1088,
"s": 1037,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 1092,
"s": 1088,
"text": "C++"
},
{
"code": null,
"e": 1097,
"s": 1092,
"text": "Java"
},
{
"code": null,
"e": 1105,
"s": 1097,
"text": "Python3"
},
{
"code": null,
"e": 1108,
"s": 1105,
"text": "C#"
},
{
"code": null,
"e": 1119,
"s": 1108,
"text": "Javascript"
},
{
"code": "// C++ program to Find all the// ways to split the given string// into Primes.#include<bits/stdc++.h>using namespace std; bool primes[1000000];const int maxn = 1000000; // Sieve of Eratosthenesvoid sieve(){ memset(primes,true,sizeof(primes)); primes[0] = primes[1] = 0; for(int i = 2; i * i <= maxn; i++) { if(primes[i]) { for(int j = i * i ; j <= maxn ; j += i) primes[j] = false; } }} // Function Convert integer// to binary stringstring toBinary(int n){ string r = \"\"; while(n != 0) { r = (n % 2 == 0 ?\"0\":\"1\") + r; n /= 2; } return (r == \"\")?\"0\":r;} // Function print all the all the// ways to split the given string// into Primes.void PrimeSplit(string str){ string temp; int cnt=0; // To store all possible strings vector<string> ans; int bt = 1<<(str.size()-1); int n = str.size(); // Exponetnital complexity n*(2^(n-1)) // for bit for(int i = 0 ; i < bt ; i++) { temp = toBinary(i) + \"0\"; int j = 0, x = n - temp.size(), y; while(j < x) { temp = \"0\" + temp; j++; } j = 0; x = 0; y = -1; string sp = \"\", tp = \"\"; bool flag = 0; while(j < n) { sp += str[j]; if(temp[j] == '1') { tp += sp + ','; y = stoi(sp); // Pruning step if(!primes[y]) { flag = 1; break; } sp = \"\"; } j++; } tp += sp; if(sp != \"\") { y = stoi(sp); if(!primes[y]) flag = 1; } if(!flag) ans.push_back(tp); } if(ans.size() == 0) { cout << -1 << endl; } for(auto i:ans) { cout << i << endl; }} // Driver codeint main(){ string str = \"11373\"; sieve(); PrimeSplit(str); return 0;}",
"e": 3195,
"s": 1119,
"text": null
},
{
"code": "// Java program to Find all the // ways to split the given string// into Primes.import java.util.*;import java.lang.*; class GFG{ static boolean[] primes = new boolean[1000001];static int maxn = 1000000; // Sieve of Eratosthenesstatic void sieve(){ Arrays.fill(primes, true); primes[0] = false; primes[1] = false; for(int i = 2; i * i <= maxn; i++) { if (primes[i]) { for(int j = i * i; j <= maxn; j += i) primes[j] = false; } }} // Function Convert integer// to binary stringstatic String toBinary(int n){ String r = \"\"; while(n != 0) { r = (n % 2 == 0 ? \"0\" : \"1\") + r; n /= 2; } return (r == \"\") ? \"0\" : r;} // Function print all the all the// ways to split the given string// into Primes.static void PrimeSplit(String str){ String temp; int cnt = 0; // To store all possible strings ArrayList<String> ans = new ArrayList<>(); int bt = 1 << (str.length() - 1); int n = str.length(); // Exponetnital complexity n*(2^(n-1)) // for bit for(int i = 0; i < bt; i++) { temp = toBinary(i) + \"0\"; int j = 0, x = n - temp.length(), y; while(j < x) { temp = \"0\" + temp; j++; } j = 0; x = 0; y = -1; String sp = \"\", tp = \"\"; boolean flag = false; while(j < n) { sp += str.charAt(j); if (temp.charAt(j) == '1') { tp += sp + ','; y = Integer.parseInt(sp); // Pruning step if (!primes[y]) { flag = true; break; } sp = \"\"; } j++; } tp += sp; if (sp != \"\") { y = Integer.parseInt(sp); if (!primes[y]) flag = true; } if (!flag) ans.add(tp); } if (ans.size() == 0) { System.out.println(-1); } for(String i : ans) { System.out.println(i); }} // Driver Codepublic static void main (String[] args){ String str = \"11373\"; sieve(); PrimeSplit(str);}} // This code is contributed by offbeat",
"e": 5552,
"s": 3195,
"text": null
},
{
"code": "# Python 3 program to Find all the# ways to split the given string# into Primes.primes = [True] * 1000001maxn = 1000000 # Sieve of Eratosthenesdef sieve(): primes[0] = primes[1] = 0 i = 2 while i * i <= maxn: if(primes[i]): for j in range(i * i, maxn + 1, i): primes[j] = False i += 1 # Function Convert integer# to binary stringdef toBinary(n): r = \"\" while(n != 0): if(n % 2 == 0 ): r = \"0\" + r else: r = \"1\" + r n //= 2 if (r == \"\"): return \"0\" return r # Function print all the all the# ways to split the given string# into Primes.def PrimeSplit(st): cnt = 0 # To store all # possible strings ans = [] bt = 1 << (len(st) - 1) n = len(st) # Exponetnital complexity # n*(2^(n-1)) for bit for i in range(bt): temp = toBinary(i) + \"0\" j = 0 x = n - len(temp) while(j < x): temp = \"0\" + temp j += 1 j = 0 x = 0 y = -1 sp = \"\" tp = \"\" flag = 0 while(j < n): sp += st[j] if(temp[j] == '1'): tp += sp + ',' y = int(sp) # Pruning step if(not primes[y]): flag = 1 break sp = \"\" j += 1 tp += sp if(sp != \"\"): y = int(sp) if(not primes[y]): flag = 1 if(not flag): ans.append(tp) if(len(ans) == 0): print (-1) for i in ans: print (i) # Driver codeif __name__ == \"__main__\": st = \"11373\" sieve() PrimeSplit(st) # This code is contributed by Chitranayal",
"e": 7416,
"s": 5552,
"text": null
},
{
"code": "// C# program to Find all the // ways to split the given string// into Primes.using System;using System.Collections.Generic;class GFG{ static bool[] primes = new bool[1000001];static int maxn = 1000000; // Sieve of Eratosthenesstatic void sieve(){ for(int i = 0; i < primes.Length; i++) { primes[i] = true; } primes[0] = false; primes[1] = false; for(int i = 2; i * i <= maxn; i++) { if (primes[i]) { for(int j = i * i; j <= maxn; j += i) primes[j] = false; } }} // Function Convert integer// to binary stringstatic String toBinary(int n){ String r = \"\"; while(n != 0) { r = (n % 2 == 0 ? \"0\" : \"1\") + r; n /= 2; } return (r == \"\") ? \"0\" : r;} // Function print all the all the// ways to split the given string// into Primes.static void PrimeSplit(String str){ String temp; // To store all possible strings List<String> ans = new List<String>(); int bt = 1 << (str.Length - 1); int n = str.Length; // Exponetnital complexity // n*(2^(n-1)) for bit for(int i = 0; i < bt; i++) { temp = toBinary(i) + \"0\"; int j = 0, x = n - temp.Length, y; while(j < x) { temp = \"0\" + temp; j++; } j = 0; x = 0; y = -1; String sp = \"\", tp = \"\"; bool flag = false; while(j < n) { sp += str[j]; if (temp[j] == '1') { tp += sp + ','; y = Int32.Parse(sp); // Pruning step if (!primes[y]) { flag = true; break; } sp = \"\"; } j++; } tp += sp; if (sp != \"\") { y = Int32.Parse(sp); if (!primes[y]) flag = true; } if (!flag) ans.Add(tp); } if (ans.Count == 0) { Console.WriteLine(-1); } foreach(String i in ans) { Console.WriteLine(i); }} // Driver Codepublic static void Main(String[] args){ String str = \"11373\"; sieve(); PrimeSplit(str);}} // This code is contributed by Rajput-Ji",
"e": 9372,
"s": 7416,
"text": null
},
{
"code": "<script>// Javascript program to Find all the// ways to split the given string// into Primes. let primes = new Array(1000000);const maxn = 1000000; // Sieve of Eratosthenesfunction sieve(){ primes.fill(true) primes[0] = primes[1] = 0; for(let i = 2; i * i <= maxn; i++) { if(primes[i]) { for(let j = i * i ; j <= maxn ; j += i) primes[j] = false; } }} // Function Convert integer// to binary stringfunction toBinary(n){ let r = \"\"; while(n != 0) { r = (n % 2 == 0 ?\"0\":\"1\") + r; n = Math.floor(n / 2); } return (r == \"\")?\"0\":r;} // Function print all the all the// ways to split the given string// into Primes.function PrimeSplit(str){ let temp; let cnt=0; // To store all possible strings let ans = new Array(); let bt = 1 << (str.length-1); let n = str.length; // Exponetnital complexity n*(2^(n-1)) // for bit for(let i = 0 ; i < bt ; i++) { temp = toBinary(i) + \"0\"; let j = 0, x = n - temp.length, y; while(j < x) { temp = \"0\" + temp; j++; } j = 0; x = 0; y = -1; let sp = \"\", tp = \"\"; let flag = 0; while(j < n) { sp += str[j]; if(temp[j] == '1') { tp += sp + ','; y = parseInt(sp); // Pruning step if(!primes[y]) { flag = 1; break; } sp = \"\"; } j++; } tp += sp; if(sp != \"\") { y = parseInt(sp); if(!primes[y]) flag = 1; } if(!flag) ans.push(tp); } if(ans.length == 0) { document.write(-1 + \"<br>\"); } for(let i of ans) { document.write(i + \"<br>\"); }} // Driver code let str = \"11373\";sieve(); PrimeSplit(str); // This code is contributed by _saurabh_jaiswal</script>",
"e": 11451,
"s": 9372,
"text": null
},
{
"code": null,
"e": 11498,
"s": 11451,
"text": "113,73\n113,7,3\n11,373\n11,37,3\n11,3,73\n11,3,7,3"
},
{
"code": null,
"e": 11506,
"s": 11498,
"text": "offbeat"
},
{
"code": null,
"e": 11516,
"s": 11506,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 11522,
"s": 11516,
"text": "ukasp"
},
{
"code": null,
"e": 11539,
"s": 11522,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 11548,
"s": 11539,
"text": "digit-DP"
},
{
"code": null,
"e": 11562,
"s": 11548,
"text": "number-digits"
},
{
"code": null,
"e": 11575,
"s": 11562,
"text": "Prime Number"
},
{
"code": null,
"e": 11581,
"s": 11575,
"text": "sieve"
},
{
"code": null,
"e": 11591,
"s": 11581,
"text": "Bit Magic"
},
{
"code": null,
"e": 11605,
"s": 11591,
"text": "Combinatorial"
},
{
"code": null,
"e": 11625,
"s": 11605,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 11638,
"s": 11625,
"text": "Mathematical"
},
{
"code": null,
"e": 11646,
"s": 11638,
"text": "Strings"
},
{
"code": null,
"e": 11654,
"s": 11646,
"text": "Strings"
},
{
"code": null,
"e": 11674,
"s": 11654,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 11687,
"s": 11674,
"text": "Mathematical"
},
{
"code": null,
"e": 11697,
"s": 11687,
"text": "Bit Magic"
},
{
"code": null,
"e": 11710,
"s": 11697,
"text": "Prime Number"
},
{
"code": null,
"e": 11716,
"s": 11710,
"text": "sieve"
},
{
"code": null,
"e": 11730,
"s": 11716,
"text": "Combinatorial"
},
{
"code": null,
"e": 11828,
"s": 11730,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11858,
"s": 11828,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 11896,
"s": 11858,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 11990,
"s": 11896,
"text": "Find a number X such that (X XOR A) is minimum and the count of set bits in X and B are equal"
},
{
"code": null,
"e": 12033,
"s": 11990,
"text": "Josephus problem | Set 1 (A O(n) Solution)"
},
{
"code": null,
"e": 12068,
"s": 12033,
"text": "Equal Sum and XOR of three Numbers"
},
{
"code": null,
"e": 12128,
"s": 12068,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 12166,
"s": 12128,
"text": "Permutation and Combination in Python"
},
{
"code": null,
"e": 12200,
"s": 12166,
"text": "Program to calculate value of nCr"
},
{
"code": null,
"e": 12228,
"s": 12200,
"text": "Factorial of a large number"
}
] |
Python PIL | Image.thumbnail() Method
|
19 Jul, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.
Image.thumbnail() Make this image into a thumbnail. This method modifies the image to contain a thumbnail version of itself, no larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the draft() method to configure the file reader (where applicable), and finally resizes the image.
Note that this function modifies the Image object in place. If you need to use the full resolution image as well, apply this method to a copy() of the original image.
Syntax: Image.thumbnail(size, resample=3)
Parameters:size β Requested size.resample β Optional resampling filter.
Returns Type: An Image object.
Image Used:
# importing Image class from PIL package from PIL import Image # creating a object image = Image.open(r"C:\Users\System-Pc\Desktop\python.png")MAX_SIZE = (100, 100) image.thumbnail(MAX_SIZE) # creating thumbnailimage.save('pythonthumb.png')image.show()
Output:
Another Example:Here used another image.
Image Used:
# importing Image class from PIL package from PIL import Image # creating a object image = Image.open(r"C:\Users\System-Pc\Desktop\house.jpg")MAX_SIZE = (500, 500) image.thumbnail(MAX_SIZE) # creating thumbnailimage.save('pythonthumb2.jpg')image.show()
Output:
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Jul, 2019"
},
{
"code": null,
"e": 355,
"s": 28,
"text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images."
},
{
"code": null,
"e": 706,
"s": 355,
"text": "Image.thumbnail() Make this image into a thumbnail. This method modifies the image to contain a thumbnail version of itself, no larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the draft() method to configure the file reader (where applicable), and finally resizes the image."
},
{
"code": null,
"e": 873,
"s": 706,
"text": "Note that this function modifies the Image object in place. If you need to use the full resolution image as well, apply this method to a copy() of the original image."
},
{
"code": null,
"e": 915,
"s": 873,
"text": "Syntax: Image.thumbnail(size, resample=3)"
},
{
"code": null,
"e": 987,
"s": 915,
"text": "Parameters:size β Requested size.resample β Optional resampling filter."
},
{
"code": null,
"e": 1018,
"s": 987,
"text": "Returns Type: An Image object."
},
{
"code": null,
"e": 1030,
"s": 1018,
"text": "Image Used:"
},
{
"code": " # importing Image class from PIL package from PIL import Image # creating a object image = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\python.png\")MAX_SIZE = (100, 100) image.thumbnail(MAX_SIZE) # creating thumbnailimage.save('pythonthumb.png')image.show()",
"e": 1292,
"s": 1030,
"text": null
},
{
"code": null,
"e": 1300,
"s": 1292,
"text": "Output:"
},
{
"code": null,
"e": 1341,
"s": 1300,
"text": "Another Example:Here used another image."
},
{
"code": null,
"e": 1353,
"s": 1341,
"text": "Image Used:"
},
{
"code": " # importing Image class from PIL package from PIL import Image # creating a object image = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\house.jpg\")MAX_SIZE = (500, 500) image.thumbnail(MAX_SIZE) # creating thumbnailimage.save('pythonthumb2.jpg')image.show()",
"e": 1615,
"s": 1353,
"text": null
},
{
"code": null,
"e": 1623,
"s": 1615,
"text": "Output:"
},
{
"code": null,
"e": 1634,
"s": 1623,
"text": "Python-pil"
},
{
"code": null,
"e": 1641,
"s": 1634,
"text": "Python"
}
] |
Python 3 - Tkinter Entry
|
The Entry widget is used to accept single-line text strings from a user.
If you want to display multiple lines of text that can be edited, then you should use the Text widget.
If you want to display multiple lines of text that can be edited, then you should use the Text widget.
If you want to display one or more lines of text that cannot be modified by the user, then you should use the Label widget.
If you want to display one or more lines of text that cannot be modified by the user, then you should use the Label widget.
Here is the simple syntax to create this widget β
w = Entry( master, option, ... )
master β This represents the parent window.
master β This represents the parent window.
options β Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.
options β Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.
bg
The normal background color displayed behind the label and indicator.
bd
The size of the border around the indicator. Default is 2 pixels.
command
A procedure to be called every time the user changes the state of this checkbutton.
cursor
If you set this option to a cursor name (arrow, dot etc.), the mouse cursor will change to that pattern when it is over the checkbutton.
font
The font used for the text.
exportselection
By default, if you select text within an Entry widget, it is automatically exported to the clipboard. To avoid this exportation, use exportselection = 0.
fg
The color used to render the text.
highlightcolor
The color of the focus highlight when the checkbutton has the focus.
justify
If the text contains multiple lines, this option controls how the text is justified: CENTER, LEFT, or RIGHT.
relief
With the default value, relief = FLAT, the checkbutton does not stand out from its background. You may set this option to any of the other styles
selectbackground
The background color to use displaying selected text.
selectborderwidth
The width of the border to use around selected text. The default is one pixel.
selectforeground
The foreground (text) color of selected text.
show
Normally, the characters that the user types appear in the entry. To make a .password. entry that echoes each character as an asterisk, set show = "*".
state
The default is state = NORMAL, but you can use state = DISABLED to gray out the control and make it unresponsive. If the cursor is currently over the checkbutton, the state is ACTIVE.
textvariable
In order to be able to retrieve the current text from your entry widget, you must set this option to an instance of the StringVar class.
width
The default width of a checkbutton is determined by the size of the displayed image or text. You can set this option to a number of characters and the checkbutton will always have room for that many characters.
xscrollcommand
If you expect that users will often enter more text than the onscreen size of the widget, you can link your entry widget to a scrollbar.
Following are commonly used methods for this widget β
delete ( first, last = None )
Deletes characters from the widget, starting with the one at index first, up to but not including the character at position last. If the second argument is omitted, only the single character at position first is deleted.
get()
Returns the entry's current text as a string.
icursor ( index )
Set the insertion cursor just before the character at the given index.
index ( index )
Shift the contents of the entry so that the character at the given index is the leftmost visible character. Has no effect if the text fits entirely within the entry.
insert ( index, s )
Inserts string s before the character at the given index.
select_adjust ( index )
This method is used to make sure that the selection includes the character at the specified index.
select_clear()
Clears the selection. If there isn't currently a selection, has no effect.
select_from ( index )
Sets the ANCHOR index position to the character selected by index, and selects that character.
select_present()
If there is a selection, returns true, else returns false.
select_range ( start, end )
Sets the selection under program control. Selects the text starting at the start index, up to but not including the character at the end index. The start position must be before the end position.
select_to ( index )
Selects all the text from the ANCHOR position up to but not including the character at the given index.
xview ( index )
This method is useful in linking the Entry widget to a horizontal scrollbar.
xview_scroll ( number, what )
Used to scroll the entry horizontally. The what argument must be either UNITS, to scroll by character widths, or PAGES, to scroll by chunks the size of the entry widget. The number is positive to scroll left to right, negative to scroll right to left.
Try the following example yourself β
# !/usr/bin/python3
from tkinter import *
top = Tk()
L1 = Label(top, text = "User Name")
L1.pack( side = LEFT)
E1 = Entry(top, bd = 5)
E1.pack(side = RIGHT)
top.mainloop()
When the above code is executed, it produces the following result β
|
[
{
"code": null,
"e": 2547,
"s": 2474,
"text": "The Entry widget is used to accept single-line text strings from a user."
},
{
"code": null,
"e": 2650,
"s": 2547,
"text": "If you want to display multiple lines of text that can be edited, then you should use the Text widget."
},
{
"code": null,
"e": 2753,
"s": 2650,
"text": "If you want to display multiple lines of text that can be edited, then you should use the Text widget."
},
{
"code": null,
"e": 2877,
"s": 2753,
"text": "If you want to display one or more lines of text that cannot be modified by the user, then you should use the Label widget."
},
{
"code": null,
"e": 3001,
"s": 2877,
"text": "If you want to display one or more lines of text that cannot be modified by the user, then you should use the Label widget."
},
{
"code": null,
"e": 3051,
"s": 3001,
"text": "Here is the simple syntax to create this widget β"
},
{
"code": null,
"e": 3085,
"s": 3051,
"text": "w = Entry( master, option, ... )\n"
},
{
"code": null,
"e": 3129,
"s": 3085,
"text": "master β This represents the parent window."
},
{
"code": null,
"e": 3173,
"s": 3129,
"text": "master β This represents the parent window."
},
{
"code": null,
"e": 3313,
"s": 3173,
"text": "options β Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas."
},
{
"code": null,
"e": 3453,
"s": 3313,
"text": "options β Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas."
},
{
"code": null,
"e": 3456,
"s": 3453,
"text": "bg"
},
{
"code": null,
"e": 3526,
"s": 3456,
"text": "The normal background color displayed behind the label and indicator."
},
{
"code": null,
"e": 3529,
"s": 3526,
"text": "bd"
},
{
"code": null,
"e": 3595,
"s": 3529,
"text": "The size of the border around the indicator. Default is 2 pixels."
},
{
"code": null,
"e": 3603,
"s": 3595,
"text": "command"
},
{
"code": null,
"e": 3687,
"s": 3603,
"text": "A procedure to be called every time the user changes the state of this checkbutton."
},
{
"code": null,
"e": 3694,
"s": 3687,
"text": "cursor"
},
{
"code": null,
"e": 3831,
"s": 3694,
"text": "If you set this option to a cursor name (arrow, dot etc.), the mouse cursor will change to that pattern when it is over the checkbutton."
},
{
"code": null,
"e": 3836,
"s": 3831,
"text": "font"
},
{
"code": null,
"e": 3864,
"s": 3836,
"text": "The font used for the text."
},
{
"code": null,
"e": 3880,
"s": 3864,
"text": "exportselection"
},
{
"code": null,
"e": 4034,
"s": 3880,
"text": "By default, if you select text within an Entry widget, it is automatically exported to the clipboard. To avoid this exportation, use exportselection = 0."
},
{
"code": null,
"e": 4037,
"s": 4034,
"text": "fg"
},
{
"code": null,
"e": 4072,
"s": 4037,
"text": "The color used to render the text."
},
{
"code": null,
"e": 4087,
"s": 4072,
"text": "highlightcolor"
},
{
"code": null,
"e": 4156,
"s": 4087,
"text": "The color of the focus highlight when the checkbutton has the focus."
},
{
"code": null,
"e": 4164,
"s": 4156,
"text": "justify"
},
{
"code": null,
"e": 4273,
"s": 4164,
"text": "If the text contains multiple lines, this option controls how the text is justified: CENTER, LEFT, or RIGHT."
},
{
"code": null,
"e": 4280,
"s": 4273,
"text": "relief"
},
{
"code": null,
"e": 4426,
"s": 4280,
"text": "With the default value, relief = FLAT, the checkbutton does not stand out from its background. You may set this option to any of the other styles"
},
{
"code": null,
"e": 4443,
"s": 4426,
"text": "selectbackground"
},
{
"code": null,
"e": 4497,
"s": 4443,
"text": "The background color to use displaying selected text."
},
{
"code": null,
"e": 4515,
"s": 4497,
"text": "selectborderwidth"
},
{
"code": null,
"e": 4594,
"s": 4515,
"text": "The width of the border to use around selected text. The default is one pixel."
},
{
"code": null,
"e": 4611,
"s": 4594,
"text": "selectforeground"
},
{
"code": null,
"e": 4657,
"s": 4611,
"text": "The foreground (text) color of selected text."
},
{
"code": null,
"e": 4662,
"s": 4657,
"text": "show"
},
{
"code": null,
"e": 4814,
"s": 4662,
"text": "Normally, the characters that the user types appear in the entry. To make a .password. entry that echoes each character as an asterisk, set show = \"*\"."
},
{
"code": null,
"e": 4820,
"s": 4814,
"text": "state"
},
{
"code": null,
"e": 5004,
"s": 4820,
"text": "The default is state = NORMAL, but you can use state = DISABLED to gray out the control and make it unresponsive. If the cursor is currently over the checkbutton, the state is ACTIVE."
},
{
"code": null,
"e": 5017,
"s": 5004,
"text": "textvariable"
},
{
"code": null,
"e": 5154,
"s": 5017,
"text": "In order to be able to retrieve the current text from your entry widget, you must set this option to an instance of the StringVar class."
},
{
"code": null,
"e": 5160,
"s": 5154,
"text": "width"
},
{
"code": null,
"e": 5371,
"s": 5160,
"text": "The default width of a checkbutton is determined by the size of the displayed image or text. You can set this option to a number of characters and the checkbutton will always have room for that many characters."
},
{
"code": null,
"e": 5386,
"s": 5371,
"text": "xscrollcommand"
},
{
"code": null,
"e": 5523,
"s": 5386,
"text": "If you expect that users will often enter more text than the onscreen size of the widget, you can link your entry widget to a scrollbar."
},
{
"code": null,
"e": 5577,
"s": 5523,
"text": "Following are commonly used methods for this widget β"
},
{
"code": null,
"e": 5607,
"s": 5577,
"text": "delete ( first, last = None )"
},
{
"code": null,
"e": 5828,
"s": 5607,
"text": "Deletes characters from the widget, starting with the one at index first, up to but not including the character at position last. If the second argument is omitted, only the single character at position first is deleted."
},
{
"code": null,
"e": 5834,
"s": 5828,
"text": "get()"
},
{
"code": null,
"e": 5880,
"s": 5834,
"text": "Returns the entry's current text as a string."
},
{
"code": null,
"e": 5898,
"s": 5880,
"text": "icursor ( index )"
},
{
"code": null,
"e": 5969,
"s": 5898,
"text": "Set the insertion cursor just before the character at the given index."
},
{
"code": null,
"e": 5985,
"s": 5969,
"text": "index ( index )"
},
{
"code": null,
"e": 6151,
"s": 5985,
"text": "Shift the contents of the entry so that the character at the given index is the leftmost visible character. Has no effect if the text fits entirely within the entry."
},
{
"code": null,
"e": 6171,
"s": 6151,
"text": "insert ( index, s )"
},
{
"code": null,
"e": 6229,
"s": 6171,
"text": "Inserts string s before the character at the given index."
},
{
"code": null,
"e": 6253,
"s": 6229,
"text": "select_adjust ( index )"
},
{
"code": null,
"e": 6352,
"s": 6253,
"text": "This method is used to make sure that the selection includes the character at the specified index."
},
{
"code": null,
"e": 6367,
"s": 6352,
"text": "select_clear()"
},
{
"code": null,
"e": 6442,
"s": 6367,
"text": "Clears the selection. If there isn't currently a selection, has no effect."
},
{
"code": null,
"e": 6464,
"s": 6442,
"text": "select_from ( index )"
},
{
"code": null,
"e": 6559,
"s": 6464,
"text": "Sets the ANCHOR index position to the character selected by index, and selects that character."
},
{
"code": null,
"e": 6576,
"s": 6559,
"text": "select_present()"
},
{
"code": null,
"e": 6635,
"s": 6576,
"text": "If there is a selection, returns true, else returns false."
},
{
"code": null,
"e": 6663,
"s": 6635,
"text": "select_range ( start, end )"
},
{
"code": null,
"e": 6859,
"s": 6663,
"text": "Sets the selection under program control. Selects the text starting at the start index, up to but not including the character at the end index. The start position must be before the end position."
},
{
"code": null,
"e": 6879,
"s": 6859,
"text": "select_to ( index )"
},
{
"code": null,
"e": 6983,
"s": 6879,
"text": "Selects all the text from the ANCHOR position up to but not including the character at the given index."
},
{
"code": null,
"e": 6999,
"s": 6983,
"text": "xview ( index )"
},
{
"code": null,
"e": 7076,
"s": 6999,
"text": "This method is useful in linking the Entry widget to a horizontal scrollbar."
},
{
"code": null,
"e": 7106,
"s": 7076,
"text": "xview_scroll ( number, what )"
},
{
"code": null,
"e": 7358,
"s": 7106,
"text": "Used to scroll the entry horizontally. The what argument must be either UNITS, to scroll by character widths, or PAGES, to scroll by chunks the size of the entry widget. The number is positive to scroll left to right, negative to scroll right to left."
},
{
"code": null,
"e": 7395,
"s": 7358,
"text": "Try the following example yourself β"
},
{
"code": null,
"e": 7569,
"s": 7395,
"text": "# !/usr/bin/python3\nfrom tkinter import *\n\ntop = Tk()\nL1 = Label(top, text = \"User Name\")\nL1.pack( side = LEFT)\nE1 = Entry(top, bd = 5)\nE1.pack(side = RIGHT)\n\ntop.mainloop()"
}
] |
How to Export SQL Server Data to a CSV File?
|
18 Oct, 2021
Here we will see, how to export SQL Server Data to CSV file by using the βImport and Export wizardβ of SQL Server Management Studio (SSMS).
CSV (Comma-separated values): It is a file that consists of plain text data in which data is separated using comma(,). It is also known as Comma Delimited Files because comma act as a delimiter for CSV files.
Step 1: Creating the Database
Use the below SQL statement to create a database called geeks.
Query:
CREATE DATABASE geeks;
Step 2: Using the Database
Use the below SQL statement to switch the database context to geeks.
Query:
USE geeks;
Step 3: Table definition
We have the following demo_table in our geekβs database.
Query:
CREATE TABLE demo_table
(FIRSTNAME VARCHAR(20),
LASTNAMENAME VARCHAR(20),
AGE INT,GENDER VARCHAR(20));
Step 4: Insert data into the table
Query:
INSERT INTO demo_table VALUES
('Romy', 'Kumari', 22, 'female'),
('Sujata', 'Jha', 20, 'female'),
('Shalini', 'Jha', 22, 'female'),
('Ayushi', 'Chaudhary', 23, 'female'),
('Rinkle', 'Arora', 23, 'female'),
('Kajal', 'Sharma' ,24, 'female');
Step 5: See the content of the table
Use the below command to see the content of the demo_table:
Query:
SELECT * FROM demo_table;
Output:
Now we see steps to Export SQL Server Data into a CSV file.
Step 1: Open object Explorer from View option in the menu bar.
It appears on the left side of the screen.
We can see the βgeeksβ database inside the database folder.
Step 2: Right click on the geeks database, Click on Tasks-> Export Data.
Step 3: Import and Export wizard will open, fill the details like server name, database etc. Then click on Next.
Step 4: Choose βFlat File destinationβ as destination and choose file path. One can choose any text file as destination file. We have selected hello.txt as destination file to save the SQL Server data. Then Click Next
Step 5: choose table name and select comma as delimiter. then Click Next to proceed.
Step 6: No changes required in Save and Run package window. Click Next.
Step 7: On the βCompleteβ Wizard window, check all the settings set during of exporting process. Click βFinishβ to start exporting SQL database to CSV.
Step 8: Below window shows the successful execution
Step 9: Check the destination file which is βhelloβ in this case.
We can see the content is same as the content of demo_table separated by comma.
Picked
SQL-Server
TrueGeek-2021
SQL
TrueGeek
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL using Python
SQL | Sub queries in From Clause
How to redirect to another page in ReactJS ?
How to remove duplicate elements from JavaScript Array ?
How to Convert Char to String in Java?
Basics of API Testing Using Postman
Types of Internet Protocols
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Oct, 2021"
},
{
"code": null,
"e": 168,
"s": 28,
"text": "Here we will see, how to export SQL Server Data to CSV file by using the βImport and Export wizardβ of SQL Server Management Studio (SSMS)."
},
{
"code": null,
"e": 377,
"s": 168,
"text": "CSV (Comma-separated values): It is a file that consists of plain text data in which data is separated using comma(,). It is also known as Comma Delimited Files because comma act as a delimiter for CSV files."
},
{
"code": null,
"e": 407,
"s": 377,
"text": "Step 1: Creating the Database"
},
{
"code": null,
"e": 470,
"s": 407,
"text": "Use the below SQL statement to create a database called geeks."
},
{
"code": null,
"e": 477,
"s": 470,
"text": "Query:"
},
{
"code": null,
"e": 500,
"s": 477,
"text": "CREATE DATABASE geeks;"
},
{
"code": null,
"e": 527,
"s": 500,
"text": "Step 2: Using the Database"
},
{
"code": null,
"e": 596,
"s": 527,
"text": "Use the below SQL statement to switch the database context to geeks."
},
{
"code": null,
"e": 603,
"s": 596,
"text": "Query:"
},
{
"code": null,
"e": 614,
"s": 603,
"text": "USE geeks;"
},
{
"code": null,
"e": 639,
"s": 614,
"text": "Step 3: Table definition"
},
{
"code": null,
"e": 696,
"s": 639,
"text": "We have the following demo_table in our geekβs database."
},
{
"code": null,
"e": 703,
"s": 696,
"text": "Query:"
},
{
"code": null,
"e": 806,
"s": 703,
"text": "CREATE TABLE demo_table\n(FIRSTNAME VARCHAR(20),\nLASTNAMENAME VARCHAR(20),\nAGE INT,GENDER VARCHAR(20));"
},
{
"code": null,
"e": 841,
"s": 806,
"text": "Step 4: Insert data into the table"
},
{
"code": null,
"e": 848,
"s": 841,
"text": "Query:"
},
{
"code": null,
"e": 1088,
"s": 848,
"text": "INSERT INTO demo_table VALUES\n('Romy', 'Kumari', 22, 'female'),\n('Sujata', 'Jha', 20, 'female'),\n('Shalini', 'Jha', 22, 'female'),\n('Ayushi', 'Chaudhary', 23, 'female'),\n('Rinkle', 'Arora', 23, 'female'),\n('Kajal', 'Sharma' ,24, 'female');"
},
{
"code": null,
"e": 1125,
"s": 1088,
"text": "Step 5: See the content of the table"
},
{
"code": null,
"e": 1185,
"s": 1125,
"text": "Use the below command to see the content of the demo_table:"
},
{
"code": null,
"e": 1192,
"s": 1185,
"text": "Query:"
},
{
"code": null,
"e": 1218,
"s": 1192,
"text": "SELECT * FROM demo_table;"
},
{
"code": null,
"e": 1226,
"s": 1218,
"text": "Output:"
},
{
"code": null,
"e": 1286,
"s": 1226,
"text": "Now we see steps to Export SQL Server Data into a CSV file."
},
{
"code": null,
"e": 1349,
"s": 1286,
"text": "Step 1: Open object Explorer from View option in the menu bar."
},
{
"code": null,
"e": 1393,
"s": 1349,
"text": "It appears on the left side of the screen. "
},
{
"code": null,
"e": 1453,
"s": 1393,
"text": "We can see the βgeeksβ database inside the database folder."
},
{
"code": null,
"e": 1527,
"s": 1453,
"text": "Step 2: Right click on the geeks database, Click on Tasks-> Export Data. "
},
{
"code": null,
"e": 1640,
"s": 1527,
"text": "Step 3: Import and Export wizard will open, fill the details like server name, database etc. Then click on Next."
},
{
"code": null,
"e": 1858,
"s": 1640,
"text": "Step 4: Choose βFlat File destinationβ as destination and choose file path. One can choose any text file as destination file. We have selected hello.txt as destination file to save the SQL Server data. Then Click Next"
},
{
"code": null,
"e": 1943,
"s": 1858,
"text": "Step 5: choose table name and select comma as delimiter. then Click Next to proceed."
},
{
"code": null,
"e": 2015,
"s": 1943,
"text": "Step 6: No changes required in Save and Run package window. Click Next."
},
{
"code": null,
"e": 2167,
"s": 2015,
"text": "Step 7: On the βCompleteβ Wizard window, check all the settings set during of exporting process. Click βFinishβ to start exporting SQL database to CSV."
},
{
"code": null,
"e": 2219,
"s": 2167,
"text": "Step 8: Below window shows the successful execution"
},
{
"code": null,
"e": 2285,
"s": 2219,
"text": "Step 9: Check the destination file which is βhelloβ in this case."
},
{
"code": null,
"e": 2365,
"s": 2285,
"text": "We can see the content is same as the content of demo_table separated by comma."
},
{
"code": null,
"e": 2372,
"s": 2365,
"text": "Picked"
},
{
"code": null,
"e": 2383,
"s": 2372,
"text": "SQL-Server"
},
{
"code": null,
"e": 2397,
"s": 2383,
"text": "TrueGeek-2021"
},
{
"code": null,
"e": 2401,
"s": 2397,
"text": "SQL"
},
{
"code": null,
"e": 2410,
"s": 2401,
"text": "TrueGeek"
},
{
"code": null,
"e": 2414,
"s": 2410,
"text": "SQL"
},
{
"code": null,
"e": 2512,
"s": 2414,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2578,
"s": 2512,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 2602,
"s": 2578,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 2634,
"s": 2602,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 2651,
"s": 2634,
"text": "SQL using Python"
},
{
"code": null,
"e": 2684,
"s": 2651,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 2729,
"s": 2684,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 2786,
"s": 2729,
"text": "How to remove duplicate elements from JavaScript Array ?"
},
{
"code": null,
"e": 2825,
"s": 2786,
"text": "How to Convert Char to String in Java?"
},
{
"code": null,
"e": 2861,
"s": 2825,
"text": "Basics of API Testing Using Postman"
}
] |
PHP | uniqid( ) Function
|
29 Aug, 2021
The uniqid() function in PHP is an inbuilt function which is used to generate a unique ID based on the current time in microseconds (micro time). The ID generated from the uniqid() function is not optimal since it is based on the system time and is not cryptographically secured. Thus it should not be for cryptographical purposes.The uniqid( ) function accepts prefix and more_entropy as parameters and returns timestamp based unique identifier as a string.
Syntax:
uniqid($prefix, $more_entropy)
Parameters Used: The uiqid() function in PHP accepts two parameters.
$prefix : It is an optional parameter which specifies a prefix to the unique id. It must be string.$more_entropy : It is an optional parameter which specifies more entropy at the end of the return value which makes the id more unique.The default value is FALSE, which returns 13 characters long string whereas when it is set to TRUE, the return string is 23 characters long.
$prefix : It is an optional parameter which specifies a prefix to the unique id. It must be string.
$more_entropy : It is an optional parameter which specifies more entropy at the end of the return value which makes the id more unique.The default value is FALSE, which returns 13 characters long string whereas when it is set to TRUE, the return string is 23 characters long.
Return Value: It returns timestamp based unique identifier as a string.Errors And Exceptions:
The uniqid() function tries to create unique identifier, but it does not guarantee 100% uniqueness of return value.Since most systems adjust system clock by NTP or like, system time is changed constantly. Therefore, it is possible that this function does not return unique ID for the process/thread.
The uniqid() function tries to create unique identifier, but it does not guarantee 100% uniqueness of return value.
Since most systems adjust system clock by NTP or like, system time is changed constantly. Therefore, it is possible that this function does not return unique ID for the process/thread.
Below programs illustrate the uniqid() function:Program 1:
php
<?php// generating unique idecho uniqid();?>
Output:
3b2c662647f18
Program 2:
php
<?php// generating unique id with prefix gfg$myuid = uniqid('gfg'); echo $myuid;?>
Output:
gfg5b2b451823970
Program 3:
php
<?php// generating unique id with prefix gfg// and higher entropy$myuid = uniqid('gfg', true); echo $myuid;?>
Output:
gfg5b2b4555ab6bd7.27884925
Reference : http://php.net/manual/en/function.uniqid.php
raghurajendran
simmytarika5
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
Split a comma delimited string into an array in PHP
Download file from URL using PHP
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Aug, 2021"
},
{
"code": null,
"e": 488,
"s": 28,
"text": "The uniqid() function in PHP is an inbuilt function which is used to generate a unique ID based on the current time in microseconds (micro time). The ID generated from the uniqid() function is not optimal since it is based on the system time and is not cryptographically secured. Thus it should not be for cryptographical purposes.The uniqid( ) function accepts prefix and more_entropy as parameters and returns timestamp based unique identifier as a string. "
},
{
"code": null,
"e": 498,
"s": 488,
"text": "Syntax: "
},
{
"code": null,
"e": 531,
"s": 498,
"text": " uniqid($prefix, $more_entropy) "
},
{
"code": null,
"e": 601,
"s": 531,
"text": "Parameters Used: The uiqid() function in PHP accepts two parameters. "
},
{
"code": null,
"e": 976,
"s": 601,
"text": "$prefix : It is an optional parameter which specifies a prefix to the unique id. It must be string.$more_entropy : It is an optional parameter which specifies more entropy at the end of the return value which makes the id more unique.The default value is FALSE, which returns 13 characters long string whereas when it is set to TRUE, the return string is 23 characters long."
},
{
"code": null,
"e": 1076,
"s": 976,
"text": "$prefix : It is an optional parameter which specifies a prefix to the unique id. It must be string."
},
{
"code": null,
"e": 1352,
"s": 1076,
"text": "$more_entropy : It is an optional parameter which specifies more entropy at the end of the return value which makes the id more unique.The default value is FALSE, which returns 13 characters long string whereas when it is set to TRUE, the return string is 23 characters long."
},
{
"code": null,
"e": 1447,
"s": 1352,
"text": "Return Value: It returns timestamp based unique identifier as a string.Errors And Exceptions: "
},
{
"code": null,
"e": 1747,
"s": 1447,
"text": "The uniqid() function tries to create unique identifier, but it does not guarantee 100% uniqueness of return value.Since most systems adjust system clock by NTP or like, system time is changed constantly. Therefore, it is possible that this function does not return unique ID for the process/thread."
},
{
"code": null,
"e": 1863,
"s": 1747,
"text": "The uniqid() function tries to create unique identifier, but it does not guarantee 100% uniqueness of return value."
},
{
"code": null,
"e": 2048,
"s": 1863,
"text": "Since most systems adjust system clock by NTP or like, system time is changed constantly. Therefore, it is possible that this function does not return unique ID for the process/thread."
},
{
"code": null,
"e": 2108,
"s": 2048,
"text": "Below programs illustrate the uniqid() function:Program 1: "
},
{
"code": null,
"e": 2112,
"s": 2108,
"text": "php"
},
{
"code": "<?php// generating unique idecho uniqid();?>",
"e": 2157,
"s": 2112,
"text": null
},
{
"code": null,
"e": 2167,
"s": 2157,
"text": "Output: "
},
{
"code": null,
"e": 2181,
"s": 2167,
"text": "3b2c662647f18"
},
{
"code": null,
"e": 2193,
"s": 2181,
"text": "Program 2: "
},
{
"code": null,
"e": 2197,
"s": 2193,
"text": "php"
},
{
"code": "<?php// generating unique id with prefix gfg$myuid = uniqid('gfg'); echo $myuid;?>",
"e": 2280,
"s": 2197,
"text": null
},
{
"code": null,
"e": 2290,
"s": 2280,
"text": "Output: "
},
{
"code": null,
"e": 2307,
"s": 2290,
"text": "gfg5b2b451823970"
},
{
"code": null,
"e": 2319,
"s": 2307,
"text": "Program 3: "
},
{
"code": null,
"e": 2323,
"s": 2319,
"text": "php"
},
{
"code": "<?php// generating unique id with prefix gfg// and higher entropy$myuid = uniqid('gfg', true); echo $myuid;?>",
"e": 2433,
"s": 2323,
"text": null
},
{
"code": null,
"e": 2443,
"s": 2433,
"text": "Output: "
},
{
"code": null,
"e": 2470,
"s": 2443,
"text": "gfg5b2b4555ab6bd7.27884925"
},
{
"code": null,
"e": 2527,
"s": 2470,
"text": "Reference : http://php.net/manual/en/function.uniqid.php"
},
{
"code": null,
"e": 2542,
"s": 2527,
"text": "raghurajendran"
},
{
"code": null,
"e": 2555,
"s": 2542,
"text": "simmytarika5"
},
{
"code": null,
"e": 2568,
"s": 2555,
"text": "PHP-function"
},
{
"code": null,
"e": 2572,
"s": 2568,
"text": "PHP"
},
{
"code": null,
"e": 2589,
"s": 2572,
"text": "Web Technologies"
},
{
"code": null,
"e": 2593,
"s": 2589,
"text": "PHP"
},
{
"code": null,
"e": 2691,
"s": 2593,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2731,
"s": 2691,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 2776,
"s": 2731,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 2803,
"s": 2776,
"text": "Comparing two dates in PHP"
},
{
"code": null,
"e": 2855,
"s": 2803,
"text": "Split a comma delimited string into an array in PHP"
},
{
"code": null,
"e": 2888,
"s": 2855,
"text": "Download file from URL using PHP"
},
{
"code": null,
"e": 2921,
"s": 2888,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2983,
"s": 2921,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3044,
"s": 2983,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3094,
"s": 3044,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python β Merge Dictionaries List with duplicate Keys
|
02 Dec, 2020
Given two List of dictionaries with possible duplicate keys, write a Python program to perform merge.
Examples:
Input : test_list1 = [{βgfgβ : 1, βbestβ : 4}, {βgeeksβ : 10, βgoodβ : 15}, {βloveβ : βgfgβ}], test_list2 = [{βgfgβ : 6}, {βbetterβ : 3, βforβ : 10, βgeeksβ : 1}, {βgfgβ : 10}] Output : [{βgfgβ: 1, βbestβ: 4}, {βgeeksβ: 10, βgoodβ: 15, βbetterβ: 3, βforβ: 10}, {βloveβ: βgfgβ, βgfgβ: 10}] Explanation : gfg while merging retains value of 1, and βbestβ is added to dictionary as key from other listβs 1st dictionary ( same index ).
Input : test_list1 = [{βgfgβ : 1, βbestβ : 4}, {βloveβ : βgfgβ}], test_list2 = [{βgfgβ : 6}, {βgfgβ : 10}] Output : [{βgfgβ: 1, βbestβ: 4}, {βloveβ: βgfgβ, βgfgβ: 10}] Explanation : gfg while merging retains value of 1, and βbestβ is added to dictionary as key from other listβs 1st dictionary ( same index ).
Approach : Using loop + keys()
In this we reconstruct the key value pair in accordance of all the keys not recurring, checking using in operator and extracting keys using keys().
Python3
# Python3 code to demonstrate working of# Merge Dictionaries List with duplicate Keys# Using loop + keys() # initializing liststest_list1 = [{"gfg": 1, "best": 4}, {"geeks": 10, "good": 15}, {"love": "gfg"}] test_list2 = [{"gfg": 6}, {"better": 3, "for": 10, "geeks": 1}, {"gfg": 10}] # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2)) for idx in range(0, len(test_list1)): # getting keys of corresponding index id_keys = list(test_list1[idx].keys()) for key in test_list2[idx]: # checking for keys presence if key not in id_keys: test_list1[idx][key] = test_list2[idx][key] # printing resultprint("The Merged Dictionary list : " + str(test_list1))
Output:
The original list 1 is : [{βgfgβ: 1, βbestβ: 4}, {βgeeksβ: 10, βgoodβ: 15}, {βloveβ: βgfgβ}]The original list 2 is : [{βgfgβ: 6}, {βbetterβ: 3, βforβ: 10, βgeeksβ: 1}, {βgfgβ: 10}]The Merged Dictionary list : [{βgfgβ: 1, βbestβ: 4}, {βgeeksβ: 10, βgoodβ: 15, βbetterβ: 3, βforβ: 10}, {βloveβ: βgfgβ, βgfgβ: 10}]
Python dictionary-programs
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Dec, 2020"
},
{
"code": null,
"e": 130,
"s": 28,
"text": "Given two List of dictionaries with possible duplicate keys, write a Python program to perform merge."
},
{
"code": null,
"e": 140,
"s": 130,
"text": "Examples:"
},
{
"code": null,
"e": 572,
"s": 140,
"text": "Input : test_list1 = [{βgfgβ : 1, βbestβ : 4}, {βgeeksβ : 10, βgoodβ : 15}, {βloveβ : βgfgβ}], test_list2 = [{βgfgβ : 6}, {βbetterβ : 3, βforβ : 10, βgeeksβ : 1}, {βgfgβ : 10}] Output : [{βgfgβ: 1, βbestβ: 4}, {βgeeksβ: 10, βgoodβ: 15, βbetterβ: 3, βforβ: 10}, {βloveβ: βgfgβ, βgfgβ: 10}] Explanation : gfg while merging retains value of 1, and βbestβ is added to dictionary as key from other listβs 1st dictionary ( same index ). "
},
{
"code": null,
"e": 883,
"s": 572,
"text": "Input : test_list1 = [{βgfgβ : 1, βbestβ : 4}, {βloveβ : βgfgβ}], test_list2 = [{βgfgβ : 6}, {βgfgβ : 10}] Output : [{βgfgβ: 1, βbestβ: 4}, {βloveβ: βgfgβ, βgfgβ: 10}] Explanation : gfg while merging retains value of 1, and βbestβ is added to dictionary as key from other listβs 1st dictionary ( same index ). "
},
{
"code": null,
"e": 914,
"s": 883,
"text": "Approach : Using loop + keys()"
},
{
"code": null,
"e": 1062,
"s": 914,
"text": "In this we reconstruct the key value pair in accordance of all the keys not recurring, checking using in operator and extracting keys using keys()."
},
{
"code": null,
"e": 1070,
"s": 1062,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Merge Dictionaries List with duplicate Keys# Using loop + keys() # initializing liststest_list1 = [{\"gfg\": 1, \"best\": 4}, {\"geeks\": 10, \"good\": 15}, {\"love\": \"gfg\"}] test_list2 = [{\"gfg\": 6}, {\"better\": 3, \"for\": 10, \"geeks\": 1}, {\"gfg\": 10}] # printing original listsprint(\"The original list 1 is : \" + str(test_list1))print(\"The original list 2 is : \" + str(test_list2)) for idx in range(0, len(test_list1)): # getting keys of corresponding index id_keys = list(test_list1[idx].keys()) for key in test_list2[idx]: # checking for keys presence if key not in id_keys: test_list1[idx][key] = test_list2[idx][key] # printing resultprint(\"The Merged Dictionary list : \" + str(test_list1))",
"e": 1869,
"s": 1070,
"text": null
},
{
"code": null,
"e": 1877,
"s": 1869,
"text": "Output:"
},
{
"code": null,
"e": 2189,
"s": 1877,
"text": "The original list 1 is : [{βgfgβ: 1, βbestβ: 4}, {βgeeksβ: 10, βgoodβ: 15}, {βloveβ: βgfgβ}]The original list 2 is : [{βgfgβ: 6}, {βbetterβ: 3, βforβ: 10, βgeeksβ: 1}, {βgfgβ: 10}]The Merged Dictionary list : [{βgfgβ: 1, βbestβ: 4}, {βgeeksβ: 10, βgoodβ: 15, βbetterβ: 3, βforβ: 10}, {βloveβ: βgfgβ, βgfgβ: 10}]"
},
{
"code": null,
"e": 2216,
"s": 2189,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 2237,
"s": 2216,
"text": "Python list-programs"
},
{
"code": null,
"e": 2244,
"s": 2237,
"text": "Python"
},
{
"code": null,
"e": 2260,
"s": 2244,
"text": "Python Programs"
},
{
"code": null,
"e": 2358,
"s": 2260,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2390,
"s": 2358,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2417,
"s": 2390,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2438,
"s": 2417,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2461,
"s": 2438,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2492,
"s": 2461,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2514,
"s": 2492,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2553,
"s": 2514,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2591,
"s": 2553,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2628,
"s": 2591,
"text": "Python Program for Fibonacci numbers"
}
] |
How to fix SSL_ERROR_RX_RECORD_TOO_LONG on Mozilla Firefox ?
|
05 Nov, 2020
What Is the Mozilla Firefox Error Message SSL_ERROR_RX_RECORD_TOO_LONG ?
Firefox SSL_ERROR_RX_RECORD_TOO_LONG message is displayed because a certain mis-configuration has been occurred on the server. Most of the time, because of the following two reasons, the SSL_ERROR_RX_RECORD_TOO_LONG error message is displayed from the server-side:
The listening port is misconfigured. For example, the website you may want to establish a secure connection is not configured to use Port 443.
Adequate TLS version may not be supported by your system.
Mostly, SSL_ERROR_RX_RECORD_TOO_LONG may occur due to any one of the issues mentioned above. Now letβs learn how to fix this issue.
Upgrade Your Support for TLS Version: TLS 1.3, called as RFC 8446, is the latest TLS version. So, check whether the SSL/TLS library is updated or not. Most systems and servers use the Open SSL library, which will support TLS 1.3. If due to any reason, your system or server cannot support TLS 1.3, then make sure that it supports for TLS 1.2 is available.
To Solve the SSL_ERROR_RX_RECORD_TOO_LONG, use the Correct Listening Port: As mentioned above, 443 is the correct listening port for HTTPS traffic. If your port doesnβt match or the trusted SSL/TLS certificate is not on that port, itβs likely youβll face this SSL_ERROR_RX_RECORD_TOO_LONG error message.
Fixing the SSL_ERROR_RX_RECORD_TOO_LONG From a Userβs Standpoint: Letβs see a user what you can do to solve this Mozilla Firefox error message SSL_ERROR_RX_RECORD_TOO_LONG.
1. Clearing the Cache- Sometimes, clearing the cache can solve this issue. One of the best and better way is to check whether the website in an Incognito or Private Window. Additionally, you can also use:
Ctrl+ Shift + R
or
Shift + click Reload current page
Mostly, it will fail. But, thereβs nothing to lose, as itβs a safe and better way to check whether it solves the issue or not.
2. Changing the Preference of the security.tls.version.max- Itβs not recommended but it can be useful in certain scenarios. For example, the website supports TLS 1.3 and Firefox also assumes it does but your Operating System on which Mozilla Firefox is running doesnβt support it. At that time, this SSL_ERROR_RX_RECORD_TOO_LONG error can occur.
So, if youβre using Microsoft Windows operating system and want to drop support for TLS 1.3 on a temporary basis, follow the steps given below.
In Mozilla Firefox, open a tab and in the address bar type βabout:configβ and click on βI accept the risk!β button.
In the search field, type: security.tls.version.max and then double-click on it.
A pop-up will be displayed, in that change the value from 4 to 3.
Another thing to note is that the values in Firefox support the TLS version. For example, 1 is for TLS 1.0, 3 is for TLS 1.3, and 3 is for TLS 1.2. Also, make sure you donβt go below TLS 1.2 as the versions below TLS 1.2 are not supported due to vulnerability issues.
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Nov, 2020"
},
{
"code": null,
"e": 101,
"s": 28,
"text": "What Is the Mozilla Firefox Error Message SSL_ERROR_RX_RECORD_TOO_LONG ?"
},
{
"code": null,
"e": 366,
"s": 101,
"text": "Firefox SSL_ERROR_RX_RECORD_TOO_LONG message is displayed because a certain mis-configuration has been occurred on the server. Most of the time, because of the following two reasons, the SSL_ERROR_RX_RECORD_TOO_LONG error message is displayed from the server-side:"
},
{
"code": null,
"e": 509,
"s": 366,
"text": "The listening port is misconfigured. For example, the website you may want to establish a secure connection is not configured to use Port 443."
},
{
"code": null,
"e": 567,
"s": 509,
"text": "Adequate TLS version may not be supported by your system."
},
{
"code": null,
"e": 699,
"s": 567,
"text": "Mostly, SSL_ERROR_RX_RECORD_TOO_LONG may occur due to any one of the issues mentioned above. Now letβs learn how to fix this issue."
},
{
"code": null,
"e": 1055,
"s": 699,
"text": "Upgrade Your Support for TLS Version: TLS 1.3, called as RFC 8446, is the latest TLS version. So, check whether the SSL/TLS library is updated or not. Most systems and servers use the Open SSL library, which will support TLS 1.3. If due to any reason, your system or server cannot support TLS 1.3, then make sure that it supports for TLS 1.2 is available."
},
{
"code": null,
"e": 1359,
"s": 1055,
"text": "To Solve the SSL_ERROR_RX_RECORD_TOO_LONG, use the Correct Listening Port: As mentioned above, 443 is the correct listening port for HTTPS traffic. If your port doesnβt match or the trusted SSL/TLS certificate is not on that port, itβs likely youβll face this SSL_ERROR_RX_RECORD_TOO_LONG error message."
},
{
"code": null,
"e": 1532,
"s": 1359,
"text": "Fixing the SSL_ERROR_RX_RECORD_TOO_LONG From a Userβs Standpoint: Letβs see a user what you can do to solve this Mozilla Firefox error message SSL_ERROR_RX_RECORD_TOO_LONG."
},
{
"code": null,
"e": 1737,
"s": 1532,
"text": "1. Clearing the Cache- Sometimes, clearing the cache can solve this issue. One of the best and better way is to check whether the website in an Incognito or Private Window. Additionally, you can also use:"
},
{
"code": null,
"e": 1753,
"s": 1737,
"text": "Ctrl+ Shift + R"
},
{
"code": null,
"e": 1758,
"s": 1753,
"text": " or"
},
{
"code": null,
"e": 1792,
"s": 1758,
"text": "Shift + click Reload current page"
},
{
"code": null,
"e": 1919,
"s": 1792,
"text": "Mostly, it will fail. But, thereβs nothing to lose, as itβs a safe and better way to check whether it solves the issue or not."
},
{
"code": null,
"e": 2265,
"s": 1919,
"text": "2. Changing the Preference of the security.tls.version.max- Itβs not recommended but it can be useful in certain scenarios. For example, the website supports TLS 1.3 and Firefox also assumes it does but your Operating System on which Mozilla Firefox is running doesnβt support it. At that time, this SSL_ERROR_RX_RECORD_TOO_LONG error can occur."
},
{
"code": null,
"e": 2409,
"s": 2265,
"text": "So, if youβre using Microsoft Windows operating system and want to drop support for TLS 1.3 on a temporary basis, follow the steps given below."
},
{
"code": null,
"e": 2525,
"s": 2409,
"text": "In Mozilla Firefox, open a tab and in the address bar type βabout:configβ and click on βI accept the risk!β button."
},
{
"code": null,
"e": 2606,
"s": 2525,
"text": "In the search field, type: security.tls.version.max and then double-click on it."
},
{
"code": null,
"e": 2672,
"s": 2606,
"text": "A pop-up will be displayed, in that change the value from 4 to 3."
},
{
"code": null,
"e": 2940,
"s": 2672,
"text": "Another thing to note is that the values in Firefox support the TLS version. For example, 1 is for TLS 1.0, 3 is for TLS 1.3, and 3 is for TLS 1.2. Also, make sure you donβt go below TLS 1.2 as the versions below TLS 1.2 are not supported due to vulnerability issues."
},
{
"code": null,
"e": 2957,
"s": 2940,
"text": "Web Technologies"
},
{
"code": null,
"e": 2984,
"s": 2957,
"text": "Web technologies Questions"
}
] |
Matplotlib.pyplot.stem() in Python
|
21 Apr, 2020
Matplotlib is a visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
matplotlib.pyplot.stem() creates stem plots. A Stem plot plots vertical lines at each x position covered under the graph from the baseline to y, and places a marker there.
Syntax: stem([x, ] y, linefmt=None, markerfmt=None, basefmt=None)
Parameters:
x (array-like, optional): The x-positions of the stems. Default: (0, 1, ..., len(y) β 1).
y (array-like): The y-values of the stem heads.
linefmt (str, optional): A string defining the properties of the vertical lines. Usually, this will be a color or a color and a linestyle:β-β: solid lineβββ: dashed lineβ-.β: dash-dot lineβ:β dotted lineNote: While it is technically possible to specify valid formats other than color or color and linestyle (e.g. βrxβ or β-.β), this is beyond the intention of the method and will most likely not result in a reasonable plot.
β-β: solid line
βββ: dashed line
β-.β: dash-dot line
β:β dotted line
Note: While it is technically possible to specify valid formats other than color or color and linestyle (e.g. βrxβ or β-.β), this is beyond the intention of the method and will most likely not result in a reasonable plot.
markerfmt (str, optional): A string defining the properties of the markers at the stem heads. Default: βC0oβ, i.e. filled circles with the first color of the color cycle.
basefmt (str, optional): A format string defining the properties of the baseline.Default: βC3-β (βC2-β in classic mode).
bottom (float, optional, default: 0): The y-position of the baseline.
label (str, optional, default: None): The label to use for the stems in legends.
use_line_collection (bool, optional, default: False): If True, store and plot the stem lines as a LineCollection instead of individual lines. This significantly increases performance, and will become the default option in Matplotlib 3.3. If False, defaults to the old behavior of using a list of Line2D objects.
Returns :
The container may be treated like a tuple(markerline, stemlines, baseline)
Example #1: Default plot
Stem plots vertical lines from a baseline to the y-coordinate and places a marker at the tip.
# importing librariesimport matplotlib.pyplot as pltimport numpy as np x = np.linspace(0.1, 2 * np.pi, 41)y = np.exp(np.sin(x)) plt.stem(x, y, use_line_collection = True)plt.show()
Output : Example #2:The position of the baseline can be adapted using bottom. The parameters linefmt, markerfmt, and basefmt control basic format properties of the plot. However, in contrast to plot not all properties are configurable via keyword arguments. For more advanced control adapt the line objects returned by pyplot.
# importing librariesimport randomimport matplotlib.pyplot as plt x = np.linspace(0.1, 2 * np.pi, 41)y = np.exp(np.sin(x)) markerline, stemlines, baseline = plt.stem( x, y, linefmt ='grey', markerfmt ='D', bottom = 1.1, use_line_collection = True) markerline.set_markerfacecolor('none')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 231,
"s": 28,
"text": "Matplotlib is a visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack."
},
{
"code": null,
"e": 403,
"s": 231,
"text": "matplotlib.pyplot.stem() creates stem plots. A Stem plot plots vertical lines at each x position covered under the graph from the baseline to y, and places a marker there."
},
{
"code": null,
"e": 469,
"s": 403,
"text": "Syntax: stem([x, ] y, linefmt=None, markerfmt=None, basefmt=None)"
},
{
"code": null,
"e": 481,
"s": 469,
"text": "Parameters:"
},
{
"code": null,
"e": 571,
"s": 481,
"text": "x (array-like, optional): The x-positions of the stems. Default: (0, 1, ..., len(y) β 1)."
},
{
"code": null,
"e": 619,
"s": 571,
"text": "y (array-like): The y-values of the stem heads."
},
{
"code": null,
"e": 1044,
"s": 619,
"text": "linefmt (str, optional): A string defining the properties of the vertical lines. Usually, this will be a color or a color and a linestyle:β-β: solid lineβββ: dashed lineβ-.β: dash-dot lineβ:β dotted lineNote: While it is technically possible to specify valid formats other than color or color and linestyle (e.g. βrxβ or β-.β), this is beyond the intention of the method and will most likely not result in a reasonable plot."
},
{
"code": null,
"e": 1060,
"s": 1044,
"text": "β-β: solid line"
},
{
"code": null,
"e": 1077,
"s": 1060,
"text": "βββ: dashed line"
},
{
"code": null,
"e": 1097,
"s": 1077,
"text": "β-.β: dash-dot line"
},
{
"code": null,
"e": 1113,
"s": 1097,
"text": "β:β dotted line"
},
{
"code": null,
"e": 1335,
"s": 1113,
"text": "Note: While it is technically possible to specify valid formats other than color or color and linestyle (e.g. βrxβ or β-.β), this is beyond the intention of the method and will most likely not result in a reasonable plot."
},
{
"code": null,
"e": 1506,
"s": 1335,
"text": "markerfmt (str, optional): A string defining the properties of the markers at the stem heads. Default: βC0oβ, i.e. filled circles with the first color of the color cycle."
},
{
"code": null,
"e": 1627,
"s": 1506,
"text": "basefmt (str, optional): A format string defining the properties of the baseline.Default: βC3-β (βC2-β in classic mode)."
},
{
"code": null,
"e": 1697,
"s": 1627,
"text": "bottom (float, optional, default: 0): The y-position of the baseline."
},
{
"code": null,
"e": 1778,
"s": 1697,
"text": "label (str, optional, default: None): The label to use for the stems in legends."
},
{
"code": null,
"e": 2090,
"s": 1778,
"text": "use_line_collection (bool, optional, default: False): If True, store and plot the stem lines as a LineCollection instead of individual lines. This significantly increases performance, and will become the default option in Matplotlib 3.3. If False, defaults to the old behavior of using a list of Line2D objects."
},
{
"code": null,
"e": 2100,
"s": 2090,
"text": "Returns :"
},
{
"code": null,
"e": 2175,
"s": 2100,
"text": "The container may be treated like a tuple(markerline, stemlines, baseline)"
},
{
"code": null,
"e": 2200,
"s": 2175,
"text": "Example #1: Default plot"
},
{
"code": null,
"e": 2294,
"s": 2200,
"text": "Stem plots vertical lines from a baseline to the y-coordinate and places a marker at the tip."
},
{
"code": "# importing librariesimport matplotlib.pyplot as pltimport numpy as np x = np.linspace(0.1, 2 * np.pi, 41)y = np.exp(np.sin(x)) plt.stem(x, y, use_line_collection = True)plt.show()",
"e": 2477,
"s": 2294,
"text": null
},
{
"code": null,
"e": 2804,
"s": 2477,
"text": "Output : Example #2:The position of the baseline can be adapted using bottom. The parameters linefmt, markerfmt, and basefmt control basic format properties of the plot. However, in contrast to plot not all properties are configurable via keyword arguments. For more advanced control adapt the line objects returned by pyplot."
},
{
"code": "# importing librariesimport randomimport matplotlib.pyplot as plt x = np.linspace(0.1, 2 * np.pi, 41)y = np.exp(np.sin(x)) markerline, stemlines, baseline = plt.stem( x, y, linefmt ='grey', markerfmt ='D', bottom = 1.1, use_line_collection = True) markerline.set_markerfacecolor('none')plt.show()",
"e": 3110,
"s": 2804,
"text": null
},
{
"code": null,
"e": 3118,
"s": 3110,
"text": "Output:"
},
{
"code": null,
"e": 3136,
"s": 3118,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 3143,
"s": 3136,
"text": "Python"
},
{
"code": null,
"e": 3241,
"s": 3143,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3259,
"s": 3241,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3301,
"s": 3259,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3323,
"s": 3301,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3358,
"s": 3323,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3384,
"s": 3358,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3416,
"s": 3384,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3445,
"s": 3416,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3472,
"s": 3445,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3493,
"s": 3472,
"text": "Python OOPs Concepts"
}
] |
Numpy | Binary Operations - GeeksforGeeks
|
15 Nov, 2018
Binary operators acts on bits and performs bit by bit operation. Binary operation is simply a rule for combining two values to create a new value.
numpy.bitwise_and() : This function is used to Compute the bit-wise AND of two array element-wise. This function computes the bit-wise AND of the underlying binary representation of the integers in the input arrays.
Code #1 :
Output :
Input number1 : 10
Input number2 : 11
bitwise_and of 10 and 11 : 10
Code #2 :
Output :
Input array1 : [2, 8, 125]
Input array2 : [3, 3, 115]
Output array after bitwise_and: [ 2 0 113]
numpy.bitwise_or() : This function is used to Compute the bit-wise OR of two array element-wise. This function computes the bit-wise OR of the underlying binary representation of the integers in the input arrays.
Code #1 :
Output :
Input number1 : 10
Input number2 : 11
bitwise_or of 10 and 11 : 11
Code #2 :
Output :
Input array1 : [2, 8, 125]
Input array2 : [3, 3, 115]
Output array after bitwise_or: [ 3 11 127]
numpy.bitwise_xor() : This function is used to Compute the bit-wise XOR of two array element-wise. This function computes the bit-wise XOR of the underlying binary representation of the integers in the input arrays.
Code #1 :
Output :
Input number1 : 10
Input number2 : 11
bitwise_xor of 10 and 11 : 1
Code #2 :
Output :
Input array1 : [2, 8, 125]
Input array2 : [3, 3, 115]
Output array after bitwise_xor: [ 1 11 14]
numpy.invert() : This function is used to Compute the bit-wise Inversion of an array element-wise. It computes the bit-wise NOT of the underlying binary representation of the integers in the input arrays.For signed integer inputs, the twoβs complement is returned. In a twoβs-complement system negative numbers are represented by the twoβs complement of the absolute value.
Code #1 :
Output :
Input number : 10
inversion of 10 : -11
Code #2 :
Output :
Input array : [2, 0, 25]
Output array after inversion: [ -3 -1 -26]
numpy.left_shift() : This function is used to Shift the bits of an integer to the left.The bits are shifted to the left by appending arr2 0s(zeroes) at the right of arr1. Since the internal representation of numbers is in binary format, this operation is equivalent to multiplying arr1 by 2**arr2. For example, if the number is 5 and we want to 2 bit left shift then after left shift 2 bit the result will be 5*(2^2) = 20
Code #1 :
Output :
Input number : 5
Number of bit shift : 2
After left shifting 2 bit : 20
Code #2 :
Output :
Input array : [2, 8, 15]
Number of bit shift : [3, 4, 5]
Output array after left shifting: [ 16 128 480]
numpy.right_shift() : This function is used to Shift the bits of an integer to the right.Because the internal representation of numbers is in binary format, this operation is equivalent to dividing arr1 by 2**arr2. For example, if the number is 20 and we want to 2-bit right shift then after right shift 2-bit the result will be 20/(2^2) = 5.
Code #1 :
Output :
Input number : 20
Number of bit shift : 2
After right shifting 2 bit : 5
Code #2 :
Output :
Input array : [24, 48, 16]
Number of bit shift : [3, 4, 2]
Output array after right shifting: [3 3 4]
numpy.binary_repr(number, width=None) : This function is used to represent binary form of the input number as a string.For negative numbers, if width is not given, a minus sign is added to the front. If width is given, the twoβs complement of the number is returned, with respect to that width.In a twoβs-complement system, negative numbers are represented by the twoβs complement of the absolute value. This is the most common method of representing signed integers on computers.
Code #1 :
Output :
Input number : 10
binary representation of 10 : 1010
Code #2 :
Output :
Input array : [5, -8]
Binary representation of 5
Without using width parameter : 101
Using width parameter: 00101
Binary representation of -8
Without using width parameter : -1000
Using width parameter : 11000
numpy.packbits(myarray, axis=None) : This function is used to packs the elements of a binary-valued array into bits in a uint8 array.The result is padded to full bytes by inserting zero bits at the end.
Code #1 :
Output :
[[[160],[64]],[[192],[32]]]
numpy.unpackbits(myarray, axis=None) : This function is used to Unpacks elements of a uint8 array into a binary-valued output array.Each element of myarray represents a bit-field that should be unpacked into a binary-valued output array. The shape of the output array is either 1-D (if axis is None) or the same shape as the input array with unpacking done along the axis specified.
Code #1 :
Output :
[[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1, 1, 1],
[0, 0, 0, 1, 0, 1, 1, 1]]
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Learn C++ Programming Step by Step - A 20 Day Curriculum!
Must Do Coding Questions for Product Based Companies
50 Common Ports You Should Know
GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?
How to Find Length of String in Bash Script?
Samsung R&D Internship Interview Experience (On-Campus)
Generate UUID in Golang
How to install PHP in windows 10 ?
Types of Distributed System
|
[
{
"code": null,
"e": 43445,
"s": 43417,
"text": "\n15 Nov, 2018"
},
{
"code": null,
"e": 43592,
"s": 43445,
"text": "Binary operators acts on bits and performs bit by bit operation. Binary operation is simply a rule for combining two values to create a new value."
},
{
"code": null,
"e": 43808,
"s": 43592,
"text": "numpy.bitwise_and() : This function is used to Compute the bit-wise AND of two array element-wise. This function computes the bit-wise AND of the underlying binary representation of the integers in the input arrays."
},
{
"code": null,
"e": 43818,
"s": 43808,
"text": "Code #1 :"
},
{
"code": null,
"e": 43827,
"s": 43818,
"text": "Output :"
},
{
"code": null,
"e": 43901,
"s": 43827,
"text": "Input number1 : 10\nInput number2 : 11\nbitwise_and of 10 and 11 : 10\n"
},
{
"code": null,
"e": 43912,
"s": 43901,
"text": " Code #2 :"
},
{
"code": null,
"e": 43921,
"s": 43912,
"text": "Output :"
},
{
"code": null,
"e": 44025,
"s": 43921,
"text": "Input array1 : [2, 8, 125]\nInput array2 : [3, 3, 115]\nOutput array after bitwise_and: [ 2 0 113]\n"
},
{
"code": null,
"e": 44239,
"s": 44025,
"text": " numpy.bitwise_or() : This function is used to Compute the bit-wise OR of two array element-wise. This function computes the bit-wise OR of the underlying binary representation of the integers in the input arrays."
},
{
"code": null,
"e": 44249,
"s": 44239,
"text": "Code #1 :"
},
{
"code": null,
"e": 44258,
"s": 44249,
"text": "Output :"
},
{
"code": null,
"e": 44331,
"s": 44258,
"text": "Input number1 : 10\nInput number2 : 11\nbitwise_or of 10 and 11 : 11\n"
},
{
"code": null,
"e": 44342,
"s": 44331,
"text": " Code #2 :"
},
{
"code": null,
"e": 44351,
"s": 44342,
"text": "Output :"
},
{
"code": null,
"e": 44454,
"s": 44351,
"text": "Input array1 : [2, 8, 125]\nInput array2 : [3, 3, 115]\nOutput array after bitwise_or: [ 3 11 127]\n"
},
{
"code": null,
"e": 44671,
"s": 44454,
"text": " numpy.bitwise_xor() : This function is used to Compute the bit-wise XOR of two array element-wise. This function computes the bit-wise XOR of the underlying binary representation of the integers in the input arrays."
},
{
"code": null,
"e": 44681,
"s": 44671,
"text": "Code #1 :"
},
{
"code": null,
"e": 44690,
"s": 44681,
"text": "Output :"
},
{
"code": null,
"e": 44763,
"s": 44690,
"text": "Input number1 : 10\nInput number2 : 11\nbitwise_xor of 10 and 11 : 1\n"
},
{
"code": null,
"e": 44774,
"s": 44763,
"text": " Code #2 :"
},
{
"code": null,
"e": 44783,
"s": 44774,
"text": "Output :"
},
{
"code": null,
"e": 44884,
"s": 44783,
"text": "Input array1 : [2, 8, 125]\nInput array2 : [3, 3, 115]\nOutput array after bitwise_xor: [ 1 11 14]\n"
},
{
"code": null,
"e": 45259,
"s": 44884,
"text": " numpy.invert() : This function is used to Compute the bit-wise Inversion of an array element-wise. It computes the bit-wise NOT of the underlying binary representation of the integers in the input arrays.For signed integer inputs, the twoβs complement is returned. In a twoβs-complement system negative numbers are represented by the twoβs complement of the absolute value."
},
{
"code": null,
"e": 45269,
"s": 45259,
"text": "Code #1 :"
},
{
"code": null,
"e": 45278,
"s": 45269,
"text": "Output :"
},
{
"code": null,
"e": 45322,
"s": 45278,
"text": "Input number : 10\ninversion of 10 : -11\n"
},
{
"code": null,
"e": 45333,
"s": 45322,
"text": " Code #2 :"
},
{
"code": null,
"e": 45342,
"s": 45333,
"text": "Output :"
},
{
"code": null,
"e": 45414,
"s": 45342,
"text": "Input array : [2, 0, 25]\nOutput array after inversion: [ -3 -1 -26]\n"
},
{
"code": null,
"e": 45837,
"s": 45414,
"text": " numpy.left_shift() : This function is used to Shift the bits of an integer to the left.The bits are shifted to the left by appending arr2 0s(zeroes) at the right of arr1. Since the internal representation of numbers is in binary format, this operation is equivalent to multiplying arr1 by 2**arr2. For example, if the number is 5 and we want to 2 bit left shift then after left shift 2 bit the result will be 5*(2^2) = 20"
},
{
"code": null,
"e": 45847,
"s": 45837,
"text": "Code #1 :"
},
{
"code": null,
"e": 45856,
"s": 45847,
"text": "Output :"
},
{
"code": null,
"e": 45934,
"s": 45856,
"text": "Input number : 5\nNumber of bit shift : 2\nAfter left shifting 2 bit : 20\n"
},
{
"code": null,
"e": 45945,
"s": 45934,
"text": " Code #2 :"
},
{
"code": null,
"e": 45954,
"s": 45945,
"text": "Output :"
},
{
"code": null,
"e": 46063,
"s": 45954,
"text": "Input array : [2, 8, 15]\nNumber of bit shift : [3, 4, 5]\nOutput array after left shifting: [ 16 128 480]\n"
},
{
"code": null,
"e": 46407,
"s": 46063,
"text": " numpy.right_shift() : This function is used to Shift the bits of an integer to the right.Because the internal representation of numbers is in binary format, this operation is equivalent to dividing arr1 by 2**arr2. For example, if the number is 20 and we want to 2-bit right shift then after right shift 2-bit the result will be 20/(2^2) = 5."
},
{
"code": null,
"e": 46417,
"s": 46407,
"text": "Code #1 :"
},
{
"code": null,
"e": 46426,
"s": 46417,
"text": "Output :"
},
{
"code": null,
"e": 46505,
"s": 46426,
"text": "Input number : 20\nNumber of bit shift : 2\nAfter right shifting 2 bit : 5\n"
},
{
"code": null,
"e": 46516,
"s": 46505,
"text": " Code #2 :"
},
{
"code": null,
"e": 46525,
"s": 46516,
"text": "Output :"
},
{
"code": null,
"e": 46631,
"s": 46525,
"text": "Input array : [24, 48, 16]\nNumber of bit shift : [3, 4, 2]\nOutput array after right shifting: [3 3 4]\n"
},
{
"code": null,
"e": 47113,
"s": 46631,
"text": " numpy.binary_repr(number, width=None) : This function is used to represent binary form of the input number as a string.For negative numbers, if width is not given, a minus sign is added to the front. If width is given, the twoβs complement of the number is returned, with respect to that width.In a twoβs-complement system, negative numbers are represented by the twoβs complement of the absolute value. This is the most common method of representing signed integers on computers."
},
{
"code": null,
"e": 47123,
"s": 47113,
"text": "Code #1 :"
},
{
"code": null,
"e": 47132,
"s": 47123,
"text": "Output :"
},
{
"code": null,
"e": 47189,
"s": 47132,
"text": "Input number : 10\nbinary representation of 10 : 1010\n"
},
{
"code": null,
"e": 47200,
"s": 47189,
"text": " Code #2 :"
},
{
"code": null,
"e": 47209,
"s": 47200,
"text": "Output :"
},
{
"code": null,
"e": 47428,
"s": 47209,
"text": "Input array : [5, -8]\nBinary representation of 5 \nWithout using width parameter : 101\nUsing width parameter: 00101\n\nBinary representation of -8 \nWithout using width parameter : -1000\nUsing width parameter : 11000"
},
{
"code": null,
"e": 47631,
"s": 47428,
"text": "numpy.packbits(myarray, axis=None) : This function is used to packs the elements of a binary-valued array into bits in a uint8 array.The result is padded to full bytes by inserting zero bits at the end."
},
{
"code": null,
"e": 47641,
"s": 47631,
"text": "Code #1 :"
},
{
"code": null,
"e": 47650,
"s": 47641,
"text": "Output :"
},
{
"code": null,
"e": 47679,
"s": 47650,
"text": "[[[160],[64]],[[192],[32]]]\n"
},
{
"code": null,
"e": 48063,
"s": 47679,
"text": " numpy.unpackbits(myarray, axis=None) : This function is used to Unpacks elements of a uint8 array into a binary-valued output array.Each element of myarray represents a bit-field that should be unpacked into a binary-valued output array. The shape of the output array is either 1-D (if axis is None) or the same shape as the input array with unpacking done along the axis specified."
},
{
"code": null,
"e": 48073,
"s": 48063,
"text": "Code #1 :"
},
{
"code": null,
"e": 48082,
"s": 48073,
"text": "Output :"
},
{
"code": null,
"e": 48164,
"s": 48082,
"text": "[[0, 0, 0, 0, 0, 0, 1, 0],\n [0, 0, 0, 0, 0, 1, 1, 1],\n [0, 0, 0, 1, 0, 1, 1, 1]]\n"
},
{
"code": null,
"e": 48264,
"s": 48166,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 48338,
"s": 48264,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 48396,
"s": 48338,
"text": "Learn C++ Programming Step by Step - A 20 Day Curriculum!"
},
{
"code": null,
"e": 48449,
"s": 48396,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 48481,
"s": 48449,
"text": "50 Common Ports You Should Know"
},
{
"code": null,
"e": 48547,
"s": 48481,
"text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?"
},
{
"code": null,
"e": 48592,
"s": 48547,
"text": "How to Find Length of String in Bash Script?"
},
{
"code": null,
"e": 48648,
"s": 48592,
"text": "Samsung R&D Internship Interview Experience (On-Campus)"
},
{
"code": null,
"e": 48672,
"s": 48648,
"text": "Generate UUID in Golang"
},
{
"code": null,
"e": 48707,
"s": 48672,
"text": "How to install PHP in windows 10 ?"
}
] |
How to add elements to an existing array dynamically in JavaScript ?
|
16 Jul, 2020
An array is a JavaScript object that can hold multiple values at a time, irrespective of the data type.
Example:
var a = ['Geeks', 'For', 'Geeks', 1];
In the above example, βGeeksβ is of type βstringβ while 1 is of βintegerβ type. An array can also store JavaScript objects. JavaScript arrays are dynamic in nature, they do not need the size during initialization. They are accessed using numbered indexes.
console.log(a[1]);
Above statement prints βForβ from the above example in the console window.
Output:
For
or
document.write(a[1]);
Output:
For
To add elements into an array dynamically in JavaScript, the programmer can use any of the following methods.
Method 1: Use number indexes to add an element to the specified index.
JavaScript
<script> // JavaScript Array Initialization var a = ['Hi', 'There']; // New element added dynamically. a[3] = 'Geeks'; document.write(a[3]); document.write("<br>"); document.write(a[2]);</script>
Output: On the console window
It can be seen that index of {0, 1} was declared only. Index 3 was dynamically created and initialized to βGeeksβ. Index 2 was created automatically and initialized to undefined, to keep up the ordering.
Method 2: Use push() method is used to add element at the end of the array.
JavaScript
<script> // JavaScript Array Declared var a = []; // Elements pushed into the // array using push() method a.push('Geeks'); a.push('For'); a.push('Geeks'); // Obtaining the value document.write(a);</script>
Output:
The console window shows an array object containing 3 values, they are [βGeeksβ, βForβ, βGeeksβ]. The push() method maintains the ordering of indexes by adding the new elements at the end of the array and returns the new length of the array.
javascript-array
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to Open URL in New Tab using JavaScript ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Jul, 2020"
},
{
"code": null,
"e": 132,
"s": 28,
"text": "An array is a JavaScript object that can hold multiple values at a time, irrespective of the data type."
},
{
"code": null,
"e": 141,
"s": 132,
"text": "Example:"
},
{
"code": null,
"e": 180,
"s": 141,
"text": "var a = ['Geeks', 'For', 'Geeks', 1];\n"
},
{
"code": null,
"e": 436,
"s": 180,
"text": "In the above example, βGeeksβ is of type βstringβ while 1 is of βintegerβ type. An array can also store JavaScript objects. JavaScript arrays are dynamic in nature, they do not need the size during initialization. They are accessed using numbered indexes."
},
{
"code": null,
"e": 456,
"s": 436,
"text": "console.log(a[1]);\n"
},
{
"code": null,
"e": 531,
"s": 456,
"text": "Above statement prints βForβ from the above example in the console window."
},
{
"code": null,
"e": 539,
"s": 531,
"text": "Output:"
},
{
"code": null,
"e": 543,
"s": 539,
"text": "For"
},
{
"code": null,
"e": 546,
"s": 543,
"text": "or"
},
{
"code": null,
"e": 568,
"s": 546,
"text": "document.write(a[1]);"
},
{
"code": null,
"e": 576,
"s": 568,
"text": "Output:"
},
{
"code": null,
"e": 580,
"s": 576,
"text": "For"
},
{
"code": null,
"e": 690,
"s": 580,
"text": "To add elements into an array dynamically in JavaScript, the programmer can use any of the following methods."
},
{
"code": null,
"e": 761,
"s": 690,
"text": "Method 1: Use number indexes to add an element to the specified index."
},
{
"code": null,
"e": 772,
"s": 761,
"text": "JavaScript"
},
{
"code": "<script> // JavaScript Array Initialization var a = ['Hi', 'There']; // New element added dynamically. a[3] = 'Geeks'; document.write(a[3]); document.write(\"<br>\"); document.write(a[2]);</script>",
"e": 993,
"s": 772,
"text": null
},
{
"code": null,
"e": 1023,
"s": 993,
"text": "Output: On the console window"
},
{
"code": null,
"e": 1227,
"s": 1023,
"text": "It can be seen that index of {0, 1} was declared only. Index 3 was dynamically created and initialized to βGeeksβ. Index 2 was created automatically and initialized to undefined, to keep up the ordering."
},
{
"code": null,
"e": 1303,
"s": 1227,
"text": "Method 2: Use push() method is used to add element at the end of the array."
},
{
"code": null,
"e": 1314,
"s": 1303,
"text": "JavaScript"
},
{
"code": "<script> // JavaScript Array Declared var a = []; // Elements pushed into the // array using push() method a.push('Geeks'); a.push('For'); a.push('Geeks'); // Obtaining the value document.write(a);</script>",
"e": 1553,
"s": 1314,
"text": null
},
{
"code": null,
"e": 1561,
"s": 1553,
"text": "Output:"
},
{
"code": null,
"e": 1803,
"s": 1561,
"text": "The console window shows an array object containing 3 values, they are [βGeeksβ, βForβ, βGeeksβ]. The push() method maintains the ordering of indexes by adding the new elements at the end of the array and returns the new length of the array."
},
{
"code": null,
"e": 1820,
"s": 1803,
"text": "javascript-array"
},
{
"code": null,
"e": 1836,
"s": 1820,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 1843,
"s": 1836,
"text": "Picked"
},
{
"code": null,
"e": 1854,
"s": 1843,
"text": "JavaScript"
},
{
"code": null,
"e": 1871,
"s": 1854,
"text": "Web Technologies"
},
{
"code": null,
"e": 1898,
"s": 1871,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 1996,
"s": 1898,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2057,
"s": 1996,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2129,
"s": 2057,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2169,
"s": 2129,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2210,
"s": 2169,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2256,
"s": 2210,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 2289,
"s": 2256,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2351,
"s": 2289,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2412,
"s": 2351,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2462,
"s": 2412,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Ngx-Bootstrap - Dropdowns
|
ngx-bootstrap dropdown component is toggleable and provides contextual overlay to display list of links etc. With dropdown directives we can make dropdowns interactive.
[bsDropdown],[dropdown]
[bsDropdown],[dropdown]
autoClose β boolean, Indicates that dropdown will be closed on item or document click, and after pressing ESC
autoClose β boolean, Indicates that dropdown will be closed on item or document click, and after pressing ESC
container β string, A selector specifying the element the popover should be appended to.
container β string, A selector specifying the element the popover should be appended to.
dropup β boolean, This attribute indicates that the dropdown should be opened upwards.
dropup β boolean, This attribute indicates that the dropdown should be opened upwards.
insideClick β boolean, This attribute indicates that the dropdown shouldn't close on inside click when autoClose is set to true.
insideClick β boolean, This attribute indicates that the dropdown shouldn't close on inside click when autoClose is set to true.
isAnimated β boolean, Indicates that dropdown will be animated
isAnimated β boolean, Indicates that dropdown will be animated
isDisabled β boolean, Disables dropdown toggle and hides dropdown menu if opened
isDisabled β boolean, Disables dropdown toggle and hides dropdown menu if opened
isOpen β boolean, Returns whether or not the popover is currently being shown
isOpen β boolean, Returns whether or not the popover is currently being shown
placement β string, Placement of a popover. Accepts: "top", "bottom", "left", "right"
placement β string, Placement of a popover. Accepts: "top", "bottom", "left", "right"
triggers β string, Specifies events that should trigger. Supports a space separated list of event names.
triggers β string, Specifies events that should trigger. Supports a space separated list of event names.
isOpenChange β Emits an event when isOpen change
isOpenChange β Emits an event when isOpen change
onHidden β Emits an event when the popover is hidden
onHidden β Emits an event when the popover is hidden
onShown β Emits an event when the popover is shown
onShown β Emits an event when the popover is shown
show() β Opens an element's popover. This is considered a 'manual' triggering of the popover.
show() β Opens an element's popover. This is considered a 'manual' triggering of the popover.
hide() β Closes an element's popover. This is considered a 'manual' triggering of the popover.
hide() β Closes an element's popover. This is considered a 'manual' triggering of the popover.
toggle() β Toggles an element's popover. This is considered a 'manual' triggering of the popover.
toggle() β Toggles an element's popover. This is considered a 'manual' triggering of the popover.
setConfig() β Set config for popover
setConfig() β Set config for popover
As we're going to use dropdowns, We've to update app.module.ts used in ngx-bootstrap DatePicker chapter to use BsDropdownModule and BsDropdownConfig.
Update app.module.ts to use the BsDropdownModule and BsDropdownConfig.
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppComponent } from './app.component';
import { TestComponent } from './test/test.component';
import { AccordionModule } from 'ngx-bootstrap/accordion';
import { AlertModule,AlertConfig } from 'ngx-bootstrap/alert';
import { ButtonsModule } from 'ngx-bootstrap/buttons';
import { FormsModule } from '@angular/forms';
import { CarouselModule } from 'ngx-bootstrap/carousel';
import { CollapseModule } from 'ngx-bootstrap/collapse';
import { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker';
import { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown';
@NgModule({
declarations: [
AppComponent,
TestComponent
],
imports: [
BrowserAnimationsModule,
BrowserModule,
AccordionModule,
AlertModule,
ButtonsModule,
FormsModule,
CarouselModule,
CollapseModule,
BsDatepickerModule.forRoot(),
BsDropdownModule
],
providers: [AlertConfig, BsDatepickerConfig, BsDropdownConfig],
bootstrap: [AppComponent]
})
export class AppModule { }
Update test.component.html to use the dropdowns.
test.component.html
<div class="btn-group" dropdown #dropdown="bs-dropdown" [autoClose]="false">
<button id="button-basic" dropdownToggle type="button"
class="btn btn-primary dropdown-toggle"
aria-controls="dropdown-basic">
Menu <span class="caret"></span>
</button>
<ul id="dropdown-basic" *dropdownMenu class="dropdown-menu"
role="menu" aria-labelledby="button-basic">
<li role="menuitem"><a class="dropdown-item" href="#">File</a></li>
<li role="menuitem"><a class="dropdown-item" href="#">Edit</a></li>
<li role="menuitem"><a class="dropdown-item" href="#">Search</a></li>
<li class="divider dropdown-divider"></li>
<li role="menuitem"><a class="dropdown-item" href="#">Recents</a>
</li>
</ul>
</div>
<button type="button" class="btn btn-primary"
(click)="dropdown.isOpen = !dropdown.isOpen">Show/Hide
</button>
Update test.component.ts for corresponding variables and methods.
test.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
constructor() {}
ngOnInit(): void {}
}
Run the following command to start the angular server.
ng serve
Once server is up and running. Open http://localhost:4200 and verify the following output.
|
[
{
"code": null,
"e": 2403,
"s": 2234,
"text": "ngx-bootstrap dropdown component is toggleable and provides contextual overlay to display list of links etc. With dropdown directives we can make dropdowns interactive."
},
{
"code": null,
"e": 2427,
"s": 2403,
"text": "[bsDropdown],[dropdown]"
},
{
"code": null,
"e": 2451,
"s": 2427,
"text": "[bsDropdown],[dropdown]"
},
{
"code": null,
"e": 2561,
"s": 2451,
"text": "autoClose β boolean, Indicates that dropdown will be closed on item or document click, and after pressing ESC"
},
{
"code": null,
"e": 2671,
"s": 2561,
"text": "autoClose β boolean, Indicates that dropdown will be closed on item or document click, and after pressing ESC"
},
{
"code": null,
"e": 2760,
"s": 2671,
"text": "container β string, A selector specifying the element the popover should be appended to."
},
{
"code": null,
"e": 2849,
"s": 2760,
"text": "container β string, A selector specifying the element the popover should be appended to."
},
{
"code": null,
"e": 2936,
"s": 2849,
"text": "dropup β boolean, This attribute indicates that the dropdown should be opened upwards."
},
{
"code": null,
"e": 3023,
"s": 2936,
"text": "dropup β boolean, This attribute indicates that the dropdown should be opened upwards."
},
{
"code": null,
"e": 3152,
"s": 3023,
"text": "insideClick β boolean, This attribute indicates that the dropdown shouldn't close on inside click when autoClose is set to true."
},
{
"code": null,
"e": 3281,
"s": 3152,
"text": "insideClick β boolean, This attribute indicates that the dropdown shouldn't close on inside click when autoClose is set to true."
},
{
"code": null,
"e": 3344,
"s": 3281,
"text": "isAnimated β boolean, Indicates that dropdown will be animated"
},
{
"code": null,
"e": 3407,
"s": 3344,
"text": "isAnimated β boolean, Indicates that dropdown will be animated"
},
{
"code": null,
"e": 3488,
"s": 3407,
"text": "isDisabled β boolean, Disables dropdown toggle and hides dropdown menu if opened"
},
{
"code": null,
"e": 3569,
"s": 3488,
"text": "isDisabled β boolean, Disables dropdown toggle and hides dropdown menu if opened"
},
{
"code": null,
"e": 3647,
"s": 3569,
"text": "isOpen β boolean, Returns whether or not the popover is currently being shown"
},
{
"code": null,
"e": 3725,
"s": 3647,
"text": "isOpen β boolean, Returns whether or not the popover is currently being shown"
},
{
"code": null,
"e": 3811,
"s": 3725,
"text": "placement β string, Placement of a popover. Accepts: \"top\", \"bottom\", \"left\", \"right\""
},
{
"code": null,
"e": 3897,
"s": 3811,
"text": "placement β string, Placement of a popover. Accepts: \"top\", \"bottom\", \"left\", \"right\""
},
{
"code": null,
"e": 4002,
"s": 3897,
"text": "triggers β string, Specifies events that should trigger. Supports a space separated list of event names."
},
{
"code": null,
"e": 4107,
"s": 4002,
"text": "triggers β string, Specifies events that should trigger. Supports a space separated list of event names."
},
{
"code": null,
"e": 4156,
"s": 4107,
"text": "isOpenChange β Emits an event when isOpen change"
},
{
"code": null,
"e": 4205,
"s": 4156,
"text": "isOpenChange β Emits an event when isOpen change"
},
{
"code": null,
"e": 4258,
"s": 4205,
"text": "onHidden β Emits an event when the popover is hidden"
},
{
"code": null,
"e": 4311,
"s": 4258,
"text": "onHidden β Emits an event when the popover is hidden"
},
{
"code": null,
"e": 4362,
"s": 4311,
"text": "onShown β Emits an event when the popover is shown"
},
{
"code": null,
"e": 4413,
"s": 4362,
"text": "onShown β Emits an event when the popover is shown"
},
{
"code": null,
"e": 4507,
"s": 4413,
"text": "show() β Opens an element's popover. This is considered a 'manual' triggering of the popover."
},
{
"code": null,
"e": 4601,
"s": 4507,
"text": "show() β Opens an element's popover. This is considered a 'manual' triggering of the popover."
},
{
"code": null,
"e": 4696,
"s": 4601,
"text": "hide() β Closes an element's popover. This is considered a 'manual' triggering of the popover."
},
{
"code": null,
"e": 4791,
"s": 4696,
"text": "hide() β Closes an element's popover. This is considered a 'manual' triggering of the popover."
},
{
"code": null,
"e": 4889,
"s": 4791,
"text": "toggle() β Toggles an element's popover. This is considered a 'manual' triggering of the popover."
},
{
"code": null,
"e": 4987,
"s": 4889,
"text": "toggle() β Toggles an element's popover. This is considered a 'manual' triggering of the popover."
},
{
"code": null,
"e": 5024,
"s": 4987,
"text": "setConfig() β Set config for popover"
},
{
"code": null,
"e": 5061,
"s": 5024,
"text": "setConfig() β Set config for popover"
},
{
"code": null,
"e": 5211,
"s": 5061,
"text": "As we're going to use dropdowns, We've to update app.module.ts used in ngx-bootstrap DatePicker chapter to use BsDropdownModule and BsDropdownConfig."
},
{
"code": null,
"e": 5282,
"s": 5211,
"text": "Update app.module.ts to use the BsDropdownModule and BsDropdownConfig."
},
{
"code": null,
"e": 5296,
"s": 5282,
"text": "app.module.ts"
},
{
"code": null,
"e": 6537,
"s": 5296,
"text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { AppComponent } from './app.component';\nimport { TestComponent } from './test/test.component';\nimport { AccordionModule } from 'ngx-bootstrap/accordion';\nimport { AlertModule,AlertConfig } from 'ngx-bootstrap/alert';\nimport { ButtonsModule } from 'ngx-bootstrap/buttons';\nimport { FormsModule } from '@angular/forms';\nimport { CarouselModule } from 'ngx-bootstrap/carousel';\nimport { CollapseModule } from 'ngx-bootstrap/collapse';\nimport { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker';\nimport { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown';\n\n@NgModule({\n declarations: [\n AppComponent,\n TestComponent\n ],\n imports: [\n BrowserAnimationsModule,\n BrowserModule,\n AccordionModule,\n AlertModule,\n ButtonsModule,\n FormsModule,\n CarouselModule,\n CollapseModule,\n BsDatepickerModule.forRoot(),\n BsDropdownModule\n ],\n providers: [AlertConfig, BsDatepickerConfig, BsDropdownConfig],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }"
},
{
"code": null,
"e": 6586,
"s": 6537,
"text": "Update test.component.html to use the dropdowns."
},
{
"code": null,
"e": 6606,
"s": 6586,
"text": "test.component.html"
},
{
"code": null,
"e": 7479,
"s": 6606,
"text": "<div class=\"btn-group\" dropdown #dropdown=\"bs-dropdown\" [autoClose]=\"false\">\n <button id=\"button-basic\" dropdownToggle type=\"button\" \n class=\"btn btn-primary dropdown-toggle\"\n aria-controls=\"dropdown-basic\">\n Menu <span class=\"caret\"></span>\n </button>\n <ul id=\"dropdown-basic\" *dropdownMenu class=\"dropdown-menu\"\n role=\"menu\" aria-labelledby=\"button-basic\">\n <li role=\"menuitem\"><a class=\"dropdown-item\" href=\"#\">File</a></li>\n <li role=\"menuitem\"><a class=\"dropdown-item\" href=\"#\">Edit</a></li>\n <li role=\"menuitem\"><a class=\"dropdown-item\" href=\"#\">Search</a></li>\n <li class=\"divider dropdown-divider\"></li>\n <li role=\"menuitem\"><a class=\"dropdown-item\" href=\"#\">Recents</a>\n </li>\n </ul>\n</div>\n<button type=\"button\" class=\"btn btn-primary\" \n (click)=\"dropdown.isOpen = !dropdown.isOpen\">Show/Hide\n</button>"
},
{
"code": null,
"e": 7545,
"s": 7479,
"text": "Update test.component.ts for corresponding variables and methods."
},
{
"code": null,
"e": 7563,
"s": 7545,
"text": "test.component.ts"
},
{
"code": null,
"e": 7829,
"s": 7563,
"text": "import { Component, OnInit } from '@angular/core';\n\n@Component({\n selector: 'app-test',\n templateUrl: './test.component.html',\n styleUrls: ['./test.component.css']\n})\nexport class TestComponent implements OnInit {\n constructor() {}\n\n ngOnInit(): void {}\n}"
},
{
"code": null,
"e": 7884,
"s": 7829,
"text": "Run the following command to start the angular server."
},
{
"code": null,
"e": 7894,
"s": 7884,
"text": "ng serve\n"
}
] |
Largest number less than N with digit sum greater than the digit sum of N
|
08 Jul, 2022
Given an integer N, the task is to find the greatest number less than N such that the sum of its digits is greater than the sum of the digits of N. If the condition isnβt satisfied for any number then print -1.Examples:
Input: N = 100 Output: 99 99 is the largest number less than 100 sum of whose digits is greater than the sum of the digits of 100Input: N = 49 Output: -1
Approach: Start a loop from N-1 to 1 and check whether the sum of the digits of any number is greater than the sum of the digits of N. The first number that satisfies the condition is the required number.Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <iostream>using namespace std; // Function to return the sum of the digits of nint sumOfDigits(int n){ int res = 0; // Loop for each digit of the number while (n > 0) { res += n % 10; n /= 10; } return res;} // Function to return the greatest// number less than n such that// the sum of its digits is greater// than the sum of the digits of nint findNumber(int n){ // Starting from n-1 int i = n - 1; // Check until 1 while (i > 0) { // If i satisfies the given condition if (sumOfDigits(i) > sumOfDigits(n)) return i; i--; } // If the condition is not satisfied return -1;} // Driver codeint main(){ int n = 824; cout << findNumber(n); return 0;}
//Java implementation of the approach import java.io.*; class GFG { // Function to return the sum of the digits of nstatic int sumOfDigits(int n){ int res = 0; // Loop for each digit of the number while (n > 0) { res += n % 10; n /= 10; } return res;} // Function to return the greatest// number less than n such that// the sum of its digits is greater// than the sum of the digits of nstatic int findNumber(int n){ // Starting from n-1 int i = n - 1; // Check until 1 while (i > 0) { // If i satisfies the given condition if (sumOfDigits(i) > sumOfDigits(n)) return i; i--; } // If the condition is not satisfied return -1;} // Driver code public static void main (String[] args) { int n = 824; System.out.println (findNumber(n)); }//This code is contributed by akt_mit }
# Python3 implementation of the approach # Function to return the sum# of the digits of ndef sumOfDigits(n) : res = 0; # Loop for each digit of the number while (n > 0) : res += n % 10 n /= 10 return res; # Function to return the greatest# number less than n such that# the sum of its digits is greater# than the sum of the digits of ndef findNumber(n) : # Starting from n-1 i = n - 1; # Check until 1 while (i > 0) : # If i satisfies the given condition if (sumOfDigits(i) > sumOfDigits(n)) : return i i -= 1 # If the condition is not satisfied return -1; # Driver codeif __name__ == "__main__" : n = 824; print(findNumber(n)) # This code is contributed by Ryuga
// C# implementation of the approachusing System; class GFG{// Function to return the sum// of the digits of nstatic int sumOfDigits(int n){ int res = 0; // Loop for each digit of // the number while (n > 0) { res += n % 10; n /= 10; } return res;} // Function to return the greatest// number less than n such that// the sum of its digits is greater// than the sum of the digits of nstatic int findNumber(int n){ // Starting from n-1 int i = n - 1; // Check until 1 while (i > 0) { // If i satisfies the given condition if (sumOfDigits(i) > sumOfDigits(n)) return i; i--; } // If the condition is // not satisfied return -1;} // Driver codestatic public void Main (){ int n = 824; Console.WriteLine (findNumber(n));}} // This code is contributed by @Tushil
<?php//PHP implementation of the approach // Function to return the sum of// the digits of nfunction sumOfDigits($n){ $res = 0; // Loop for each digit of the number while ($n > 0) { $res += $n % 10; $n /= 10; } return $res;} // Function to return the greatest// number less than n such that// the sum of its digits is greater// than the sum of the digits of nfunction findNumber($n){ // Starting from n-1 $i = $n - 1; // Check until 1 while ($i > 0) { // If i satisfies the given condition if (sumOfDigits($i) > sumOfDigits($n)) return $i; $i--; } // If the condition is not satisfied return -1;} // Driver code$n = 824; echo findNumber($n); // This code is contributed by Mukul singh?>
<script>// javascript implementation of the approach // Function to return the sum of the digits of n function sumOfDigits(n) { var res = 0; // Loop for each digit of the number while (n > 0) { res += n % 10; n = parseInt(n/10); } return res; } // Function to return the greatest // number less than n such that // the sum of its digits is greater // than the sum of the digits of n function findNumber(n) { // Starting from n-1 var i = n - 1; // Check until 1 while (i > 0) { // If i satisfies the given condition if (sumOfDigits(i) > sumOfDigits(n)) return i; i--; } // If the condition is not satisfied return -1; } // Driver code var n = 824; document.write(findNumber(n)); // This code is contributed by Princi Singh</script>
819
Time Complexity: O(N * log10N)
Auxiliary Space: O(1)
jit_t
Code_Mech
ankthon
princi singh
rohan07
subhamkumarm348
number-digits
Competitive Programming
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jul, 2022"
},
{
"code": null,
"e": 250,
"s": 28,
"text": "Given an integer N, the task is to find the greatest number less than N such that the sum of its digits is greater than the sum of the digits of N. If the condition isnβt satisfied for any number then print -1.Examples: "
},
{
"code": null,
"e": 406,
"s": 250,
"text": "Input: N = 100 Output: 99 99 is the largest number less than 100 sum of whose digits is greater than the sum of the digits of 100Input: N = 49 Output: -1 "
},
{
"code": null,
"e": 664,
"s": 408,
"text": "Approach: Start a loop from N-1 to 1 and check whether the sum of the digits of any number is greater than the sum of the digits of N. The first number that satisfies the condition is the required number.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 668,
"s": 664,
"text": "C++"
},
{
"code": null,
"e": 673,
"s": 668,
"text": "Java"
},
{
"code": null,
"e": 681,
"s": 673,
"text": "Python3"
},
{
"code": null,
"e": 684,
"s": 681,
"text": "C#"
},
{
"code": null,
"e": 688,
"s": 684,
"text": "PHP"
},
{
"code": null,
"e": 699,
"s": 688,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <iostream>using namespace std; // Function to return the sum of the digits of nint sumOfDigits(int n){ int res = 0; // Loop for each digit of the number while (n > 0) { res += n % 10; n /= 10; } return res;} // Function to return the greatest// number less than n such that// the sum of its digits is greater// than the sum of the digits of nint findNumber(int n){ // Starting from n-1 int i = n - 1; // Check until 1 while (i > 0) { // If i satisfies the given condition if (sumOfDigits(i) > sumOfDigits(n)) return i; i--; } // If the condition is not satisfied return -1;} // Driver codeint main(){ int n = 824; cout << findNumber(n); return 0;}",
"e": 1491,
"s": 699,
"text": null
},
{
"code": "//Java implementation of the approach import java.io.*; class GFG { // Function to return the sum of the digits of nstatic int sumOfDigits(int n){ int res = 0; // Loop for each digit of the number while (n > 0) { res += n % 10; n /= 10; } return res;} // Function to return the greatest// number less than n such that// the sum of its digits is greater// than the sum of the digits of nstatic int findNumber(int n){ // Starting from n-1 int i = n - 1; // Check until 1 while (i > 0) { // If i satisfies the given condition if (sumOfDigits(i) > sumOfDigits(n)) return i; i--; } // If the condition is not satisfied return -1;} // Driver code public static void main (String[] args) { int n = 824; System.out.println (findNumber(n)); }//This code is contributed by akt_mit }",
"e": 2370,
"s": 1491,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the sum# of the digits of ndef sumOfDigits(n) : res = 0; # Loop for each digit of the number while (n > 0) : res += n % 10 n /= 10 return res; # Function to return the greatest# number less than n such that# the sum of its digits is greater# than the sum of the digits of ndef findNumber(n) : # Starting from n-1 i = n - 1; # Check until 1 while (i > 0) : # If i satisfies the given condition if (sumOfDigits(i) > sumOfDigits(n)) : return i i -= 1 # If the condition is not satisfied return -1; # Driver codeif __name__ == \"__main__\" : n = 824; print(findNumber(n)) # This code is contributed by Ryuga",
"e": 3141,
"s": 2370,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{// Function to return the sum// of the digits of nstatic int sumOfDigits(int n){ int res = 0; // Loop for each digit of // the number while (n > 0) { res += n % 10; n /= 10; } return res;} // Function to return the greatest// number less than n such that// the sum of its digits is greater// than the sum of the digits of nstatic int findNumber(int n){ // Starting from n-1 int i = n - 1; // Check until 1 while (i > 0) { // If i satisfies the given condition if (sumOfDigits(i) > sumOfDigits(n)) return i; i--; } // If the condition is // not satisfied return -1;} // Driver codestatic public void Main (){ int n = 824; Console.WriteLine (findNumber(n));}} // This code is contributed by @Tushil",
"e": 4004,
"s": 3141,
"text": null
},
{
"code": "<?php//PHP implementation of the approach // Function to return the sum of// the digits of nfunction sumOfDigits($n){ $res = 0; // Loop for each digit of the number while ($n > 0) { $res += $n % 10; $n /= 10; } return $res;} // Function to return the greatest// number less than n such that// the sum of its digits is greater// than the sum of the digits of nfunction findNumber($n){ // Starting from n-1 $i = $n - 1; // Check until 1 while ($i > 0) { // If i satisfies the given condition if (sumOfDigits($i) > sumOfDigits($n)) return $i; $i--; } // If the condition is not satisfied return -1;} // Driver code$n = 824; echo findNumber($n); // This code is contributed by Mukul singh?>",
"e": 4789,
"s": 4004,
"text": null
},
{
"code": "<script>// javascript implementation of the approach // Function to return the sum of the digits of n function sumOfDigits(n) { var res = 0; // Loop for each digit of the number while (n > 0) { res += n % 10; n = parseInt(n/10); } return res; } // Function to return the greatest // number less than n such that // the sum of its digits is greater // than the sum of the digits of n function findNumber(n) { // Starting from n-1 var i = n - 1; // Check until 1 while (i > 0) { // If i satisfies the given condition if (sumOfDigits(i) > sumOfDigits(n)) return i; i--; } // If the condition is not satisfied return -1; } // Driver code var n = 824; document.write(findNumber(n)); // This code is contributed by Princi Singh</script>",
"e": 5739,
"s": 4789,
"text": null
},
{
"code": null,
"e": 5743,
"s": 5739,
"text": "819"
},
{
"code": null,
"e": 5776,
"s": 5745,
"text": "Time Complexity: O(N * log10N)"
},
{
"code": null,
"e": 5798,
"s": 5776,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 5804,
"s": 5798,
"text": "jit_t"
},
{
"code": null,
"e": 5814,
"s": 5804,
"text": "Code_Mech"
},
{
"code": null,
"e": 5822,
"s": 5814,
"text": "ankthon"
},
{
"code": null,
"e": 5835,
"s": 5822,
"text": "princi singh"
},
{
"code": null,
"e": 5843,
"s": 5835,
"text": "rohan07"
},
{
"code": null,
"e": 5859,
"s": 5843,
"text": "subhamkumarm348"
},
{
"code": null,
"e": 5873,
"s": 5859,
"text": "number-digits"
},
{
"code": null,
"e": 5897,
"s": 5873,
"text": "Competitive Programming"
},
{
"code": null,
"e": 5910,
"s": 5897,
"text": "Mathematical"
},
{
"code": null,
"e": 5923,
"s": 5910,
"text": "Mathematical"
}
] |
PyQt5 β Capsule shaped Progress Bar
|
22 Apr, 2020
In this article we will see how to create capsule shaped progress bar. By default when we create progress bar, it is in rectangular shape although we can change the shape with the help of resize method. But this will only allows to change the shape from rectangle to square. Below is representation of normal progress bar vs the capsule shaped progress bar.
In order to do so we have to change the radius of the border of both background and the bar of progress bar, this is done by changing the CSS style sheet, below is the style sheet code.
QProgressBar
{
border: solid grey;
border-radius: 15px;
color: black;
}
QProgressBar::chunk
{
background-color: #05B8CC;
border-radius :15px;
}
This style sheet is used which setStyleSheet method, below is the implementation.
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting background color to window # self.setStyleSheet("background-color : yellow") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating progress bar bar = QProgressBar(self) # setting geometry to progress bar bar.setGeometry(200, 100, 200, 30) # setting the value bar.setValue(70) # setting alignment to center bar.setAlignment(Qt.AlignCenter) # setting background to color and radius # and bar color and bar radius bar.setStyleSheet("QProgressBar" "{" "border: solid grey;" "border-radius: 15px;" " color: black; " "}" "QProgressBar::chunk " "{background-color: # 05B8CC;" "border-radius :15px;" "}") App = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
How to drop one or multiple columns in Pandas Dataframe
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 410,
"s": 52,
"text": "In this article we will see how to create capsule shaped progress bar. By default when we create progress bar, it is in rectangular shape although we can change the shape with the help of resize method. But this will only allows to change the shape from rectangle to square. Below is representation of normal progress bar vs the capsule shaped progress bar."
},
{
"code": null,
"e": 598,
"s": 412,
"text": "In order to do so we have to change the radius of the border of both background and the bar of progress bar, this is done by changing the CSS style sheet, below is the style sheet code."
},
{
"code": null,
"e": 750,
"s": 598,
"text": "QProgressBar\n{\nborder: solid grey;\nborder-radius: 15px;\ncolor: black;\n}\nQProgressBar::chunk \n{\nbackground-color: #05B8CC;\nborder-radius :15px;\n} \n"
},
{
"code": null,
"e": 832,
"s": 750,
"text": "This style sheet is used which setStyleSheet method, below is the implementation."
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting background color to window # self.setStyleSheet(\"background-color : yellow\") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating progress bar bar = QProgressBar(self) # setting geometry to progress bar bar.setGeometry(200, 100, 200, 30) # setting the value bar.setValue(70) # setting alignment to center bar.setAlignment(Qt.AlignCenter) # setting background to color and radius # and bar color and bar radius bar.setStyleSheet(\"QProgressBar\" \"{\" \"border: solid grey;\" \"border-radius: 15px;\" \" color: black; \" \"}\" \"QProgressBar::chunk \" \"{background-color: # 05B8CC;\" \"border-radius :15px;\" \"}\") App = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 2367,
"s": 832,
"text": null
},
{
"code": null,
"e": 2376,
"s": 2367,
"text": "Output :"
},
{
"code": null,
"e": 2387,
"s": 2376,
"text": "Python-gui"
},
{
"code": null,
"e": 2399,
"s": 2387,
"text": "Python-PyQt"
},
{
"code": null,
"e": 2406,
"s": 2399,
"text": "Python"
},
{
"code": null,
"e": 2504,
"s": 2406,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2546,
"s": 2504,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2568,
"s": 2546,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2594,
"s": 2568,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2626,
"s": 2594,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2655,
"s": 2626,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2682,
"s": 2655,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2703,
"s": 2682,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2726,
"s": 2703,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2762,
"s": 2726,
"text": "Convert integer to string in Python"
}
] |
8086 program to transfer a block of bytes by using string instruction
|
09 Jun, 2022
Problem: Write an assembly language program to transfer a block of bytes from one memory location to another memory location by using string instruction.
Example: Example:
In this example, the counter value stored in CX register is 4.The block of data which is stored from memory location starting from 501 to 504 offset is transferred to another memory location which is starting from 600 to 603 offset.
In this example, the counter value stored in CX register is 4.
The block of data which is stored from memory location starting from 501 to 504 offset is transferred to another memory location which is starting from 600 to 603 offset.
The value of counter which tells the number of bytes to be transferred is stored at offset 500.
The 8-bit data which have to be transfer is stored in continuous memory location starting from 501.
The data is transferred to a continuous memory location starting from 600.
The value of DS and ES is taken equal to 0000.
the program starts from offset 400.
CLD instruction is used to clear the directional flag, i.e., DF=0. Now, value of SI and DI will be increased.
SI=SI+1
DI=DI+1
REP instruction is used to repeat the step until the value of CX is not equal to zero and the value of CX is decremented by one at every step, i.e.,
CX=CX-1
MOVSB instruction is used to transfer bytes only from source memory location (MADS) to destination memory location (MAES).
MADS-->MAES
where MADS=DS*10+SI
MAES=ES*10+DI
Here, value of SI and DI is updated automatically.
if DF=0, SI=SI+1 and DI=DI+1
set the value of offset SI equal to 500.set the value of offset DI equal to 600.load the value 0000 into register AX.load the data of AX register into DS(data segment).load the data of AX register into ES(extra segment).load the data of offset SI into the CL register and load value 00 into CH register.increment the value of SI by one.clear the directional flag so that data is read from lower memory to higher memory location.check the value of CX, if not equal to zero then repeat step 10 otherwise go to step 11.transfer the data from source memory location to destination memory location and decrease the value of CX by one.Stop.
set the value of offset SI equal to 500.
set the value of offset DI equal to 600.
load the value 0000 into register AX.
load the data of AX register into DS(data segment).
load the data of AX register into ES(extra segment).
load the data of offset SI into the CL register and load value 00 into CH register.
increment the value of SI by one.
clear the directional flag so that data is read from lower memory to higher memory location.
check the value of CX, if not equal to zero then repeat step 10 otherwise go to step 11.
transfer the data from source memory location to destination memory location and decrease the value of CX by one.
Stop.
MOV SI, 500: load the value 500 into offset SI.MOV DI, 600: load the value 600 into offset DI.MOV AX, 0000: load the value 0000 into AX register.MOV DS, AX: load the value of AX register into DS (data segment).MOV ES, AX: load the value of the AX register into ES (extra segment).MOV CL, [SI]: load the data of offset SI into the CL register.MOV CH, 00: load value 00 into CH register.INC SI: increment the value of SI by one.CLD: clears the directional flag i.e. DF=0.REP: repeat until value of CX is not equal to zero and decrement the value of CX by one at each step.MOVSB: transfer the data from the source memory location to the destination memory location.HLT: end.
MOV SI, 500: load the value 500 into offset SI.
MOV DI, 600: load the value 600 into offset DI.
MOV AX, 0000: load the value 0000 into AX register.
MOV DS, AX: load the value of AX register into DS (data segment).
MOV ES, AX: load the value of the AX register into ES (extra segment).
MOV CL, [SI]: load the data of offset SI into the CL register.
MOV CH, 00: load value 00 into CH register.
INC SI: increment the value of SI by one.
CLD: clears the directional flag i.e. DF=0.
REP: repeat until value of CX is not equal to zero and decrement the value of CX by one at each step.
MOVSB: transfer the data from the source memory location to the destination memory location.
HLT: end.
Akanksha_Rai
surinderdawra388
guptamridul75
microprocessor
system-programming
Computer Organization & Architecture
microprocessor
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Logical and Physical Address in Operating System
Direct Access Media (DMA) Controller in Computer Architecture
Computer Organization | RISC and CISC
Memory Hierarchy Design and its Characteristics
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Interrupts
Architecture of 8085 microprocessor
Control Characters
Computer Organization | Instruction Formats (Zero, One, Two and Three Address Instruction)
Programmable peripheral interface 8255
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 209,
"s": 54,
"text": "Problem: Write an assembly language program to transfer a block of bytes from one memory location to another memory location by using string instruction. "
},
{
"code": null,
"e": 227,
"s": 209,
"text": "Example: Example:"
},
{
"code": null,
"e": 460,
"s": 227,
"text": "In this example, the counter value stored in CX register is 4.The block of data which is stored from memory location starting from 501 to 504 offset is transferred to another memory location which is starting from 600 to 603 offset."
},
{
"code": null,
"e": 523,
"s": 460,
"text": "In this example, the counter value stored in CX register is 4."
},
{
"code": null,
"e": 694,
"s": 523,
"text": "The block of data which is stored from memory location starting from 501 to 504 offset is transferred to another memory location which is starting from 600 to 603 offset."
},
{
"code": null,
"e": 790,
"s": 694,
"text": "The value of counter which tells the number of bytes to be transferred is stored at offset 500."
},
{
"code": null,
"e": 890,
"s": 790,
"text": "The 8-bit data which have to be transfer is stored in continuous memory location starting from 501."
},
{
"code": null,
"e": 965,
"s": 890,
"text": "The data is transferred to a continuous memory location starting from 600."
},
{
"code": null,
"e": 1012,
"s": 965,
"text": "The value of DS and ES is taken equal to 0000."
},
{
"code": null,
"e": 1048,
"s": 1012,
"text": "the program starts from offset 400."
},
{
"code": null,
"e": 1158,
"s": 1048,
"text": "CLD instruction is used to clear the directional flag, i.e., DF=0. Now, value of SI and DI will be increased."
},
{
"code": null,
"e": 1177,
"s": 1158,
"text": " SI=SI+1\n DI=DI+1 "
},
{
"code": null,
"e": 1326,
"s": 1177,
"text": "REP instruction is used to repeat the step until the value of CX is not equal to zero and the value of CX is decremented by one at every step, i.e.,"
},
{
"code": null,
"e": 1335,
"s": 1326,
"text": "CX=CX-1 "
},
{
"code": null,
"e": 1458,
"s": 1335,
"text": "MOVSB instruction is used to transfer bytes only from source memory location (MADS) to destination memory location (MAES)."
},
{
"code": null,
"e": 1511,
"s": 1458,
"text": "MADS-->MAES\nwhere MADS=DS*10+SI\n MAES=ES*10+DI "
},
{
"code": null,
"e": 1562,
"s": 1511,
"text": "Here, value of SI and DI is updated automatically."
},
{
"code": null,
"e": 1593,
"s": 1562,
"text": "if DF=0, SI=SI+1 and DI=DI+1 "
},
{
"code": null,
"e": 2228,
"s": 1593,
"text": "set the value of offset SI equal to 500.set the value of offset DI equal to 600.load the value 0000 into register AX.load the data of AX register into DS(data segment).load the data of AX register into ES(extra segment).load the data of offset SI into the CL register and load value 00 into CH register.increment the value of SI by one.clear the directional flag so that data is read from lower memory to higher memory location.check the value of CX, if not equal to zero then repeat step 10 otherwise go to step 11.transfer the data from source memory location to destination memory location and decrease the value of CX by one.Stop."
},
{
"code": null,
"e": 2269,
"s": 2228,
"text": "set the value of offset SI equal to 500."
},
{
"code": null,
"e": 2310,
"s": 2269,
"text": "set the value of offset DI equal to 600."
},
{
"code": null,
"e": 2348,
"s": 2310,
"text": "load the value 0000 into register AX."
},
{
"code": null,
"e": 2400,
"s": 2348,
"text": "load the data of AX register into DS(data segment)."
},
{
"code": null,
"e": 2453,
"s": 2400,
"text": "load the data of AX register into ES(extra segment)."
},
{
"code": null,
"e": 2537,
"s": 2453,
"text": "load the data of offset SI into the CL register and load value 00 into CH register."
},
{
"code": null,
"e": 2571,
"s": 2537,
"text": "increment the value of SI by one."
},
{
"code": null,
"e": 2664,
"s": 2571,
"text": "clear the directional flag so that data is read from lower memory to higher memory location."
},
{
"code": null,
"e": 2753,
"s": 2664,
"text": "check the value of CX, if not equal to zero then repeat step 10 otherwise go to step 11."
},
{
"code": null,
"e": 2867,
"s": 2753,
"text": "transfer the data from source memory location to destination memory location and decrease the value of CX by one."
},
{
"code": null,
"e": 2873,
"s": 2867,
"text": "Stop."
},
{
"code": null,
"e": 3545,
"s": 2873,
"text": "MOV SI, 500: load the value 500 into offset SI.MOV DI, 600: load the value 600 into offset DI.MOV AX, 0000: load the value 0000 into AX register.MOV DS, AX: load the value of AX register into DS (data segment).MOV ES, AX: load the value of the AX register into ES (extra segment).MOV CL, [SI]: load the data of offset SI into the CL register.MOV CH, 00: load value 00 into CH register.INC SI: increment the value of SI by one.CLD: clears the directional flag i.e. DF=0.REP: repeat until value of CX is not equal to zero and decrement the value of CX by one at each step.MOVSB: transfer the data from the source memory location to the destination memory location.HLT: end."
},
{
"code": null,
"e": 3593,
"s": 3545,
"text": "MOV SI, 500: load the value 500 into offset SI."
},
{
"code": null,
"e": 3641,
"s": 3593,
"text": "MOV DI, 600: load the value 600 into offset DI."
},
{
"code": null,
"e": 3693,
"s": 3641,
"text": "MOV AX, 0000: load the value 0000 into AX register."
},
{
"code": null,
"e": 3759,
"s": 3693,
"text": "MOV DS, AX: load the value of AX register into DS (data segment)."
},
{
"code": null,
"e": 3830,
"s": 3759,
"text": "MOV ES, AX: load the value of the AX register into ES (extra segment)."
},
{
"code": null,
"e": 3893,
"s": 3830,
"text": "MOV CL, [SI]: load the data of offset SI into the CL register."
},
{
"code": null,
"e": 3937,
"s": 3893,
"text": "MOV CH, 00: load value 00 into CH register."
},
{
"code": null,
"e": 3979,
"s": 3937,
"text": "INC SI: increment the value of SI by one."
},
{
"code": null,
"e": 4023,
"s": 3979,
"text": "CLD: clears the directional flag i.e. DF=0."
},
{
"code": null,
"e": 4125,
"s": 4023,
"text": "REP: repeat until value of CX is not equal to zero and decrement the value of CX by one at each step."
},
{
"code": null,
"e": 4218,
"s": 4125,
"text": "MOVSB: transfer the data from the source memory location to the destination memory location."
},
{
"code": null,
"e": 4228,
"s": 4218,
"text": "HLT: end."
},
{
"code": null,
"e": 4241,
"s": 4228,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 4258,
"s": 4241,
"text": "surinderdawra388"
},
{
"code": null,
"e": 4272,
"s": 4258,
"text": "guptamridul75"
},
{
"code": null,
"e": 4287,
"s": 4272,
"text": "microprocessor"
},
{
"code": null,
"e": 4306,
"s": 4287,
"text": "system-programming"
},
{
"code": null,
"e": 4343,
"s": 4306,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 4358,
"s": 4343,
"text": "microprocessor"
},
{
"code": null,
"e": 4456,
"s": 4358,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4505,
"s": 4456,
"text": "Logical and Physical Address in Operating System"
},
{
"code": null,
"e": 4567,
"s": 4505,
"text": "Direct Access Media (DMA) Controller in Computer Architecture"
},
{
"code": null,
"e": 4605,
"s": 4567,
"text": "Computer Organization | RISC and CISC"
},
{
"code": null,
"e": 4653,
"s": 4605,
"text": "Memory Hierarchy Design and its Characteristics"
},
{
"code": null,
"e": 4748,
"s": 4653,
"text": "Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)"
},
{
"code": null,
"e": 4759,
"s": 4748,
"text": "Interrupts"
},
{
"code": null,
"e": 4795,
"s": 4759,
"text": "Architecture of 8085 microprocessor"
},
{
"code": null,
"e": 4814,
"s": 4795,
"text": "Control Characters"
},
{
"code": null,
"e": 4905,
"s": 4814,
"text": "Computer Organization | Instruction Formats (Zero, One, Two and Three Address Instruction)"
}
] |
Minimum steps to reach a destination
|
28 Jun, 2022
Given a number line from -infinity to +infinity. You start at 0 and can go either to the left or to the right. The condition is that in iβth move, you take i steps.
Find if you can reach a given number x Find the most optimal way to reach a given number x, if we can indeed reach it. For example, 3 can be reached in 2 steps, (0, 1) (1, 3) and 4 can be reached in 3 steps (0, -1), (-1, 1) (1, 4).
Find if you can reach a given number x
Find the most optimal way to reach a given number x, if we can indeed reach it. For example, 3 can be reached in 2 steps, (0, 1) (1, 3) and 4 can be reached in 3 steps (0, -1), (-1, 1) (1, 4).
Source: Flipkart Interview Question
The important thing to note is we can reach any destination as it is always possible to make a move of length 1. At any step i, we can move forward i, then backward i + 1.Below is a recursive solution suggested by Arpit Thapar here.
Since distance of + 5 and β 5 from 0 is same, hence we find answer for absolute value of destination.We use a recursive function which takes as arguments: Source Vertex Value of last step taken Destination If at any point source vertex = destination; return number of steps.Otherwise we can go in both of the possible directions. Take the minimum of steps in both cases.From any vertex we can go to : (current source + last step +1) and (current source β last step -1)If at any point, absolute value of our position exceeds the absolute value of our destination then it is intuitive that the shortest path is not possible from here. Hence we make the value of steps INT_MAX, so that when i take the minimum of both possibilities, this one gets eliminated.
Since distance of + 5 and β 5 from 0 is same, hence we find answer for absolute value of destination.
We use a recursive function which takes as arguments: Source Vertex Value of last step taken Destination
Source Vertex Value of last step taken Destination
Source Vertex
Value of last step taken
Destination
If at any point source vertex = destination; return number of steps.
Otherwise we can go in both of the possible directions. Take the minimum of steps in both cases.From any vertex we can go to : (current source + last step +1) and (current source β last step -1)
From any vertex we can go to : (current source + last step +1) and (current source β last step -1)
(current source + last step +1) and
(current source β last step -1)
If at any point, absolute value of our position exceeds the absolute value of our destination then it is intuitive that the shortest path is not possible from here. Hence we make the value of steps INT_MAX, so that when i take the minimum of both possibilities, this one gets eliminated.
If we donβt use this last step, the program enters into an INFINITE recursion and gives RUN TIME ERROR.
Below is the implementation of above idea. Note that the solution only counts steps.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to count number of// steps to reach a point#include<bits/stdc++.h>using namespace std; // Function to count number of steps// required to reach a destination // source -> source vertex// step -> value of last step taken// dest -> destination vertexint steps(int source, int step, int dest){ // base cases if (abs(source) > (dest)) return INT_MAX; if (source == dest) return step; // at each point we can go either way // if we go on positive side int pos = steps(source + step + 1, step + 1, dest); // if we go on negative side int neg = steps(source - step - 1, step + 1, dest); // minimum of both cases return min(pos, neg);} // Driver codeint main(){ int dest = 11; cout << "No. of steps required to reach " << dest << " is " << steps(0, 0, dest); return 0;}
// Java program to count number of// steps to reach a pointimport java.io.*; class GFG{ // Function to count number of steps // required to reach a destination // source -> source vertex // step -> value of last step taken // dest -> destination vertex static int steps(int source, int step, int dest) { // base cases if (Math.abs(source) > (dest)) return Integer.MAX_VALUE; if (source == dest) return step; // at each point we can go either way // if we go on positive side int pos = steps(source + step + 1, step + 1, dest); // if we go on negative side int neg = steps(source - step - 1, step + 1, dest); // minimum of both cases return Math.min(pos, neg); } // Driver Code public static void main(String[] args) { int dest = 11; System.out.println("No. of steps required"+ " to reach " + dest + " is " + steps(0, 0, dest)); }} // This code is contributed by Prerna Saini
# python program to count number of# steps to reach a pointimport sys # Function to count number of steps# required to reach a destination # source -> source vertex# step -> value of last step taken# dest -> destination vertexdef steps(source, step, dest): #base cases if (abs(source) > (dest)) : return sys.maxsize if (source == dest): return step # at each point we can go # either way # if we go on positive side pos = steps(source + step + 1, step + 1, dest) # if we go on negative side neg = steps(source - step - 1, step + 1, dest) # minimum of both cases return min(pos, neg) # Driver Codedest = 11;print("No. of steps required", " to reach " ,dest , " is " , steps(0, 0, dest)); # This code is contributed by Sam007.
// C# program to count number of// steps to reach a pointusing System; class GFG{ // Function to count number of steps // required to reach a destination // source -> source vertex // step -> value of last step taken // dest -> destination vertex static int steps(int source, int step, int dest) { // base cases if (Math.Abs(source) > (dest)) return int.MaxValue; if (source == dest) return step; // at each point we can go either way // if we go on positive side int pos = steps(source + step + 1, step + 1, dest); // if we go on negative side int neg = steps(source - step - 1, step + 1, dest); // minimum of both cases return Math.Min(pos, neg); } // Driver Code public static void Main() { int dest = 11; Console.WriteLine("No. of steps required"+ " to reach " + dest + " is " + steps(0, 0, dest)); }} // This code is contributed by Sam007
<?php// PHP program to count number// of steps to reach a point // Function to count number// of steps required to reach// a destination // source -> source vertex// step -> value of last step taken// dest -> destination vertexfunction steps($source, $step, $dest){ // base cases if (abs($source) > ($dest)) return PHP_INT_MAX; if ($source == $dest) return $step; // at each point we // can go either way // if we go on positive side $pos = steps($source + $step + 1, $step + 1, $dest); // if we go on negative side $neg = steps($source - $step - 1, $step + 1, $dest); // minimum of both cases return min($pos, $neg);} // Driver code$dest = 11;echo "No. of steps required to reach ", $dest, " is ", steps(0, 0, $dest); // This code is contributed by aj_36?>
<script>// JavaScript program to count number of// steps to reach a point // Function to count number of steps// required to reach a destination // source -> source vertex// step -> value of last step taken// dest -> destination vertexfunction steps(source, step, dest){ // base cases if (Math.abs(source) > (dest)) return Number.MAX_SAFE_INTEGER; if (source == dest) return step; // at each point we can go either way // if we go on positive side let pos = steps(source + step + 1, step + 1, dest); // if we go on negative side let neg = steps(source - step - 1, step + 1, dest); // minimum of both cases return Math.min(pos, neg);} // Driver code let dest = 11; document.write("No. of steps required to reach " + dest + " is " + steps(0, 0, dest)); // This code is contributed by Surbhi Tyagi.</script>
No. of steps required to reach 11 is 5
Thanks to Arpit Thapar for providing above algorithm and implementation.
Optimized Solution : Find minimum moves to reach target on an infinite line
This article is contributed by Abhay. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Sam007
jit_t
yvvijay
surbhityagi15
hardikkoriintern
Amazon
BFS
DFS
Flipkart
Goldman Sachs
InMobi
Microsoft
Dynamic Programming
Graph
Recursion
Flipkart
Amazon
Microsoft
Goldman Sachs
InMobi
Dynamic Programming
Recursion
DFS
Graph
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jun, 2022"
},
{
"code": null,
"e": 218,
"s": 52,
"text": "Given a number line from -infinity to +infinity. You start at 0 and can go either to the left or to the right. The condition is that in iβth move, you take i steps. "
},
{
"code": null,
"e": 450,
"s": 218,
"text": "Find if you can reach a given number x Find the most optimal way to reach a given number x, if we can indeed reach it. For example, 3 can be reached in 2 steps, (0, 1) (1, 3) and 4 can be reached in 3 steps (0, -1), (-1, 1) (1, 4)."
},
{
"code": null,
"e": 490,
"s": 450,
"text": "Find if you can reach a given number x "
},
{
"code": null,
"e": 683,
"s": 490,
"text": "Find the most optimal way to reach a given number x, if we can indeed reach it. For example, 3 can be reached in 2 steps, (0, 1) (1, 3) and 4 can be reached in 3 steps (0, -1), (-1, 1) (1, 4)."
},
{
"code": null,
"e": 719,
"s": 683,
"text": "Source: Flipkart Interview Question"
},
{
"code": null,
"e": 953,
"s": 719,
"text": "The important thing to note is we can reach any destination as it is always possible to make a move of length 1. At any step i, we can move forward i, then backward i + 1.Below is a recursive solution suggested by Arpit Thapar here. "
},
{
"code": null,
"e": 1710,
"s": 953,
"text": "Since distance of + 5 and β 5 from 0 is same, hence we find answer for absolute value of destination.We use a recursive function which takes as arguments: Source Vertex Value of last step taken Destination If at any point source vertex = destination; return number of steps.Otherwise we can go in both of the possible directions. Take the minimum of steps in both cases.From any vertex we can go to : (current source + last step +1) and (current source β last step -1)If at any point, absolute value of our position exceeds the absolute value of our destination then it is intuitive that the shortest path is not possible from here. Hence we make the value of steps INT_MAX, so that when i take the minimum of both possibilities, this one gets eliminated. "
},
{
"code": null,
"e": 1812,
"s": 1710,
"text": "Since distance of + 5 and β 5 from 0 is same, hence we find answer for absolute value of destination."
},
{
"code": null,
"e": 1917,
"s": 1812,
"text": "We use a recursive function which takes as arguments: Source Vertex Value of last step taken Destination"
},
{
"code": null,
"e": 1968,
"s": 1917,
"text": "Source Vertex Value of last step taken Destination"
},
{
"code": null,
"e": 1983,
"s": 1968,
"text": "Source Vertex "
},
{
"code": null,
"e": 2009,
"s": 1983,
"text": "Value of last step taken "
},
{
"code": null,
"e": 2021,
"s": 2009,
"text": "Destination"
},
{
"code": null,
"e": 2091,
"s": 2021,
"text": " If at any point source vertex = destination; return number of steps."
},
{
"code": null,
"e": 2286,
"s": 2091,
"text": "Otherwise we can go in both of the possible directions. Take the minimum of steps in both cases.From any vertex we can go to : (current source + last step +1) and (current source β last step -1)"
},
{
"code": null,
"e": 2385,
"s": 2286,
"text": "From any vertex we can go to : (current source + last step +1) and (current source β last step -1)"
},
{
"code": null,
"e": 2422,
"s": 2385,
"text": "(current source + last step +1) and "
},
{
"code": null,
"e": 2454,
"s": 2422,
"text": "(current source β last step -1)"
},
{
"code": null,
"e": 2743,
"s": 2454,
"text": "If at any point, absolute value of our position exceeds the absolute value of our destination then it is intuitive that the shortest path is not possible from here. Hence we make the value of steps INT_MAX, so that when i take the minimum of both possibilities, this one gets eliminated. "
},
{
"code": null,
"e": 2847,
"s": 2743,
"text": "If we donβt use this last step, the program enters into an INFINITE recursion and gives RUN TIME ERROR."
},
{
"code": null,
"e": 2933,
"s": 2847,
"text": "Below is the implementation of above idea. Note that the solution only counts steps. "
},
{
"code": null,
"e": 2937,
"s": 2933,
"text": "C++"
},
{
"code": null,
"e": 2942,
"s": 2937,
"text": "Java"
},
{
"code": null,
"e": 2950,
"s": 2942,
"text": "Python3"
},
{
"code": null,
"e": 2953,
"s": 2950,
"text": "C#"
},
{
"code": null,
"e": 2957,
"s": 2953,
"text": "PHP"
},
{
"code": null,
"e": 2968,
"s": 2957,
"text": "Javascript"
},
{
"code": "// C++ program to count number of// steps to reach a point#include<bits/stdc++.h>using namespace std; // Function to count number of steps// required to reach a destination // source -> source vertex// step -> value of last step taken// dest -> destination vertexint steps(int source, int step, int dest){ // base cases if (abs(source) > (dest)) return INT_MAX; if (source == dest) return step; // at each point we can go either way // if we go on positive side int pos = steps(source + step + 1, step + 1, dest); // if we go on negative side int neg = steps(source - step - 1, step + 1, dest); // minimum of both cases return min(pos, neg);} // Driver codeint main(){ int dest = 11; cout << \"No. of steps required to reach \" << dest << \" is \" << steps(0, 0, dest); return 0;}",
"e": 3888,
"s": 2968,
"text": null
},
{
"code": "// Java program to count number of// steps to reach a pointimport java.io.*; class GFG{ // Function to count number of steps // required to reach a destination // source -> source vertex // step -> value of last step taken // dest -> destination vertex static int steps(int source, int step, int dest) { // base cases if (Math.abs(source) > (dest)) return Integer.MAX_VALUE; if (source == dest) return step; // at each point we can go either way // if we go on positive side int pos = steps(source + step + 1, step + 1, dest); // if we go on negative side int neg = steps(source - step - 1, step + 1, dest); // minimum of both cases return Math.min(pos, neg); } // Driver Code public static void main(String[] args) { int dest = 11; System.out.println(\"No. of steps required\"+ \" to reach \" + dest + \" is \" + steps(0, 0, dest)); }} // This code is contributed by Prerna Saini",
"e": 5051,
"s": 3888,
"text": null
},
{
"code": "# python program to count number of# steps to reach a pointimport sys # Function to count number of steps# required to reach a destination # source -> source vertex# step -> value of last step taken# dest -> destination vertexdef steps(source, step, dest): #base cases if (abs(source) > (dest)) : return sys.maxsize if (source == dest): return step # at each point we can go # either way # if we go on positive side pos = steps(source + step + 1, step + 1, dest) # if we go on negative side neg = steps(source - step - 1, step + 1, dest) # minimum of both cases return min(pos, neg) # Driver Codedest = 11;print(\"No. of steps required\", \" to reach \" ,dest , \" is \" , steps(0, 0, dest)); # This code is contributed by Sam007.",
"e": 5910,
"s": 5051,
"text": null
},
{
"code": "// C# program to count number of// steps to reach a pointusing System; class GFG{ // Function to count number of steps // required to reach a destination // source -> source vertex // step -> value of last step taken // dest -> destination vertex static int steps(int source, int step, int dest) { // base cases if (Math.Abs(source) > (dest)) return int.MaxValue; if (source == dest) return step; // at each point we can go either way // if we go on positive side int pos = steps(source + step + 1, step + 1, dest); // if we go on negative side int neg = steps(source - step - 1, step + 1, dest); // minimum of both cases return Math.Min(pos, neg); } // Driver Code public static void Main() { int dest = 11; Console.WriteLine(\"No. of steps required\"+ \" to reach \" + dest + \" is \" + steps(0, 0, dest)); }} // This code is contributed by Sam007",
"e": 7041,
"s": 5910,
"text": null
},
{
"code": "<?php// PHP program to count number// of steps to reach a point // Function to count number// of steps required to reach// a destination // source -> source vertex// step -> value of last step taken// dest -> destination vertexfunction steps($source, $step, $dest){ // base cases if (abs($source) > ($dest)) return PHP_INT_MAX; if ($source == $dest) return $step; // at each point we // can go either way // if we go on positive side $pos = steps($source + $step + 1, $step + 1, $dest); // if we go on negative side $neg = steps($source - $step - 1, $step + 1, $dest); // minimum of both cases return min($pos, $neg);} // Driver code$dest = 11;echo \"No. of steps required to reach \", $dest, \" is \", steps(0, 0, $dest); // This code is contributed by aj_36?>",
"e": 7890,
"s": 7041,
"text": null
},
{
"code": "<script>// JavaScript program to count number of// steps to reach a point // Function to count number of steps// required to reach a destination // source -> source vertex// step -> value of last step taken// dest -> destination vertexfunction steps(source, step, dest){ // base cases if (Math.abs(source) > (dest)) return Number.MAX_SAFE_INTEGER; if (source == dest) return step; // at each point we can go either way // if we go on positive side let pos = steps(source + step + 1, step + 1, dest); // if we go on negative side let neg = steps(source - step - 1, step + 1, dest); // minimum of both cases return Math.min(pos, neg);} // Driver code let dest = 11; document.write(\"No. of steps required to reach \" + dest + \" is \" + steps(0, 0, dest)); // This code is contributed by Surbhi Tyagi.</script>",
"e": 8830,
"s": 7890,
"text": null
},
{
"code": null,
"e": 8869,
"s": 8830,
"text": "No. of steps required to reach 11 is 5"
},
{
"code": null,
"e": 8943,
"s": 8869,
"text": "Thanks to Arpit Thapar for providing above algorithm and implementation. "
},
{
"code": null,
"e": 9019,
"s": 8943,
"text": "Optimized Solution : Find minimum moves to reach target on an infinite line"
},
{
"code": null,
"e": 9182,
"s": 9019,
"text": "This article is contributed by Abhay. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 9189,
"s": 9182,
"text": "Sam007"
},
{
"code": null,
"e": 9195,
"s": 9189,
"text": "jit_t"
},
{
"code": null,
"e": 9203,
"s": 9195,
"text": "yvvijay"
},
{
"code": null,
"e": 9217,
"s": 9203,
"text": "surbhityagi15"
},
{
"code": null,
"e": 9234,
"s": 9217,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 9241,
"s": 9234,
"text": "Amazon"
},
{
"code": null,
"e": 9245,
"s": 9241,
"text": "BFS"
},
{
"code": null,
"e": 9249,
"s": 9245,
"text": "DFS"
},
{
"code": null,
"e": 9258,
"s": 9249,
"text": "Flipkart"
},
{
"code": null,
"e": 9272,
"s": 9258,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 9279,
"s": 9272,
"text": "InMobi"
},
{
"code": null,
"e": 9289,
"s": 9279,
"text": "Microsoft"
},
{
"code": null,
"e": 9309,
"s": 9289,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 9315,
"s": 9309,
"text": "Graph"
},
{
"code": null,
"e": 9325,
"s": 9315,
"text": "Recursion"
},
{
"code": null,
"e": 9334,
"s": 9325,
"text": "Flipkart"
},
{
"code": null,
"e": 9341,
"s": 9334,
"text": "Amazon"
},
{
"code": null,
"e": 9351,
"s": 9341,
"text": "Microsoft"
},
{
"code": null,
"e": 9365,
"s": 9351,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 9372,
"s": 9365,
"text": "InMobi"
},
{
"code": null,
"e": 9392,
"s": 9372,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 9402,
"s": 9392,
"text": "Recursion"
},
{
"code": null,
"e": 9406,
"s": 9402,
"text": "DFS"
},
{
"code": null,
"e": 9412,
"s": 9406,
"text": "Graph"
},
{
"code": null,
"e": 9416,
"s": 9412,
"text": "BFS"
}
] |
SED command in Linux | Set 2
|
23 Dec, 2021
We have discussed some of the SED command options in Sed Command in Linux/Unix with examples
SED is used for finding, filtering, text substitution, replacement and text manipulations like insertion, deletion search, etc. Itβs a one of the powerful utilities offered by Linux/Unix systems. We can use sed with regular expressions. I hope atleast you have the basic knowledge about Linux regular expressions.
It provides Non-interactive editing of text files thatβs why itβs used to automate editing and has two buffers β pattern buffer and hold buffer. Sed use Pattern buffer when it read files, line by line and that currently read line is inserted into pattern buffer whereas hold buffer is a long-term storage, it catch the information, store it and reuse it when it is needed. Initially, both are empty. SED command is used for performing different operations without even opening the file.
sed general syntax β sed OPTIONS... [SCRIPT] [INPUTFILE...]
First create a.txt file on which I am going to perform operations for SED commands. In this blog, I used βa.txtβ file to explain all the examples. Blog will become too long if i write the output of each sed command. So, you may refer the same file to practice all the commands initially.
[root@rhel7 ~]# cat a.txt
life isn't meant to be easy, life is meant to be lived.
Try to learn & understand something new everyday in life.
Respect everyone & most important love everyone.
Donβt hesitate to ask for love & donβt hesitate to show love too.
Life is too short to be shy.
In life, experience will help you differentiating right from wrong.
# Letβs start with File Spacing 1 β Insert one blank line after each line β
[root@rhel7 ~]# sed G a.txt
2 β To insert two blank lines β
[root@rhel7 ~]# sed 'G;G' a.txt
3 β Delete blank lines and insert one blank line after each line β
[root@rhel7 ~]# sed '/^$/d;G' a.txt
4 β Insert a black line above every line which matches βloveβ β
[root@rhel7 ~]# sed '/love/{x;p;x;}' a.txt
5 β Insert a blank line below every line which matches βloveβ β
[root@rhel7 ~]# sed '/love/G' a.txt
6 β Insert 5 spaces to the left of every lines β
[root@rhel7 ~]# sed 's/^/ /' a.txt
# Numbering lines 1 β Number each line of a file (left alignment). **=** is used to number the line. \t is used for tab between number and sentence β
[root@rhel7 ~]# sed = a.txt | sed 'N;s/\n/\t/'
2 β Number each line of a file (number on left, right-aligned). This command is similar to `cat -n filename`.
[root@rhel7 ~]# sed = a.txt | sed 'N; s/^/ /; s/ *\(.\{4,\}\)\n/\1 /'
3 β Number each line of file, only if line is not blank β
[root@rhel7 ~]# sed '/./=' a.txt | sed '/./N; s/\n/ /'
# Deleting lines 1 β Delete a particular line β Syntax: sed βndβ filename Example :
[root@rhel7 ~]# sed '5d' a.txt
2 β Delete the last line Syntax: sed β$dβ filename
3 β Delete line from range x to y Syntax: sed βx,ydβ filename Example :
[root@rhel7 ~]# sed '3,5d' a.txt
4 β Delete from nth to last line Syntax: sed βnth,$dβ filename Example :
[root@rhel7 ~]# sed '2,$d' a.txt
5 β Delete the pattern matching line β Syntax: sed β/pattern/dβ filename Example :
[root@rhel7 ~]# sed '/life/d' a.txt
6 β Delete lines starting from nth line and every 2nd line from there β Syntax: sed βn~2dβ filename Example :
[root@rhel7 ~]# sed '3~2d' a.txt
7 β Delete the lines which matches the pattern and 2 lines after to that β Syntax: sed β/pattern/,+2dβ filename Example :
[root@rhel7 ~]# sed '/easy/,+2d' a.txt
8 β Delete blank Lines
[root@rhel7 ~]# sed '/^$/d' a.txt
9 β Delete empty lines or those begins with β#β β
[root@rhel7 ~]# sed -i '/^#/d;/^$/d' a.txt
# View/Print the files If we want to view content of file, then we use cat command and if we want to view the bottom and the top content of any file, we use tools such as head and tail. But what if we need to view a particular section in the middle of any file? Here weβll discuss, how to use SED command to view a section of any file.
1 β Viewing a file from x to y range β Syntax: sed -n βx,ypβ filename Example :
[root@rhel7 ~]# sed -n '2,5p' a.txt
2 β View the entire file except the given range β Syntax: sed βx,ydβ filename Example :
[root@rhel7 ~]# sed '2,4d' a.txt
3 β Print nth line of the file β Syntax: sed -n βaddressβp filename Example :
[root@rhel7 ~]# sed -n '4'p a.txt
4 β Print lines from xth line to yth line. Syntax: sed -n βx,yβp filename Example :
[root@rhel7 ~]# sed -n '4,6'p a.txt
5 β Print only the last line β Syntax: sed -n β$βp filename
6 β Print from nth line to end of file β Syntax: sed -n βn,$pβ filename Example :
[root@rhel7 ~]# sed -n '3,$'p a.txt
Pattern Printing 7 β Print the line only which matches the pattern β Syntax: sed -n /pattern/p filename Example :
[root@rhel7 ~]# sed -n /every/p a.txt
8 β Print lines which matches the pattern i.e from input to xth line. Syntax: sed -n β/pattern/,xpβ filename Example :
[root@rhel7 ~]# sed -n '/everyone/,5p' a.txt
Following prints lines which matches the pattern, 3rd line matches the pattern βeveryoneβ, so it prints from 3rd line to 5th line. Use $ in place of 5, if want to print the file till end.
9 β Prints lines from the xth line of the input, up-to the line which matches the pattern. If the pattern doesnβt found then it prints up-to end of the file. Syntax: sed -n βx,/pattern/pβ filename Example :
sed -n '1,/everyone/p' a.txt
10 β Print the lines which matches the pattern up-to the next xth lines β Syntax: sed -n β/pattern/,+xpβ filename Example :
sed -n '/learn/,+2p' a.txt
# Replacement with the sed command 1 β Change the first occurrence of the pattern β
[root@rhel7 ~]# sed 's/life/leaves/' a.txt
2 β Replacing the nth occurrence of a pattern in a line β Syntax: sed βs/old_pattern/new_pattern/nβ filename Example :
[root@rhel7 ~]# sed 's/to/two/2' a.txt
We wrote β2β because we replaces the second occurrence. Likewise you can use 3, 4 etc according to need.
3 β Replacing all the occurrence of the pattern in a line.
[root@rhel7 ~]# sed 's/life/learn/g' a.txt
4 β Replace pattern from nth occurrence to all occurrences in a line. Syntax: sed βs/old_pattern/new_pattern/ngβ filename Example :
[root@rhel7 ~]# sed 's/to/TWO/2g' a.txt
Note β This sed command replaces the second, third, etc occurrences of pattern βtoβ with βTWOβ in a line.
If you wish to print only the replaced lines, then use β-nβ option along with β/pβ print flag to display only the replaced lines β
[root@rhel7 ~]# sed -n 's/to/TWO/p' a.txt
And if you wish to print the replaced lines twice, then only use β/pβ print flag without β-nβ option-
[root@rhel7 ~]# sed 's/to/TWO/p' a.txt
5 β Replacing pattern on a specific line number. Here, βmβ is the line number. Syntax: sed βm s/old_pattern/new_pattern/β filename Example :
[root@rhel7 ~]# sed '3 s/every/each/' a.txt
If you wish to print only the replaced lines β
[root@rhel7 ~]# sed -n '3 s/every/each/p' a.txt
6 β Replace string on a defined range of lines β Syntax: sed βx,y s/old_pattern/new_pattern/β filename where, x = starting line number and y = ending line number
Example :
[root@rhel7 ~]# sed '2,5 s/to/TWO/' a.txt
Note β $ can be used in place of βyβ if we wish to change the pattern up-to last line in the file. Example :
[root@rhel7 ~]# sed '2,$ s/to/TWO/' a.txt
7 β If you wish to replace pattern in order to ignore character case (beginning with uppercase or lowercase), then there are two ways to replace such patterns β First, By using β/iβ print flag β Syntax: sed βs/old_pattern/new_pattern/iβ filename Example :
[root@rhel7 ~]# sed 's/life/Love/i' a.txt
Second, By using regular expressions β
[root@rhel7 ~]# sed 's/[Ll]ife/Love/g' a.txt
8 β To replace multiple spaces with a single space β
[root@rhel7 clang]# sed 's/ */ /g' filename
9 β Replace one pattern followed by the another pattern β Syntax: sed β/followed_pattern/ s/old_pattern/new_pattern/β filename Example :
[root@rhel7 ~]# sed '/is/ s/live/love/' a.txt
10 β Replace a pattern with other except in the nth line. Syntax: sed βn!s/old_pattern/new_pattern/β filename Example :
[root@rhel7 ~]# sed -i '5!s/life/love/' a.txt
gabaa406
sweetyty
meetgor
linux-command
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
Tail command in Linux with examples
Conditional Statements | Shell Script
Docker - COPY Instruction
scp command in Linux with Examples
UDP Server-Client implementation in C
Cat command in Linux with examples
echo command in Linux with Examples
touch command in Linux with Examples
Introduction to Linux Operating System
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Dec, 2021"
},
{
"code": null,
"e": 148,
"s": 54,
"text": "We have discussed some of the SED command options in Sed Command in Linux/Unix with examples "
},
{
"code": null,
"e": 463,
"s": 148,
"text": "SED is used for finding, filtering, text substitution, replacement and text manipulations like insertion, deletion search, etc. Itβs a one of the powerful utilities offered by Linux/Unix systems. We can use sed with regular expressions. I hope atleast you have the basic knowledge about Linux regular expressions. "
},
{
"code": null,
"e": 951,
"s": 463,
"text": "It provides Non-interactive editing of text files thatβs why itβs used to automate editing and has two buffers β pattern buffer and hold buffer. Sed use Pattern buffer when it read files, line by line and that currently read line is inserted into pattern buffer whereas hold buffer is a long-term storage, it catch the information, store it and reuse it when it is needed. Initially, both are empty. SED command is used for performing different operations without even opening the file. "
},
{
"code": null,
"e": 1012,
"s": 951,
"text": "sed general syntax β sed OPTIONS... [SCRIPT] [INPUTFILE...] "
},
{
"code": null,
"e": 1302,
"s": 1012,
"text": "First create a.txt file on which I am going to perform operations for SED commands. In this blog, I used βa.txtβ file to explain all the examples. Blog will become too long if i write the output of each sed command. So, you may refer the same file to practice all the commands initially. "
},
{
"code": null,
"e": 1654,
"s": 1302,
"text": "[root@rhel7 ~]# cat a.txt\nlife isn't meant to be easy, life is meant to be lived.\nTry to learn & understand something new everyday in life.\nRespect everyone & most important love everyone.\nDonβt hesitate to ask for love & donβt hesitate to show love too.\nLife is too short to be shy.\nIn life, experience will help you differentiating right from wrong."
},
{
"code": null,
"e": 1732,
"s": 1654,
"text": "# Letβs start with File Spacing 1 β Insert one blank line after each line β "
},
{
"code": null,
"e": 1761,
"s": 1732,
"text": "[root@rhel7 ~]# sed G a.txt "
},
{
"code": null,
"e": 1795,
"s": 1761,
"text": "2 β To insert two blank lines β "
},
{
"code": null,
"e": 1827,
"s": 1795,
"text": "[root@rhel7 ~]# sed 'G;G' a.txt"
},
{
"code": null,
"e": 1896,
"s": 1827,
"text": "3 β Delete blank lines and insert one blank line after each line β "
},
{
"code": null,
"e": 1932,
"s": 1896,
"text": "[root@rhel7 ~]# sed '/^$/d;G' a.txt"
},
{
"code": null,
"e": 1998,
"s": 1932,
"text": "4 β Insert a black line above every line which matches βloveβ β "
},
{
"code": null,
"e": 2041,
"s": 1998,
"text": "[root@rhel7 ~]# sed '/love/{x;p;x;}' a.txt"
},
{
"code": null,
"e": 2107,
"s": 2041,
"text": "5 β Insert a blank line below every line which matches βloveβ β "
},
{
"code": null,
"e": 2143,
"s": 2107,
"text": "[root@rhel7 ~]# sed '/love/G' a.txt"
},
{
"code": null,
"e": 2194,
"s": 2143,
"text": "6 β Insert 5 spaces to the left of every lines β "
},
{
"code": null,
"e": 2233,
"s": 2194,
"text": "[root@rhel7 ~]# sed 's/^/ /' a.txt"
},
{
"code": null,
"e": 2384,
"s": 2233,
"text": "# Numbering lines 1 β Number each line of a file (left alignment). **=** is used to number the line. \\t is used for tab between number and sentence β "
},
{
"code": null,
"e": 2432,
"s": 2384,
"text": "[root@rhel7 ~]# sed = a.txt | sed 'N;s/\\n/\\t/'"
},
{
"code": null,
"e": 2543,
"s": 2432,
"text": "2 β Number each line of a file (number on left, right-aligned). This command is similar to `cat -n filename`. "
},
{
"code": null,
"e": 2618,
"s": 2543,
"text": "[root@rhel7 ~]# sed = a.txt | sed 'N; s/^/ /; s/ *\\(.\\{4,\\}\\)\\n/\\1 /'"
},
{
"code": null,
"e": 2678,
"s": 2618,
"text": "3 β Number each line of file, only if line is not blank β "
},
{
"code": null,
"e": 2734,
"s": 2678,
"text": "[root@rhel7 ~]# sed '/./=' a.txt | sed '/./N; s/\\n/ /'"
},
{
"code": null,
"e": 2820,
"s": 2734,
"text": "# Deleting lines 1 β Delete a particular line β Syntax: sed βndβ filename Example : "
},
{
"code": null,
"e": 2851,
"s": 2820,
"text": "[root@rhel7 ~]# sed '5d' a.txt"
},
{
"code": null,
"e": 2903,
"s": 2851,
"text": "2 β Delete the last line Syntax: sed β$dβ filename "
},
{
"code": null,
"e": 2977,
"s": 2903,
"text": "3 β Delete line from range x to y Syntax: sed βx,ydβ filename Example : "
},
{
"code": null,
"e": 3010,
"s": 2977,
"text": "[root@rhel7 ~]# sed '3,5d' a.txt"
},
{
"code": null,
"e": 3084,
"s": 3010,
"text": "4 β Delete from nth to last line Syntax: sed βnth,$dβ filename Example : "
},
{
"code": null,
"e": 3117,
"s": 3084,
"text": "[root@rhel7 ~]# sed '2,$d' a.txt"
},
{
"code": null,
"e": 3202,
"s": 3117,
"text": "5 β Delete the pattern matching line β Syntax: sed β/pattern/dβ filename Example : "
},
{
"code": null,
"e": 3238,
"s": 3202,
"text": "[root@rhel7 ~]# sed '/life/d' a.txt"
},
{
"code": null,
"e": 3350,
"s": 3238,
"text": "6 β Delete lines starting from nth line and every 2nd line from there β Syntax: sed βn~2dβ filename Example : "
},
{
"code": null,
"e": 3383,
"s": 3350,
"text": "[root@rhel7 ~]# sed '3~2d' a.txt"
},
{
"code": null,
"e": 3507,
"s": 3383,
"text": "7 β Delete the lines which matches the pattern and 2 lines after to that β Syntax: sed β/pattern/,+2dβ filename Example : "
},
{
"code": null,
"e": 3546,
"s": 3507,
"text": "[root@rhel7 ~]# sed '/easy/,+2d' a.txt"
},
{
"code": null,
"e": 3571,
"s": 3546,
"text": "8 β Delete blank Lines "
},
{
"code": null,
"e": 3605,
"s": 3571,
"text": "[root@rhel7 ~]# sed '/^$/d' a.txt"
},
{
"code": null,
"e": 3657,
"s": 3605,
"text": "9 β Delete empty lines or those begins with β#β β "
},
{
"code": null,
"e": 3700,
"s": 3657,
"text": "[root@rhel7 ~]# sed -i '/^#/d;/^$/d' a.txt"
},
{
"code": null,
"e": 4037,
"s": 3700,
"text": "# View/Print the files If we want to view content of file, then we use cat command and if we want to view the bottom and the top content of any file, we use tools such as head and tail. But what if we need to view a particular section in the middle of any file? Here weβll discuss, how to use SED command to view a section of any file. "
},
{
"code": null,
"e": 4118,
"s": 4037,
"text": "1 β Viewing a file from x to y range β Syntax: sed -n βx,ypβ filename Example : "
},
{
"code": null,
"e": 4154,
"s": 4118,
"text": "[root@rhel7 ~]# sed -n '2,5p' a.txt"
},
{
"code": null,
"e": 4244,
"s": 4154,
"text": "2 β View the entire file except the given range β Syntax: sed βx,ydβ filename Example : "
},
{
"code": null,
"e": 4277,
"s": 4244,
"text": "[root@rhel7 ~]# sed '2,4d' a.txt"
},
{
"code": null,
"e": 4357,
"s": 4277,
"text": "3 β Print nth line of the file β Syntax: sed -n βaddressβp filename Example : "
},
{
"code": null,
"e": 4391,
"s": 4357,
"text": "[root@rhel7 ~]# sed -n '4'p a.txt"
},
{
"code": null,
"e": 4477,
"s": 4391,
"text": "4 β Print lines from xth line to yth line. Syntax: sed -n βx,yβp filename Example : "
},
{
"code": null,
"e": 4513,
"s": 4477,
"text": "[root@rhel7 ~]# sed -n '4,6'p a.txt"
},
{
"code": null,
"e": 4574,
"s": 4513,
"text": "5 β Print only the last line β Syntax: sed -n β$βp filename "
},
{
"code": null,
"e": 4657,
"s": 4574,
"text": "6 β Print from nth line to end of file β Syntax: sed -n βn,$pβ filename Example : "
},
{
"code": null,
"e": 4693,
"s": 4657,
"text": "[root@rhel7 ~]# sed -n '3,$'p a.txt"
},
{
"code": null,
"e": 4808,
"s": 4693,
"text": "Pattern Printing 7 β Print the line only which matches the pattern β Syntax: sed -n /pattern/p filename Example : "
},
{
"code": null,
"e": 4846,
"s": 4808,
"text": "[root@rhel7 ~]# sed -n /every/p a.txt"
},
{
"code": null,
"e": 4967,
"s": 4846,
"text": "8 β Print lines which matches the pattern i.e from input to xth line. Syntax: sed -n β/pattern/,xpβ filename Example : "
},
{
"code": null,
"e": 5012,
"s": 4967,
"text": "[root@rhel7 ~]# sed -n '/everyone/,5p' a.txt"
},
{
"code": null,
"e": 5201,
"s": 5012,
"text": "Following prints lines which matches the pattern, 3rd line matches the pattern βeveryoneβ, so it prints from 3rd line to 5th line. Use $ in place of 5, if want to print the file till end. "
},
{
"code": null,
"e": 5409,
"s": 5201,
"text": "9 β Prints lines from the xth line of the input, up-to the line which matches the pattern. If the pattern doesnβt found then it prints up-to end of the file. Syntax: sed -n βx,/pattern/pβ filename Example : "
},
{
"code": null,
"e": 5438,
"s": 5409,
"text": "sed -n '1,/everyone/p' a.txt"
},
{
"code": null,
"e": 5564,
"s": 5438,
"text": "10 β Print the lines which matches the pattern up-to the next xth lines β Syntax: sed -n β/pattern/,+xpβ filename Example : "
},
{
"code": null,
"e": 5591,
"s": 5564,
"text": "sed -n '/learn/,+2p' a.txt"
},
{
"code": null,
"e": 5676,
"s": 5591,
"text": "# Replacement with the sed command 1 β Change the first occurrence of the pattern β "
},
{
"code": null,
"e": 5719,
"s": 5676,
"text": "[root@rhel7 ~]# sed 's/life/leaves/' a.txt"
},
{
"code": null,
"e": 5840,
"s": 5719,
"text": "2 β Replacing the nth occurrence of a pattern in a line β Syntax: sed βs/old_pattern/new_pattern/nβ filename Example : "
},
{
"code": null,
"e": 5879,
"s": 5840,
"text": "[root@rhel7 ~]# sed 's/to/two/2' a.txt"
},
{
"code": null,
"e": 5985,
"s": 5879,
"text": "We wrote β2β because we replaces the second occurrence. Likewise you can use 3, 4 etc according to need. "
},
{
"code": null,
"e": 6046,
"s": 5985,
"text": "3 β Replacing all the occurrence of the pattern in a line. "
},
{
"code": null,
"e": 6089,
"s": 6046,
"text": "[root@rhel7 ~]# sed 's/life/learn/g' a.txt"
},
{
"code": null,
"e": 6223,
"s": 6089,
"text": "4 β Replace pattern from nth occurrence to all occurrences in a line. Syntax: sed βs/old_pattern/new_pattern/ngβ filename Example : "
},
{
"code": null,
"e": 6263,
"s": 6223,
"text": "[root@rhel7 ~]# sed 's/to/TWO/2g' a.txt"
},
{
"code": null,
"e": 6370,
"s": 6263,
"text": "Note β This sed command replaces the second, third, etc occurrences of pattern βtoβ with βTWOβ in a line. "
},
{
"code": null,
"e": 6502,
"s": 6370,
"text": "If you wish to print only the replaced lines, then use β-nβ option along with β/pβ print flag to display only the replaced lines β "
},
{
"code": null,
"e": 6544,
"s": 6502,
"text": "[root@rhel7 ~]# sed -n 's/to/TWO/p' a.txt"
},
{
"code": null,
"e": 6648,
"s": 6544,
"text": "And if you wish to print the replaced lines twice, then only use β/pβ print flag without β-nβ option- "
},
{
"code": null,
"e": 6687,
"s": 6648,
"text": "[root@rhel7 ~]# sed 's/to/TWO/p' a.txt"
},
{
"code": null,
"e": 6830,
"s": 6687,
"text": "5 β Replacing pattern on a specific line number. Here, βmβ is the line number. Syntax: sed βm s/old_pattern/new_pattern/β filename Example : "
},
{
"code": null,
"e": 6874,
"s": 6830,
"text": "[root@rhel7 ~]# sed '3 s/every/each/' a.txt"
},
{
"code": null,
"e": 6923,
"s": 6874,
"text": "If you wish to print only the replaced lines β "
},
{
"code": null,
"e": 6971,
"s": 6923,
"text": "[root@rhel7 ~]# sed -n '3 s/every/each/p' a.txt"
},
{
"code": null,
"e": 7134,
"s": 6971,
"text": "6 β Replace string on a defined range of lines β Syntax: sed βx,y s/old_pattern/new_pattern/β filename where, x = starting line number and y = ending line number "
},
{
"code": null,
"e": 7145,
"s": 7134,
"text": "Example : "
},
{
"code": null,
"e": 7187,
"s": 7145,
"text": "[root@rhel7 ~]# sed '2,5 s/to/TWO/' a.txt"
},
{
"code": null,
"e": 7298,
"s": 7187,
"text": "Note β $ can be used in place of βyβ if we wish to change the pattern up-to last line in the file. Example : "
},
{
"code": null,
"e": 7340,
"s": 7298,
"text": "[root@rhel7 ~]# sed '2,$ s/to/TWO/' a.txt"
},
{
"code": null,
"e": 7598,
"s": 7340,
"text": "7 β If you wish to replace pattern in order to ignore character case (beginning with uppercase or lowercase), then there are two ways to replace such patterns β First, By using β/iβ print flag β Syntax: sed βs/old_pattern/new_pattern/iβ filename Example : "
},
{
"code": null,
"e": 7640,
"s": 7598,
"text": "[root@rhel7 ~]# sed 's/life/Love/i' a.txt"
},
{
"code": null,
"e": 7681,
"s": 7640,
"text": "Second, By using regular expressions β "
},
{
"code": null,
"e": 7726,
"s": 7681,
"text": "[root@rhel7 ~]# sed 's/[Ll]ife/Love/g' a.txt"
},
{
"code": null,
"e": 7781,
"s": 7726,
"text": "8 β To replace multiple spaces with a single space β "
},
{
"code": null,
"e": 7826,
"s": 7781,
"text": "[root@rhel7 clang]# sed 's/ */ /g' filename"
},
{
"code": null,
"e": 7965,
"s": 7826,
"text": "9 β Replace one pattern followed by the another pattern β Syntax: sed β/followed_pattern/ s/old_pattern/new_pattern/β filename Example : "
},
{
"code": null,
"e": 8011,
"s": 7965,
"text": "[root@rhel7 ~]# sed '/is/ s/live/love/' a.txt"
},
{
"code": null,
"e": 8133,
"s": 8011,
"text": "10 β Replace a pattern with other except in the nth line. Syntax: sed βn!s/old_pattern/new_pattern/β filename Example : "
},
{
"code": null,
"e": 8179,
"s": 8133,
"text": "[root@rhel7 ~]# sed -i '5!s/life/love/' a.txt"
},
{
"code": null,
"e": 8190,
"s": 8181,
"text": "gabaa406"
},
{
"code": null,
"e": 8199,
"s": 8190,
"text": "sweetyty"
},
{
"code": null,
"e": 8207,
"s": 8199,
"text": "meetgor"
},
{
"code": null,
"e": 8221,
"s": 8207,
"text": "linux-command"
},
{
"code": null,
"e": 8232,
"s": 8221,
"text": "Linux-Unix"
},
{
"code": null,
"e": 8330,
"s": 8232,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8365,
"s": 8330,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 8401,
"s": 8365,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 8439,
"s": 8401,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 8465,
"s": 8439,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 8500,
"s": 8465,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 8538,
"s": 8500,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 8573,
"s": 8538,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 8609,
"s": 8573,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 8646,
"s": 8609,
"text": "touch command in Linux with Examples"
}
] |
Tryit Editor v3.6 - Show React
|
import React from 'react';
import ReactDOM from 'react-dom/client';
ReactDOM.render(<p>Hello</p>, document.getElementById('root'));
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport"
content="width=device-width, initial-scale=1" />
|
[
{
"code": null,
"e": 136,
"s": 0,
"text": "\nimport React from 'react';\nimport ReactDOM from 'react-dom/client';\n\nReactDOM.render(<p>Hello</p>, document.getElementById('root'));\n\n"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.