title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Hashing | Set 2 (Separate Chaining) - GeeksforGeeks | 28 Jun, 2021
We strongly recommend to refer below post as a prerequisite of this. Hashing | Set 1 (Introduction)
What is Collision? Since a hash function gets us a small number for a key which is a big integer or string, there is a possibility that two keys result in the same value. The situation where a newly inserted key maps to an already occupied slot in the hash table is called collision and must be handled using some collision handling technique.
What are the chances of collisions with large table? Collisions are very likely even if we have big table to store keys. An important observation is Birthday Paradox. With only 23 persons, the probability that two people have the same birthday is 50%.
How to handle Collisions? There are mainly two methods to handle collision: 1) Separate Chaining 2) Open Addressing In this article, only separate chaining is discussed. We will be discussing Open addressing in the next post.
Separate Chaining: The idea is to make each cell of hash table point to a linked list of records that have same hash function value.
Let us consider a simple hash function as “key mod 7” and sequence of keys as 50, 700, 76, 85, 92, 73, 101.
C++ program for hashing with chaining
Advantages: 1) Simple to implement. 2) Hash table never fills up, we can always add more elements to the chain. 3) Less sensitive to the hash function or load factors. 4) It is mostly used when it is unknown how many and how frequently keys may be inserted or deleted.
Disadvantages: 1) Cache performance of chaining is not good as keys are stored using a linked list. Open addressing provides better cache performance as everything is stored in the same table. 2) Wastage of Space (Some Parts of hash table are never used) 3) If the chain becomes long, then search time can become O(n) in the worst case. 4) Uses extra space for links.
Performance of Chaining: Performance of hashing can be evaluated under the assumption that each key is equally likely to be hashed to any slot of table (simple uniform hashing).
m = Number of slots in hash table
n = Number of keys to be inserted in hash table
Load factor α = n/m
Expected time to search = O(1 + α)
Expected time to delete = O(1 + α)
Time to insert = O(1)
Time complexity of search insert and delete is
O(1) if α is O(1)
Linked listsSearch: O(l) where l = length of linked listDelete: O(l)Insert: O(l)Not cache friendly
Search: O(l) where l = length of linked list
Delete: O(l)
Insert: O(l)
Not cache friendly
Dynamic Sized Arrays ( Vectors in C++, ArrayList in Java, list in Python)Search: O(l) where l = length of arrayDelete: O(l)Insert: O(l)Cache friendly
Search: O(l) where l = length of array
Delete: O(l)
Insert: O(l)
Cache friendly
Self Balancing BST ( AVL Trees, Red Black Trees)Search: O(log(l))Delete: O(log(l))Insert: O(l)Not cache friendlyJava 8 onwards use this for HashMap
Search: O(log(l))
Delete: O(log(l))
Insert: O(l)
Not cache friendly
Java 8 onwards use this for HashMap
YouTubeGeeksforGeeks507K subscribersHashing | Set 2 (Separate Chaining) | 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 / 7:49•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=_xA8UvfOGgU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Next Post: Open Addressing for Collision Handling
References: http://courses.csail.mit.edu/6.006/fall09/lecture_notes/lecture05.pdf Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ConnorFehrenbach
NandkishorNangre
scisaif
Hash
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Internal Working of HashMap in Java
Count pairs with given sum
Sort string of characters
Counting frequencies of array elements
Most frequent element in an array
Sorting a Map by value in C++ STL
Longest Consecutive Subsequence
Return maximum occurring character in an input string
C++ program for hashing with chaining
Quadratic Probing in Hashing | [
{
"code": null,
"e": 39003,
"s": 38975,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 39104,
"s": 39003,
"text": "We strongly recommend to refer below post as a prerequisite of this. Hashing | Set 1 (Introduction) "
},
{
"code": null,
"e": 39450,
"s": 39104,
"text": "What is Collision? Since a hash function gets us a small number for a key which is a big integer or string, there is a possibility that two keys result in the same value. The situation where a newly inserted key maps to an already occupied slot in the hash table is called collision and must be handled using some collision handling technique. "
},
{
"code": null,
"e": 39703,
"s": 39450,
"text": "What are the chances of collisions with large table? Collisions are very likely even if we have big table to store keys. An important observation is Birthday Paradox. With only 23 persons, the probability that two people have the same birthday is 50%. "
},
{
"code": null,
"e": 39930,
"s": 39703,
"text": "How to handle Collisions? There are mainly two methods to handle collision: 1) Separate Chaining 2) Open Addressing In this article, only separate chaining is discussed. We will be discussing Open addressing in the next post. "
},
{
"code": null,
"e": 40064,
"s": 39930,
"text": "Separate Chaining: The idea is to make each cell of hash table point to a linked list of records that have same hash function value. "
},
{
"code": null,
"e": 40174,
"s": 40064,
"text": "Let us consider a simple hash function as “key mod 7” and sequence of keys as 50, 700, 76, 85, 92, 73, 101. "
},
{
"code": null,
"e": 40213,
"s": 40174,
"text": "C++ program for hashing with chaining "
},
{
"code": null,
"e": 40483,
"s": 40213,
"text": "Advantages: 1) Simple to implement. 2) Hash table never fills up, we can always add more elements to the chain. 3) Less sensitive to the hash function or load factors. 4) It is mostly used when it is unknown how many and how frequently keys may be inserted or deleted. "
},
{
"code": null,
"e": 40852,
"s": 40483,
"text": "Disadvantages: 1) Cache performance of chaining is not good as keys are stored using a linked list. Open addressing provides better cache performance as everything is stored in the same table. 2) Wastage of Space (Some Parts of hash table are never used) 3) If the chain becomes long, then search time can become O(n) in the worst case. 4) Uses extra space for links. "
},
{
"code": null,
"e": 41032,
"s": 40852,
"text": "Performance of Chaining: Performance of hashing can be evaluated under the assumption that each key is equally likely to be hashed to any slot of table (simple uniform hashing). "
},
{
"code": null,
"e": 41310,
"s": 41032,
"text": " m = Number of slots in hash table\n n = Number of keys to be inserted in hash table\n \n Load factor α = n/m \n \n Expected time to search = O(1 + α)\n \n Expected time to delete = O(1 + α)\n\nTime to insert = O(1)\n\n Time complexity of search insert and delete is \n O(1) if α is O(1)"
},
{
"code": null,
"e": 41409,
"s": 41310,
"text": "Linked listsSearch: O(l) where l = length of linked listDelete: O(l)Insert: O(l)Not cache friendly"
},
{
"code": null,
"e": 41454,
"s": 41409,
"text": "Search: O(l) where l = length of linked list"
},
{
"code": null,
"e": 41467,
"s": 41454,
"text": "Delete: O(l)"
},
{
"code": null,
"e": 41480,
"s": 41467,
"text": "Insert: O(l)"
},
{
"code": null,
"e": 41499,
"s": 41480,
"text": "Not cache friendly"
},
{
"code": null,
"e": 41649,
"s": 41499,
"text": "Dynamic Sized Arrays ( Vectors in C++, ArrayList in Java, list in Python)Search: O(l) where l = length of arrayDelete: O(l)Insert: O(l)Cache friendly"
},
{
"code": null,
"e": 41688,
"s": 41649,
"text": "Search: O(l) where l = length of array"
},
{
"code": null,
"e": 41701,
"s": 41688,
"text": "Delete: O(l)"
},
{
"code": null,
"e": 41714,
"s": 41701,
"text": "Insert: O(l)"
},
{
"code": null,
"e": 41729,
"s": 41714,
"text": "Cache friendly"
},
{
"code": null,
"e": 41877,
"s": 41729,
"text": "Self Balancing BST ( AVL Trees, Red Black Trees)Search: O(log(l))Delete: O(log(l))Insert: O(l)Not cache friendlyJava 8 onwards use this for HashMap"
},
{
"code": null,
"e": 41895,
"s": 41877,
"text": "Search: O(log(l))"
},
{
"code": null,
"e": 41913,
"s": 41895,
"text": "Delete: O(log(l))"
},
{
"code": null,
"e": 41926,
"s": 41913,
"text": "Insert: O(l)"
},
{
"code": null,
"e": 41945,
"s": 41926,
"text": "Not cache friendly"
},
{
"code": null,
"e": 41981,
"s": 41945,
"text": "Java 8 onwards use this for HashMap"
},
{
"code": null,
"e": 42815,
"s": 41981,
"text": "YouTubeGeeksforGeeks507K subscribersHashing | Set 2 (Separate Chaining) | 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 / 7:49•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=_xA8UvfOGgU\" 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": 42866,
"s": 42815,
"text": "Next Post: Open Addressing for Collision Handling "
},
{
"code": null,
"e": 43073,
"s": 42866,
"text": "References: http://courses.csail.mit.edu/6.006/fall09/lecture_notes/lecture05.pdf Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 43090,
"s": 43073,
"text": "ConnorFehrenbach"
},
{
"code": null,
"e": 43107,
"s": 43090,
"text": "NandkishorNangre"
},
{
"code": null,
"e": 43115,
"s": 43107,
"text": "scisaif"
},
{
"code": null,
"e": 43120,
"s": 43115,
"text": "Hash"
},
{
"code": null,
"e": 43125,
"s": 43120,
"text": "Hash"
},
{
"code": null,
"e": 43223,
"s": 43125,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43259,
"s": 43223,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 43286,
"s": 43259,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 43312,
"s": 43286,
"text": "Sort string of characters"
},
{
"code": null,
"e": 43351,
"s": 43312,
"text": "Counting frequencies of array elements"
},
{
"code": null,
"e": 43385,
"s": 43351,
"text": "Most frequent element in an array"
},
{
"code": null,
"e": 43419,
"s": 43385,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 43451,
"s": 43419,
"text": "Longest Consecutive Subsequence"
},
{
"code": null,
"e": 43505,
"s": 43451,
"text": "Return maximum occurring character in an input string"
},
{
"code": null,
"e": 43543,
"s": 43505,
"text": "C++ program for hashing with chaining"
}
] |
Properties of Fourier Transform - GeeksforGeeks | 04 Dec, 2019
Fourier Transform: Fourier transform is the input tool that is used to decompose an image into its sine and cosine components.
Properties of Fourier Transform:
Linearity:Addition of two functions corresponding to the addition of the two frequency spectrum is called the linearity. If we multiply a function by a constant, the Fourier transform of the resultant function is multiplied by the same constant. The Fourier transform of sum of two or more functions is the sum of the Fourier transforms of the functions.Case I.
If h(x) -> H(f) then ah(x) -> aH(f)
Case II.
If h(x) -> H(f) and g(x) -> G(f) then h(x)+g(x) -> H(f)+G(f)
Case I.
If h(x) -> H(f) then ah(x) -> aH(f)
Case II.
If h(x) -> H(f) and g(x) -> G(f) then h(x)+g(x) -> H(f)+G(f)
Scaling:Scaling is the method that is used to the change the range of the independent variables or features of data. If we stretch a function by the factor in the time domain then squeeze the Fourier transform by the same factor in the frequency domain.If f(t) -> F(w) then f(at) -> (1/|a|)F(w/a)
If f(t) -> F(w) then f(at) -> (1/|a|)F(w/a)
Differentiation:Differentiating function with respect to time yields to the constant multiple of the initial function.If f(t) -> F(w) then f'(t) -> jwF(w)
If f(t) -> F(w) then f'(t) -> jwF(w)
Convolution:It includes the multiplication of two functions. The Fourier transform of a convolution of two functions is the point-wise product of their respective Fourier transforms.If f(t) -> F(w) and g(t) -> G(w)
then f(t)*g(t) -> F(w)*G(w)
If f(t) -> F(w) and g(t) -> G(w)
then f(t)*g(t) -> F(w)*G(w)
Frequency Shift:Frequency is shifted according to the co-ordinates. There is a duality between the time and frequency domains and frequency shift affects the time shift.If f(t) -> F(w) then f(t)exp[jw't] -> F(w-w')
If f(t) -> F(w) then f(t)exp[jw't] -> F(w-w')
Time Shift:The time variable shift also effects the frequency function. The time shifting property concludes that a linear displacement in time corresponds to a linear phase factor in the frequency domain.If f(t) -> F(w) then f(t-t') -> F(w)exp[-jwt']
If f(t) -> F(w) then f(t-t') -> F(w)exp[-jwt']
computer-graphics
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Activation Functions
Characteristics of Internet of Things
Advantages and Disadvantages of OOP
Sensors in Internet of Things(IoT)
Challenges in Internet of things (IoT)
Election algorithm and distributed processing
Introduction to Internet of Things (IoT) | Set 1
Introduction to Electronic Mail
Communication Models in IoT (Internet of Things )
Introduction to Parallel Computing | [
{
"code": null,
"e": 25893,
"s": 25865,
"text": "\n04 Dec, 2019"
},
{
"code": null,
"e": 26020,
"s": 25893,
"text": "Fourier Transform: Fourier transform is the input tool that is used to decompose an image into its sine and cosine components."
},
{
"code": null,
"e": 26053,
"s": 26020,
"text": "Properties of Fourier Transform:"
},
{
"code": null,
"e": 26523,
"s": 26053,
"text": "Linearity:Addition of two functions corresponding to the addition of the two frequency spectrum is called the linearity. If we multiply a function by a constant, the Fourier transform of the resultant function is multiplied by the same constant. The Fourier transform of sum of two or more functions is the sum of the Fourier transforms of the functions.Case I.\n If h(x) -> H(f) then ah(x) -> aH(f)\nCase II.\n If h(x) -> H(f) and g(x) -> G(f) then h(x)+g(x) -> H(f)+G(f)"
},
{
"code": null,
"e": 26639,
"s": 26523,
"text": "Case I.\n If h(x) -> H(f) then ah(x) -> aH(f)\nCase II.\n If h(x) -> H(f) and g(x) -> G(f) then h(x)+g(x) -> H(f)+G(f)"
},
{
"code": null,
"e": 26936,
"s": 26639,
"text": "Scaling:Scaling is the method that is used to the change the range of the independent variables or features of data. If we stretch a function by the factor in the time domain then squeeze the Fourier transform by the same factor in the frequency domain.If f(t) -> F(w) then f(at) -> (1/|a|)F(w/a)"
},
{
"code": null,
"e": 26980,
"s": 26936,
"text": "If f(t) -> F(w) then f(at) -> (1/|a|)F(w/a)"
},
{
"code": null,
"e": 27135,
"s": 26980,
"text": "Differentiation:Differentiating function with respect to time yields to the constant multiple of the initial function.If f(t) -> F(w) then f'(t) -> jwF(w)"
},
{
"code": null,
"e": 27172,
"s": 27135,
"text": "If f(t) -> F(w) then f'(t) -> jwF(w)"
},
{
"code": null,
"e": 27415,
"s": 27172,
"text": "Convolution:It includes the multiplication of two functions. The Fourier transform of a convolution of two functions is the point-wise product of their respective Fourier transforms.If f(t) -> F(w) and g(t) -> G(w)\nthen f(t)*g(t) -> F(w)*G(w)"
},
{
"code": null,
"e": 27476,
"s": 27415,
"text": "If f(t) -> F(w) and g(t) -> G(w)\nthen f(t)*g(t) -> F(w)*G(w)"
},
{
"code": null,
"e": 27691,
"s": 27476,
"text": "Frequency Shift:Frequency is shifted according to the co-ordinates. There is a duality between the time and frequency domains and frequency shift affects the time shift.If f(t) -> F(w) then f(t)exp[jw't] -> F(w-w')"
},
{
"code": null,
"e": 27737,
"s": 27691,
"text": "If f(t) -> F(w) then f(t)exp[jw't] -> F(w-w')"
},
{
"code": null,
"e": 27989,
"s": 27737,
"text": "Time Shift:The time variable shift also effects the frequency function. The time shifting property concludes that a linear displacement in time corresponds to a linear phase factor in the frequency domain.If f(t) -> F(w) then f(t-t') -> F(w)exp[-jwt']"
},
{
"code": null,
"e": 28036,
"s": 27989,
"text": "If f(t) -> F(w) then f(t-t') -> F(w)exp[-jwt']"
},
{
"code": null,
"e": 28054,
"s": 28036,
"text": "computer-graphics"
},
{
"code": null,
"e": 28059,
"s": 28054,
"text": "Misc"
},
{
"code": null,
"e": 28064,
"s": 28059,
"text": "Misc"
},
{
"code": null,
"e": 28069,
"s": 28064,
"text": "Misc"
},
{
"code": null,
"e": 28167,
"s": 28069,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28188,
"s": 28167,
"text": "Activation Functions"
},
{
"code": null,
"e": 28226,
"s": 28188,
"text": "Characteristics of Internet of Things"
},
{
"code": null,
"e": 28262,
"s": 28226,
"text": "Advantages and Disadvantages of OOP"
},
{
"code": null,
"e": 28297,
"s": 28262,
"text": "Sensors in Internet of Things(IoT)"
},
{
"code": null,
"e": 28336,
"s": 28297,
"text": "Challenges in Internet of things (IoT)"
},
{
"code": null,
"e": 28382,
"s": 28336,
"text": "Election algorithm and distributed processing"
},
{
"code": null,
"e": 28431,
"s": 28382,
"text": "Introduction to Internet of Things (IoT) | Set 1"
},
{
"code": null,
"e": 28463,
"s": 28431,
"text": "Introduction to Electronic Mail"
},
{
"code": null,
"e": 28513,
"s": 28463,
"text": "Communication Models in IoT (Internet of Things )"
}
] |
How to Generate a Random Directed Acyclic Graph for a Given Number of Edges in Java? - GeeksforGeeks | 04 Dec, 2020
A Directed Acyclic Graph is a directed graph with no directed cycles. In a directed graph, the edges are connected so that each edge only goes one way. A directed acyclic graph means that the graph is not cyclic, or that it is impossible to start at one point in the graph and traverse the entire graph. Each edge is directed from an earlier edge to a later edge.
To generate a random DAG(Directed Acyclic Graph) for a given number of edges.
Directed Acyclic Graph
Examples:
Input:
Enter the number of Edges :
20
Output:
The Generated Random Graph is :
1 -> { Isolated Vertex! }
2 -> { Isolated Vertex! }
3 -> { 18 }
4 -> { 5 }
5 -> { 16 8 }
6 -> { Isolated Vertex! }
7 -> { Isolated Vertex! }
8 -> { }
9 -> { Isolated Vertex! }
10 -> { Isolated Vertex! }
11 -> { Isolated Vertex! }
12 -> { }
13 -> { Isolated Vertex! }
14 -> { 18 }
15 -> { Isolated Vertex! }
16 -> { }
17 -> { 19 3 5 4 }
18 -> { }
19 -> { }
20 -> { 12 }
Input:
Enter the number of Edges :
30
Output:
The Generated Random Graph is :
1 -> { 12 8 7 16 5 11 }
2 -> { 16 }
3 -> { }
4 -> { 10 }
5 -> { }
6 -> { 7 }
7 -> { 5 }
8 -> { 7 12 20 }
9 -> { 16 12 }
10 -> { 3 }
11 -> { 17 14 }
12 -> { 4 3 }
13 -> { 12 5 }
14 -> { 15 17 }
15 -> { }
16 -> { 20 }
17 -> { 20 13 }
18 -> { }
19 -> { 12 11 }
20 -> { 18 }
Approach:
Take the input of the number of edges for the random Directed Acyclic Graph.
Build a connection between two random vertex and check if any cycle is generated due to this edge.
If any cycle is found, this edge is discarded and a random vertex pair is generated again.
Implementation:
Java
// Java program to Generate a Random Directed// Acyclic Graph for a Given Number of Edges import java.io.*;import java.util.*;import java.util.Random; public class RandomDAG { // The maximum number of vertex for the random graph static int maxVertex = 20; // Function to check for cycle, upon addition of a new // edge in the graph public static boolean checkAcyclic(int[][] edge, int ed, boolean[] check, int v) { int i; boolean value; // If the current vertex is visited already, then // the graph contains cycle if (check[v] == true) return false; else { check[v] = true; // For each vertex, go for all the vertex // connected to it for (i = ed; i >= 0; i--) { if (edge[i][0] == v) return checkAcyclic(edge, ed, check, edge[i][1]); } } // In case, if the path ends then reassign the // vertexes visited in that path to false again check[v] = false; if (i == 0) return true; return true; } // Function to generate random graph public static void generateRandomGraphs(int e) { int i = 0, j = 0, count = 0; int[][] edge = new int[e][2]; boolean[] check = new boolean[21]; Random rand = new Random(); // Build a connection between two random vertex while (i < e) { edge[i][0] = rand.nextInt(maxVertex) + 1; edge[i][1] = rand.nextInt(maxVertex) + 1; for (j = 1; j <= 20; j++) check[j] = false; if (checkAcyclic(edge, i, check, edge[i][0]) == true) i++; // Check for cycle and if found discard this // edge and generate random vertex pair again } System.out.println("The Generated Random Graph is :"); // Print the Graph for (i = 0; i < maxVertex; i++) { count = 0; System.out.print((i + 1) + " -> { "); for (j = 0; j < e; j++) { if (edge[j][0] == i + 1) { System.out.print(edge[j][1] + " "); count++; } else if (edge[j][1] == i + 1) { count++; } else if (j == e - 1 && count == 0) System.out.print("Isolated Vertex!"); } System.out.print(" }\n"); } } public static void main(String args[]) throws Exception { int e = 4; System.out.println("Enter the number of Edges :"+ e); // Function to generate a Random Directed Acyclic // Graph generateRandomGraphs(e); }}
Enter the number of Edges :4
The Generated Random Graph is :
1 -> { Isolated Vertex! }
2 -> { 10 }
3 -> { }
4 -> { Isolated Vertex! }
5 -> { }
6 -> { 11 }
7 -> { Isolated Vertex! }
8 -> { Isolated Vertex! }
9 -> { Isolated Vertex! }
10 -> { 5 }
11 -> { }
12 -> { Isolated Vertex! }
13 -> { Isolated Vertex! }
14 -> { Isolated Vertex! }
15 -> { 3 }
16 -> { Isolated Vertex! }
17 -> { Isolated Vertex! }
18 -> { Isolated Vertex! }
19 -> { Isolated Vertex! }
20 -> { Isolated Vertex! }
Picked
Java
Java Programs
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
Initialize an ArrayList in Java
Stack Class in Java
Initializing a List in Java
Convert a String to Character Array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class | [
{
"code": null,
"e": 25845,
"s": 25817,
"text": "\n04 Dec, 2020"
},
{
"code": null,
"e": 26209,
"s": 25845,
"text": "A Directed Acyclic Graph is a directed graph with no directed cycles. In a directed graph, the edges are connected so that each edge only goes one way. A directed acyclic graph means that the graph is not cyclic, or that it is impossible to start at one point in the graph and traverse the entire graph. Each edge is directed from an earlier edge to a later edge."
},
{
"code": null,
"e": 26287,
"s": 26209,
"text": "To generate a random DAG(Directed Acyclic Graph) for a given number of edges."
},
{
"code": null,
"e": 26310,
"s": 26287,
"text": "Directed Acyclic Graph"
},
{
"code": null,
"e": 26320,
"s": 26310,
"text": "Examples:"
},
{
"code": null,
"e": 27159,
"s": 26320,
"text": "Input:\nEnter the number of Edges :\n20\nOutput: \nThe Generated Random Graph is :\n1 -> { Isolated Vertex! }\n2 -> { Isolated Vertex! }\n3 -> { 18 }\n4 -> { 5 }\n5 -> { 16 8 }\n6 -> { Isolated Vertex! }\n7 -> { Isolated Vertex! }\n8 -> { }\n9 -> { Isolated Vertex! }\n10 -> { Isolated Vertex! }\n11 -> { Isolated Vertex! }\n12 -> { }\n13 -> { Isolated Vertex! }\n14 -> { 18 }\n15 -> { Isolated Vertex! }\n16 -> { }\n17 -> { 19 3 5 4 }\n18 -> { }\n19 -> { }\n20 -> { 12 }\n\nInput:\nEnter the number of Edges :\n30\nOutput: \nThe Generated Random Graph is :\n1 -> { 12 8 7 16 5 11 } \n2 -> { 16 }\n3 -> { }\n4 -> { 10 }\n5 -> { }\n6 -> { 7 }\n7 -> { 5 }\n8 -> { 7 12 20 }\n9 -> { 16 12 }\n10 -> { 3 }\n11 -> { 17 14 }\n12 -> { 4 3 }\n13 -> { 12 5 }\n14 -> { 15 17 }\n15 -> { }\n16 -> { 20 }\n17 -> { 20 13 }\n18 -> { }\n19 -> { 12 11 }\n20 -> { 18 }"
},
{
"code": null,
"e": 27169,
"s": 27159,
"text": "Approach:"
},
{
"code": null,
"e": 27246,
"s": 27169,
"text": "Take the input of the number of edges for the random Directed Acyclic Graph."
},
{
"code": null,
"e": 27345,
"s": 27246,
"text": "Build a connection between two random vertex and check if any cycle is generated due to this edge."
},
{
"code": null,
"e": 27436,
"s": 27345,
"text": "If any cycle is found, this edge is discarded and a random vertex pair is generated again."
},
{
"code": null,
"e": 27452,
"s": 27436,
"text": "Implementation:"
},
{
"code": null,
"e": 27457,
"s": 27452,
"text": "Java"
},
{
"code": "// Java program to Generate a Random Directed// Acyclic Graph for a Given Number of Edges import java.io.*;import java.util.*;import java.util.Random; public class RandomDAG { // The maximum number of vertex for the random graph static int maxVertex = 20; // Function to check for cycle, upon addition of a new // edge in the graph public static boolean checkAcyclic(int[][] edge, int ed, boolean[] check, int v) { int i; boolean value; // If the current vertex is visited already, then // the graph contains cycle if (check[v] == true) return false; else { check[v] = true; // For each vertex, go for all the vertex // connected to it for (i = ed; i >= 0; i--) { if (edge[i][0] == v) return checkAcyclic(edge, ed, check, edge[i][1]); } } // In case, if the path ends then reassign the // vertexes visited in that path to false again check[v] = false; if (i == 0) return true; return true; } // Function to generate random graph public static void generateRandomGraphs(int e) { int i = 0, j = 0, count = 0; int[][] edge = new int[e][2]; boolean[] check = new boolean[21]; Random rand = new Random(); // Build a connection between two random vertex while (i < e) { edge[i][0] = rand.nextInt(maxVertex) + 1; edge[i][1] = rand.nextInt(maxVertex) + 1; for (j = 1; j <= 20; j++) check[j] = false; if (checkAcyclic(edge, i, check, edge[i][0]) == true) i++; // Check for cycle and if found discard this // edge and generate random vertex pair again } System.out.println(\"The Generated Random Graph is :\"); // Print the Graph for (i = 0; i < maxVertex; i++) { count = 0; System.out.print((i + 1) + \" -> { \"); for (j = 0; j < e; j++) { if (edge[j][0] == i + 1) { System.out.print(edge[j][1] + \" \"); count++; } else if (edge[j][1] == i + 1) { count++; } else if (j == e - 1 && count == 0) System.out.print(\"Isolated Vertex!\"); } System.out.print(\" }\\n\"); } } public static void main(String args[]) throws Exception { int e = 4; System.out.println(\"Enter the number of Edges :\"+ e); // Function to generate a Random Directed Acyclic // Graph generateRandomGraphs(e); }}",
"e": 30533,
"s": 27457,
"text": null
},
{
"code": null,
"e": 31024,
"s": 30533,
"text": "Enter the number of Edges :4\nThe Generated Random Graph is :\n1 -> { Isolated Vertex! }\n2 -> { 10 }\n3 -> { }\n4 -> { Isolated Vertex! }\n5 -> { }\n6 -> { 11 }\n7 -> { Isolated Vertex! }\n8 -> { Isolated Vertex! }\n9 -> { Isolated Vertex! }\n10 -> { 5 }\n11 -> { }\n12 -> { Isolated Vertex! }\n13 -> { Isolated Vertex! }\n14 -> { Isolated Vertex! }\n15 -> { 3 }\n16 -> { Isolated Vertex! }\n17 -> { Isolated Vertex! }\n18 -> { Isolated Vertex! }\n19 -> { Isolated Vertex! }\n20 -> { Isolated Vertex! }\n"
},
{
"code": null,
"e": 31031,
"s": 31024,
"text": "Picked"
},
{
"code": null,
"e": 31036,
"s": 31031,
"text": "Java"
},
{
"code": null,
"e": 31050,
"s": 31036,
"text": "Java Programs"
},
{
"code": null,
"e": 31055,
"s": 31050,
"text": "Java"
},
{
"code": null,
"e": 31153,
"s": 31055,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31172,
"s": 31153,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 31187,
"s": 31172,
"text": "Stream In Java"
},
{
"code": null,
"e": 31205,
"s": 31187,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 31237,
"s": 31205,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 31257,
"s": 31237,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 31285,
"s": 31257,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 31329,
"s": 31285,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 31355,
"s": 31329,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 31389,
"s": 31355,
"text": "Convert Double to Integer in Java"
}
] |
Priority Inheritance Protocol (PIP) in Synchronization - GeeksforGeeks | 25 May, 2020
Prerequisite – Introduction of Process SynchronizationPriority Inheritance Protocol (PIP) is a technique which is used for sharing critical resources among different tasks. This allows the sharing of critical resources among different without the occurrence of unbounded priority inversions.
Basic Concept of PIP :The basic concept of PIP is that when a task goes through priority inversion, the priority of the lower priority task which has the critical resource is increased by the priority inheritance mechanism. It allows this task to use the critical resource as early as possible without going through the preemption. It avoids the unbounded priority inversion.
Working of PIP :
When several tasks are waiting for the same critical resource, the task which is currently holding this critical resource is given the highest priority among all the tasks which are waiting for the same critical resource.
Now after the lower priority task having the critical resource is given the highest priority then the intermediate priority tasks can not preempt this task. This helps in avoiding the unbounded priority inversion.
When the task which is given the highest priority among all tasks, finishes the job and releases the critical resource then it gets back to its original priority value (which may be less or equal).
If a task is holding multiple critical resources then after releasing one critical resource it can not go back to it original priority value. In this case it inherits the highest priority among all tasks waiting for the same critical resource.
If the critical resource is free then
allocate the resource
If the critical resource is held by higher priority task then
wait for the resource
If the critical resource is held by lower priority task
{
lower priority task is provided the highest priority
other tasks wait for the resource
}
Advantages of PIP :Priority Inheritance protocol has the following advantages:
It allows the different priority tasks to share the critical resources.
The most prominent advantage with Priority Inheritance Protocol is that it avoids the unbounded priority inversion.
Disadvantages of PIP :Priority Inheritance Protocol has two major problems which may occur:
Deadlock –There is possibility of deadlock in the priority inheritance protocol.For example, there are two tasks T1 and T2. Suppose T1 has the higher priority than T2. T2 starts running first and holds the critical resource CR2.After that, T1 arrives and preempts T2. T1 holds critical resource CR1 and also tries to hold CR2 which is held by T2. Now T1 blocks and T2 inherits the priority of T1 according to PIP. T2 starts execution and now T2 tries to hold CR1 which is held by T1.Thus, both T1 and T2 are deadlocked.
For example, there are two tasks T1 and T2. Suppose T1 has the higher priority than T2. T2 starts running first and holds the critical resource CR2.
After that, T1 arrives and preempts T2. T1 holds critical resource CR1 and also tries to hold CR2 which is held by T2. Now T1 blocks and T2 inherits the priority of T1 according to PIP. T2 starts execution and now T2 tries to hold CR1 which is held by T1.
Thus, both T1 and T2 are deadlocked.
Chain Blocking –When a task goes through priority inversion each time it needs a resource then this process is called chain blocking.For example, there are two tasks T1 and T2. Suppose T1 has the higher priority than T2. T2 holds the critical resource CR1 and CR2. T1 arrives and requests for CR1. T2 undergoes the priority inversion according to PIP.Now, T1 request CR2, again T2 goes for priority inversion according to PIP.Hence, multiple priority inversion to hold the critical resource leads to chain blocking.
For example, there are two tasks T1 and T2. Suppose T1 has the higher priority than T2. T2 holds the critical resource CR1 and CR2. T1 arrives and requests for CR1. T2 undergoes the priority inversion according to PIP.
Now, T1 request CR2, again T2 goes for priority inversion according to PIP.
Hence, multiple priority inversion to hold the critical resource leads to chain blocking.
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Memory Management in Operating System
File Allocation Methods
Logical and Physical Address in Operating System
Difference between Internal and External fragmentation
File Access Methods in Operating System
Memory Hierarchy Design and its Characteristics
File Systems in Operating System
Process Table and Process Control Block (PCB)
States of a Process in Operating Systems
Introduction of Process Management | [
{
"code": null,
"e": 25737,
"s": 25709,
"text": "\n25 May, 2020"
},
{
"code": null,
"e": 26029,
"s": 25737,
"text": "Prerequisite – Introduction of Process SynchronizationPriority Inheritance Protocol (PIP) is a technique which is used for sharing critical resources among different tasks. This allows the sharing of critical resources among different without the occurrence of unbounded priority inversions."
},
{
"code": null,
"e": 26405,
"s": 26029,
"text": "Basic Concept of PIP :The basic concept of PIP is that when a task goes through priority inversion, the priority of the lower priority task which has the critical resource is increased by the priority inheritance mechanism. It allows this task to use the critical resource as early as possible without going through the preemption. It avoids the unbounded priority inversion."
},
{
"code": null,
"e": 26422,
"s": 26405,
"text": "Working of PIP :"
},
{
"code": null,
"e": 26644,
"s": 26422,
"text": "When several tasks are waiting for the same critical resource, the task which is currently holding this critical resource is given the highest priority among all the tasks which are waiting for the same critical resource."
},
{
"code": null,
"e": 26858,
"s": 26644,
"text": "Now after the lower priority task having the critical resource is given the highest priority then the intermediate priority tasks can not preempt this task. This helps in avoiding the unbounded priority inversion."
},
{
"code": null,
"e": 27056,
"s": 26858,
"text": "When the task which is given the highest priority among all tasks, finishes the job and releases the critical resource then it gets back to its original priority value (which may be less or equal)."
},
{
"code": null,
"e": 27300,
"s": 27056,
"text": "If a task is holding multiple critical resources then after releasing one critical resource it can not go back to it original priority value. In this case it inherits the highest priority among all tasks waiting for the same critical resource."
},
{
"code": null,
"e": 27634,
"s": 27300,
"text": "If the critical resource is free then\n allocate the resource\nIf the critical resource is held by higher priority task then\n wait for the resource\nIf the critical resource is held by lower priority task\n { \n lower priority task is provided the highest priority\n other tasks wait for the resource\n } "
},
{
"code": null,
"e": 27713,
"s": 27634,
"text": "Advantages of PIP :Priority Inheritance protocol has the following advantages:"
},
{
"code": null,
"e": 27785,
"s": 27713,
"text": "It allows the different priority tasks to share the critical resources."
},
{
"code": null,
"e": 27901,
"s": 27785,
"text": "The most prominent advantage with Priority Inheritance Protocol is that it avoids the unbounded priority inversion."
},
{
"code": null,
"e": 27993,
"s": 27901,
"text": "Disadvantages of PIP :Priority Inheritance Protocol has two major problems which may occur:"
},
{
"code": null,
"e": 28513,
"s": 27993,
"text": "Deadlock –There is possibility of deadlock in the priority inheritance protocol.For example, there are two tasks T1 and T2. Suppose T1 has the higher priority than T2. T2 starts running first and holds the critical resource CR2.After that, T1 arrives and preempts T2. T1 holds critical resource CR1 and also tries to hold CR2 which is held by T2. Now T1 blocks and T2 inherits the priority of T1 according to PIP. T2 starts execution and now T2 tries to hold CR1 which is held by T1.Thus, both T1 and T2 are deadlocked."
},
{
"code": null,
"e": 28662,
"s": 28513,
"text": "For example, there are two tasks T1 and T2. Suppose T1 has the higher priority than T2. T2 starts running first and holds the critical resource CR2."
},
{
"code": null,
"e": 28918,
"s": 28662,
"text": "After that, T1 arrives and preempts T2. T1 holds critical resource CR1 and also tries to hold CR2 which is held by T2. Now T1 blocks and T2 inherits the priority of T1 according to PIP. T2 starts execution and now T2 tries to hold CR1 which is held by T1."
},
{
"code": null,
"e": 28955,
"s": 28918,
"text": "Thus, both T1 and T2 are deadlocked."
},
{
"code": null,
"e": 29471,
"s": 28955,
"text": "Chain Blocking –When a task goes through priority inversion each time it needs a resource then this process is called chain blocking.For example, there are two tasks T1 and T2. Suppose T1 has the higher priority than T2. T2 holds the critical resource CR1 and CR2. T1 arrives and requests for CR1. T2 undergoes the priority inversion according to PIP.Now, T1 request CR2, again T2 goes for priority inversion according to PIP.Hence, multiple priority inversion to hold the critical resource leads to chain blocking."
},
{
"code": null,
"e": 29690,
"s": 29471,
"text": "For example, there are two tasks T1 and T2. Suppose T1 has the higher priority than T2. T2 holds the critical resource CR1 and CR2. T1 arrives and requests for CR1. T2 undergoes the priority inversion according to PIP."
},
{
"code": null,
"e": 29766,
"s": 29690,
"text": "Now, T1 request CR2, again T2 goes for priority inversion according to PIP."
},
{
"code": null,
"e": 29856,
"s": 29766,
"text": "Hence, multiple priority inversion to hold the critical resource leads to chain blocking."
},
{
"code": null,
"e": 29874,
"s": 29856,
"text": "Operating Systems"
},
{
"code": null,
"e": 29892,
"s": 29874,
"text": "Operating Systems"
},
{
"code": null,
"e": 29990,
"s": 29892,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30028,
"s": 29990,
"text": "Memory Management in Operating System"
},
{
"code": null,
"e": 30052,
"s": 30028,
"text": "File Allocation Methods"
},
{
"code": null,
"e": 30101,
"s": 30052,
"text": "Logical and Physical Address in Operating System"
},
{
"code": null,
"e": 30156,
"s": 30101,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 30196,
"s": 30156,
"text": "File Access Methods in Operating System"
},
{
"code": null,
"e": 30244,
"s": 30196,
"text": "Memory Hierarchy Design and its Characteristics"
},
{
"code": null,
"e": 30277,
"s": 30244,
"text": "File Systems in Operating System"
},
{
"code": null,
"e": 30323,
"s": 30277,
"text": "Process Table and Process Control Block (PCB)"
},
{
"code": null,
"e": 30364,
"s": 30323,
"text": "States of a Process in Operating Systems"
}
] |
How to remove close button from jQuery UI dialog using jQuery ? - GeeksforGeeks | 30 Dec, 2021
In this article, we will learn how to remove the close button on the jQuery UI dialog using JavaScript, This can be achieved using the hide() method. jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library. A dialog box is a temporary window. An application creates a dialog box to retrieve user input, prompt the user for additional information for menu items.
Syntax:
$("Selector").dialog();
Approach:
Firstly, add the below jQuery and JQuery UI CDN links to the script or download them to your local machine.<script src=”http://code.jquery.com/jquery-2.1.3.js”></script><script src=”http://code.jquery.com/ui/1.11.2/jquery-ui.js”></script>
<script src=”http://code.jquery.com/jquery-2.1.3.js”></script><script src=”http://code.jquery.com/ui/1.11.2/jquery-ui.js”></script>
Create a div in the body, for the dialog box and keep id as demoDialog.
Now, using the jQuery dialog() method, create the jQuery UI dialog.
Example 1: This example illustrates the dialog box with a close button.
HTML
<!DOCTYPE html><html> <head> <title>jQuery UI Dialog : demo dialog</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/dark-hive/jquery-ui.css"> <script src="https://code.jquery.com/jquery-2.1.3.js"> </script> <script src="https://code.jquery.com/ui/1.11.2/jquery-ui.js"> </script> <script> $(document).ready(function() { $("#demoDialog").dialog(); }); </script></head> <body> <h1> Dialog Widget with Close button</h1> <div id="demoDialog" title="My Dialog Box"> <p>Welcome to GeeksforGeeks</p> </div></body> </html>
Output:
Here, we will see removing the close button on the jQuery UI dialog using JavaScript.
Syntax:
$("Selector").dialog({
open: function () { $(".ui-dialog-titlebar-close").hide(); }
});
Approach: Create a div in the body, for the dialog box and keep id as demoDialog. Now, using the jQuery dialog() method, create the jQuery UI dialog, and in the open event, the handler will write a function to remove the hide button. Select the close button using the class “ui-dialog-titlebar-close” and hide it using the hide() method.
Example 2: This example illustrates the removing the close button from the dialog box.
HTML
<!DOCTYPE html><html> <head> <title>jQuery UI Dialog : demo dialog</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/dark-hive/jquery-ui.css"> <script src="https://code.jquery.com/jquery-2.1.3.js"> </script> <script src="https://code.jquery.com/ui/1.11.2/jquery-ui.js"> </script> <script> $(function() { $("#demoDialog").dialog({ open: function() { $(".ui-dialog-titlebar-close").hide(); } }); }); </script></head> <body> <h1> Dialog Widget without Close button</h1> <div id="demoDialog" title="My Dialog Box"> <p>Welcome to GeeksforGeeks</p> </div></body> </html>
Output:
jQuery-Questions
jQuery-UI
jQuery-UI-Dialog
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show and Hide div elements using radio buttons?
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
jQuery | removeAttr() with Examples
How to get the value in an input text box using jQuery ?
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": 27144,
"s": 27116,
"text": "\n30 Dec, 2021"
},
{
"code": null,
"e": 27584,
"s": 27144,
"text": "In this article, we will learn how to remove the close button on the jQuery UI dialog using JavaScript, This can be achieved using the hide() method. jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library. A dialog box is a temporary window. An application creates a dialog box to retrieve user input, prompt the user for additional information for menu items."
},
{
"code": null,
"e": 27592,
"s": 27584,
"text": "Syntax:"
},
{
"code": null,
"e": 27616,
"s": 27592,
"text": "$(\"Selector\").dialog();"
},
{
"code": null,
"e": 27626,
"s": 27616,
"text": "Approach:"
},
{
"code": null,
"e": 27865,
"s": 27626,
"text": "Firstly, add the below jQuery and JQuery UI CDN links to the script or download them to your local machine.<script src=”http://code.jquery.com/jquery-2.1.3.js”></script><script src=”http://code.jquery.com/ui/1.11.2/jquery-ui.js”></script>"
},
{
"code": null,
"e": 27997,
"s": 27865,
"text": "<script src=”http://code.jquery.com/jquery-2.1.3.js”></script><script src=”http://code.jquery.com/ui/1.11.2/jquery-ui.js”></script>"
},
{
"code": null,
"e": 28069,
"s": 27997,
"text": "Create a div in the body, for the dialog box and keep id as demoDialog."
},
{
"code": null,
"e": 28137,
"s": 28069,
"text": "Now, using the jQuery dialog() method, create the jQuery UI dialog."
},
{
"code": null,
"e": 28209,
"s": 28137,
"text": "Example 1: This example illustrates the dialog box with a close button."
},
{
"code": null,
"e": 28214,
"s": 28209,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>jQuery UI Dialog : demo dialog</title> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/dark-hive/jquery-ui.css\"> <script src=\"https://code.jquery.com/jquery-2.1.3.js\"> </script> <script src=\"https://code.jquery.com/ui/1.11.2/jquery-ui.js\"> </script> <script> $(document).ready(function() { $(\"#demoDialog\").dialog(); }); </script></head> <body> <h1> Dialog Widget with Close button</h1> <div id=\"demoDialog\" title=\"My Dialog Box\"> <p>Welcome to GeeksforGeeks</p> </div></body> </html>",
"e": 28956,
"s": 28214,
"text": null
},
{
"code": null,
"e": 28964,
"s": 28956,
"text": "Output:"
},
{
"code": null,
"e": 29050,
"s": 28964,
"text": "Here, we will see removing the close button on the jQuery UI dialog using JavaScript."
},
{
"code": null,
"e": 29058,
"s": 29050,
"text": "Syntax:"
},
{
"code": null,
"e": 29154,
"s": 29058,
"text": "$(\"Selector\").dialog({\n open: function () { $(\".ui-dialog-titlebar-close\").hide(); }\n});"
},
{
"code": null,
"e": 29493,
"s": 29154,
"text": "Approach: Create a div in the body, for the dialog box and keep id as demoDialog. Now, using the jQuery dialog() method, create the jQuery UI dialog, and in the open event, the handler will write a function to remove the hide button. Select the close button using the class “ui-dialog-titlebar-close” and hide it using the hide() method. "
},
{
"code": null,
"e": 29580,
"s": 29493,
"text": "Example 2: This example illustrates the removing the close button from the dialog box."
},
{
"code": null,
"e": 29585,
"s": 29580,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>jQuery UI Dialog : demo dialog</title> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/dark-hive/jquery-ui.css\"> <script src=\"https://code.jquery.com/jquery-2.1.3.js\"> </script> <script src=\"https://code.jquery.com/ui/1.11.2/jquery-ui.js\"> </script> <script> $(function() { $(\"#demoDialog\").dialog({ open: function() { $(\".ui-dialog-titlebar-close\").hide(); } }); }); </script></head> <body> <h1> Dialog Widget without Close button</h1> <div id=\"demoDialog\" title=\"My Dialog Box\"> <p>Welcome to GeeksforGeeks</p> </div></body> </html>",
"e": 30437,
"s": 29585,
"text": null
},
{
"code": null,
"e": 30445,
"s": 30437,
"text": "Output:"
},
{
"code": null,
"e": 30462,
"s": 30445,
"text": "jQuery-Questions"
},
{
"code": null,
"e": 30472,
"s": 30462,
"text": "jQuery-UI"
},
{
"code": null,
"e": 30489,
"s": 30472,
"text": "jQuery-UI-Dialog"
},
{
"code": null,
"e": 30496,
"s": 30489,
"text": "Picked"
},
{
"code": null,
"e": 30503,
"s": 30496,
"text": "JQuery"
},
{
"code": null,
"e": 30520,
"s": 30503,
"text": "Web Technologies"
},
{
"code": null,
"e": 30618,
"s": 30520,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30673,
"s": 30618,
"text": "How to Show and Hide div elements using radio buttons?"
},
{
"code": null,
"e": 30746,
"s": 30673,
"text": "How to prevent Body from scrolling when a modal is opened using jQuery ?"
},
{
"code": null,
"e": 30769,
"s": 30746,
"text": "jQuery | ajax() Method"
},
{
"code": null,
"e": 30805,
"s": 30769,
"text": "jQuery | removeAttr() with Examples"
},
{
"code": null,
"e": 30862,
"s": 30805,
"text": "How to get the value in an input text box using jQuery ?"
},
{
"code": null,
"e": 30902,
"s": 30862,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30935,
"s": 30902,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30980,
"s": 30935,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31023,
"s": 30980,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
HTML | <input type="tel"> - GeeksforGeeks | 31 May, 2019
The HTML <input type=”tel”> is used to define a field that entering a user telephone Number.
Syntax:
<input type="tel">
Example:
<!DOCTYPE html><html> <head> <title> HTML Input Type Tel </title></head><style> #Geek_p { font-size: 30px; color: green; }</style> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h2>HTML <Input Type="tel"> </h2> <form> Phone No.: <input type="tel"> <br> <br> </form></body> </html>
Output:
Supported Browsers:
Google Chrome
Firefox
Edge
Opera
Apple Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26139,
"s": 26111,
"text": "\n31 May, 2019"
},
{
"code": null,
"e": 26232,
"s": 26139,
"text": "The HTML <input type=”tel”> is used to define a field that entering a user telephone Number."
},
{
"code": null,
"e": 26240,
"s": 26232,
"text": "Syntax:"
},
{
"code": null,
"e": 26260,
"s": 26240,
"text": "<input type=\"tel\"> "
},
{
"code": null,
"e": 26269,
"s": 26260,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML Input Type Tel </title></head><style> #Geek_p { font-size: 30px; color: green; }</style> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h2>HTML <Input Type=\"tel\"> </h2> <form> Phone No.: <input type=\"tel\"> <br> <br> </form></body> </html>",
"e": 26686,
"s": 26269,
"text": null
},
{
"code": null,
"e": 26694,
"s": 26686,
"text": "Output:"
},
{
"code": null,
"e": 26714,
"s": 26694,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 26728,
"s": 26714,
"text": "Google Chrome"
},
{
"code": null,
"e": 26736,
"s": 26728,
"text": "Firefox"
},
{
"code": null,
"e": 26741,
"s": 26736,
"text": "Edge"
},
{
"code": null,
"e": 26747,
"s": 26741,
"text": "Opera"
},
{
"code": null,
"e": 26760,
"s": 26747,
"text": "Apple Safari"
},
{
"code": null,
"e": 26897,
"s": 26760,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 26913,
"s": 26897,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 26918,
"s": 26913,
"text": "HTML"
},
{
"code": null,
"e": 26935,
"s": 26918,
"text": "Web Technologies"
},
{
"code": null,
"e": 26940,
"s": 26935,
"text": "HTML"
},
{
"code": null,
"e": 27038,
"s": 26940,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27062,
"s": 27038,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 27103,
"s": 27062,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 27140,
"s": 27103,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 27169,
"s": 27140,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 27189,
"s": 27169,
"text": "Angular File Upload"
},
{
"code": null,
"e": 27229,
"s": 27189,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27262,
"s": 27229,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27307,
"s": 27262,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27350,
"s": 27307,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Number of co-prime pairs in an array - GeeksforGeeks | 28 Apr, 2021
Co-prime or mutually prime pair are those pair of numbers whose GCD is 1. Given an array of size n, find number of Co-Prime or mutually prime pairs in the array.
Examples:
Input : 1 2 3
Output : 3
Here, Co-prime pairs are ( 1, 2), ( 2, 3),
( 1, 3)
Input :4 8 3 9
Output :4
Here, Co-prime pairs are ( 4, 3), ( 8, 3),
( 4, 9 ), ( 8, 9 )
Approach : Using two loop, check every possible pair of the array. If Gcd of the pair is 1 increment counter value and at last display it.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find// number of co-prime// pairs in array#include <bits/stdc++.h>using namespace std; // function to check for gcdbool coprime(int a, int b){ return (__gcd(a, b) == 1);} // Recursive function to// return gcd of a and bint numOfPairs(int arr[], int n){ int count = 0; for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) if (coprime(arr[i], arr[j])) count++; return count;} // driver codeint main(){ int arr[] = { 1, 2, 5, 4, 8, 3, 9 }; int n = sizeof(arr) / sizeof(arr[0]); cout << numOfPairs(arr, n); return 0;}
// Java program to find// number of co-prime// pairs in arrayimport java.io.*; class GFG { // Recursive function to // return gcd of a and b static int gcd(int a, int b) { // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a-b, b); return gcd(a, b-a); } // function to check for gcd static boolean coprime(int a, int b) { return (gcd(a, b) == 1); } // Returns count of co-prime // pairs present in array static int numOfPairs(int arr[], int n) { int count = 0; for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) if (coprime(arr[i], arr[j])) count++; return count; } // driver code public static void main(String args[]) throws IOException { int arr[] = { 1, 2, 5, 4, 8, 3, 9 }; int n = arr.length; System.out.println(numOfPairs(arr, n)); }} /* This code is contributed by Nikita Tiwari.*/
# Python 3 program to# find number of co# prime pairs in array # Recursive function to# return gcd of a and bdef gcd(a, b): # Everything divides 0 if (a == 0 or b == 0): return False # base case if (a == b): return a # a is greater if (a > b): return gcd(a-b, b) return gcd(a, b-a) # function to check# for gcddef coprime(a, b) : return (gcd(a, b) == 1) # Returns count of# co-prime pairs# present in arraydef numOfPairs(arr, n) : count = 0 for i in range(0, n-1) : for j in range(i+1, n) : if (coprime(arr[i], arr[j])) : count = count + 1 return count # driver codearr = [1, 2, 5, 4, 8, 3, 9]n = len(arr) print(numOfPairs(arr, n)) # This code is contributed by Nikita Tiwari.
// C# program to find number of// co-prime pairs in arrayusing System; class GFG { // Recursive function to // return gcd of a and b static int gcd(int a, int b) { // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a-b, b); return gcd(a, b-a); } // function to check for gcd static bool coprime(int a, int b) { return (gcd(a, b) == 1); } // Returns count of co-prime // pairs present in array static int numOfPairs(int []arr, int n) { int count = 0; for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) if (coprime(arr[i], arr[j])) count++; return count; } // driver code public static void Main() { int []arr = { 1, 2, 5, 4, 8, 3, 9 }; int n = arr.Length; Console.WriteLine(numOfPairs(arr, n)); }} //This code is contributed by Anant Agarwal.
<?php// PHP program to find// number of co-prime// pairs in array // Recursive function to// return gcd of a and bfunction __gcd( $a, $b){ // Everything divides 0 if ($a == 0 or $b == 0) return 0; // base case if ($a == $b) return $a; // a is greater if ($a > $b) return __gcd($a - $b, $b); return __gcd($a, $b - $a);} // function to check for gcdfunction coprime($a, $b){ return (__gcd($a, $b) == 1);} // Recursive function to// return gcd of a and bfunction numOfPairs($arr, $n){ $count = 0; for ( $i = 0; $i < $n - 1; $i++) for ($j = $i + 1; $j < $n; $j++) if (coprime($arr[$i], $arr[$j])) $count++; return $count;} // Driver code $arr = array(1, 2, 5, 4, 8, 3, 9); $n = count($arr); echo numOfPairs($arr, $n); // This code is contributed by anuj_67.?>
<script> // Javascript program to find// number of co-prime // pairs in array // Recursive function to// return gcd of a and bfunction gcd(a, b){ // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a);} // Function to check for gcdfunction coprime(a, b){ return (gcd(a, b) == 1);} // Returns count of co-prime// pairs present in arrayfunction numOfPairs(arr, n){ let count = 0; for(let i = 0; i < n - 1; i++) for(let j = i + 1; j < n; j++) if (coprime(arr[i], arr[j])) count++; return count;} // Driver codelet arr = [ 1, 2, 5, 4, 8, 3, 9 ];let n = arr.length; document.write(numOfPairs(arr, n)); // This code is contributed by susmitakundugoaldanga </script>
Output:
17
This article is contributed by Dibyendu Roy Chaudhuri. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
kusalsaraf5
susmitakundugoaldanga
GCD-LCM
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Print all possible combinations of r elements in a given array of size n
Operators in C / C++
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
C++ Classes and Objects | [
{
"code": null,
"e": 26116,
"s": 26088,
"text": "\n28 Apr, 2021"
},
{
"code": null,
"e": 26278,
"s": 26116,
"text": "Co-prime or mutually prime pair are those pair of numbers whose GCD is 1. Given an array of size n, find number of Co-Prime or mutually prime pairs in the array."
},
{
"code": null,
"e": 26290,
"s": 26278,
"text": "Examples: "
},
{
"code": null,
"e": 26512,
"s": 26290,
"text": "Input : 1 2 3\nOutput : 3\nHere, Co-prime pairs are ( 1, 2), ( 2, 3), \n ( 1, 3) \n\nInput :4 8 3 9\nOutput :4\nHere, Co-prime pairs are ( 4, 3), ( 8, 3), \n ( 4, 9 ), ( 8, 9 ) "
},
{
"code": null,
"e": 26653,
"s": 26512,
"text": "Approach : Using two loop, check every possible pair of the array. If Gcd of the pair is 1 increment counter value and at last display it. "
},
{
"code": null,
"e": 26657,
"s": 26653,
"text": "C++"
},
{
"code": null,
"e": 26662,
"s": 26657,
"text": "Java"
},
{
"code": null,
"e": 26670,
"s": 26662,
"text": "Python3"
},
{
"code": null,
"e": 26673,
"s": 26670,
"text": "C#"
},
{
"code": null,
"e": 26677,
"s": 26673,
"text": "PHP"
},
{
"code": null,
"e": 26688,
"s": 26677,
"text": "Javascript"
},
{
"code": "// C++ program to find// number of co-prime// pairs in array#include <bits/stdc++.h>using namespace std; // function to check for gcdbool coprime(int a, int b){ return (__gcd(a, b) == 1);} // Recursive function to// return gcd of a and bint numOfPairs(int arr[], int n){ int count = 0; for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) if (coprime(arr[i], arr[j])) count++; return count;} // driver codeint main(){ int arr[] = { 1, 2, 5, 4, 8, 3, 9 }; int n = sizeof(arr) / sizeof(arr[0]); cout << numOfPairs(arr, n); return 0;}",
"e": 27312,
"s": 26688,
"text": null
},
{
"code": "// Java program to find// number of co-prime// pairs in arrayimport java.io.*; class GFG { // Recursive function to // return gcd of a and b static int gcd(int a, int b) { // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a-b, b); return gcd(a, b-a); } // function to check for gcd static boolean coprime(int a, int b) { return (gcd(a, b) == 1); } // Returns count of co-prime // pairs present in array static int numOfPairs(int arr[], int n) { int count = 0; for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) if (coprime(arr[i], arr[j])) count++; return count; } // driver code public static void main(String args[]) throws IOException { int arr[] = { 1, 2, 5, 4, 8, 3, 9 }; int n = arr.length; System.out.println(numOfPairs(arr, n)); }} /* This code is contributed by Nikita Tiwari.*/",
"e": 28527,
"s": 27312,
"text": null
},
{
"code": "# Python 3 program to# find number of co# prime pairs in array # Recursive function to# return gcd of a and bdef gcd(a, b): # Everything divides 0 if (a == 0 or b == 0): return False # base case if (a == b): return a # a is greater if (a > b): return gcd(a-b, b) return gcd(a, b-a) # function to check# for gcddef coprime(a, b) : return (gcd(a, b) == 1) # Returns count of# co-prime pairs# present in arraydef numOfPairs(arr, n) : count = 0 for i in range(0, n-1) : for j in range(i+1, n) : if (coprime(arr[i], arr[j])) : count = count + 1 return count # driver codearr = [1, 2, 5, 4, 8, 3, 9]n = len(arr) print(numOfPairs(arr, n)) # This code is contributed by Nikita Tiwari.",
"e": 29337,
"s": 28527,
"text": null
},
{
"code": "// C# program to find number of// co-prime pairs in arrayusing System; class GFG { // Recursive function to // return gcd of a and b static int gcd(int a, int b) { // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a-b, b); return gcd(a, b-a); } // function to check for gcd static bool coprime(int a, int b) { return (gcd(a, b) == 1); } // Returns count of co-prime // pairs present in array static int numOfPairs(int []arr, int n) { int count = 0; for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) if (coprime(arr[i], arr[j])) count++; return count; } // driver code public static void Main() { int []arr = { 1, 2, 5, 4, 8, 3, 9 }; int n = arr.Length; Console.WriteLine(numOfPairs(arr, n)); }} //This code is contributed by Anant Agarwal.",
"e": 30478,
"s": 29337,
"text": null
},
{
"code": "<?php// PHP program to find// number of co-prime// pairs in array // Recursive function to// return gcd of a and bfunction __gcd( $a, $b){ // Everything divides 0 if ($a == 0 or $b == 0) return 0; // base case if ($a == $b) return $a; // a is greater if ($a > $b) return __gcd($a - $b, $b); return __gcd($a, $b - $a);} // function to check for gcdfunction coprime($a, $b){ return (__gcd($a, $b) == 1);} // Recursive function to// return gcd of a and bfunction numOfPairs($arr, $n){ $count = 0; for ( $i = 0; $i < $n - 1; $i++) for ($j = $i + 1; $j < $n; $j++) if (coprime($arr[$i], $arr[$j])) $count++; return $count;} // Driver code $arr = array(1, 2, 5, 4, 8, 3, 9); $n = count($arr); echo numOfPairs($arr, $n); // This code is contributed by anuj_67.?>",
"e": 31367,
"s": 30478,
"text": null
},
{
"code": "<script> // Javascript program to find// number of co-prime // pairs in array // Recursive function to// return gcd of a and bfunction gcd(a, b){ // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a);} // Function to check for gcdfunction coprime(a, b){ return (gcd(a, b) == 1);} // Returns count of co-prime// pairs present in arrayfunction numOfPairs(arr, n){ let count = 0; for(let i = 0; i < n - 1; i++) for(let j = i + 1; j < n; j++) if (coprime(arr[i], arr[j])) count++; return count;} // Driver codelet arr = [ 1, 2, 5, 4, 8, 3, 9 ];let n = arr.length; document.write(numOfPairs(arr, n)); // This code is contributed by susmitakundugoaldanga </script>",
"e": 32276,
"s": 31367,
"text": null
},
{
"code": null,
"e": 32285,
"s": 32276,
"text": "Output: "
},
{
"code": null,
"e": 32288,
"s": 32285,
"text": "17"
},
{
"code": null,
"e": 32723,
"s": 32288,
"text": "This article is contributed by Dibyendu Roy Chaudhuri. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 32728,
"s": 32723,
"text": "vt_m"
},
{
"code": null,
"e": 32740,
"s": 32728,
"text": "kusalsaraf5"
},
{
"code": null,
"e": 32762,
"s": 32740,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 32770,
"s": 32762,
"text": "GCD-LCM"
},
{
"code": null,
"e": 32783,
"s": 32770,
"text": "Mathematical"
},
{
"code": null,
"e": 32802,
"s": 32783,
"text": "School Programming"
},
{
"code": null,
"e": 32815,
"s": 32802,
"text": "Mathematical"
},
{
"code": null,
"e": 32913,
"s": 32815,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32937,
"s": 32913,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 32980,
"s": 32937,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 32994,
"s": 32980,
"text": "Prime Numbers"
},
{
"code": null,
"e": 33067,
"s": 32994,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 33088,
"s": 33067,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 33106,
"s": 33088,
"text": "Python Dictionary"
},
{
"code": null,
"e": 33122,
"s": 33106,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 33141,
"s": 33122,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 33166,
"s": 33141,
"text": "Reverse a string in Java"
}
] |
Expected number of cluster of cars formed on infinite Road - GeeksforGeeks | 19 Jan, 2022
Given an array speed[] of size N denoting the speed of N cars moving on an infinitely long single lane road (i.e. no overtaking is allowed) from left to right. Initially, the rightmost car is at the first position and whenever a car with higher speed reaches a car with lower speed they start moving with the speed to the slower car and form a cluster. The task is to find the total number of clusters that will form.
Note: A single car is also considered a cluster.
Examples:
Input: speed[] = {1, 4, 5, 2, 17, 4 }Output: 3Explanation: After a certain time, car with speed 17 will reach car with speed 4(car5) and will form a cluster. And similarly, cars with speed 4 and 5 will start moving with speed 2 on reaching car3.The clusters will be (car0), (car1, car2, car3), (car4, car5).
Input: speed[] = {2, 3, 4, 7, 7}Output: 5Explanation: Each car will form a cluster.
Approach: The solution is based on greedy approach. Here, a car with less speed forms a cluster with all the cars behind it and having speeds greater than itself. Follow the steps below to solve the problem:
Start iterating from the last index of array speed[].Store the speed of the car in a variable, say currentCar.A cluster is formed till the speed of cars behind the currentCar is greater than itself. Therefore increase the value of clusters as soon as a car with less speed is found behind it or when the array is out of bounds.
Start iterating from the last index of array speed[].
Store the speed of the car in a variable, say currentCar.
A cluster is formed till the speed of cars behind the currentCar is greater than itself. Therefore increase the value of clusters as soon as a car with less speed is found behind it or when the array is out of bounds.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ code to implement above approach#include <bits/stdc++.h>#include <vector>using namespace std; // Function to count total number of clustersint countClusters(vector<int>& speed){ int N = speed.size(); // For number of clusters int cluster = 0; for (int i = N - 1; i >= 0; i--) { int currentCar = speed[i]; // comparing with previous car while (i != 0 and speed[i - 1] > currentCar) { i--; } cluster++; } return cluster;} // Driver codeint main(){ vector<int> speed = { 1, 4, 5, 2, 17, 4 }; int clusters = countClusters(speed); cout << clusters; return 0;}
// Java program to implement// the above approachclass GFG{ // Function to count total number of clusters static int countClusters(int []speed) { int N = speed.length; // For number of clusters int cluster = 0; for (int i = N - 1; i >= 0; i--) { int currentCar = speed[i]; // comparing with previous car while (i != 0 && speed[i - 1] > currentCar) { i--; } cluster++; } return cluster; } // Driver Code public static void main(String args[]) { int []speed = { 1, 4, 5, 2, 17, 4 }; int clusters = countClusters(speed); System.out.println(clusters); }} // This code is contributed by Saurabh Jaiswal
# Python code to implement above approach # Function to count total number of clustersdef countClusters(speed): N = len(speed) clusters = 0 i = N-1 while(i >= 0): currentCar = speed[i] while(i != 0 and speed[i-1] > currentCar): i = i-1 clusters = clusters+1 i = i-1 return clusters # Driver codeif __name__ == '__main__': speed = [1, 4, 5, 2, 17, 4] clusters = countClusters(speed) print(clusters)
// C# program to implement// the above approachusing System;class GFG{ // Function to count total number of clusters static int countClusters(int []speed) { int N = speed.Length; // For number of clusters int cluster = 0; for (int i = N - 1; i >= 0; i--) { int currentCar = speed[i]; // comparing with previous car while (i != 0 && speed[i - 1] > currentCar) { i--; } cluster++; } return cluster; } // Driver Code public static void Main() { int []speed = { 1, 4, 5, 2, 17, 4 }; int clusters = countClusters(speed); Console.Write(clusters); }} // This code is contributed by Samim Hossain Mondal.
<script> // JavaScript code for the above approach // Function to count total number of clusters function countClusters(speed) { let N = speed.length; // For number of clusters let cluster = 0; for (let i = N - 1; i >= 0; i--) { let currentCar = speed[i]; // comparing with previous car while (i != 0 && speed[i - 1] > currentCar) { i--; } cluster++; } return cluster; } // Driver code let speed = [1, 4, 5, 2, 17, 4]; let clusters = countClusters(speed); document.write(clusters); // This code is contributed by Potta Lokesh </script>
3
Time Complexity: O(N)Auxiliary Space: O(1)
lokeshpotta20
samim2000
_saurabh_jaiswal
Google
Arrays
Combinatorial
Greedy
Mathematical
Google
Arrays
Greedy
Mathematical
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Write a program to print all permutations of a given string
Permutation and Combination in Python
itertools.combinations() module in Python to print all possible combinations
Combinational Sum
Factorial of a large number | [
{
"code": null,
"e": 26737,
"s": 26709,
"text": "\n19 Jan, 2022"
},
{
"code": null,
"e": 27155,
"s": 26737,
"text": "Given an array speed[] of size N denoting the speed of N cars moving on an infinitely long single lane road (i.e. no overtaking is allowed) from left to right. Initially, the rightmost car is at the first position and whenever a car with higher speed reaches a car with lower speed they start moving with the speed to the slower car and form a cluster. The task is to find the total number of clusters that will form."
},
{
"code": null,
"e": 27204,
"s": 27155,
"text": "Note: A single car is also considered a cluster."
},
{
"code": null,
"e": 27214,
"s": 27204,
"text": "Examples:"
},
{
"code": null,
"e": 27522,
"s": 27214,
"text": "Input: speed[] = {1, 4, 5, 2, 17, 4 }Output: 3Explanation: After a certain time, car with speed 17 will reach car with speed 4(car5) and will form a cluster. And similarly, cars with speed 4 and 5 will start moving with speed 2 on reaching car3.The clusters will be (car0), (car1, car2, car3), (car4, car5)."
},
{
"code": null,
"e": 27606,
"s": 27522,
"text": "Input: speed[] = {2, 3, 4, 7, 7}Output: 5Explanation: Each car will form a cluster."
},
{
"code": null,
"e": 27814,
"s": 27606,
"text": "Approach: The solution is based on greedy approach. Here, a car with less speed forms a cluster with all the cars behind it and having speeds greater than itself. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 28142,
"s": 27814,
"text": "Start iterating from the last index of array speed[].Store the speed of the car in a variable, say currentCar.A cluster is formed till the speed of cars behind the currentCar is greater than itself. Therefore increase the value of clusters as soon as a car with less speed is found behind it or when the array is out of bounds."
},
{
"code": null,
"e": 28196,
"s": 28142,
"text": "Start iterating from the last index of array speed[]."
},
{
"code": null,
"e": 28254,
"s": 28196,
"text": "Store the speed of the car in a variable, say currentCar."
},
{
"code": null,
"e": 28472,
"s": 28254,
"text": "A cluster is formed till the speed of cars behind the currentCar is greater than itself. Therefore increase the value of clusters as soon as a car with less speed is found behind it or when the array is out of bounds."
},
{
"code": null,
"e": 28523,
"s": 28472,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 28527,
"s": 28523,
"text": "C++"
},
{
"code": null,
"e": 28532,
"s": 28527,
"text": "Java"
},
{
"code": null,
"e": 28540,
"s": 28532,
"text": "Python3"
},
{
"code": null,
"e": 28543,
"s": 28540,
"text": "C#"
},
{
"code": null,
"e": 28554,
"s": 28543,
"text": "Javascript"
},
{
"code": "// C++ code to implement above approach#include <bits/stdc++.h>#include <vector>using namespace std; // Function to count total number of clustersint countClusters(vector<int>& speed){ int N = speed.size(); // For number of clusters int cluster = 0; for (int i = N - 1; i >= 0; i--) { int currentCar = speed[i]; // comparing with previous car while (i != 0 and speed[i - 1] > currentCar) { i--; } cluster++; } return cluster;} // Driver codeint main(){ vector<int> speed = { 1, 4, 5, 2, 17, 4 }; int clusters = countClusters(speed); cout << clusters; return 0;}",
"e": 29221,
"s": 28554,
"text": null
},
{
"code": "// Java program to implement// the above approachclass GFG{ // Function to count total number of clusters static int countClusters(int []speed) { int N = speed.length; // For number of clusters int cluster = 0; for (int i = N - 1; i >= 0; i--) { int currentCar = speed[i]; // comparing with previous car while (i != 0 && speed[i - 1] > currentCar) { i--; } cluster++; } return cluster; } // Driver Code public static void main(String args[]) { int []speed = { 1, 4, 5, 2, 17, 4 }; int clusters = countClusters(speed); System.out.println(clusters); }} // This code is contributed by Saurabh Jaiswal",
"e": 29904,
"s": 29221,
"text": null
},
{
"code": "# Python code to implement above approach # Function to count total number of clustersdef countClusters(speed): N = len(speed) clusters = 0 i = N-1 while(i >= 0): currentCar = speed[i] while(i != 0 and speed[i-1] > currentCar): i = i-1 clusters = clusters+1 i = i-1 return clusters # Driver codeif __name__ == '__main__': speed = [1, 4, 5, 2, 17, 4] clusters = countClusters(speed) print(clusters)",
"e": 30365,
"s": 29904,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;class GFG{ // Function to count total number of clusters static int countClusters(int []speed) { int N = speed.Length; // For number of clusters int cluster = 0; for (int i = N - 1; i >= 0; i--) { int currentCar = speed[i]; // comparing with previous car while (i != 0 && speed[i - 1] > currentCar) { i--; } cluster++; } return cluster; } // Driver Code public static void Main() { int []speed = { 1, 4, 5, 2, 17, 4 }; int clusters = countClusters(speed); Console.Write(clusters); }} // This code is contributed by Samim Hossain Mondal.",
"e": 31047,
"s": 30365,
"text": null
},
{
"code": "<script> // JavaScript code for the above approach // Function to count total number of clusters function countClusters(speed) { let N = speed.length; // For number of clusters let cluster = 0; for (let i = N - 1; i >= 0; i--) { let currentCar = speed[i]; // comparing with previous car while (i != 0 && speed[i - 1] > currentCar) { i--; } cluster++; } return cluster; } // Driver code let speed = [1, 4, 5, 2, 17, 4]; let clusters = countClusters(speed); document.write(clusters); // This code is contributed by Potta Lokesh </script>",
"e": 31806,
"s": 31047,
"text": null
},
{
"code": null,
"e": 31811,
"s": 31809,
"text": "3"
},
{
"code": null,
"e": 31856,
"s": 31813,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 31872,
"s": 31858,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 31882,
"s": 31872,
"text": "samim2000"
},
{
"code": null,
"e": 31899,
"s": 31882,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 31906,
"s": 31899,
"text": "Google"
},
{
"code": null,
"e": 31913,
"s": 31906,
"text": "Arrays"
},
{
"code": null,
"e": 31927,
"s": 31913,
"text": "Combinatorial"
},
{
"code": null,
"e": 31934,
"s": 31927,
"text": "Greedy"
},
{
"code": null,
"e": 31947,
"s": 31934,
"text": "Mathematical"
},
{
"code": null,
"e": 31954,
"s": 31947,
"text": "Google"
},
{
"code": null,
"e": 31961,
"s": 31954,
"text": "Arrays"
},
{
"code": null,
"e": 31968,
"s": 31961,
"text": "Greedy"
},
{
"code": null,
"e": 31981,
"s": 31968,
"text": "Mathematical"
},
{
"code": null,
"e": 31995,
"s": 31981,
"text": "Combinatorial"
},
{
"code": null,
"e": 32093,
"s": 31995,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32161,
"s": 32093,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 32205,
"s": 32161,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 32253,
"s": 32205,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 32276,
"s": 32253,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 32308,
"s": 32276,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 32368,
"s": 32308,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 32406,
"s": 32368,
"text": "Permutation and Combination in Python"
},
{
"code": null,
"e": 32483,
"s": 32406,
"text": "itertools.combinations() module in Python to print all possible combinations"
},
{
"code": null,
"e": 32501,
"s": 32483,
"text": "Combinational Sum"
}
] |
Code Injection and Mitigation with Example - GeeksforGeeks | 23 May, 2017
Code injection is the malicious injection or introduction of code into an application. The code introduced or injected is capable of compromising database integrity and/or compromising privacy properties, security and even data correctness. It can also steal data and/or bypass access and authentication control. Code injection attacks can plague applications that depend on user input for execution.
Code Injection differs from Command Injection. Here an attacker is only limited by the functionality of the injected language itself. For example, if an attacker is able to inject PHP code into an application and have it executed, he is only limited by what PHP is capable of.
Code injection vulnerabilities range from easy to difficult-to-find ones. Many solutions have been developed for thwarting these types of code injection attacks, for both application and architecture domain. Some examples include input validation, parameterization, privilege setting for different actions, addition of extra layer of protection and others.
Example:When a developer uses the PHP eval() function and passes it untrusted data that an attacker can modify, code injection could be possible.
The example below shows a dangerous way to use the eval() function:
// A dangerous way to use the eval() function // in PHP$myvar = "varname";$x = $_GET['arg'];eval("\$myvar = \$x;");
As there is no input validation, the code above is vulnerable to a Code Injection attack.
For example:
/index.php?arg=1; phpinfo()
Above will show all the info of php.
While exploiting bugs like these, an attacker may want to execute system commands. In this case, a code injection bug can also be used for command injection, for example:
/index.php?arg=1; system('id')
This will tell the ids of the process.uid=33(www-data) gid=33(www-data) groups=33(www-data)
MitigationIdeally, a developer should use existing API for their language. For example (Java): Rather than use Runtime.exec() to issue a ‘mail’ command, use the available Java API located at javax.mail.*If no such available API exists, the developer should scrub all input for malicious characters. Implementing a positive security model would be most efficient. Typically, it is much easier to define the legal characters than the illegal characters.
Referencehttps://en.wikipedia.org/wiki/Code_injectionhttps://www.cse.unr.edu/~mgunes/cpe401/cpe401sp11/student/CodeInjection.pptx
This article is contributed by Akash Sharan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
secure-coding
Advanced Computer Subject
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Reinforcement learning
Decision Tree
Decision Tree Introduction with example
System Design Tutorial
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
DSA Sheet by Love Babbar
Socket Programming in C/C++
GET and POST requests using Python
Must Do Coding Questions for Product Based Companies | [
{
"code": null,
"e": 25867,
"s": 25839,
"text": "\n23 May, 2017"
},
{
"code": null,
"e": 26268,
"s": 25867,
"text": "Code injection is the malicious injection or introduction of code into an application. The code introduced or injected is capable of compromising database integrity and/or compromising privacy properties, security and even data correctness. It can also steal data and/or bypass access and authentication control. Code injection attacks can plague applications that depend on user input for execution."
},
{
"code": null,
"e": 26545,
"s": 26268,
"text": "Code Injection differs from Command Injection. Here an attacker is only limited by the functionality of the injected language itself. For example, if an attacker is able to inject PHP code into an application and have it executed, he is only limited by what PHP is capable of."
},
{
"code": null,
"e": 26902,
"s": 26545,
"text": "Code injection vulnerabilities range from easy to difficult-to-find ones. Many solutions have been developed for thwarting these types of code injection attacks, for both application and architecture domain. Some examples include input validation, parameterization, privilege setting for different actions, addition of extra layer of protection and others."
},
{
"code": null,
"e": 27048,
"s": 26902,
"text": "Example:When a developer uses the PHP eval() function and passes it untrusted data that an attacker can modify, code injection could be possible."
},
{
"code": null,
"e": 27116,
"s": 27048,
"text": "The example below shows a dangerous way to use the eval() function:"
},
{
"code": "// A dangerous way to use the eval() function // in PHP$myvar = \"varname\";$x = $_GET['arg'];eval(\"\\$myvar = \\$x;\");",
"e": 27232,
"s": 27116,
"text": null
},
{
"code": null,
"e": 27322,
"s": 27232,
"text": "As there is no input validation, the code above is vulnerable to a Code Injection attack."
},
{
"code": null,
"e": 27335,
"s": 27322,
"text": "For example:"
},
{
"code": null,
"e": 27363,
"s": 27335,
"text": "/index.php?arg=1; phpinfo()"
},
{
"code": null,
"e": 27400,
"s": 27363,
"text": "Above will show all the info of php."
},
{
"code": null,
"e": 27571,
"s": 27400,
"text": "While exploiting bugs like these, an attacker may want to execute system commands. In this case, a code injection bug can also be used for command injection, for example:"
},
{
"code": null,
"e": 27602,
"s": 27571,
"text": "/index.php?arg=1; system('id')"
},
{
"code": null,
"e": 27694,
"s": 27602,
"text": "This will tell the ids of the process.uid=33(www-data) gid=33(www-data) groups=33(www-data)"
},
{
"code": null,
"e": 28146,
"s": 27694,
"text": "MitigationIdeally, a developer should use existing API for their language. For example (Java): Rather than use Runtime.exec() to issue a ‘mail’ command, use the available Java API located at javax.mail.*If no such available API exists, the developer should scrub all input for malicious characters. Implementing a positive security model would be most efficient. Typically, it is much easier to define the legal characters than the illegal characters."
},
{
"code": null,
"e": 28276,
"s": 28146,
"text": "Referencehttps://en.wikipedia.org/wiki/Code_injectionhttps://www.cse.unr.edu/~mgunes/cpe401/cpe401sp11/student/CodeInjection.pptx"
},
{
"code": null,
"e": 28576,
"s": 28276,
"text": "This article is contributed by Akash Sharan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 28701,
"s": 28576,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 28715,
"s": 28701,
"text": "secure-coding"
},
{
"code": null,
"e": 28741,
"s": 28715,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 28747,
"s": 28741,
"text": "GBlog"
},
{
"code": null,
"e": 28845,
"s": 28747,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28868,
"s": 28845,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 28891,
"s": 28868,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 28905,
"s": 28891,
"text": "Decision Tree"
},
{
"code": null,
"e": 28945,
"s": 28905,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 28968,
"s": 28945,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 29042,
"s": 28968,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 29067,
"s": 29042,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 29095,
"s": 29067,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 29130,
"s": 29095,
"text": "GET and POST requests using Python"
}
] |
scipy.fft() in Python - GeeksforGeeks | 29 Aug, 2020
With the help of scipy.fft() method, we can compute the fast fourier transformation by passing simple 1-D numpy array and it will return the transformed array by using this method.
Fast Fourier Transformation
Syntax : scipy.fft(x)
Return : Return the transformed array.
Example #1 :
In this example we can see that by using scipy.fft() method, we are able to compute the fast fourier transformation by passing sequence of numbers and return the transformed array.
Python3
# import scipy and numpyimport scipyimport numpy as np x = np.array(np.arange(10))# Using scipy.fft() methodgfg = scipy.fft(x) print(gfg)
Output :
[45. +0.j -5.+15.38841769j -5. +6.8819096j -5. +3.63271264j
-5. +1.62459848j -5. +0.j -5. -1.62459848j -5. -3.63271264j
-5. -6.8819096j -5.-15.38841769j]
Example #2 :
Python3
# import scipy and numpyimport scipyimport numpy as np x = np.array(np.arange(5))# Using scipy.fft() methodgfg = scipy.fft(x) print(gfg)
Output :
[10. +0.j -2.5+3.4409548j -2.5+0.81229924j -2.5-0.81229924j
-2.5-3.4409548j ]
Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n29 Aug, 2020"
},
{
"code": null,
"e": 25718,
"s": 25537,
"text": "With the help of scipy.fft() method, we can compute the fast fourier transformation by passing simple 1-D numpy array and it will return the transformed array by using this method."
},
{
"code": null,
"e": 25746,
"s": 25718,
"text": "Fast Fourier Transformation"
},
{
"code": null,
"e": 25768,
"s": 25746,
"text": "Syntax : scipy.fft(x)"
},
{
"code": null,
"e": 25807,
"s": 25768,
"text": "Return : Return the transformed array."
},
{
"code": null,
"e": 25820,
"s": 25807,
"text": "Example #1 :"
},
{
"code": null,
"e": 26001,
"s": 25820,
"text": "In this example we can see that by using scipy.fft() method, we are able to compute the fast fourier transformation by passing sequence of numbers and return the transformed array."
},
{
"code": null,
"e": 26009,
"s": 26001,
"text": "Python3"
},
{
"code": "# import scipy and numpyimport scipyimport numpy as np x = np.array(np.arange(10))# Using scipy.fft() methodgfg = scipy.fft(x) print(gfg)",
"e": 26149,
"s": 26009,
"text": null
},
{
"code": null,
"e": 26158,
"s": 26149,
"text": "Output :"
},
{
"code": null,
"e": 26227,
"s": 26158,
"text": "[45. +0.j -5.+15.38841769j -5. +6.8819096j -5. +3.63271264j"
},
{
"code": null,
"e": 26295,
"s": 26227,
"text": "-5. +1.62459848j -5. +0.j -5. -1.62459848j -5. -3.63271264j"
},
{
"code": null,
"e": 26330,
"s": 26295,
"text": "-5. -6.8819096j -5.-15.38841769j]"
},
{
"code": null,
"e": 26343,
"s": 26330,
"text": "Example #2 :"
},
{
"code": null,
"e": 26351,
"s": 26343,
"text": "Python3"
},
{
"code": "# import scipy and numpyimport scipyimport numpy as np x = np.array(np.arange(5))# Using scipy.fft() methodgfg = scipy.fft(x) print(gfg)",
"e": 26490,
"s": 26351,
"text": null
},
{
"code": null,
"e": 26499,
"s": 26490,
"text": "Output :"
},
{
"code": null,
"e": 26568,
"s": 26499,
"text": "[10. +0.j -2.5+3.4409548j -2.5+0.81229924j -2.5-0.81229924j"
},
{
"code": null,
"e": 26586,
"s": 26568,
"text": "-2.5-3.4409548j ]"
},
{
"code": null,
"e": 26615,
"s": 26586,
"text": "Python scipy-stats-functions"
},
{
"code": null,
"e": 26628,
"s": 26615,
"text": "Python-scipy"
},
{
"code": null,
"e": 26635,
"s": 26628,
"text": "Python"
},
{
"code": null,
"e": 26733,
"s": 26635,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26765,
"s": 26733,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26807,
"s": 26765,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26849,
"s": 26807,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26876,
"s": 26849,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26932,
"s": 26876,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26954,
"s": 26932,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26993,
"s": 26954,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27024,
"s": 26993,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27053,
"s": 27024,
"text": "Create a directory in Python"
}
] |
Find the index of the maximum value in R DataFrame - GeeksforGeeks | 11 Oct, 2021
In this article, we will see how to find the index of the maximum value from a DataFrame in the R Programming Language
We can find the maximum value index in a dataframe using the which.max() function.
Syntax:
which.max(dataframe_name$columnname)
“$” is used to access particular column of a dataframe.
Given below are various implementations, depicting various datatypes and situations to help uou understand better.
Example 1:
R
# vector 1data1=c("sravan","bobby","pinkey","rohith","gnanesh") # vector 2data2=c(98,78,79,97,89) # creating a dataframe with names and marks# using above vectorsfinal <- data.frame(names=data1,marks=data2) print(final) # display the maximum value index in 2 nd column# (marks column) in a dataframeprint(paste("highest index is : ",which.max(final$marks)))
Output:
If there is more than one maximum value, then it will return index of first number which is repeated.
Example 2:
R
# vector 1data1=c("sravan","bobby","pinkey","rohith", "gnanesh",'divya',"satwik","chandu") # vector 2data2=c(98,78,79,97,89,89,99,99) # creating a dataframe with names and marks# using above vectorsfinal <- data.frame(names=data1,marks=data2) print(final) print(paste("highest index is : ",which.max(final$marks)))
Output:
If the data is of type character, it will find the maximum value using ASCII values.
Example 3:
R
# vector 1data1=c("sravan","bobby","pinkey","rohith", "gnanesh",'divya',"satwik","zhandu") # vector 2data2=c(98,78,79,97,89,89,99,99) # creating a dataframe with names and marks# using above vectorsfinal <- data.frame(names=data1,marks=data2) print(final) # display maximum value index for character valuesprint(paste("highest index is : ",which.max(final$names)))
Output:
Example 4:
R
# vector 1 that contains NA values as charactersdata1=c(NA,"sravan",NA,NA,NA) # vector 2 contains all datadata2=c(102,98,98,102,102) # creating a dataframe with names and marks# using above vectorsfinal <- data.frame(names=data1,marks=data2) print(final) # display maximum value index for character valuesprint(paste("highest index is : ",which.max(final$names))) # display maximum value index for marks valuesprint(paste("highest index is : ",which.max(final$marks)))
Output:
If row containing all the values are same so all are higher. So it will return index of first element.
Example 5:
R
# vector contains all same datadata2=c(102,102,102,102,102) # creating a dataframe marks using above vectorfinal <- data.frame(marks=data2) print(final) # display maximum value index for marks valuesprint(paste("highest index is : ",which.max(final$marks)))
Output:
If the data contains values as NA, then it will return empty.
Example 6:
R
# vector contains all NA'sdata2=c(NA,NA) # creating a dataframe marks using# above vectorfinal <- data.frame(marks=data2) print(final) # display maximum value index for marks valuesprint(paste("highest index is : ",which.max(final$marks)))
Output:
prachisoda1234
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Convert Matrix to Dataframe in R | [
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 26606,
"s": 26487,
"text": "In this article, we will see how to find the index of the maximum value from a DataFrame in the R Programming Language"
},
{
"code": null,
"e": 26689,
"s": 26606,
"text": "We can find the maximum value index in a dataframe using the which.max() function."
},
{
"code": null,
"e": 26697,
"s": 26689,
"text": "Syntax:"
},
{
"code": null,
"e": 26734,
"s": 26697,
"text": "which.max(dataframe_name$columnname)"
},
{
"code": null,
"e": 26790,
"s": 26734,
"text": "“$” is used to access particular column of a dataframe."
},
{
"code": null,
"e": 26905,
"s": 26790,
"text": "Given below are various implementations, depicting various datatypes and situations to help uou understand better."
},
{
"code": null,
"e": 26917,
"s": 26905,
"text": "Example 1: "
},
{
"code": null,
"e": 26919,
"s": 26917,
"text": "R"
},
{
"code": "# vector 1data1=c(\"sravan\",\"bobby\",\"pinkey\",\"rohith\",\"gnanesh\") # vector 2data2=c(98,78,79,97,89) # creating a dataframe with names and marks# using above vectorsfinal <- data.frame(names=data1,marks=data2) print(final) # display the maximum value index in 2 nd column# (marks column) in a dataframeprint(paste(\"highest index is : \",which.max(final$marks)))",
"e": 27296,
"s": 26919,
"text": null
},
{
"code": null,
"e": 27304,
"s": 27296,
"text": "Output:"
},
{
"code": null,
"e": 27406,
"s": 27304,
"text": "If there is more than one maximum value, then it will return index of first number which is repeated."
},
{
"code": null,
"e": 27417,
"s": 27406,
"text": "Example 2:"
},
{
"code": null,
"e": 27419,
"s": 27417,
"text": "R"
},
{
"code": "# vector 1data1=c(\"sravan\",\"bobby\",\"pinkey\",\"rohith\", \"gnanesh\",'divya',\"satwik\",\"chandu\") # vector 2data2=c(98,78,79,97,89,89,99,99) # creating a dataframe with names and marks# using above vectorsfinal <- data.frame(names=data1,marks=data2) print(final) print(paste(\"highest index is : \",which.max(final$marks)))",
"e": 27760,
"s": 27419,
"text": null
},
{
"code": null,
"e": 27768,
"s": 27760,
"text": "Output:"
},
{
"code": null,
"e": 27853,
"s": 27768,
"text": "If the data is of type character, it will find the maximum value using ASCII values."
},
{
"code": null,
"e": 27864,
"s": 27853,
"text": "Example 3:"
},
{
"code": null,
"e": 27866,
"s": 27864,
"text": "R"
},
{
"code": "# vector 1data1=c(\"sravan\",\"bobby\",\"pinkey\",\"rohith\", \"gnanesh\",'divya',\"satwik\",\"zhandu\") # vector 2data2=c(98,78,79,97,89,89,99,99) # creating a dataframe with names and marks# using above vectorsfinal <- data.frame(names=data1,marks=data2) print(final) # display maximum value index for character valuesprint(paste(\"highest index is : \",which.max(final$names)))",
"e": 28257,
"s": 27866,
"text": null
},
{
"code": null,
"e": 28265,
"s": 28257,
"text": "Output:"
},
{
"code": null,
"e": 28276,
"s": 28265,
"text": "Example 4:"
},
{
"code": null,
"e": 28278,
"s": 28276,
"text": "R"
},
{
"code": "# vector 1 that contains NA values as charactersdata1=c(NA,\"sravan\",NA,NA,NA) # vector 2 contains all datadata2=c(102,98,98,102,102) # creating a dataframe with names and marks# using above vectorsfinal <- data.frame(names=data1,marks=data2) print(final) # display maximum value index for character valuesprint(paste(\"highest index is : \",which.max(final$names))) # display maximum value index for marks valuesprint(paste(\"highest index is : \",which.max(final$marks)))",
"e": 28767,
"s": 28278,
"text": null
},
{
"code": null,
"e": 28775,
"s": 28767,
"text": "Output:"
},
{
"code": null,
"e": 28878,
"s": 28775,
"text": "If row containing all the values are same so all are higher. So it will return index of first element."
},
{
"code": null,
"e": 28889,
"s": 28878,
"text": "Example 5:"
},
{
"code": null,
"e": 28891,
"s": 28889,
"text": "R"
},
{
"code": "# vector contains all same datadata2=c(102,102,102,102,102) # creating a dataframe marks using above vectorfinal <- data.frame(marks=data2) print(final) # display maximum value index for marks valuesprint(paste(\"highest index is : \",which.max(final$marks)))",
"e": 29169,
"s": 28891,
"text": null
},
{
"code": null,
"e": 29177,
"s": 29169,
"text": "Output:"
},
{
"code": null,
"e": 29239,
"s": 29177,
"text": "If the data contains values as NA, then it will return empty."
},
{
"code": null,
"e": 29250,
"s": 29239,
"text": "Example 6:"
},
{
"code": null,
"e": 29252,
"s": 29250,
"text": "R"
},
{
"code": "# vector contains all NA'sdata2=c(NA,NA) # creating a dataframe marks using# above vectorfinal <- data.frame(marks=data2) print(final) # display maximum value index for marks valuesprint(paste(\"highest index is : \",which.max(final$marks)))",
"e": 29512,
"s": 29252,
"text": null
},
{
"code": null,
"e": 29520,
"s": 29512,
"text": "Output:"
},
{
"code": null,
"e": 29535,
"s": 29520,
"text": "prachisoda1234"
},
{
"code": null,
"e": 29542,
"s": 29535,
"text": "Picked"
},
{
"code": null,
"e": 29563,
"s": 29542,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 29575,
"s": 29563,
"text": "R-DataFrame"
},
{
"code": null,
"e": 29586,
"s": 29575,
"text": "R Language"
},
{
"code": null,
"e": 29597,
"s": 29586,
"text": "R Programs"
},
{
"code": null,
"e": 29695,
"s": 29597,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29747,
"s": 29695,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 29782,
"s": 29747,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 29820,
"s": 29782,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 29878,
"s": 29820,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 29921,
"s": 29878,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 29979,
"s": 29921,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 30022,
"s": 29979,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 30071,
"s": 30022,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 30121,
"s": 30071,
"text": "How to filter R dataframe by multiple conditions?"
}
] |
Comprehensive Guide to Scatter Plot using ggplot2 in R - GeeksforGeeks | 23 Feb, 2022
In this article, we are going to see how to use scatter plots using ggplot2 in the R programming language.
ggplot2 package is a free, open-source, and easy-to-use visualization package widely used in R. It is the most powerful visualization package written by Hadley Wickham. This package can be installed using the R function install.packages().
install.packages("ggplot2")
A scatter plot uses dots to represent values for two different numeric variables and is used to observe relationships between those variables. To plot scatterplot we will use we will be using geom_point() function. Following is brief information about ggplot function, geom_point().
Syntax : geom_point(size, color, fill, shape, stroke)
Parameter :
size : Size of Points
color : Color of Points/Border
fill : Color of Points
shape : Shape of Points in in range from 0 to 25
stroke : Thickness of point border
Return : It creates scatterplots.
Example: Simple scatterplot
R
library(ggplot2)ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point()
Output:
Here we will use distinguish the values by a group of data (i.e. factor level data). aes() function controls the color of the group and it should be factor variable.
Syntax:
aes(color = factor(variable))
Example: Scatterplot with groups
R
# Scatter plot with groups ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point(aes(color = factor(Sepal.Width)))
Output:
Here we use aes() methods color attributes to change the color of the datapoints with specific variables.
Example: Changing color
R
# Changing color ggplot(iris) + geom_point(aes(x = Sepal.Length, y = Sepal.Width, color = Species))
Output:
To change the shape of the datapoints we will use shape attributes with aes() methods.
Example: Changing shape
R
# Changing point shapes in a ggplot scatter plot# Changing color ggplot(iris) + geom_point(aes(x = Sepal.Length, y = Sepal.Width, shape = Species , color = Species))
Output:
To change the aesthetic or datapoints we will use size attributes in aes() methods.
Example: Changing size
R
# Changing the size aesthetic mapping in a# ggplot scatter plot ggplot(iris) + geom_point(aes(x = Sepal.Length, y = Sepal.Width, size = .5))
Output:
To deploy the labels on the datapoint we will use label into the geom_text() methods.
Example: Label points in the scatter plot
R
# Label points in the scatter plot ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point() + geom_text(label=rownames(iris))
Output:
Regression models a target prediction value supported independent variables and mostly used for finding out the relationship between variables and forecasting. In R we can use the stat_smooth() function to smoothen the visualization.
Syntax: stat_smooth(method=”method_name”, formula=fromula_to_be_used, geom=’method name’)
Parameters:
method: It is the smoothing method (function) to use for smoothing the line
formula: It is the formula to use in the smoothing function
geom: It is the geometric object to use display the data
Example: Regression line
R
# Add regression lines with stat_smoothggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point() + stat_smooth(method=lm)
Output:
Example: Using stat_mooth with loess mode
R
# Add regression lines with stat_smoothggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point() + stat_smooth()
Output:
geom_smooth() function to represent a regression line and smoothen the visualization.
Syntax: geom_smooth(method=”method_name”, formula=fromula_to_be_used)
Parameters:
method: It is the smoothing method (function) to use for smoothing the line
formula: It is the formula to use in the smoothing function
Example: Using geom_smooth()
R
# Add regression lines with geom_smoothggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point() + geom_smooth()
Output:
In order to show the regression line on the graphical medium with help of geom_smooth() function, we pass the method as “loess” and the formula used as y ~ x.
Example: geom_smooth with loess mode
R
# Add regression lines with geom_smoothggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point() + geom_smooth(method=lm, se=FALSE)
Output:
The intercept and slope can be easily calculated by the lm() function which is used for linear regression followed by coefficients().
Example: Intercept and slope
R
# Add regression lines with geom_smoothggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point() + geom_smooth(intercept = 37, slope = -5, color="red", linetype="dashed", size=1.5)
Output:
scale_fill_manual, scale_size_manual, scale_shape_manual, scale_linetype_manual, are builtin types which is assign desired colors to categorical data, we use one of them scale_color_manual() function, which is used to scale (map).
Syntax :
scale_shape_manualValue) for point shapes
scale_color_manual(Value) for point colors
scale_size_manual(Value) for point sizes
Parameter :
values : A set of aesthetic values to map the data. Here we take desired set of colors.
Return : Scale the manual values of colors on data
Example: Changing aesthetics
R
# Change the point color/shape/size manuallylibrary(ggplot2) # Change point shapes and colors manuallyggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) + geom_point() + geom_smooth(method=lm, se=FALSE, fullrange=TRUE)+ scale_shape_manual(values=c(3, 16, 17))+ scale_color_manual(values=c('#999999','#E69F00', '#56B4E9'))+ theme(legend.position="top")
Output:
To add marginal rugs to the scatter plot we will use geom_rug() methods.
Example: Marginal rugs
R
# Add marginal rugs to a scatter plot# Changing point shapes in a ggplot scatter plot# Changing color ggplot(iris) + geom_point(aes(x = Sepal.Length, y = Sepal.Width, shape = Species , color = Species))+ geom_rug()
Output:
Here we will add marginal rugs into the scatter plot
Example: Marginal rugs
R
# Add marginal rugs to a scatter plot ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point()+ geom_rug()
Output:
To create density estimation in scatter plot we will use geom_density_2d() methods and geom_density_2d_filled() from ggplot2.
Syntax: ggplot( aes(x)) + geom_density_2d( fill, color, alpha)
Parameters:
fill: background color below the plot
color: the color of the plotline
alpha: transparency of graph
Example: Scatterplots with 2-D density estimation
R
# Scatter plots with the 2d density estimation ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point()+ geom_density_2d()
Output:
Using geom_density_2d_filled() to visualize the situation of color inside the datapoints
Example: Adding aesthetics
R
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point()+ geom_density_2d(alpha = 0.5)+ geom_density_2d_filled()
Output:
stat_density_2d() can be also used to deploy the 2d density estimation.
Example: Deploy density estimation
R
# Scatter plots with the 2d density estimation ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point()+ stat_density_2d()
Output:
To add a circle or ellipse around a cluster of data points, we use the stat_ellipse() function. This function automatically computes the circle/ellipse radius to draw around the cluster of points by categorical data.
Example: Scatterplot with ellipses
R
# Scatter plots with ellipses ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point()+ stat_ellipse()
Output:
kk9826225
germanshephered48
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
R - if statement
How to import an Excel File into R ?
Plot mean and standard deviation using ggplot2 in R
How to filter R dataframe by multiple conditions? | [
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n23 Feb, 2022"
},
{
"code": null,
"e": 26594,
"s": 26487,
"text": "In this article, we are going to see how to use scatter plots using ggplot2 in the R programming language."
},
{
"code": null,
"e": 26834,
"s": 26594,
"text": "ggplot2 package is a free, open-source, and easy-to-use visualization package widely used in R. It is the most powerful visualization package written by Hadley Wickham. This package can be installed using the R function install.packages()."
},
{
"code": null,
"e": 26862,
"s": 26834,
"text": "install.packages(\"ggplot2\")"
},
{
"code": null,
"e": 27145,
"s": 26862,
"text": "A scatter plot uses dots to represent values for two different numeric variables and is used to observe relationships between those variables. To plot scatterplot we will use we will be using geom_point() function. Following is brief information about ggplot function, geom_point()."
},
{
"code": null,
"e": 27199,
"s": 27145,
"text": "Syntax : geom_point(size, color, fill, shape, stroke)"
},
{
"code": null,
"e": 27211,
"s": 27199,
"text": "Parameter :"
},
{
"code": null,
"e": 27233,
"s": 27211,
"text": "size : Size of Points"
},
{
"code": null,
"e": 27264,
"s": 27233,
"text": "color : Color of Points/Border"
},
{
"code": null,
"e": 27287,
"s": 27264,
"text": "fill : Color of Points"
},
{
"code": null,
"e": 27336,
"s": 27287,
"text": "shape : Shape of Points in in range from 0 to 25"
},
{
"code": null,
"e": 27371,
"s": 27336,
"text": "stroke : Thickness of point border"
},
{
"code": null,
"e": 27405,
"s": 27371,
"text": "Return : It creates scatterplots."
},
{
"code": null,
"e": 27433,
"s": 27405,
"text": "Example: Simple scatterplot"
},
{
"code": null,
"e": 27435,
"s": 27433,
"text": "R"
},
{
"code": "library(ggplot2)ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point()",
"e": 27522,
"s": 27435,
"text": null
},
{
"code": null,
"e": 27533,
"s": 27525,
"text": "Output:"
},
{
"code": null,
"e": 27703,
"s": 27537,
"text": "Here we will use distinguish the values by a group of data (i.e. factor level data). aes() function controls the color of the group and it should be factor variable."
},
{
"code": null,
"e": 27715,
"s": 27705,
"text": " Syntax: "
},
{
"code": null,
"e": 27747,
"s": 27717,
"text": "aes(color = factor(variable))"
},
{
"code": null,
"e": 27782,
"s": 27749,
"text": "Example: Scatterplot with groups"
},
{
"code": null,
"e": 27786,
"s": 27784,
"text": "R"
},
{
"code": "# Scatter plot with groups ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point(aes(color = factor(Sepal.Width)))",
"e": 27916,
"s": 27786,
"text": null
},
{
"code": null,
"e": 27927,
"s": 27919,
"text": "Output:"
},
{
"code": null,
"e": 28037,
"s": 27931,
"text": "Here we use aes() methods color attributes to change the color of the datapoints with specific variables."
},
{
"code": null,
"e": 28063,
"s": 28039,
"text": "Example: Changing color"
},
{
"code": null,
"e": 28067,
"s": 28065,
"text": "R"
},
{
"code": "# Changing color ggplot(iris) + geom_point(aes(x = Sepal.Length, y = Sepal.Width, color = Species))",
"e": 28206,
"s": 28067,
"text": null
},
{
"code": null,
"e": 28217,
"s": 28209,
"text": "Output:"
},
{
"code": null,
"e": 28308,
"s": 28221,
"text": "To change the shape of the datapoints we will use shape attributes with aes() methods."
},
{
"code": null,
"e": 28334,
"s": 28310,
"text": "Example: Changing shape"
},
{
"code": null,
"e": 28338,
"s": 28336,
"text": "R"
},
{
"code": "# Changing point shapes in a ggplot scatter plot# Changing color ggplot(iris) + geom_point(aes(x = Sepal.Length, y = Sepal.Width, shape = Species , color = Species))",
"e": 28525,
"s": 28338,
"text": null
},
{
"code": null,
"e": 28536,
"s": 28528,
"text": "Output:"
},
{
"code": null,
"e": 28624,
"s": 28540,
"text": "To change the aesthetic or datapoints we will use size attributes in aes() methods."
},
{
"code": null,
"e": 28649,
"s": 28626,
"text": "Example: Changing size"
},
{
"code": null,
"e": 28653,
"s": 28651,
"text": "R"
},
{
"code": "# Changing the size aesthetic mapping in a# ggplot scatter plot ggplot(iris) + geom_point(aes(x = Sepal.Length, y = Sepal.Width, size = .5))",
"e": 28833,
"s": 28653,
"text": null
},
{
"code": null,
"e": 28844,
"s": 28836,
"text": "Output:"
},
{
"code": null,
"e": 28934,
"s": 28848,
"text": "To deploy the labels on the datapoint we will use label into the geom_text() methods."
},
{
"code": null,
"e": 28978,
"s": 28936,
"text": "Example: Label points in the scatter plot"
},
{
"code": null,
"e": 28982,
"s": 28980,
"text": "R"
},
{
"code": "# Label points in the scatter plot ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point() + geom_text(label=rownames(iris))",
"e": 29125,
"s": 28982,
"text": null
},
{
"code": null,
"e": 29136,
"s": 29128,
"text": "Output:"
},
{
"code": null,
"e": 29374,
"s": 29140,
"text": "Regression models a target prediction value supported independent variables and mostly used for finding out the relationship between variables and forecasting. In R we can use the stat_smooth() function to smoothen the visualization."
},
{
"code": null,
"e": 29466,
"s": 29376,
"text": "Syntax: stat_smooth(method=”method_name”, formula=fromula_to_be_used, geom=’method name’)"
},
{
"code": null,
"e": 29480,
"s": 29466,
"text": "Parameters: "
},
{
"code": null,
"e": 29556,
"s": 29480,
"text": "method: It is the smoothing method (function) to use for smoothing the line"
},
{
"code": null,
"e": 29616,
"s": 29556,
"text": "formula: It is the formula to use in the smoothing function"
},
{
"code": null,
"e": 29673,
"s": 29616,
"text": "geom: It is the geometric object to use display the data"
},
{
"code": null,
"e": 29700,
"s": 29675,
"text": "Example: Regression line"
},
{
"code": null,
"e": 29704,
"s": 29702,
"text": "R"
},
{
"code": "# Add regression lines with stat_smoothggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point() + stat_smooth(method=lm)",
"e": 29842,
"s": 29704,
"text": null
},
{
"code": null,
"e": 29853,
"s": 29845,
"text": "Output:"
},
{
"code": null,
"e": 29899,
"s": 29857,
"text": "Example: Using stat_mooth with loess mode"
},
{
"code": null,
"e": 29903,
"s": 29901,
"text": "R"
},
{
"code": "# Add regression lines with stat_smoothggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point() + stat_smooth()",
"e": 30032,
"s": 29903,
"text": null
},
{
"code": null,
"e": 30043,
"s": 30035,
"text": "Output:"
},
{
"code": null,
"e": 30135,
"s": 30047,
"text": "geom_smooth() function to represent a regression line and smoothen the visualization. "
},
{
"code": null,
"e": 30207,
"s": 30137,
"text": "Syntax: geom_smooth(method=”method_name”, formula=fromula_to_be_used)"
},
{
"code": null,
"e": 30219,
"s": 30207,
"text": "Parameters:"
},
{
"code": null,
"e": 30295,
"s": 30219,
"text": "method: It is the smoothing method (function) to use for smoothing the line"
},
{
"code": null,
"e": 30355,
"s": 30295,
"text": "formula: It is the formula to use in the smoothing function"
},
{
"code": null,
"e": 30386,
"s": 30357,
"text": "Example: Using geom_smooth()"
},
{
"code": null,
"e": 30390,
"s": 30388,
"text": "R"
},
{
"code": "# Add regression lines with geom_smoothggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point() + geom_smooth()",
"e": 30519,
"s": 30390,
"text": null
},
{
"code": null,
"e": 30530,
"s": 30522,
"text": "Output:"
},
{
"code": null,
"e": 30693,
"s": 30534,
"text": "In order to show the regression line on the graphical medium with help of geom_smooth() function, we pass the method as “loess” and the formula used as y ~ x."
},
{
"code": null,
"e": 30732,
"s": 30695,
"text": "Example: geom_smooth with loess mode"
},
{
"code": null,
"e": 30736,
"s": 30734,
"text": "R"
},
{
"code": "# Add regression lines with geom_smoothggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point() + geom_smooth(method=lm, se=FALSE)",
"e": 30884,
"s": 30736,
"text": null
},
{
"code": null,
"e": 30895,
"s": 30887,
"text": "Output:"
},
{
"code": null,
"e": 31033,
"s": 30899,
"text": "The intercept and slope can be easily calculated by the lm() function which is used for linear regression followed by coefficients()."
},
{
"code": null,
"e": 31064,
"s": 31035,
"text": "Example: Intercept and slope"
},
{
"code": null,
"e": 31068,
"s": 31066,
"text": "R"
},
{
"code": "# Add regression lines with geom_smoothggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point() + geom_smooth(intercept = 37, slope = -5, color=\"red\", linetype=\"dashed\", size=1.5)",
"e": 31281,
"s": 31068,
"text": null
},
{
"code": null,
"e": 31292,
"s": 31284,
"text": "Output:"
},
{
"code": null,
"e": 31527,
"s": 31296,
"text": "scale_fill_manual, scale_size_manual, scale_shape_manual, scale_linetype_manual, are builtin types which is assign desired colors to categorical data, we use one of them scale_color_manual() function, which is used to scale (map)."
},
{
"code": null,
"e": 31539,
"s": 31529,
"text": "Syntax : "
},
{
"code": null,
"e": 31581,
"s": 31539,
"text": "scale_shape_manualValue) for point shapes"
},
{
"code": null,
"e": 31624,
"s": 31581,
"text": "scale_color_manual(Value) for point colors"
},
{
"code": null,
"e": 31665,
"s": 31624,
"text": "scale_size_manual(Value) for point sizes"
},
{
"code": null,
"e": 31677,
"s": 31665,
"text": "Parameter :"
},
{
"code": null,
"e": 31765,
"s": 31677,
"text": "values : A set of aesthetic values to map the data. Here we take desired set of colors."
},
{
"code": null,
"e": 31816,
"s": 31765,
"text": "Return : Scale the manual values of colors on data"
},
{
"code": null,
"e": 31847,
"s": 31818,
"text": "Example: Changing aesthetics"
},
{
"code": null,
"e": 31851,
"s": 31849,
"text": "R"
},
{
"code": "# Change the point color/shape/size manuallylibrary(ggplot2) # Change point shapes and colors manuallyggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) + geom_point() + geom_smooth(method=lm, se=FALSE, fullrange=TRUE)+ scale_shape_manual(values=c(3, 16, 17))+ scale_color_manual(values=c('#999999','#E69F00', '#56B4E9'))+ theme(legend.position=\"top\")",
"e": 32237,
"s": 31851,
"text": null
},
{
"code": null,
"e": 32248,
"s": 32240,
"text": "Output:"
},
{
"code": null,
"e": 32325,
"s": 32252,
"text": "To add marginal rugs to the scatter plot we will use geom_rug() methods."
},
{
"code": null,
"e": 32350,
"s": 32327,
"text": "Example: Marginal rugs"
},
{
"code": null,
"e": 32354,
"s": 32352,
"text": "R"
},
{
"code": "# Add marginal rugs to a scatter plot# Changing point shapes in a ggplot scatter plot# Changing color ggplot(iris) + geom_point(aes(x = Sepal.Length, y = Sepal.Width, shape = Species , color = Species))+ geom_rug()",
"e": 32593,
"s": 32354,
"text": null
},
{
"code": null,
"e": 32604,
"s": 32596,
"text": "Output:"
},
{
"code": null,
"e": 32661,
"s": 32608,
"text": "Here we will add marginal rugs into the scatter plot"
},
{
"code": null,
"e": 32686,
"s": 32663,
"text": "Example: Marginal rugs"
},
{
"code": null,
"e": 32690,
"s": 32688,
"text": "R"
},
{
"code": "# Add marginal rugs to a scatter plot ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point()+ geom_rug()",
"e": 32814,
"s": 32690,
"text": null
},
{
"code": null,
"e": 32825,
"s": 32817,
"text": "Output:"
},
{
"code": null,
"e": 32955,
"s": 32829,
"text": "To create density estimation in scatter plot we will use geom_density_2d() methods and geom_density_2d_filled() from ggplot2."
},
{
"code": null,
"e": 33020,
"s": 32957,
"text": "Syntax: ggplot( aes(x)) + geom_density_2d( fill, color, alpha)"
},
{
"code": null,
"e": 33032,
"s": 33020,
"text": "Parameters:"
},
{
"code": null,
"e": 33070,
"s": 33032,
"text": "fill: background color below the plot"
},
{
"code": null,
"e": 33103,
"s": 33070,
"text": "color: the color of the plotline"
},
{
"code": null,
"e": 33132,
"s": 33103,
"text": "alpha: transparency of graph"
},
{
"code": null,
"e": 33184,
"s": 33134,
"text": "Example: Scatterplots with 2-D density estimation"
},
{
"code": null,
"e": 33188,
"s": 33186,
"text": "R"
},
{
"code": "# Scatter plots with the 2d density estimation ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point()+ geom_density_2d()",
"e": 33328,
"s": 33188,
"text": null
},
{
"code": null,
"e": 33339,
"s": 33331,
"text": "Output:"
},
{
"code": null,
"e": 33432,
"s": 33343,
"text": "Using geom_density_2d_filled() to visualize the situation of color inside the datapoints"
},
{
"code": null,
"e": 33461,
"s": 33434,
"text": "Example: Adding aesthetics"
},
{
"code": null,
"e": 33465,
"s": 33463,
"text": "R"
},
{
"code": "ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point()+ geom_density_2d(alpha = 0.5)+ geom_density_2d_filled()",
"e": 33598,
"s": 33465,
"text": null
},
{
"code": null,
"e": 33609,
"s": 33601,
"text": "Output:"
},
{
"code": null,
"e": 33685,
"s": 33613,
"text": "stat_density_2d() can be also used to deploy the 2d density estimation."
},
{
"code": null,
"e": 33722,
"s": 33687,
"text": "Example: Deploy density estimation"
},
{
"code": null,
"e": 33726,
"s": 33724,
"text": "R"
},
{
"code": "# Scatter plots with the 2d density estimation ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point()+ stat_density_2d()",
"e": 33866,
"s": 33726,
"text": null
},
{
"code": null,
"e": 33877,
"s": 33869,
"text": "Output:"
},
{
"code": null,
"e": 34098,
"s": 33881,
"text": "To add a circle or ellipse around a cluster of data points, we use the stat_ellipse() function. This function automatically computes the circle/ellipse radius to draw around the cluster of points by categorical data."
},
{
"code": null,
"e": 34135,
"s": 34100,
"text": "Example: Scatterplot with ellipses"
},
{
"code": null,
"e": 34139,
"s": 34137,
"text": "R"
},
{
"code": "# Scatter plots with ellipses ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point()+ stat_ellipse()",
"e": 34259,
"s": 34139,
"text": null
},
{
"code": null,
"e": 34270,
"s": 34262,
"text": "Output:"
},
{
"code": null,
"e": 34284,
"s": 34274,
"text": "kk9826225"
},
{
"code": null,
"e": 34302,
"s": 34284,
"text": "germanshephered48"
},
{
"code": null,
"e": 34309,
"s": 34302,
"text": "Picked"
},
{
"code": null,
"e": 34318,
"s": 34309,
"text": "R-ggplot"
},
{
"code": null,
"e": 34329,
"s": 34318,
"text": "R Language"
},
{
"code": null,
"e": 34427,
"s": 34329,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34479,
"s": 34427,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 34514,
"s": 34479,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 34552,
"s": 34514,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 34610,
"s": 34552,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 34653,
"s": 34610,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 34702,
"s": 34653,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 34719,
"s": 34702,
"text": "R - if statement"
},
{
"code": null,
"e": 34756,
"s": 34719,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 34808,
"s": 34756,
"text": "Plot mean and standard deviation using ggplot2 in R"
}
] |
OOAD Princhiples Q/A #1 | Question:What is inheritance? Discuss types of inheritance with example.
Answer:
Inheritance is the mechanism to allow a class A to inherit properties of class b i.e A inherits from B. Objects of class A thus have accesses to attribute and methods of class B without the need to redefine them. If class A inherits from class B , then B is called super class of A and A is called subclass of B. Supper classes are also called base classes or parents classes. Subclasses may be called derived classes or child classes.
Inheritance is one of the most powerful features of object oriented programming. Most important advantages of inheritance are:
Reusability - Inheritance allows deriving new classes from existing classes without modifying it. This helps in reusability of information in the child class as well as adding extra functionality in to it.
Saves times and efforts - The concept of reusability achieved by inheritance saves a lot of programmer time and effort as the main code written can be reused in various situations as needed.
Closeness with the real world - Inheritance allows the capability to express the inheritance relationship and ensures closeness with the real world models.
Easy modification - Inheritance allows modification to be done in an easier manner.
Transitive Nature of inheritance - If a class A inherits properties of another class B then all subclasses of A will automatically inherits the properties of B. This concept is called transitive nature of inheritance.
Reusability - Inheritance allows deriving new classes from existing classes without modifying it. This helps in reusability of information in the child class as well as adding extra functionality in to it.
Reusability - Inheritance allows deriving new classes from existing classes without modifying it. This helps in reusability of information in the child class as well as adding extra functionality in to it.
Saves times and efforts - The concept of reusability achieved by inheritance saves a lot of programmer time and effort as the main code written can be reused in various situations as needed.
Saves times and efforts - The concept of reusability achieved by inheritance saves a lot of programmer time and effort as the main code written can be reused in various situations as needed.
Closeness with the real world - Inheritance allows the capability to express the inheritance relationship and ensures closeness with the real world models.
Closeness with the real world - Inheritance allows the capability to express the inheritance relationship and ensures closeness with the real world models.
Easy modification - Inheritance allows modification to be done in an easier manner.
Easy modification - Inheritance allows modification to be done in an easier manner.
Transitive Nature of inheritance - If a class A inherits properties of another class B then all subclasses of A will automatically inherits the properties of B. This concept is called transitive nature of inheritance.
Transitive Nature of inheritance - If a class A inherits properties of another class B then all subclasses of A will automatically inherits the properties of B. This concept is called transitive nature of inheritance.
class subclass: visibility_mode superclass_name
{
...
}
Here class is keyword. superclass_name is the neme of the derived class which is a valid identifier. Visibility modes are of three types public, private and protected.
Various types of inheritance are supported by C++. These are:
Single Inheritance - When a subclass inherits properties from one base class, it is called single inheritance. In single inheritance , there is only one base class and one derived class.
Multiple Inheritance - When a subclass inherits properties from multiple base classes, it is known as multiple inheritance. In multiple Inheritance , there is only one derived class and several base classes.
Hierarchical Inheritance - When two or more subclasses inherit properties from a single base class, It is known as Hierarchical inheritance . In hierarchical inheritance , the feature of one class may be inherited by more then one class.
Multilevel Inheritance - In multilevel Inheritance , A class is derived from an already derived class. The transitive nature of inheritance is reflected by this form of inheritance.
Hybrid Inheritance - When two or more type of inheritance are required to code a program, such type of inheritance is called hybrid inheritance.
Figure shown below is a combination of multilevel and multiple inheritance.
Single Inheritance - When a subclass inherits properties from one base class, it is called single inheritance. In single inheritance , there is only one base class and one derived class.
Single Inheritance - When a subclass inherits properties from one base class, it is called single inheritance. In single inheritance , there is only one base class and one derived class.
Multiple Inheritance - When a subclass inherits properties from multiple base classes, it is known as multiple inheritance. In multiple Inheritance , there is only one derived class and several base classes.
Multiple Inheritance - When a subclass inherits properties from multiple base classes, it is known as multiple inheritance. In multiple Inheritance , there is only one derived class and several base classes.
Hierarchical Inheritance - When two or more subclasses inherit properties from a single base class, It is known as Hierarchical inheritance . In hierarchical inheritance , the feature of one class may be inherited by more then one class.
Hierarchical Inheritance - When two or more subclasses inherit properties from a single base class, It is known as Hierarchical inheritance . In hierarchical inheritance , the feature of one class may be inherited by more then one class.
Multilevel Inheritance - In multilevel Inheritance , A class is derived from an already derived class. The transitive nature of inheritance is reflected by this form of inheritance.
Multilevel Inheritance - In multilevel Inheritance , A class is derived from an already derived class. The transitive nature of inheritance is reflected by this form of inheritance.
Hybrid Inheritance - When two or more type of inheritance are required to code a program, such type of inheritance is called hybrid inheritance.
Figure shown below is a combination of multilevel and multiple inheritance.
Hybrid Inheritance - When two or more type of inheritance are required to code a program, such type of inheritance is called hybrid inheritance.
Figure shown below is a combination of multilevel and multiple inheritance.
14 Lectures
1.5 hours
Harshit Srivastava
60 Lectures
8 hours
DigiFisk (Programming Is Fun)
11 Lectures
35 mins
Sandip Bhattacharya
21 Lectures
2 hours
Pranjal Srivastava
6 Lectures
43 mins
Frahaan Hussain
49 Lectures
4.5 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2060,
"s": 1987,
"text": "Question:What is inheritance? Discuss types of inheritance with example."
},
{
"code": null,
"e": 2068,
"s": 2060,
"text": "Answer:"
},
{
"code": null,
"e": 2507,
"s": 2068,
"text": "Inheritance is the mechanism to allow a class A to inherit properties of class b i.e A inherits from B. Objects of class A thus have accesses to attribute and methods of class B without the need to redefine them. If class A inherits from class B , then B is called super class of A and A is called subclass of B. Supper classes are also called base classes or parents classes. Subclasses may be called derived classes or child classes."
},
{
"code": null,
"e": 2634,
"s": 2507,
"text": "Inheritance is one of the most powerful features of object oriented programming. Most important advantages of inheritance are:"
},
{
"code": null,
"e": 3494,
"s": 2634,
"text": "\nReusability - Inheritance allows deriving new classes from existing classes without modifying it. This helps in reusability of information in the child class as well as adding extra functionality in to it.\nSaves times and efforts - The concept of reusability achieved by inheritance saves a lot of programmer time and effort as the main code written can be reused in various situations as needed.\nCloseness with the real world - Inheritance allows the capability to express the inheritance relationship and ensures closeness with the real world models.\nEasy modification - Inheritance allows modification to be done in an easier manner.\nTransitive Nature of inheritance - If a class A inherits properties of another class B then all subclasses of A will automatically inherits the properties of B. This concept is called transitive nature of inheritance.\n"
},
{
"code": null,
"e": 3700,
"s": 3494,
"text": "Reusability - Inheritance allows deriving new classes from existing classes without modifying it. This helps in reusability of information in the child class as well as adding extra functionality in to it."
},
{
"code": null,
"e": 3906,
"s": 3700,
"text": "Reusability - Inheritance allows deriving new classes from existing classes without modifying it. This helps in reusability of information in the child class as well as adding extra functionality in to it."
},
{
"code": null,
"e": 4098,
"s": 3906,
"text": "Saves times and efforts - The concept of reusability achieved by inheritance saves a lot of programmer time and effort as the main code written can be reused in various situations as needed."
},
{
"code": null,
"e": 4290,
"s": 4098,
"text": "Saves times and efforts - The concept of reusability achieved by inheritance saves a lot of programmer time and effort as the main code written can be reused in various situations as needed."
},
{
"code": null,
"e": 4447,
"s": 4290,
"text": "Closeness with the real world - Inheritance allows the capability to express the inheritance relationship and ensures closeness with the real world models."
},
{
"code": null,
"e": 4604,
"s": 4447,
"text": "Closeness with the real world - Inheritance allows the capability to express the inheritance relationship and ensures closeness with the real world models."
},
{
"code": null,
"e": 4688,
"s": 4604,
"text": "Easy modification - Inheritance allows modification to be done in an easier manner."
},
{
"code": null,
"e": 4772,
"s": 4688,
"text": "Easy modification - Inheritance allows modification to be done in an easier manner."
},
{
"code": null,
"e": 4991,
"s": 4772,
"text": "Transitive Nature of inheritance - If a class A inherits properties of another class B then all subclasses of A will automatically inherits the properties of B. This concept is called transitive nature of inheritance."
},
{
"code": null,
"e": 5210,
"s": 4991,
"text": "Transitive Nature of inheritance - If a class A inherits properties of another class B then all subclasses of A will automatically inherits the properties of B. This concept is called transitive nature of inheritance."
},
{
"code": null,
"e": 5268,
"s": 5210,
"text": "class subclass: visibility_mode superclass_name \n{\n...\n}"
},
{
"code": null,
"e": 5436,
"s": 5268,
"text": "Here class is keyword. superclass_name is the neme of the derived class which is a valid identifier. Visibility modes are of three types public, private and protected."
},
{
"code": null,
"e": 5498,
"s": 5436,
"text": "Various types of inheritance are supported by C++. These are:"
},
{
"code": null,
"e": 6545,
"s": 5498,
"text": "\nSingle Inheritance - When a subclass inherits properties from one base class, it is called single inheritance. In single inheritance , there is only one base class and one derived class. \nMultiple Inheritance - When a subclass inherits properties from multiple base classes, it is known as multiple inheritance. In multiple Inheritance , there is only one derived class and several base classes.\nHierarchical Inheritance - When two or more subclasses inherit properties from a single base class, It is known as Hierarchical inheritance . In hierarchical inheritance , the feature of one class may be inherited by more then one class.\nMultilevel Inheritance - In multilevel Inheritance , A class is derived from an already derived class. The transitive nature of inheritance is reflected by this form of inheritance.\nHybrid Inheritance - When two or more type of inheritance are required to code a program, such type of inheritance is called hybrid inheritance.\nFigure shown below is a combination of multilevel and multiple inheritance.\n"
},
{
"code": null,
"e": 6733,
"s": 6545,
"text": "Single Inheritance - When a subclass inherits properties from one base class, it is called single inheritance. In single inheritance , there is only one base class and one derived class. "
},
{
"code": null,
"e": 6921,
"s": 6733,
"text": "Single Inheritance - When a subclass inherits properties from one base class, it is called single inheritance. In single inheritance , there is only one base class and one derived class. "
},
{
"code": null,
"e": 7131,
"s": 6921,
"text": "Multiple Inheritance - When a subclass inherits properties from multiple base classes, it is known as multiple inheritance. In multiple Inheritance , there is only one derived class and several base classes."
},
{
"code": null,
"e": 7341,
"s": 7131,
"text": "Multiple Inheritance - When a subclass inherits properties from multiple base classes, it is known as multiple inheritance. In multiple Inheritance , there is only one derived class and several base classes."
},
{
"code": null,
"e": 7583,
"s": 7341,
"text": "Hierarchical Inheritance - When two or more subclasses inherit properties from a single base class, It is known as Hierarchical inheritance . In hierarchical inheritance , the feature of one class may be inherited by more then one class."
},
{
"code": null,
"e": 7825,
"s": 7583,
"text": "Hierarchical Inheritance - When two or more subclasses inherit properties from a single base class, It is known as Hierarchical inheritance . In hierarchical inheritance , the feature of one class may be inherited by more then one class."
},
{
"code": null,
"e": 8007,
"s": 7825,
"text": "Multilevel Inheritance - In multilevel Inheritance , A class is derived from an already derived class. The transitive nature of inheritance is reflected by this form of inheritance."
},
{
"code": null,
"e": 8189,
"s": 8007,
"text": "Multilevel Inheritance - In multilevel Inheritance , A class is derived from an already derived class. The transitive nature of inheritance is reflected by this form of inheritance."
},
{
"code": null,
"e": 8412,
"s": 8189,
"text": "Hybrid Inheritance - When two or more type of inheritance are required to code a program, such type of inheritance is called hybrid inheritance.\nFigure shown below is a combination of multilevel and multiple inheritance."
},
{
"code": null,
"e": 8635,
"s": 8412,
"text": "Hybrid Inheritance - When two or more type of inheritance are required to code a program, such type of inheritance is called hybrid inheritance.\nFigure shown below is a combination of multilevel and multiple inheritance."
},
{
"code": null,
"e": 8670,
"s": 8635,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8690,
"s": 8670,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 8723,
"s": 8690,
"text": "\n 60 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 8754,
"s": 8723,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 8786,
"s": 8754,
"text": "\n 11 Lectures \n 35 mins\n"
},
{
"code": null,
"e": 8807,
"s": 8786,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 8840,
"s": 8807,
"text": "\n 21 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 8860,
"s": 8840,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 8891,
"s": 8860,
"text": "\n 6 Lectures \n 43 mins\n"
},
{
"code": null,
"e": 8908,
"s": 8891,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 8943,
"s": 8908,
"text": "\n 49 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 8960,
"s": 8943,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 8967,
"s": 8960,
"text": " Print"
},
{
"code": null,
"e": 8978,
"s": 8967,
"text": " Add Notes"
}
] |
How to create a COVID19 Data Representation GUI? - GeeksforGeeks | 15 Feb, 2021
Prerequisites: Python Requests, Python GUI – tkinterSometimes we just want a quick fast tool to really tell whats the current update, we just need a bare minimum of data. Web scrapping deals with taking some data from the web and then processing it and displaying the relevant content in a short and crisp manner. What the code is doing ?
First we are using Tkinter Library to make GUI required for our script
We are using requests Library to get the data from the unofficial api
Then we are displaying the data we need in this case its Total active cases: and confirmed cases
below is the implementation.
Python3
import requestsimport jsonfrom tkinter import * window = Tk() # creating the Boxwindow.title("Covid-19") # Determining the size of the Boxwindow.geometry('220x70') # Including labelslbl = Label(window, text ="Total active cases:-......")lbl1 = Label(window, text ="Total confirmed cases:-...") lbl.grid(column = 1, row = 0)lbl1.grid(column = 1, row = 1)lbl2 = Label(window, text ="")lbl2.grid(column = 1, row = 3) def clicked(): # Opening the url and loading the # json data using json Library url = "https://api.covid19india.org / data.json" page = requests.get(url) data = json.loads(page.text) lbl.configure(text ="Total active cases:-" + data["statewise"][0]["active"]) lbl1.configure(text ="Total Confirmed cases:-" + data["statewise"][0]["confirmed"]) lbl2.configure(text ="Data refreshed") btn = Button(window, text ="Refresh", command = clicked)btn.grid(column = 2, row = 0) window.mainloop()
Output:
abhigoya
Python web-scraping-exercises
Python-requests
Python-tkinter
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Convert string to integer in Python
Python infinity
How to set input type date in dd-mm-yyyy format using HTML ?
Matplotlib.pyplot.title() in Python | [
{
"code": null,
"e": 24823,
"s": 24795,
"text": "\n15 Feb, 2021"
},
{
"code": null,
"e": 25164,
"s": 24823,
"text": "Prerequisites: Python Requests, Python GUI – tkinterSometimes we just want a quick fast tool to really tell whats the current update, we just need a bare minimum of data. Web scrapping deals with taking some data from the web and then processing it and displaying the relevant content in a short and crisp manner. What the code is doing ? "
},
{
"code": null,
"e": 25235,
"s": 25164,
"text": "First we are using Tkinter Library to make GUI required for our script"
},
{
"code": null,
"e": 25305,
"s": 25235,
"text": "We are using requests Library to get the data from the unofficial api"
},
{
"code": null,
"e": 25402,
"s": 25305,
"text": "Then we are displaying the data we need in this case its Total active cases: and confirmed cases"
},
{
"code": null,
"e": 25433,
"s": 25402,
"text": "below is the implementation. "
},
{
"code": null,
"e": 25441,
"s": 25433,
"text": "Python3"
},
{
"code": "import requestsimport jsonfrom tkinter import * window = Tk() # creating the Boxwindow.title(\"Covid-19\") # Determining the size of the Boxwindow.geometry('220x70') # Including labelslbl = Label(window, text =\"Total active cases:-......\")lbl1 = Label(window, text =\"Total confirmed cases:-...\") lbl.grid(column = 1, row = 0)lbl1.grid(column = 1, row = 1)lbl2 = Label(window, text =\"\")lbl2.grid(column = 1, row = 3) def clicked(): # Opening the url and loading the # json data using json Library url = \"https://api.covid19india.org / data.json\" page = requests.get(url) data = json.loads(page.text) lbl.configure(text =\"Total active cases:-\" + data[\"statewise\"][0][\"active\"]) lbl1.configure(text =\"Total Confirmed cases:-\" + data[\"statewise\"][0][\"confirmed\"]) lbl2.configure(text =\"Data refreshed\") btn = Button(window, text =\"Refresh\", command = clicked)btn.grid(column = 2, row = 0) window.mainloop()",
"e": 26440,
"s": 25441,
"text": null
},
{
"code": null,
"e": 26448,
"s": 26440,
"text": "Output:"
},
{
"code": null,
"e": 26461,
"s": 26452,
"text": "abhigoya"
},
{
"code": null,
"e": 26491,
"s": 26461,
"text": "Python web-scraping-exercises"
},
{
"code": null,
"e": 26507,
"s": 26491,
"text": "Python-requests"
},
{
"code": null,
"e": 26522,
"s": 26507,
"text": "Python-tkinter"
},
{
"code": null,
"e": 26529,
"s": 26522,
"text": "Python"
},
{
"code": null,
"e": 26545,
"s": 26529,
"text": "Write From Home"
},
{
"code": null,
"e": 26643,
"s": 26545,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26652,
"s": 26643,
"text": "Comments"
},
{
"code": null,
"e": 26665,
"s": 26652,
"text": "Old Comments"
},
{
"code": null,
"e": 26687,
"s": 26665,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26719,
"s": 26687,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26761,
"s": 26719,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26787,
"s": 26761,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26824,
"s": 26787,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26860,
"s": 26824,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 26896,
"s": 26860,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 26912,
"s": 26896,
"text": "Python infinity"
},
{
"code": null,
"e": 26973,
"s": 26912,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Stop copy-pasting notebooks, embrace Jupyter templates! | by Emanuele Fabbiani | Towards Data Science | Jupyter notebooks are awesome. They combine code, output and text, enabling fast prototyping, early debugging and effective storytelling.
Nonetheless, notebooks come with their own limitations, the most annoying ones being limited scalability, tendency to push developers to duplicate code and lack of a standard structure.
Lots of articles, posts and talks deal with these topics. Two of them have special relevance for the sake of this article. Joel Grus, in I don’t like notebooks, accuses notebooks for instillating bad habits in developers and data scientist. Answering Joel on Medium, Will Koehrsen suggest to blame sins and not sinners and proposes an interesting solution.
A template. A standard yet flexible skeleton for every kind of Data Science notebook. If people are provided with a proper structure to fill with their content, Will argues, they are nudged to implement best practices.
The benefit of this approach is that it changes the defaults.
When we read Will’s post, xtream’s data science team and I immediately looked for a package implementing the solution. Unfortunately, we found that no such thing existed on PiPy or conda.
Then, we decided to build our own: we developed a Jupyter extension with two main features.
First, it allows you to create every new notebook from a template. The template is a notebook itself, so that it can be easily edited by users and adapted to different needs. We also provide the possibility of inserting the template in an existing notebook.
The default template, shipped with the extension, is made of 6 sections:
Abstract: a quick summary of the notebook, is terms of its purpose, methodology, results and suggested next stepsSetup: package and local module imports, with the most common data science libraries already imported with their standard aliasParameters: definition of the parameters which affect the notebookData import: statements to load all the data to be used in the notebookData processing: core processing, often to be further divided into sub-sectionsReferences: useful references to literature or other notebooks
Abstract: a quick summary of the notebook, is terms of its purpose, methodology, results and suggested next steps
Setup: package and local module imports, with the most common data science libraries already imported with their standard alias
Parameters: definition of the parameters which affect the notebook
Data import: statements to load all the data to be used in the notebook
Data processing: core processing, often to be further divided into sub-sections
References: useful references to literature or other notebooks
It is important to note that this is just a default template. Every Data Scientist may create its own. If you happen to do so, let me know so that we may improve our repository.
Second, every time a notebook is saved as Untitled, the user is asked to rename it.
Of course, both the features can be enabled or disabled from the configuration of the extension.
Notable improvements became visible as soon as we introduced the usage of the extension in our workflow.
With a common skeleton, notebooks from other team members became easier to read and share. The Abstract, in particular, provided us with a 2-minute summary, allowing the reader to decide whether to dive deep into the code or look into other places.
With sections ready to be filled, we started feeling guilty when documenting our code superficially. This led to longer and more insightful comments, thus improving the overall readability of the notebooks.
With local imports configured and ready to be used, there was no excuse to prevent refactoring of relevant code out of the notebook and into common modules.
With naming conventions explicit in the template, no one could forget about them.
Finally, with standard imports embedded in the template, we were able to save some minutes googling for the way to correctly import modules.
Our extension is available in the package jupytemplate, open-source and published on GitHub: https://github.com/xtreamsrl/jupytemplate.
Although not strictly required, we suggest to start downloading the whole set of jupyter extensions, which currently does not include jupytemplate.
Then, install jupytemplate by running:
pip install jupytemplate
Finally, enable the extension in your local Jupyter instance:
jupyter nbextension install --py jupytemplate --sys-prefixjupyter nbextension enable jupytemplate/main --sys-prefix
More details in the documentation on GitHub.
That’s it. You should now be able to do something like this.
Thank you, my reader, for getting here!
Every comment, question, or general feedback is always welcome. You can get in touch with me on LinkedIn (link below).
If you appreciated this article, you may be interested in:
Lessons from a real Machine Learning project, part 1: from Jupyter to Luigi
Lessons from a real Machine Learning project, part 2: traps of Data Exploration
Introducing tsviz, interactive time series visualization in R Studio
If you are curious about about me or xtream, check us out on LinkedIn! | [
{
"code": null,
"e": 309,
"s": 171,
"text": "Jupyter notebooks are awesome. They combine code, output and text, enabling fast prototyping, early debugging and effective storytelling."
},
{
"code": null,
"e": 495,
"s": 309,
"text": "Nonetheless, notebooks come with their own limitations, the most annoying ones being limited scalability, tendency to push developers to duplicate code and lack of a standard structure."
},
{
"code": null,
"e": 852,
"s": 495,
"text": "Lots of articles, posts and talks deal with these topics. Two of them have special relevance for the sake of this article. Joel Grus, in I don’t like notebooks, accuses notebooks for instillating bad habits in developers and data scientist. Answering Joel on Medium, Will Koehrsen suggest to blame sins and not sinners and proposes an interesting solution."
},
{
"code": null,
"e": 1071,
"s": 852,
"text": "A template. A standard yet flexible skeleton for every kind of Data Science notebook. If people are provided with a proper structure to fill with their content, Will argues, they are nudged to implement best practices."
},
{
"code": null,
"e": 1133,
"s": 1071,
"text": "The benefit of this approach is that it changes the defaults."
},
{
"code": null,
"e": 1321,
"s": 1133,
"text": "When we read Will’s post, xtream’s data science team and I immediately looked for a package implementing the solution. Unfortunately, we found that no such thing existed on PiPy or conda."
},
{
"code": null,
"e": 1413,
"s": 1321,
"text": "Then, we decided to build our own: we developed a Jupyter extension with two main features."
},
{
"code": null,
"e": 1671,
"s": 1413,
"text": "First, it allows you to create every new notebook from a template. The template is a notebook itself, so that it can be easily edited by users and adapted to different needs. We also provide the possibility of inserting the template in an existing notebook."
},
{
"code": null,
"e": 1744,
"s": 1671,
"text": "The default template, shipped with the extension, is made of 6 sections:"
},
{
"code": null,
"e": 2263,
"s": 1744,
"text": "Abstract: a quick summary of the notebook, is terms of its purpose, methodology, results and suggested next stepsSetup: package and local module imports, with the most common data science libraries already imported with their standard aliasParameters: definition of the parameters which affect the notebookData import: statements to load all the data to be used in the notebookData processing: core processing, often to be further divided into sub-sectionsReferences: useful references to literature or other notebooks"
},
{
"code": null,
"e": 2377,
"s": 2263,
"text": "Abstract: a quick summary of the notebook, is terms of its purpose, methodology, results and suggested next steps"
},
{
"code": null,
"e": 2505,
"s": 2377,
"text": "Setup: package and local module imports, with the most common data science libraries already imported with their standard alias"
},
{
"code": null,
"e": 2572,
"s": 2505,
"text": "Parameters: definition of the parameters which affect the notebook"
},
{
"code": null,
"e": 2644,
"s": 2572,
"text": "Data import: statements to load all the data to be used in the notebook"
},
{
"code": null,
"e": 2724,
"s": 2644,
"text": "Data processing: core processing, often to be further divided into sub-sections"
},
{
"code": null,
"e": 2787,
"s": 2724,
"text": "References: useful references to literature or other notebooks"
},
{
"code": null,
"e": 2965,
"s": 2787,
"text": "It is important to note that this is just a default template. Every Data Scientist may create its own. If you happen to do so, let me know so that we may improve our repository."
},
{
"code": null,
"e": 3049,
"s": 2965,
"text": "Second, every time a notebook is saved as Untitled, the user is asked to rename it."
},
{
"code": null,
"e": 3146,
"s": 3049,
"text": "Of course, both the features can be enabled or disabled from the configuration of the extension."
},
{
"code": null,
"e": 3251,
"s": 3146,
"text": "Notable improvements became visible as soon as we introduced the usage of the extension in our workflow."
},
{
"code": null,
"e": 3500,
"s": 3251,
"text": "With a common skeleton, notebooks from other team members became easier to read and share. The Abstract, in particular, provided us with a 2-minute summary, allowing the reader to decide whether to dive deep into the code or look into other places."
},
{
"code": null,
"e": 3707,
"s": 3500,
"text": "With sections ready to be filled, we started feeling guilty when documenting our code superficially. This led to longer and more insightful comments, thus improving the overall readability of the notebooks."
},
{
"code": null,
"e": 3864,
"s": 3707,
"text": "With local imports configured and ready to be used, there was no excuse to prevent refactoring of relevant code out of the notebook and into common modules."
},
{
"code": null,
"e": 3946,
"s": 3864,
"text": "With naming conventions explicit in the template, no one could forget about them."
},
{
"code": null,
"e": 4087,
"s": 3946,
"text": "Finally, with standard imports embedded in the template, we were able to save some minutes googling for the way to correctly import modules."
},
{
"code": null,
"e": 4223,
"s": 4087,
"text": "Our extension is available in the package jupytemplate, open-source and published on GitHub: https://github.com/xtreamsrl/jupytemplate."
},
{
"code": null,
"e": 4371,
"s": 4223,
"text": "Although not strictly required, we suggest to start downloading the whole set of jupyter extensions, which currently does not include jupytemplate."
},
{
"code": null,
"e": 4410,
"s": 4371,
"text": "Then, install jupytemplate by running:"
},
{
"code": null,
"e": 4435,
"s": 4410,
"text": "pip install jupytemplate"
},
{
"code": null,
"e": 4497,
"s": 4435,
"text": "Finally, enable the extension in your local Jupyter instance:"
},
{
"code": null,
"e": 4613,
"s": 4497,
"text": "jupyter nbextension install --py jupytemplate --sys-prefixjupyter nbextension enable jupytemplate/main --sys-prefix"
},
{
"code": null,
"e": 4658,
"s": 4613,
"text": "More details in the documentation on GitHub."
},
{
"code": null,
"e": 4719,
"s": 4658,
"text": "That’s it. You should now be able to do something like this."
},
{
"code": null,
"e": 4759,
"s": 4719,
"text": "Thank you, my reader, for getting here!"
},
{
"code": null,
"e": 4878,
"s": 4759,
"text": "Every comment, question, or general feedback is always welcome. You can get in touch with me on LinkedIn (link below)."
},
{
"code": null,
"e": 4937,
"s": 4878,
"text": "If you appreciated this article, you may be interested in:"
},
{
"code": null,
"e": 5013,
"s": 4937,
"text": "Lessons from a real Machine Learning project, part 1: from Jupyter to Luigi"
},
{
"code": null,
"e": 5093,
"s": 5013,
"text": "Lessons from a real Machine Learning project, part 2: traps of Data Exploration"
},
{
"code": null,
"e": 5162,
"s": 5093,
"text": "Introducing tsviz, interactive time series visualization in R Studio"
}
] |
Lexicographically smallest string of length N and sum K - GeeksforGeeks | 14 May, 2021
Given two integers N and K. The task is to print the lexicographically smallest string of length N consisting of lower-case English alphabates such that the sum of the characters of the string equals to K where ‘a’ = 1, ‘b’ = 2, ‘c’ = 3, ..... and ‘z’ = 26.Examples:
Input: N = 5, K = 42 Output: aaamz “aaany”, “babmx”, “aablz” etc. are also valid strings but “aaamz” is the lexicographically smallest.Input: N = 3, K = 25 Output: aaw
Approach:
Initialize char array of size N and fill all the element by ‘a’.
Start traversing from the end of the array and replace the elements of the array by ‘z’ if K ≥ 26 or replace it by the character having ASCII value (K + 97 – 1).
At the same time decrease the value of K by replaced element value i.e. for a = 1, b = 2, c = 3, ..., z = 26.
Also, note that we are subtracting previous element value i.e. (total ‘a’) before current element and adding the same before the end of for loop.
Check for K < 0 condition and break the for loop.
Return the new string formed by the elements of the char array as the answer.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include<bits/stdc++.h>using namespace std; // Function to return the lexicographically// smallest string of length n that// satisfies the given conditionstring lexo_small(int n, int k){ string arr = ""; for(int i = 0; i < n; i++) arr += 'a'; // Iteration from the last position // in the array for (int i = n - 1; i >= 0; i--) { k -= i; // If k is a positive integer if (k >= 0) { // 'z' needs to be inserted if (k >= 26) { arr[i] = 'z'; k -= 26; } // Add the required character else { char c= (char)(k + 97 - 1); arr[i] = c; k -= arr[i] - 'a' + 1; } } else break; k += i; } return arr;} // Driver codeint main(){ int n = 5, k = 42; string arr = lexo_small(n, k); cout << arr;} // This code is contributed by Mohit Kumar
// Java implementation of the approachimport java.util.Arrays; public class Main { // Function to return the lexicographically // smallest string of length n that // satisfies the given condition public static char[] lexo_small(int n, int k) { char arr[] = new char[n]; Arrays.fill(arr, 'a'); // Iteration from the last position // in the array for (int i = n - 1; i >= 0; i--) { k -= i; // If k is a positive integer if (k >= 0) { // 'z' needs to be inserted if (k >= 26) { arr[i] = 'z'; k -= 26; } // Add the required character else { arr[i] = (char)(k + 97 - 1); k -= arr[i] - 'a' + 1; } } else break; k += i; } return arr; } // Driver code public static void main(String[] args) { int n = 5, k = 42; char arr[] = lexo_small(n, k); System.out.print(new String(arr)); }}
# Python implementation of the approach # Function to return the lexicographically# smallest string of length n that# satisfies the given conditiondef lexo_small(n, k): arr = ""; for i in range(n): arr += 'a'; # Iteration from the last position # in the array for i in range(n-1,-1,-1): k -= i; # If k is a positive integer if (k >= 0): # 'z' needs to be inserted if (k >= 26): arr = arr[:i] + 'z' + arr[i+1:]; k -= 26; # Add the required character else: c= (k + 97 - 1); arr = arr[:i] + chr(c) + arr[i+1:]; k -= ord(arr[i]) - ord('a') + 1; else: break; k += i; return arr; # Driver codeif __name__ == '__main__': n = 5; k = 42; arr = lexo_small(n, k); print(arr); # This code contributed by PrinciRaj1992
// C# implementation of the approachusing System; class GFG{ // Function to return the lexicographically // smallest string of length n that // satisfies the given condition public static char[] lexo_small(int n, int k) { char []arr = new char[n]; int i; for(i = 0; i < n; i++) arr[i] = 'a' ; // Iteration from the last position // in the array for (i = n - 1; i >= 0; i--) { k -= i; // If k is a positive integer if (k >= 0) { // 'z' needs to be inserted if (k >= 26) { arr[i] = 'z'; k -= 26; } // Add the required character else { arr[i] = (char)(k + 97 - 1); k -= arr[i] - 'a' + 1; } } else break; k += i; } return arr; } // Driver code public static void Main() { int n = 5, k = 42; char []arr = lexo_small(n, k); Console.WriteLine(new string(arr)); }} // This code is contributed by AnkitRai01
<script> // javascript implementation of the approach // Function to return the lexicographically// smallest string of length n that// satisfies the given conditionfunction lexo_small(n , k){ var arr = Array.from({length: n}, (_, i) => 'a'); // Iteration from the last position // in the array for (var i = n - 1; i >= 0; i--) { k -= i; // If k is a positive integer if (k >= 0) { // 'z' needs to be inserted if (k >= 26) { arr[i] = 'z'; k -= 26; } // Add the required character else { arr[i] = String.fromCharCode(k + 97 - 1); k -= arr[i] - 'a' + 1; } } else break; k += i; } return arr;} // Driver codevar n = 5, k = 42; var arr = lexo_small(n, k); document.write(arr.join('')); // This code contributed by shikhasingrajput</script>
aaamz
ankthon
mohit kumar 29
princiraj1992
shikhasingrajput
Deutsche Bank
lexicographic-ordering
Greedy
Strings
Strings
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program for First Fit algorithm in Memory Management
Program for Best Fit algorithm in Memory Management
Optimal Page Replacement Algorithm
Max Flow Problem Introduction
Program for Worst Fit algorithm in Memory Management
Reverse a string in Java
Write a program to reverse an array or string
C++ Data Types
Longest Common Subsequence | DP-4
Different methods to reverse a string in C/C++ | [
{
"code": null,
"e": 25240,
"s": 25212,
"text": "\n14 May, 2021"
},
{
"code": null,
"e": 25509,
"s": 25240,
"text": "Given two integers N and K. The task is to print the lexicographically smallest string of length N consisting of lower-case English alphabates such that the sum of the characters of the string equals to K where ‘a’ = 1, ‘b’ = 2, ‘c’ = 3, ..... and ‘z’ = 26.Examples: "
},
{
"code": null,
"e": 25679,
"s": 25509,
"text": "Input: N = 5, K = 42 Output: aaamz “aaany”, “babmx”, “aablz” etc. are also valid strings but “aaamz” is the lexicographically smallest.Input: N = 3, K = 25 Output: aaw "
},
{
"code": null,
"e": 25693,
"s": 25681,
"text": "Approach: "
},
{
"code": null,
"e": 25758,
"s": 25693,
"text": "Initialize char array of size N and fill all the element by ‘a’."
},
{
"code": null,
"e": 25920,
"s": 25758,
"text": "Start traversing from the end of the array and replace the elements of the array by ‘z’ if K ≥ 26 or replace it by the character having ASCII value (K + 97 – 1)."
},
{
"code": null,
"e": 26030,
"s": 25920,
"text": "At the same time decrease the value of K by replaced element value i.e. for a = 1, b = 2, c = 3, ..., z = 26."
},
{
"code": null,
"e": 26176,
"s": 26030,
"text": "Also, note that we are subtracting previous element value i.e. (total ‘a’) before current element and adding the same before the end of for loop."
},
{
"code": null,
"e": 26226,
"s": 26176,
"text": "Check for K < 0 condition and break the for loop."
},
{
"code": null,
"e": 26304,
"s": 26226,
"text": "Return the new string formed by the elements of the char array as the answer."
},
{
"code": null,
"e": 26357,
"s": 26304,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26361,
"s": 26357,
"text": "C++"
},
{
"code": null,
"e": 26366,
"s": 26361,
"text": "Java"
},
{
"code": null,
"e": 26374,
"s": 26366,
"text": "Python3"
},
{
"code": null,
"e": 26377,
"s": 26374,
"text": "C#"
},
{
"code": null,
"e": 26388,
"s": 26377,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include<bits/stdc++.h>using namespace std; // Function to return the lexicographically// smallest string of length n that// satisfies the given conditionstring lexo_small(int n, int k){ string arr = \"\"; for(int i = 0; i < n; i++) arr += 'a'; // Iteration from the last position // in the array for (int i = n - 1; i >= 0; i--) { k -= i; // If k is a positive integer if (k >= 0) { // 'z' needs to be inserted if (k >= 26) { arr[i] = 'z'; k -= 26; } // Add the required character else { char c= (char)(k + 97 - 1); arr[i] = c; k -= arr[i] - 'a' + 1; } } else break; k += i; } return arr;} // Driver codeint main(){ int n = 5, k = 42; string arr = lexo_small(n, k); cout << arr;} // This code is contributed by Mohit Kumar",
"e": 27419,
"s": 26388,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.Arrays; public class Main { // Function to return the lexicographically // smallest string of length n that // satisfies the given condition public static char[] lexo_small(int n, int k) { char arr[] = new char[n]; Arrays.fill(arr, 'a'); // Iteration from the last position // in the array for (int i = n - 1; i >= 0; i--) { k -= i; // If k is a positive integer if (k >= 0) { // 'z' needs to be inserted if (k >= 26) { arr[i] = 'z'; k -= 26; } // Add the required character else { arr[i] = (char)(k + 97 - 1); k -= arr[i] - 'a' + 1; } } else break; k += i; } return arr; } // Driver code public static void main(String[] args) { int n = 5, k = 42; char arr[] = lexo_small(n, k); System.out.print(new String(arr)); }}",
"e": 28552,
"s": 27419,
"text": null
},
{
"code": "# Python implementation of the approach # Function to return the lexicographically# smallest string of length n that# satisfies the given conditiondef lexo_small(n, k): arr = \"\"; for i in range(n): arr += 'a'; # Iteration from the last position # in the array for i in range(n-1,-1,-1): k -= i; # If k is a positive integer if (k >= 0): # 'z' needs to be inserted if (k >= 26): arr = arr[:i] + 'z' + arr[i+1:]; k -= 26; # Add the required character else: c= (k + 97 - 1); arr = arr[:i] + chr(c) + arr[i+1:]; k -= ord(arr[i]) - ord('a') + 1; else: break; k += i; return arr; # Driver codeif __name__ == '__main__': n = 5; k = 42; arr = lexo_small(n, k); print(arr); # This code contributed by PrinciRaj1992",
"e": 29475,
"s": 28552,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the lexicographically // smallest string of length n that // satisfies the given condition public static char[] lexo_small(int n, int k) { char []arr = new char[n]; int i; for(i = 0; i < n; i++) arr[i] = 'a' ; // Iteration from the last position // in the array for (i = n - 1; i >= 0; i--) { k -= i; // If k is a positive integer if (k >= 0) { // 'z' needs to be inserted if (k >= 26) { arr[i] = 'z'; k -= 26; } // Add the required character else { arr[i] = (char)(k + 97 - 1); k -= arr[i] - 'a' + 1; } } else break; k += i; } return arr; } // Driver code public static void Main() { int n = 5, k = 42; char []arr = lexo_small(n, k); Console.WriteLine(new string(arr)); }} // This code is contributed by AnkitRai01",
"e": 30706,
"s": 29475,
"text": null
},
{
"code": "<script> // javascript implementation of the approach // Function to return the lexicographically// smallest string of length n that// satisfies the given conditionfunction lexo_small(n , k){ var arr = Array.from({length: n}, (_, i) => 'a'); // Iteration from the last position // in the array for (var i = n - 1; i >= 0; i--) { k -= i; // If k is a positive integer if (k >= 0) { // 'z' needs to be inserted if (k >= 26) { arr[i] = 'z'; k -= 26; } // Add the required character else { arr[i] = String.fromCharCode(k + 97 - 1); k -= arr[i] - 'a' + 1; } } else break; k += i; } return arr;} // Driver codevar n = 5, k = 42; var arr = lexo_small(n, k); document.write(arr.join('')); // This code contributed by shikhasingrajput</script>",
"e": 31647,
"s": 30706,
"text": null
},
{
"code": null,
"e": 31653,
"s": 31647,
"text": "aaamz"
},
{
"code": null,
"e": 31663,
"s": 31655,
"text": "ankthon"
},
{
"code": null,
"e": 31678,
"s": 31663,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 31692,
"s": 31678,
"text": "princiraj1992"
},
{
"code": null,
"e": 31709,
"s": 31692,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 31723,
"s": 31709,
"text": "Deutsche Bank"
},
{
"code": null,
"e": 31746,
"s": 31723,
"text": "lexicographic-ordering"
},
{
"code": null,
"e": 31753,
"s": 31746,
"text": "Greedy"
},
{
"code": null,
"e": 31761,
"s": 31753,
"text": "Strings"
},
{
"code": null,
"e": 31769,
"s": 31761,
"text": "Strings"
},
{
"code": null,
"e": 31776,
"s": 31769,
"text": "Greedy"
},
{
"code": null,
"e": 31874,
"s": 31776,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31883,
"s": 31874,
"text": "Comments"
},
{
"code": null,
"e": 31896,
"s": 31883,
"text": "Old Comments"
},
{
"code": null,
"e": 31949,
"s": 31896,
"text": "Program for First Fit algorithm in Memory Management"
},
{
"code": null,
"e": 32001,
"s": 31949,
"text": "Program for Best Fit algorithm in Memory Management"
},
{
"code": null,
"e": 32036,
"s": 32001,
"text": "Optimal Page Replacement Algorithm"
},
{
"code": null,
"e": 32066,
"s": 32036,
"text": "Max Flow Problem Introduction"
},
{
"code": null,
"e": 32119,
"s": 32066,
"text": "Program for Worst Fit algorithm in Memory Management"
},
{
"code": null,
"e": 32144,
"s": 32119,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 32190,
"s": 32144,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 32205,
"s": 32190,
"text": "C++ Data Types"
},
{
"code": null,
"e": 32239,
"s": 32205,
"text": "Longest Common Subsequence | DP-4"
}
] |
How to initialize a boolean array in JavaScript? | To initialize a Boolean array in JavaScript, try to run the following code −
Live Demo
<html>
<head>
<title>JavaScript Boolean</title>
</head>
<body>
<script>
var myArr = [];
var value = 2;
for(var i = 0; i < value; i++) {
myArr.push(false);
}
alert(myArr);
</script>
</body>
</html> | [
{
"code": null,
"e": 1139,
"s": 1062,
"text": "To initialize a Boolean array in JavaScript, try to run the following code −"
},
{
"code": null,
"e": 1149,
"s": 1139,
"text": "Live Demo"
},
{
"code": null,
"e": 1435,
"s": 1149,
"text": "<html>\n <head>\n <title>JavaScript Boolean</title>\n </head>\n \n <body>\n <script>\n var myArr = [];\n var value = 2;\n for(var i = 0; i < value; i++) {\n myArr.push(false);\n }\n alert(myArr);\n </script>\n </body>\n</html>"
}
] |
Variadic function templates in C++ | Variadic function templates in C++ is a function which can take a multiple number of arguments.
template(typename arg, typename... args)
return_type function_name(arg var1, args... var2)
Live Demo
#include <iostream>
using namespace std;
void show() //base case. {
cout << "I am now empty";
}
template <typename T, typename... T2>// variadic function
void show(T v1, T2... v2) {
cout << v1 << endl;
show(v2...) ;
}
int main() {
show(7, 6, 0.04, "hi ","I am variadic function","I will show\n");
return 0;
}
7
6
0.04
hi I am variadic function
I will show
I am now empty | [
{
"code": null,
"e": 1158,
"s": 1062,
"text": "Variadic function templates in C++ is a function which can take a multiple number of arguments."
},
{
"code": null,
"e": 1249,
"s": 1158,
"text": "template(typename arg, typename... args)\nreturn_type function_name(arg var1, args... var2)"
},
{
"code": null,
"e": 1260,
"s": 1249,
"text": " Live Demo"
},
{
"code": null,
"e": 1586,
"s": 1260,
"text": "#include <iostream>\nusing namespace std;\nvoid show() //base case. {\n cout << \"I am now empty\";\n}\n\ntemplate <typename T, typename... T2>// variadic function\nvoid show(T v1, T2... v2) {\n cout << v1 << endl;\n show(v2...) ;\n}\n\nint main() {\n show(7, 6, 0.04, \"hi \",\"I am variadic function\",\"I will show\\n\");\n return 0;\n}"
},
{
"code": null,
"e": 1649,
"s": 1586,
"text": "7\n6\n0.04\nhi I am variadic function\nI will show\n\nI am now empty"
}
] |
How to pretty print JSON using the Gson library in Java? | A Gson is a JSON library for java, which is created by Google. By using Gson, we can generate JSON and convert JSON to java objects. By default, Gson can print the JSON in compact format. To enable Gson pretty print, we must configure the Gson instance using the setPrettyPrinting() method of GsonBuilder class and this method configures Gson to output JSON that fits in a page for pretty printing.
public GsonBuilder setPrettyPrinting()
import java.util.*;
import com.google.gson.*;
public class PrettyJSONTest {
public static void main( String[] args ) {
Employee emp = new Employee("Raja", "115", "Content Engineer", "Java", "Hyderabad");
Gson gson = new GsonBuilder().setPrettyPrinting().create(); // pretty print
String prettyJson = gson.toJson(emp);
System.out.println(prettyJson);
}
}
// Employee class
class Employee {
private String name, id, designation, technology, location;
public Employee(String name, String id, String designation, String technology, String location) {
super();
this.name = name;
this.id = id;
this.designation = designation;
this.technology = technology;
this.location = location;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
public String getDesignation() {
return designation;
}
public String getTechnology() {
return technology;
}
public String getLocation() {
return location;
}
}
{
"name": "Raja",
"id": "115",
"designation": "Content Engineer",
"technology": "Java",
"location": "Hyderabad"
} | [
{
"code": null,
"e": 1461,
"s": 1062,
"text": "A Gson is a JSON library for java, which is created by Google. By using Gson, we can generate JSON and convert JSON to java objects. By default, Gson can print the JSON in compact format. To enable Gson pretty print, we must configure the Gson instance using the setPrettyPrinting() method of GsonBuilder class and this method configures Gson to output JSON that fits in a page for pretty printing."
},
{
"code": null,
"e": 1500,
"s": 1461,
"text": "public GsonBuilder setPrettyPrinting()"
},
{
"code": null,
"e": 2550,
"s": 1500,
"text": "import java.util.*;\nimport com.google.gson.*;\npublic class PrettyJSONTest {\n public static void main( String[] args ) {\n Employee emp = new Employee(\"Raja\", \"115\", \"Content Engineer\", \"Java\", \"Hyderabad\");\n Gson gson = new GsonBuilder().setPrettyPrinting().create(); // pretty print\n String prettyJson = gson.toJson(emp);\n System.out.println(prettyJson);\n }\n}\n// Employee class\nclass Employee {\n private String name, id, designation, technology, location;\n public Employee(String name, String id, String designation, String technology, String location) {\n super();\n this.name = name;\n this.id = id;\n this.designation = designation;\n this.technology = technology;\n this.location = location;\n }\n public String getName() {\n return name;\n }\n public String getId() {\n return id;\n }\n public String getDesignation() {\n return designation;\n }\n public String getTechnology() {\n return technology;\n }\n public String getLocation() {\n return location;\n }\n}"
},
{
"code": null,
"e": 2669,
"s": 2550,
"text": "{\n \"name\": \"Raja\",\n \"id\": \"115\",\n \"designation\": \"Content Engineer\",\n \"technology\": \"Java\",\n \"location\": \"Hyderabad\"\n}"
}
] |
Style the Bootstrap modal | Use the .modal-body class in Bootstrap to style the modal.
You can try to run the following code to style modal −/p>
LIve Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class = "container">
<h2>Website Information</h2>
<button type = "button" class = "btn btn-lg" data-toggle = "modal" data-target = "#new">Info</button>
<div class = "modal fade" id="new" role="dialog">
<div class = "modal-dialog">
<div class = "modal-content">
<div class = "modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Warning</h4>
</div>
<div class = "modal-body">
<p>If JavaScript isn't enabled in your web browser, then you may not be able to see this information correcty.</p>
</div>
<div class = "modal-footer">
<button type = "button" class = "btn btn-default" data-dismiss = "modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html> | [
{
"code": null,
"e": 1121,
"s": 1062,
"text": "Use the .modal-body class in Bootstrap to style the modal."
},
{
"code": null,
"e": 1179,
"s": 1121,
"text": "You can try to run the following code to style modal −/p>"
},
{
"code": null,
"e": 1189,
"s": 1179,
"text": "LIve Demo"
},
{
"code": null,
"e": 2611,
"s": 1189,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link rel = \"stylesheet\" href = \"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"container\">\n <h2>Website Information</h2>\n <button type = \"button\" class = \"btn btn-lg\" data-toggle = \"modal\" data-target = \"#new\">Info</button>\n <div class = \"modal fade\" id=\"new\" role=\"dialog\">\n <div class = \"modal-dialog\">\n <div class = \"modal-content\">\n <div class = \"modal-header\">\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\">×</button>\n <h4 class=\"modal-title\">Warning</h4>\n </div>\n <div class = \"modal-body\">\n <p>If JavaScript isn't enabled in your web browser, then you may not be able to see this information correcty.</p>\n </div>\n <div class = \"modal-footer\">\n <button type = \"button\" class = \"btn btn-default\" data-dismiss = \"modal\">Close</button>\n </div>\n </div>\n </div>\n </div>\n </div>\n </body>\n</html>"
}
] |
Angular 2 - Templates | In the chapter on Components, we have already seen an example of the following template.
template: '
<div>
<h1>{{appTitle}}</h1>
<div>To Tutorials Point</div>
</div>
'
This is known as an inline template. There are other ways to define a template and that can be done via the templateURL command. The simplest way to use this in the component is as follows.
templateURL:
viewname.component.html
viewname − This is the name of the app component module.
viewname − This is the name of the app component module.
After the viewname, the component needs to be added to the file name.
Following are the steps to define an inline template.
Step 1 − Create a file called app.component.html. This will contain the html code for the view.
Step 2 − Add the following code in the above created file.
<div>{{appTitle}} Tutorialspoint </div>
This defines a simple div tag and references the appTitle property from the app.component class.
Step 3 − In the app.component.ts file, add the following code.
import { Component } from '@angular/core';
@Component ({
selector: 'my-app',
templateUrl: 'app/app.component.html'
})
export class AppComponent {
appTitle: string = 'Welcome';
}
From the above code, the only change that can be noted is from the templateURL, which gives the link to the app.component.html file which is located in the app folder.
Step 4 − Run the code in the browser, you will get the following output.
From the output, it can be seen that the template file (app.component.html) file is being called accordingly.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2386,
"s": 2297,
"text": "In the chapter on Components, we have already seen an example of the following template."
},
{
"code": null,
"e": 2483,
"s": 2386,
"text": "template: '\n <div>\n <h1>{{appTitle}}</h1>\n <div>To Tutorials Point</div>\n </div>\n'"
},
{
"code": null,
"e": 2673,
"s": 2483,
"text": "This is known as an inline template. There are other ways to define a template and that can be done via the templateURL command. The simplest way to use this in the component is as follows."
},
{
"code": null,
"e": 2711,
"s": 2673,
"text": "templateURL:\nviewname.component.html\n"
},
{
"code": null,
"e": 2768,
"s": 2711,
"text": "viewname − This is the name of the app component module."
},
{
"code": null,
"e": 2825,
"s": 2768,
"text": "viewname − This is the name of the app component module."
},
{
"code": null,
"e": 2895,
"s": 2825,
"text": "After the viewname, the component needs to be added to the file name."
},
{
"code": null,
"e": 2949,
"s": 2895,
"text": "Following are the steps to define an inline template."
},
{
"code": null,
"e": 3045,
"s": 2949,
"text": "Step 1 − Create a file called app.component.html. This will contain the html code for the view."
},
{
"code": null,
"e": 3104,
"s": 3045,
"text": "Step 2 − Add the following code in the above created file."
},
{
"code": null,
"e": 3145,
"s": 3104,
"text": "<div>{{appTitle}} Tutorialspoint </div>\n"
},
{
"code": null,
"e": 3242,
"s": 3145,
"text": "This defines a simple div tag and references the appTitle property from the app.component class."
},
{
"code": null,
"e": 3305,
"s": 3242,
"text": "Step 3 − In the app.component.ts file, add the following code."
},
{
"code": null,
"e": 3496,
"s": 3305,
"text": "import { Component } from '@angular/core';\n\n@Component ({\n selector: 'my-app',\n templateUrl: 'app/app.component.html' \n})\n\nexport class AppComponent {\n appTitle: string = 'Welcome';\n}"
},
{
"code": null,
"e": 3664,
"s": 3496,
"text": "From the above code, the only change that can be noted is from the templateURL, which gives the link to the app.component.html file which is located in the app folder."
},
{
"code": null,
"e": 3737,
"s": 3664,
"text": "Step 4 − Run the code in the browser, you will get the following output."
},
{
"code": null,
"e": 3847,
"s": 3737,
"text": "From the output, it can be seen that the template file (app.component.html) file is being called accordingly."
},
{
"code": null,
"e": 3882,
"s": 3847,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3896,
"s": 3882,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3931,
"s": 3896,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3945,
"s": 3931,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3980,
"s": 3945,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 4000,
"s": 3980,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 4035,
"s": 4000,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4052,
"s": 4035,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4085,
"s": 4052,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4097,
"s": 4085,
"text": " Senol Atac"
},
{
"code": null,
"e": 4132,
"s": 4097,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4144,
"s": 4132,
"text": " Senol Atac"
},
{
"code": null,
"e": 4151,
"s": 4144,
"text": " Print"
},
{
"code": null,
"e": 4162,
"s": 4151,
"text": " Add Notes"
}
] |
Difference between order by and group by clause in SQL - GeeksforGeeks | 22 Apr, 2020
1. Order By :Order by keyword sort the result-set either in ascending or in descending order. This clause sorts the result-set in ascending order by default. In order to sort the result-set in descending order DESC keyword is used.
Order By Syntax –
SELECT column_1, column_2, column_3...........
FROM Table_Name
ORDER BY column_1, column_2, column_3....... ASC|DESC;
Table_Name: Name of the table.
ASC: keyword for ascending order
DESC: keyword for descending order
2. Group By :Group by statement is used to group the rows that have the same value. It is often used with aggregate functions for example:AVG(), MAX(), COUNT(), MIN() etc. One thing to remember about the group by clause is that the tuples are grouped based on the similarity between the attribute values of tuples.
Group By Syntax –
SELECT function_Name(column_1), column_2
FROM Table_Name
WHERE condition
GROUP BY column_1, column_2
ORDER BY column_1, column_2;
function_Name: Name of the aggregate function, for example:
SUM(), AVG(), COUNT() etc.
Table_Name: Name of the table.
Let’s see the difference between Order by and group by clause:-
ashushrma378
DBMS
Difference Between
GATE CS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
CTE in SQL
SQL Trigger | Student Database
Introduction of B-Tree
Difference between Clustered and Non-clustered index
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Differences between IPv4 and IPv6 | [
{
"code": null,
"e": 25211,
"s": 25183,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 25443,
"s": 25211,
"text": "1. Order By :Order by keyword sort the result-set either in ascending or in descending order. This clause sorts the result-set in ascending order by default. In order to sort the result-set in descending order DESC keyword is used."
},
{
"code": null,
"e": 25461,
"s": 25443,
"text": "Order By Syntax –"
},
{
"code": null,
"e": 25681,
"s": 25461,
"text": "SELECT column_1, column_2, column_3...........\nFROM Table_Name\nORDER BY column_1, column_2, column_3....... ASC|DESC;\n\n\nTable_Name: Name of the table.\nASC: keyword for ascending order\nDESC: keyword for descending order "
},
{
"code": null,
"e": 25996,
"s": 25681,
"text": "2. Group By :Group by statement is used to group the rows that have the same value. It is often used with aggregate functions for example:AVG(), MAX(), COUNT(), MIN() etc. One thing to remember about the group by clause is that the tuples are grouped based on the similarity between the attribute values of tuples."
},
{
"code": null,
"e": 26014,
"s": 25996,
"text": "Group By Syntax –"
},
{
"code": null,
"e": 26145,
"s": 26014,
"text": "SELECT function_Name(column_1), column_2\nFROM Table_Name\nWHERE condition\nGROUP BY column_1, column_2\nORDER BY column_1, column_2; "
},
{
"code": null,
"e": 26205,
"s": 26145,
"text": "function_Name: Name of the aggregate function, for example:"
},
{
"code": null,
"e": 26265,
"s": 26205,
"text": "SUM(), AVG(), COUNT() etc.\n\nTable_Name: Name of the table. "
},
{
"code": null,
"e": 26329,
"s": 26265,
"text": "Let’s see the difference between Order by and group by clause:-"
},
{
"code": null,
"e": 26342,
"s": 26329,
"text": "ashushrma378"
},
{
"code": null,
"e": 26347,
"s": 26342,
"text": "DBMS"
},
{
"code": null,
"e": 26366,
"s": 26347,
"text": "Difference Between"
},
{
"code": null,
"e": 26374,
"s": 26366,
"text": "GATE CS"
},
{
"code": null,
"e": 26378,
"s": 26374,
"text": "SQL"
},
{
"code": null,
"e": 26383,
"s": 26378,
"text": "DBMS"
},
{
"code": null,
"e": 26387,
"s": 26383,
"text": "SQL"
},
{
"code": null,
"e": 26485,
"s": 26387,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26509,
"s": 26485,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 26520,
"s": 26509,
"text": "CTE in SQL"
},
{
"code": null,
"e": 26551,
"s": 26520,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 26574,
"s": 26551,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 26627,
"s": 26574,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 26658,
"s": 26627,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 26698,
"s": 26658,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 26730,
"s": 26698,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 26791,
"s": 26730,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
GitLab - Squashing Commits | Squashing is a way of combining all commits into one when you are obtaining a merge request.
Step 1 − Go to your project directory and check out a new branch with the name squash-chapter by using the git checkout command −
The flag -b indicates new branch name.
Step 2 − Now, create a new file with two commits, add that file to working directory and store the changes to the repository along with the commit messages as shown below −
Step 3 − Now, squash the above two commits into one commit by using the below command −
$ git rebase -i HEAD~2
Here, git rebase command is used to integrate changes from one branch to another and HEAD~2 specifies last two squashed commits and if you want to squash four commits, then you need to write as HEAD~4. One more important point is, you need atleast two commits to complete the squash operation.
Step 4 − After entering the above command, it will open the below editor in which you have to change the pick word to squash word in the second line (you need to squash this commit).
Now press the Esc key, then colon(:) and type wq to save and exit from the screen.
Step 5 − Now push the branch to remote repository as shown below −
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2417,
"s": 2324,
"text": "Squashing is a way of combining all commits into one when you are obtaining a merge request."
},
{
"code": null,
"e": 2547,
"s": 2417,
"text": "Step 1 − Go to your project directory and check out a new branch with the name squash-chapter by using the git checkout command −"
},
{
"code": null,
"e": 2586,
"s": 2547,
"text": "The flag -b indicates new branch name."
},
{
"code": null,
"e": 2759,
"s": 2586,
"text": "Step 2 − Now, create a new file with two commits, add that file to working directory and store the changes to the repository along with the commit messages as shown below −"
},
{
"code": null,
"e": 2847,
"s": 2759,
"text": "Step 3 − Now, squash the above two commits into one commit by using the below command −"
},
{
"code": null,
"e": 2871,
"s": 2847,
"text": "$ git rebase -i HEAD~2\n"
},
{
"code": null,
"e": 3165,
"s": 2871,
"text": "Here, git rebase command is used to integrate changes from one branch to another and HEAD~2 specifies last two squashed commits and if you want to squash four commits, then you need to write as HEAD~4. One more important point is, you need atleast two commits to complete the squash operation."
},
{
"code": null,
"e": 3349,
"s": 3165,
"text": "Step 4 − After entering the above command, it will open the below editor in which you have to change the pick word to squash word in the second line (you need to squash this commit)."
},
{
"code": null,
"e": 3432,
"s": 3349,
"text": "Now press the Esc key, then colon(:) and type wq to save and exit from the screen."
},
{
"code": null,
"e": 3499,
"s": 3432,
"text": "Step 5 − Now push the branch to remote repository as shown below −"
},
{
"code": null,
"e": 3506,
"s": 3499,
"text": " Print"
},
{
"code": null,
"e": 3517,
"s": 3506,
"text": " Add Notes"
}
] |
JavaScript | string.length - GeeksforGeeks | 02 Jul, 2018
The string.length is a property in JavaScript which is used to find the length of a given string.Syntax:
string.length
Parameter: It does not accept any parameter.Return Values: It returns the length of the given string.
<script> // Taking some strings var x = 'geeksforgeeks'; var y = 'gfg'; var z = ''; // Returning the length of the string. document.write(x.length + "<br>"); document.write(y.length + "<br>"); document.write(z.length); </script>
Output:
13
3
0
Code #2:
<script> // Taking some strings. var x = '2341312134'; var y = '@#$%^&**((*&^'; // Variable z contains two spaces var z = ' '; // Returning the length of the string. document.write(x.length + "<br>"); document.write(y.length + "<br>"); document.write(z.length); </script>
Output:
10
13
2
javascript-string
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
Difference Between PUT and PATCH Request
Set the value of an input field in JavaScript
How to Use the JavaScript Fetch API to Get Data?
Node.js | fs.writeFileSync() Method
Difference between TypeScript and JavaScript
Create a Responsive Navbar using ReactJS
Form validation using HTML and JavaScript | [
{
"code": null,
"e": 24527,
"s": 24499,
"text": "\n02 Jul, 2018"
},
{
"code": null,
"e": 24632,
"s": 24527,
"text": "The string.length is a property in JavaScript which is used to find the length of a given string.Syntax:"
},
{
"code": null,
"e": 24646,
"s": 24632,
"text": "string.length"
},
{
"code": null,
"e": 24748,
"s": 24646,
"text": "Parameter: It does not accept any parameter.Return Values: It returns the length of the given string."
},
{
"code": "<script> // Taking some strings var x = 'geeksforgeeks'; var y = 'gfg'; var z = ''; // Returning the length of the string. document.write(x.length + \"<br>\"); document.write(y.length + \"<br>\"); document.write(z.length); </script>",
"e": 25006,
"s": 24748,
"text": null
},
{
"code": null,
"e": 25014,
"s": 25006,
"text": "Output:"
},
{
"code": null,
"e": 25021,
"s": 25014,
"text": "13\n3\n0"
},
{
"code": null,
"e": 25030,
"s": 25021,
"text": "Code #2:"
},
{
"code": "<script> // Taking some strings. var x = '2341312134'; var y = '@#$%^&**((*&^'; // Variable z contains two spaces var z = ' '; // Returning the length of the string. document.write(x.length + \"<br>\"); document.write(y.length + \"<br>\"); document.write(z.length); </script>",
"e": 25337,
"s": 25030,
"text": null
},
{
"code": null,
"e": 25345,
"s": 25337,
"text": "Output:"
},
{
"code": null,
"e": 25353,
"s": 25345,
"text": "10\n13\n2"
},
{
"code": null,
"e": 25371,
"s": 25353,
"text": "javascript-string"
},
{
"code": null,
"e": 25382,
"s": 25371,
"text": "JavaScript"
},
{
"code": null,
"e": 25480,
"s": 25382,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25489,
"s": 25480,
"text": "Comments"
},
{
"code": null,
"e": 25502,
"s": 25489,
"text": "Old Comments"
},
{
"code": null,
"e": 25563,
"s": 25502,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 25608,
"s": 25563,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 25680,
"s": 25608,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 25721,
"s": 25680,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 25767,
"s": 25721,
"text": "Set the value of an input field in JavaScript"
},
{
"code": null,
"e": 25816,
"s": 25767,
"text": "How to Use the JavaScript Fetch API to Get Data?"
},
{
"code": null,
"e": 25852,
"s": 25816,
"text": "Node.js | fs.writeFileSync() Method"
},
{
"code": null,
"e": 25897,
"s": 25852,
"text": "Difference between TypeScript and JavaScript"
},
{
"code": null,
"e": 25938,
"s": 25897,
"text": "Create a Responsive Navbar using ReactJS"
}
] |
Dictionary.Item[] Property in C# | The Dictionary.Item[] property in C# is used to get or set the value associated with the specified key in the Dictionary.
Following is the syntax −
public TValue this[TKey key] { get; set; }
Let us now see an example to implement the Dictionary.Item[] property −
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Dictionary<string, string> dict =
new Dictionary<string, string>();
dict.Add("One", "Chris");
dict.Add("Two", "Steve");
dict.Add("Three", "Messi");
dict.Add("Four", "Ryan");
dict.Add("Five", "Nathan");
Console.WriteLine("Count of elements = "+dict.Count);
Console.WriteLine("\nKey/value pairs...");
foreach(KeyValuePair<string, string> res in dict){
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
Console.WriteLine("Value for key three = "+dict["Three"]);
dict["Three"] = "Ronaldo";
Console.Write("Updated value associated with key Three...");
Console.WriteLine(dict["Three"]);
if (dict.ContainsValue("Angelina"))
Console.WriteLine("\n\nValue found!");
else
Console.WriteLine("\n\nValue isn't in the dictionary!");
dict.Clear();
Console.WriteLine("Cleared Key/value pairs...");
foreach(KeyValuePair<string, string> res in dict){
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
Console.WriteLine("Count of elements now = "+dict.Count);
}
}
This will produce the following output −
Count of elements = 5
Key/value pairs...
Key = One, Value = Chris
Key = Two, Value = Steve
Key = Three, Value = Messi
Key = Four, Value = Ryan
Key = Five, Value = Nathan
Value for key three = Messi
Updated value associated with key Three...Ronaldo
Value isn't in the dictionary!
Cleared Key/value pairs...
Count of elements now = 0
Let us now see another example to implement the Dictionary.Item[] method −
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Dictionary<string, string> dict =
new Dictionary<string, string>();
dict.Add("One", "Chris");
dict.Add("Two", "Steve");
dict.Add("Three", "Messi");
dict.Add("Four", "Ryan");
dict.Add("Five", "Nathan");
Console.WriteLine("Count of elements = "+dict.Count);
Console.WriteLine("\nKey/value pairs...");
foreach(KeyValuePair<string, string> res in dict){
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
Console.WriteLine("Value for key three = "+dict["Three"]);
dict["Three"] = "Katie";
Console.Write("Updated value associated with key Three...");
Console.WriteLine(dict["Three"]);
}
}
This will produce the following output −
Count of elements = 5
Key/value pairs...
Key = One, Value = Chris
Key = Two, Value = Steve
Key = Three, Value = Messi
Key = Four, Value = Ryan
Key = Five, Value = Nathan
Value for key three = Messi
Updated value associated with key Three...Katie | [
{
"code": null,
"e": 1184,
"s": 1062,
"text": "The Dictionary.Item[] property in C# is used to get or set the value associated with the specified key in the Dictionary."
},
{
"code": null,
"e": 1210,
"s": 1184,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 1253,
"s": 1210,
"text": "public TValue this[TKey key] { get; set; }"
},
{
"code": null,
"e": 1325,
"s": 1253,
"text": "Let us now see an example to implement the Dictionary.Item[] property −"
},
{
"code": null,
"e": 2572,
"s": 1325,
"text": "using System;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main(){\n Dictionary<string, string> dict =\n new Dictionary<string, string>();\n dict.Add(\"One\", \"Chris\");\n dict.Add(\"Two\", \"Steve\");\n dict.Add(\"Three\", \"Messi\");\n dict.Add(\"Four\", \"Ryan\");\n dict.Add(\"Five\", \"Nathan\");\n Console.WriteLine(\"Count of elements = \"+dict.Count);\n Console.WriteLine(\"\\nKey/value pairs...\");\n foreach(KeyValuePair<string, string> res in dict){\n Console.WriteLine(\"Key = {0}, Value = {1}\", res.Key, res.Value);\n }\n Console.WriteLine(\"Value for key three = \"+dict[\"Three\"]);\n dict[\"Three\"] = \"Ronaldo\";\n Console.Write(\"Updated value associated with key Three...\");\n Console.WriteLine(dict[\"Three\"]);\n if (dict.ContainsValue(\"Angelina\"))\n Console.WriteLine(\"\\n\\nValue found!\");\n else\n Console.WriteLine(\"\\n\\nValue isn't in the dictionary!\");\n dict.Clear();\n Console.WriteLine(\"Cleared Key/value pairs...\");\n foreach(KeyValuePair<string, string> res in dict){\n Console.WriteLine(\"Key = {0}, Value = {1}\", res.Key, res.Value);\n }\n Console.WriteLine(\"Count of elements now = \"+dict.Count);\n }\n}"
},
{
"code": null,
"e": 2613,
"s": 2572,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2945,
"s": 2613,
"text": "Count of elements = 5\nKey/value pairs...\nKey = One, Value = Chris\nKey = Two, Value = Steve\nKey = Three, Value = Messi\nKey = Four, Value = Ryan\nKey = Five, Value = Nathan\nValue for key three = Messi\nUpdated value associated with key Three...Ronaldo\nValue isn't in the dictionary!\nCleared Key/value pairs...\nCount of elements now = 0"
},
{
"code": null,
"e": 3020,
"s": 2945,
"text": "Let us now see another example to implement the Dictionary.Item[] method −"
},
{
"code": null,
"e": 3820,
"s": 3020,
"text": "using System;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main(){\n Dictionary<string, string> dict =\n new Dictionary<string, string>();\n dict.Add(\"One\", \"Chris\");\n dict.Add(\"Two\", \"Steve\");\n dict.Add(\"Three\", \"Messi\");\n dict.Add(\"Four\", \"Ryan\");\n dict.Add(\"Five\", \"Nathan\");\n Console.WriteLine(\"Count of elements = \"+dict.Count);\n Console.WriteLine(\"\\nKey/value pairs...\");\n foreach(KeyValuePair<string, string> res in dict){\n Console.WriteLine(\"Key = {0}, Value = {1}\", res.Key, res.Value);\n }\n Console.WriteLine(\"Value for key three = \"+dict[\"Three\"]);\n dict[\"Three\"] = \"Katie\";\n Console.Write(\"Updated value associated with key Three...\");\n Console.WriteLine(dict[\"Three\"]);\n }\n}"
},
{
"code": null,
"e": 3861,
"s": 3820,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 4107,
"s": 3861,
"text": "Count of elements = 5\nKey/value pairs...\nKey = One, Value = Chris\nKey = Two, Value = Steve\nKey = Three, Value = Messi\nKey = Four, Value = Ryan\nKey = Five, Value = Nathan\nValue for key three = Messi\nUpdated value associated with key Three...Katie"
}
] |
Write a program to design a chess board using PHP | 05 Nov, 2021
Chess is a recreational and competitive board game played between two players. It is played on a square chessboard with 64 squares arranged in an eight-by-eight grid black-white alternatively. In this article, we will learn how to design a Chess Board using PHP.
Approach:
To create Chess in php; we have to run 2 loops each will create 8 blocks.
The inner-loop will generate table-row with black/white background-color based upon a value .
If value is even, Black background is generated .
If value is odd, White background is generated
Chess Board using For-Loop:
PHP
<!DOCTYPE html><html> <body> <table width="400px" border="1px" cellspacing="0px"> <?php echo "Chess by GeeksforGeeks"; $value = 0; for($col = 0; $col < 8; $col++) { echo "<tr>"; $value = $col; for($row = 0; $row < 8; $row++) { if($value%2 == 0) { echo "<td height=40px width=20px bgcolor=black></td>"; $value++; } else { echo "<td height=40px width=20px bgcolor=white></td>"; $value++; } } echo "</tr>"; } ?> </table></body> </html>
Chess Board using while-Loop:
PHP
<!DOCTYPE html><html> <body> <table width="400px" border="1px" cellspacing="0px"> <?php echo "Chess by GeeksforGeeks"; $value = 0; $col = 0; while($col < 8) { $row = 0; echo "<tr>"; $value = $col; while($row < 8) { if($value%2 == 0) { echo "<td height=40px width=20px bgcolor=black></td>"; $value++; } else { echo "<td height=40px width=20px bgcolor=white></td>"; $value++; } $row++; } echo "</tr>"; $col++; } ?> </table></body> </html>
Chess Board using do-while loop:
PHP
<!DOCTYPE html><html> <body> <table width="400px" border="1px" cellspacing="0px"> <?php echo "Chess by GeeksforGeeks"; $value = 0; $col = 0; do { $row = 0; echo "<tr>"; $value = $col; do { if($value%2 == 0) { echo "<td height=40px width=20px bgcolor=black></td>"; $value++; } else { echo "<td height=40px width=20px bgcolor=white></td>"; $value++; } $row++; }while($row < 8); echo "</tr>"; $col++; }while($col < 8); ?> </table></body> </html>
Output: All the code will give the same output.
HTML-Questions
PHP-Questions
Picked
HTML
PHP
Web Technologies
HTML
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Angular File Upload
How to execute PHP code using command line ?
PHP in_array() Function
How to delete an array element based on key in PHP?
How to convert array to string in PHP ?
How to pop an alert message box using PHP ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Nov, 2021"
},
{
"code": null,
"e": 291,
"s": 28,
"text": "Chess is a recreational and competitive board game played between two players. It is played on a square chessboard with 64 squares arranged in an eight-by-eight grid black-white alternatively. In this article, we will learn how to design a Chess Board using PHP."
},
{
"code": null,
"e": 301,
"s": 291,
"text": "Approach:"
},
{
"code": null,
"e": 375,
"s": 301,
"text": "To create Chess in php; we have to run 2 loops each will create 8 blocks."
},
{
"code": null,
"e": 469,
"s": 375,
"text": "The inner-loop will generate table-row with black/white background-color based upon a value ."
},
{
"code": null,
"e": 519,
"s": 469,
"text": "If value is even, Black background is generated ."
},
{
"code": null,
"e": 566,
"s": 519,
"text": "If value is odd, White background is generated"
},
{
"code": null,
"e": 594,
"s": 566,
"text": "Chess Board using For-Loop:"
},
{
"code": null,
"e": 598,
"s": 594,
"text": "PHP"
},
{
"code": "<!DOCTYPE html><html> <body> <table width=\"400px\" border=\"1px\" cellspacing=\"0px\"> <?php echo \"Chess by GeeksforGeeks\"; $value = 0; for($col = 0; $col < 8; $col++) { echo \"<tr>\"; $value = $col; for($row = 0; $row < 8; $row++) { if($value%2 == 0) { echo \"<td height=40px width=20px bgcolor=black></td>\"; $value++; } else { echo \"<td height=40px width=20px bgcolor=white></td>\"; $value++; } } echo \"</tr>\"; } ?> </table></body> </html>",
"e": 1276,
"s": 598,
"text": null
},
{
"code": null,
"e": 1308,
"s": 1278,
"text": "Chess Board using while-Loop:"
},
{
"code": null,
"e": 1312,
"s": 1308,
"text": "PHP"
},
{
"code": "<!DOCTYPE html><html> <body> <table width=\"400px\" border=\"1px\" cellspacing=\"0px\"> <?php echo \"Chess by GeeksforGeeks\"; $value = 0; $col = 0; while($col < 8) { $row = 0; echo \"<tr>\"; $value = $col; while($row < 8) { if($value%2 == 0) { echo \"<td height=40px width=20px bgcolor=black></td>\"; $value++; } else { echo \"<td height=40px width=20px bgcolor=white></td>\"; $value++; } $row++; } echo \"</tr>\"; $col++; } ?> </table></body> </html>",
"e": 2046,
"s": 1312,
"text": null
},
{
"code": null,
"e": 2079,
"s": 2046,
"text": "Chess Board using do-while loop:"
},
{
"code": null,
"e": 2083,
"s": 2079,
"text": "PHP"
},
{
"code": "<!DOCTYPE html><html> <body> <table width=\"400px\" border=\"1px\" cellspacing=\"0px\"> <?php echo \"Chess by GeeksforGeeks\"; $value = 0; $col = 0; do { $row = 0; echo \"<tr>\"; $value = $col; do { if($value%2 == 0) { echo \"<td height=40px width=20px bgcolor=black></td>\"; $value++; } else { echo \"<td height=40px width=20px bgcolor=white></td>\"; $value++; } $row++; }while($row < 8); echo \"</tr>\"; $col++; }while($col < 8); ?> </table></body> </html>",
"e": 2817,
"s": 2083,
"text": null
},
{
"code": null,
"e": 2865,
"s": 2817,
"text": "Output: All the code will give the same output."
},
{
"code": null,
"e": 2880,
"s": 2865,
"text": "HTML-Questions"
},
{
"code": null,
"e": 2894,
"s": 2880,
"text": "PHP-Questions"
},
{
"code": null,
"e": 2901,
"s": 2894,
"text": "Picked"
},
{
"code": null,
"e": 2906,
"s": 2901,
"text": "HTML"
},
{
"code": null,
"e": 2910,
"s": 2906,
"text": "PHP"
},
{
"code": null,
"e": 2927,
"s": 2910,
"text": "Web Technologies"
},
{
"code": null,
"e": 2932,
"s": 2927,
"text": "HTML"
},
{
"code": null,
"e": 2936,
"s": 2932,
"text": "PHP"
},
{
"code": null,
"e": 3034,
"s": 2936,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3058,
"s": 3034,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 3097,
"s": 3058,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 3136,
"s": 3097,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 3173,
"s": 3136,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 3193,
"s": 3173,
"text": "Angular File Upload"
},
{
"code": null,
"e": 3238,
"s": 3193,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 3262,
"s": 3238,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 3314,
"s": 3262,
"text": "How to delete an array element based on key in PHP?"
},
{
"code": null,
"e": 3354,
"s": 3314,
"text": "How to convert array to string in PHP ?"
}
] |
Namedtuple in Python | 25 Jan, 2022
Python supports a type of container like dictionaries called “namedtuple()” present in the module, “collections“. Like dictionaries, they contain keys that are hashed to a particular value. But on contrary, it supports both access from key-value and iteration, the functionality that dictionaries lack.
Example:
Python3
# Python code to demonstrate namedtuple() from collections import namedtuple # Declaring namedtuple()Student = namedtuple('Student', ['name', 'age', 'DOB']) # Adding valuesS = Student('Nandini', '19', '2541997') # Access using indexprint("The Student age using index is : ", end="")print(S[1]) # Access using nameprint("The Student name using keyname is : ", end="")print(S.name)
Output:
The Student age using index is : 19
The Student name using keyname is : Nandini
Access by index: The attribute values of namedtuple() are ordered and can be accessed using the index number unlike dictionaries which are not accessible by index.
Access by keyname: Access by keyname is also allowed as in dictionaries.
using getattr(): This is yet another way to access the value by giving namedtuple and key value as its argument.
Python3
# Python code to demonstrate namedtuple() and# Access by name, index and getattr() # importing "collections" for namedtuple()import collections # Declaring namedtuple()Student = collections.namedtuple('Student', ['name', 'age', 'DOB']) # Adding valuesS = Student('Nandini', '19', '2541997') # Access using indexprint("The Student age using index is : ", end="")print(S[1]) # Access using nameprint("The Student name using keyname is : ", end="")print(S.name) # Access using getattr()print("The Student DOB using getattr() is : ", end="")print(getattr(S, 'DOB'))
Output :
The Student age using index is : 19
The Student name using keyname is : Nandini
The Student DOB using getattr() is : 2541997
_make() :- This function is used to return a namedtuple() from the iterable passed as argument.
_asdict() :- This function returns the OrderedDict() as constructed from the mapped values of namedtuple().
using “**” (double star) operator :- This function is used to convert a dictionary into the namedtuple().
Python3
# Python code to demonstrate namedtuple() and# _make(), _asdict() and "**" operator # importing "collections" for namedtuple()import collections # Declaring namedtuple()Student = collections.namedtuple('Student', ['name', 'age', 'DOB']) # Adding valuesS = Student('Nandini', '19', '2541997') # initializing iterableli = ['Manjeet', '19', '411997'] # initializing dictdi = {'name': "Nikhil", 'age': 19, 'DOB': '1391997'} # using _make() to return namedtuple()print("The namedtuple instance using iterable is : ")print(Student._make(li)) # using _asdict() to return an OrderedDict()print("The OrderedDict instance using namedtuple is : ")print(S._asdict()) # using ** operator to return namedtuple from dictionaryprint("The namedtuple instance from dict is : ")print(Student(**di))
Output :
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
The namedtuple instance using iterable is :
Student(name='Manjeet', age='19', DOB='411997')
The OrderedDict instance using namedtuple is :
OrderedDict([('name', 'Nandini'), ('age', '19'), ('DOB', '2541997')])
The namedtuple instance from dict is :
Student(name='Nikhil', age=19, DOB='1391997')
_fields: This function is used to return all the keynames of the namespace declared.
_replace(): _replace() is like str.replace() but targets named fields( does not modify the original values)
Python3
# Python code to demonstrate namedtuple() and# _fields and _replace() # importing "collections" for namedtuple()import collections # Declaring namedtuple()Student = collections.namedtuple('Student', ['name', 'age', 'DOB']) # Adding valuesS = Student('Nandini', '19', '2541997') # using _fields to display all the keynames of namedtuple()print("All the fields of students are : ")print(S._fields) # ._replace returns a new namedtuple, it does not modify the originalprint("returns a new namedtuple : ")print(S._replace(name='Manjeet'))# original namedtupleprint(S)
Output :
All the fields of students are :
('name', 'age', 'DOB')
The modified namedtuple is :
Student(name='Manjeet', age='19', DOB='2541997')
Python Programming Tutorial | Namedtuple in Python | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersPython Programming Tutorial | Namedtuple in 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 / 2:50•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=SLs2VCzmA9c" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
BengalTiger
itssaurav
hasanfaraaz2
amartyaghoshgfg
Python collections-module
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n25 Jan, 2022"
},
{
"code": null,
"e": 357,
"s": 54,
"text": "Python supports a type of container like dictionaries called “namedtuple()” present in the module, “collections“. Like dictionaries, they contain keys that are hashed to a particular value. But on contrary, it supports both access from key-value and iteration, the functionality that dictionaries lack."
},
{
"code": null,
"e": 367,
"s": 357,
"text": "Example: "
},
{
"code": null,
"e": 375,
"s": 367,
"text": "Python3"
},
{
"code": "# Python code to demonstrate namedtuple() from collections import namedtuple # Declaring namedtuple()Student = namedtuple('Student', ['name', 'age', 'DOB']) # Adding valuesS = Student('Nandini', '19', '2541997') # Access using indexprint(\"The Student age using index is : \", end=\"\")print(S[1]) # Access using nameprint(\"The Student name using keyname is : \", end=\"\")print(S.name)",
"e": 755,
"s": 375,
"text": null
},
{
"code": null,
"e": 763,
"s": 755,
"text": "Output:"
},
{
"code": null,
"e": 843,
"s": 763,
"text": "The Student age using index is : 19\nThe Student name using keyname is : Nandini"
},
{
"code": null,
"e": 1007,
"s": 843,
"text": "Access by index: The attribute values of namedtuple() are ordered and can be accessed using the index number unlike dictionaries which are not accessible by index."
},
{
"code": null,
"e": 1080,
"s": 1007,
"text": "Access by keyname: Access by keyname is also allowed as in dictionaries."
},
{
"code": null,
"e": 1193,
"s": 1080,
"text": "using getattr(): This is yet another way to access the value by giving namedtuple and key value as its argument."
},
{
"code": null,
"e": 1201,
"s": 1193,
"text": "Python3"
},
{
"code": "# Python code to demonstrate namedtuple() and# Access by name, index and getattr() # importing \"collections\" for namedtuple()import collections # Declaring namedtuple()Student = collections.namedtuple('Student', ['name', 'age', 'DOB']) # Adding valuesS = Student('Nandini', '19', '2541997') # Access using indexprint(\"The Student age using index is : \", end=\"\")print(S[1]) # Access using nameprint(\"The Student name using keyname is : \", end=\"\")print(S.name) # Access using getattr()print(\"The Student DOB using getattr() is : \", end=\"\")print(getattr(S, 'DOB'))",
"e": 1763,
"s": 1201,
"text": null
},
{
"code": null,
"e": 1773,
"s": 1763,
"text": "Output : "
},
{
"code": null,
"e": 1898,
"s": 1773,
"text": "The Student age using index is : 19\nThe Student name using keyname is : Nandini\nThe Student DOB using getattr() is : 2541997"
},
{
"code": null,
"e": 1994,
"s": 1898,
"text": "_make() :- This function is used to return a namedtuple() from the iterable passed as argument."
},
{
"code": null,
"e": 2102,
"s": 1994,
"text": "_asdict() :- This function returns the OrderedDict() as constructed from the mapped values of namedtuple()."
},
{
"code": null,
"e": 2208,
"s": 2102,
"text": "using “**” (double star) operator :- This function is used to convert a dictionary into the namedtuple()."
},
{
"code": null,
"e": 2216,
"s": 2208,
"text": "Python3"
},
{
"code": "# Python code to demonstrate namedtuple() and# _make(), _asdict() and \"**\" operator # importing \"collections\" for namedtuple()import collections # Declaring namedtuple()Student = collections.namedtuple('Student', ['name', 'age', 'DOB']) # Adding valuesS = Student('Nandini', '19', '2541997') # initializing iterableli = ['Manjeet', '19', '411997'] # initializing dictdi = {'name': \"Nikhil\", 'age': 19, 'DOB': '1391997'} # using _make() to return namedtuple()print(\"The namedtuple instance using iterable is : \")print(Student._make(li)) # using _asdict() to return an OrderedDict()print(\"The OrderedDict instance using namedtuple is : \")print(S._asdict()) # using ** operator to return namedtuple from dictionaryprint(\"The namedtuple instance from dict is : \")print(Student(**di))",
"e": 3031,
"s": 2216,
"text": null
},
{
"code": null,
"e": 3041,
"s": 3031,
"text": "Output : "
},
{
"code": null,
"e": 3050,
"s": 3041,
"text": "Chapters"
},
{
"code": null,
"e": 3077,
"s": 3050,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 3127,
"s": 3077,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 3150,
"s": 3127,
"text": "captions off, selected"
},
{
"code": null,
"e": 3158,
"s": 3150,
"text": "English"
},
{
"code": null,
"e": 3182,
"s": 3158,
"text": "This is a modal window."
},
{
"code": null,
"e": 3251,
"s": 3182,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 3273,
"s": 3251,
"text": "End of dialog window."
},
{
"code": null,
"e": 3573,
"s": 3273,
"text": "The namedtuple instance using iterable is : \nStudent(name='Manjeet', age='19', DOB='411997')\nThe OrderedDict instance using namedtuple is : \nOrderedDict([('name', 'Nandini'), ('age', '19'), ('DOB', '2541997')])\nThe namedtuple instance from dict is : \nStudent(name='Nikhil', age=19, DOB='1391997')"
},
{
"code": null,
"e": 3658,
"s": 3573,
"text": "_fields: This function is used to return all the keynames of the namespace declared."
},
{
"code": null,
"e": 3766,
"s": 3658,
"text": "_replace(): _replace() is like str.replace() but targets named fields( does not modify the original values)"
},
{
"code": null,
"e": 3774,
"s": 3766,
"text": "Python3"
},
{
"code": "# Python code to demonstrate namedtuple() and# _fields and _replace() # importing \"collections\" for namedtuple()import collections # Declaring namedtuple()Student = collections.namedtuple('Student', ['name', 'age', 'DOB']) # Adding valuesS = Student('Nandini', '19', '2541997') # using _fields to display all the keynames of namedtuple()print(\"All the fields of students are : \")print(S._fields) # ._replace returns a new namedtuple, it does not modify the originalprint(\"returns a new namedtuple : \")print(S._replace(name='Manjeet'))# original namedtupleprint(S)",
"e": 4338,
"s": 3774,
"text": null
},
{
"code": null,
"e": 4348,
"s": 4338,
"text": "Output : "
},
{
"code": null,
"e": 4485,
"s": 4348,
"text": "All the fields of students are : \n('name', 'age', 'DOB')\nThe modified namedtuple is : \nStudent(name='Manjeet', age='19', DOB='2541997') "
},
{
"code": null,
"e": 5403,
"s": 4485,
"text": "Python Programming Tutorial | Namedtuple in Python | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersPython Programming Tutorial | Namedtuple in 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 / 2:50•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=SLs2VCzmA9c\" 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": 5700,
"s": 5403,
"text": "This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 5826,
"s": 5700,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 5838,
"s": 5826,
"text": "BengalTiger"
},
{
"code": null,
"e": 5848,
"s": 5838,
"text": "itssaurav"
},
{
"code": null,
"e": 5861,
"s": 5848,
"text": "hasanfaraaz2"
},
{
"code": null,
"e": 5877,
"s": 5861,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 5903,
"s": 5877,
"text": "Python collections-module"
},
{
"code": null,
"e": 5910,
"s": 5903,
"text": "Python"
},
{
"code": null,
"e": 5929,
"s": 5910,
"text": "Technical Scripter"
}
] |
Program to find if a character is vowel or Consonant | 08 Mar, 2022
Given a character, check if it is vowel or consonant. Vowels are ‘a’, ‘e’, ‘i’, ‘o’ and ‘u’. All other characters (‘b’, ‘c’, ‘d’, ‘f’ ....) are consonants.
Examples:
Input : x = 'c'
Output : Consonant
Input : x = 'u'
Output : Vowel
We check whether the given character matches any of the 5 vowels. If yes, we print “Vowel”, else we print “Consonant”.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to check if a given character// is vowel or consonant.#include <iostream>using namespace std; // Function to check whether a character is// vowel or notvoid vowelOrConsonant(char x){ if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u') cout << "Vowel" << endl; else cout << "Consonant" << endl} // Driver codeint main(){ vowelOrConsonant('c'); vowelOrConsonant('e'); return 0;}
// java program to check if a given// character is vowel or consonant.import java.io.*; public class GFG { // Function to check whether a // character is vowel or not static void vowelOrConsonant(char x) { if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u') System.out.println("Vowel"); else System.out.println("Consonant"); } // Driver code static public void main(String[] args) { vowelOrConsonant('c'); vowelOrConsonant('e'); }} // This code is contributed by vt_m.
# Python3 program to check if a given# character is vowel or consonant. # Function to check whether a character# is vowel or notdef vowelOrConsonant(x): if (x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u'): print("Vowel") else: print("Consonant") # Driver codevowelOrConsonant('c')vowelOrConsonant('e') # This code is contributed by# mohit kumar 29
// C# program to check if a given// character is vowel or consonant.using System; public class GFG { // Function to check whether a // character is vowel or not static void vowelOrConsonant(char x) { if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u') Console.WriteLine("Vowel"); else Console.WriteLine("Consonant"); } // Driver code static public void Main() { vowelOrConsonant('c'); vowelOrConsonant('e'); }} // This code is contributed by vt_m.
<?php// PHP program to check if a given// character is vowel or consonant. // Function to check whether a// character is vowel or notfunction vowelOrConsonant($x){ if ($x == 'a' || $x == 'e' || $x == 'i' || $x == 'o' || $x == 'u') echo "Vowel" . "\n"; else echo "Consonant" . "\n";} // Driver codevowelOrConsonant('c');vowelOrConsonant('e'); // This code is contributed// by Akanksha Rai?>
<script> // Javascript program to check if a given // character is vowel or consonant. // Function to check whether a // character is vowel or not function vowelOrConsonant(x) { if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u') document.write("Vowel" + "</br>"); else document.write("Consonant" + "</br>"); } vowelOrConsonant('c'); vowelOrConsonant('e'); // This code is contributed by mukesh07.</script>
Output:
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Consonant
Vowel
Time Complexity: O(1)
Auxiliary Space: O(1)
How to handle capital letters as well?
C++
Java
Python3
C#
PHP
Javascript
// C++ program to check if a given character// is vowel or consonant.#include <iostream>using namespace std; // Function to check whether a character is// vowel or notvoid vowelOrConsonant(char x){ if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U') cout << "Vowel" << endl; else cout << "Consonant" << endl;} // Driver codeint main(){ vowelOrConsonant('c'); vowelOrConsonant('E'); return 0;}
// Java program to check if a given// character is vowel or consonantimport java.io.*; public class GFG { // Function to check whether a // character is vowel or not static void vowelOrConsonant(char x) { if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U') System.out.println("Vowel"); else System.out.println("Consonant"); } // Driver code static public void main(String[] args) { vowelOrConsonant('c'); vowelOrConsonant('E'); }} // This article is contributed by vt_m.
# Python3 program to check if a given# character is vowel or consonant. # Function to check whether a# character is vowel or notdef vowelOrConsonant(x): if (x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u' or x == 'A' or x == 'E' or x == 'I' or x == 'O' or x == 'U'): print("Vowel") else: print("Consonant") # Driver codeif __name__ == '__main__': vowelOrConsonant('c') vowelOrConsonant('E') # This code is contributed by# Sanjit_Prasad
// C# program to check if a given// character is vowel or consonantusing System;public class GFG { // Function to check whether a // character is vowel or not static void vowelOrConsonant(char x) { if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U') Console.WriteLine("Vowel"); else Console.WriteLine("Consonant"); } // Driver code static public void Main() { vowelOrConsonant('c'); vowelOrConsonant('E'); }} // This article is contributed by vt_m.
<?php// PHP program to check if a given character// is vowel or consonant. // Function to check whether a// character is vowel or notfunction vowelOrConsonant($x){ if ($x == 'a' || $x == 'e' || $x == 'i' || $x == 'o' || $x == 'u' || $x == 'A' || $x == 'E' || $x == 'I' || $x == 'O' || $x == 'U') echo "Vowel" . "\n"; else echo "Consonant" . "\n";} // Driver codevowelOrConsonant('c');vowelOrConsonant('E'); // This code is contributed// by Akanksha Rai?>
<script> // Javascript program to check if a// given character is vowel or consonant. // Function to check whether a character is// vowel or notfunction vowelOrConsonant(x){ if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U') document.write("Vowel" + "</br>"); else document.write("Consonant" + "</br>");} // Driver codevowelOrConsonant('c');vowelOrConsonant('E'); // This code is contributed by rameshtravel07 </script>
Output:
Consonant
Vowel
Time Complexity: O(1)
Auxiliary Space: O(1)
using switch case
C++
C
Java
Python3
C#
Javascript
#include <iostream> using namespace std; int isVowel(char ch){ int check = 0; switch (ch) { case 'a': case 'e': case 'i': case 'o': case 'u': case 'A': case 'E': case 'I': case 'O': case 'U': check = 1; } return check;} // Driver Codeint main(){ cout << "a is " << isVowel('a') << endl; // 1 means Vowel cout << "x is " << isVowel('x') << endl; // 0 means Consonant return 0;}
#include <stdio.h> int isVowel(char ch){ int check = 0; switch (ch) { case 'a': case 'e': case 'i': case 'o': case 'u': case 'A': case 'E': case 'I': case 'O': case 'U': check = 1; } return check;} int main(){ printf("a is %d\n", isVowel('a')); // 1 means Vowel printf("x is %d\n", isVowel('x')); // 0 means Consonant return 0;}
/*package whatever //do not write package name here */ import java.io.*; class GFG { static int isVowel(char ch) { int check = 0; switch (ch) { case 'a': case 'e': case 'i': case 'o': case 'u': case 'A': case 'E': case 'I': case 'O': case 'U': check = 1; } return check; } // Driver Code public static void main(String[] args) { System.out.println("a is " + isVowel('a')); System.out.println("x is " + isVowel('x')); }}
def isVowel(ch): switcher = { 'a': "Vowel", 'e': "Vowel", 'i': "Vowel", 'o': "Vowel", 'u': "Vowel", 'A': "Vowel", 'E': "Vowel", 'I': "Vowel", 'O': "Vowel", 'U': "Vowel" } return switcher.get(ch, "Consonant") # Driver Codeprint('a is '+isVowel('a'))print('x is '+isVowel('x'))
using System; class GFG{ static int isVowel(char ch) { int check = 0; switch (ch) { case 'a': check = 1; break; case 'e': check = 1; break; case 'i': check = 1; break; case 'o': check = 1; break; case 'u': check = 1; break; case 'A': check = 1; break; case 'E': check = 1; break; case 'I': check = 1; break; case 'O': check = 1; break; case 'U': check = 1; break; } return check; } // Driver code static public void Main () { Console.WriteLine("a is " + isVowel('a')); Console.WriteLine("x is " + isVowel('x')); }} // This code is contributed by rag2127
<script> function isVowel(ch){ var check = 0; switch (ch) { case 'a': case 'e': case 'i': case 'o': case 'u': case 'A': case 'E': case 'I': case 'O': case 'U': check = 1; } return check;} // Driver Code // 1 means Voweldocument.write("a is " + isVowel('a') + "<br>"); // 0 means Consonantdocument.write("x is " + isVowel('x') + "<br>"); // This code is contributed by Shivani </script>
a is 1
x is 0
Time Complexity: O(1)
Auxiliary Space: O(1)
Another way is to find() the character in a string containing only Vowels.
C++
C
Java
Python3
C#
Javascript
#include <iostream>#include <string> using namespace std; int isVowel(char ch){ // Make the list of vowels string str = "aeiouAEIOU"; return (str.find(ch) != string::npos);} // Driver codeint main(){ cout << "a is " << isVowel('a') << endl; cout << "x is " << isVowel('x') << endl; return 0;}
#include <stdio.h>#include <string.h> int isVowel(char ch){ // Make the list of vowels char str[] = "aeiouAEIOU"; return (strchr(str, ch) != NULL);} // Driver Codeint main(){ printf("a is %d\n", isVowel('a')); printf("x is %d\n", isVowel('x')); return 0;}
/*package whatever //do not write package name here */ import java.io.*; class GFG { static int isVowel(char ch) { // Make the list of vowels String str = "aeiouAEIOU"; return (str.indexOf(ch) != -1) ? 1 : 0; } // Driver Code public static void main(String[] args) { System.out.println("a is " + isVowel('a')); System.out.println("x is " + isVowel('x')); }}
def isVowel(ch): # Make the list of vowels str = "aeiouAEIOU" return (str.find(ch) != -1) # Driver Codeprint('a is '+str(isVowel('a')))print('x is '+str(isVowel('x')))
// C# program to implement// the above approachusing System;class GFG{ static int isVowel(char ch){ // Make the list of vowels string str = "aeiouAEIOU"; return (str.IndexOf(ch) != -1) ? 1 : 0;} // Driver code static void Main(){ Console.WriteLine("a is " + isVowel('a')); Console.WriteLine("x is " + isVowel('x'));}} // This code is contributed by divyeshrabadiya07
<script>/*package whatever //do not write package name here */ function isVowel(ch) { // Make the list of vowels let str = "aeiouAEIOU"; return (str.indexOf(ch) != -1) ? 1 : 0; } // Driver Code document.write("a is " + isVowel('a')+"<br>"); document.write("x is " + isVowel('x')+"<br>"); // This code is contributed by patel2127</script>
a is 1
x is 0
Time Complexity: O(N)
Auxiliary Space: O(1) Most efficient way to check Vowel using bit shift :
In ASCII these is the respective values of every vowel both in lower and upper cases.
a
e
i
o
u
A
E
I
O
U
As very lower and upper case vowels have the same 5 LSBs. We need a number 0x208222 which gives 1 in its LSB after right-shift 1, 5, 19, 15 otherwise gives 0. The numbers depend on character encoding.
C++
C
Java
Python3
C#
Javascript
#include <iostream>using namespace std; int isVowel(char ch){ return (0x208222 >> (ch & 0x1f)) & 1; // same as (2130466 >> (ch & 31)) & 1;} // Driver Codeint main(){ cout << "a is " << isVowel('a') << endl; cout << "x is " << isVowel('x') << endl; return 0;}
#include <stdio.h> int isVowel(char ch){ return (0x208222 >> (ch & 0x1f)) & 1; // same as (2130466 >> (ch & 31)) & 1;} // Driver Codeint main(){ printf("a is %d\n", isVowel('a')); printf("x is %d\n", isVowel('x')); return 0;}
/*package whatever //do not write package name here */ import java.io.*; class GFG{ static int isVowel(char ch) { return (0x208222 >> (ch & 0x1f)) & 1; // same as (2130466 >> (ch & 31)) & 1; } // Driver Code public static void main(String[] args) { System.out.println("a is " + isVowel('a')); System.out.println("x is " + isVowel('x')); }}
def isVowel(ch): return (0x208222 >> (ord(ch) & 0x1f)) & 1 # same as (2130466 >> (ord(ch) & 31)) & 1; # Driver Codeprint('a is '+str(isVowel('a')))print('x is '+str(isVowel('x')))
// C# implementation of above approachusing System;class GFG { static int isVowel(char ch) { return (0x208222 >> (ch & 0x1f)) & 1; // same as (2130466 >> (ch & 31)) & 1; } // Driver code static void Main() { Console.WriteLine("a is " + isVowel('a')); Console.WriteLine("x is " + isVowel('x')); }} // This code is contributed by divesh072019
<script> function isVowel(ch) { return (0x208222 >> (ch.charCodeAt(0) & 0x1f)) & 1; // same as (2130466 >> (ch & 31)) & 1; } // Driver Code document.write("a is " + isVowel('a')+"<br>"); document.write("x is " + isVowel('x')+"<br>"); // This code is contributed by unknown2108</script>
a is 1
x is 0
Time Complexity: O(1)
Auxiliary Space: O(1)*We can omit the ( ch & 0x1f ) part on X86 machines as the result of SHR/SAR (which is >> ) masked to 0x1f automatically.
*For machines bitmap check is faster than table check, but if the ch variable stored in register than it may perform faster.
vt_m
mohit kumar 29
Akanksha_Rai
Sanjit_Prasad
meghnagupta812
scorchingeagle
divyeshrabadiya07
divyesh072019
rag2127
mukesh07
rameshtravel07
patel2127
unknown2108
shivanisinghss2110
rohitsingh07052
vowel-consonant
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction To PYTHON
Interfaces in Java
C++ Classes and Objects
C++ Data Types
Types of Operating Systems
Operator Overloading in C++
Polymorphism in C++
Constructors in Java
Constructors in C++
Exceptions in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Mar, 2022"
},
{
"code": null,
"e": 208,
"s": 52,
"text": "Given a character, check if it is vowel or consonant. Vowels are ‘a’, ‘e’, ‘i’, ‘o’ and ‘u’. All other characters (‘b’, ‘c’, ‘d’, ‘f’ ....) are consonants."
},
{
"code": null,
"e": 220,
"s": 208,
"text": "Examples: "
},
{
"code": null,
"e": 287,
"s": 220,
"text": "Input : x = 'c'\nOutput : Consonant\n\nInput : x = 'u'\nOutput : Vowel"
},
{
"code": null,
"e": 407,
"s": 287,
"text": "We check whether the given character matches any of the 5 vowels. If yes, we print “Vowel”, else we print “Consonant”. "
},
{
"code": null,
"e": 411,
"s": 407,
"text": "C++"
},
{
"code": null,
"e": 416,
"s": 411,
"text": "Java"
},
{
"code": null,
"e": 424,
"s": 416,
"text": "Python3"
},
{
"code": null,
"e": 427,
"s": 424,
"text": "C#"
},
{
"code": null,
"e": 431,
"s": 427,
"text": "PHP"
},
{
"code": null,
"e": 442,
"s": 431,
"text": "Javascript"
},
{
"code": "// CPP program to check if a given character// is vowel or consonant.#include <iostream>using namespace std; // Function to check whether a character is// vowel or notvoid vowelOrConsonant(char x){ if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u') cout << \"Vowel\" << endl; else cout << \"Consonant\" << endl} // Driver codeint main(){ vowelOrConsonant('c'); vowelOrConsonant('e'); return 0;}",
"e": 891,
"s": 442,
"text": null
},
{
"code": "// java program to check if a given// character is vowel or consonant.import java.io.*; public class GFG { // Function to check whether a // character is vowel or not static void vowelOrConsonant(char x) { if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u') System.out.println(\"Vowel\"); else System.out.println(\"Consonant\"); } // Driver code static public void main(String[] args) { vowelOrConsonant('c'); vowelOrConsonant('e'); }} // This code is contributed by vt_m.",
"e": 1474,
"s": 891,
"text": null
},
{
"code": "# Python3 program to check if a given# character is vowel or consonant. # Function to check whether a character# is vowel or notdef vowelOrConsonant(x): if (x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u'): print(\"Vowel\") else: print(\"Consonant\") # Driver codevowelOrConsonant('c')vowelOrConsonant('e') # This code is contributed by# mohit kumar 29",
"e": 1864,
"s": 1474,
"text": null
},
{
"code": "// C# program to check if a given// character is vowel or consonant.using System; public class GFG { // Function to check whether a // character is vowel or not static void vowelOrConsonant(char x) { if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u') Console.WriteLine(\"Vowel\"); else Console.WriteLine(\"Consonant\"); } // Driver code static public void Main() { vowelOrConsonant('c'); vowelOrConsonant('e'); }} // This code is contributed by vt_m.",
"e": 2426,
"s": 1864,
"text": null
},
{
"code": "<?php// PHP program to check if a given// character is vowel or consonant. // Function to check whether a// character is vowel or notfunction vowelOrConsonant($x){ if ($x == 'a' || $x == 'e' || $x == 'i' || $x == 'o' || $x == 'u') echo \"Vowel\" . \"\\n\"; else echo \"Consonant\" . \"\\n\";} // Driver codevowelOrConsonant('c');vowelOrConsonant('e'); // This code is contributed// by Akanksha Rai?>",
"e": 2850,
"s": 2426,
"text": null
},
{
"code": "<script> // Javascript program to check if a given // character is vowel or consonant. // Function to check whether a // character is vowel or not function vowelOrConsonant(x) { if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u') document.write(\"Vowel\" + \"</br>\"); else document.write(\"Consonant\" + \"</br>\"); } vowelOrConsonant('c'); vowelOrConsonant('e'); // This code is contributed by mukesh07.</script>",
"e": 3352,
"s": 2850,
"text": null
},
{
"code": null,
"e": 3361,
"s": 3352,
"text": "Output: "
},
{
"code": null,
"e": 3370,
"s": 3361,
"text": "Chapters"
},
{
"code": null,
"e": 3397,
"s": 3370,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 3447,
"s": 3397,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 3470,
"s": 3447,
"text": "captions off, selected"
},
{
"code": null,
"e": 3478,
"s": 3470,
"text": "English"
},
{
"code": null,
"e": 3502,
"s": 3478,
"text": "This is a modal window."
},
{
"code": null,
"e": 3571,
"s": 3502,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 3593,
"s": 3571,
"text": "End of dialog window."
},
{
"code": null,
"e": 3609,
"s": 3593,
"text": "Consonant\nVowel"
},
{
"code": null,
"e": 3631,
"s": 3609,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 3653,
"s": 3631,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 3694,
"s": 3653,
"text": "How to handle capital letters as well? "
},
{
"code": null,
"e": 3698,
"s": 3694,
"text": "C++"
},
{
"code": null,
"e": 3703,
"s": 3698,
"text": "Java"
},
{
"code": null,
"e": 3711,
"s": 3703,
"text": "Python3"
},
{
"code": null,
"e": 3714,
"s": 3711,
"text": "C#"
},
{
"code": null,
"e": 3718,
"s": 3714,
"text": "PHP"
},
{
"code": null,
"e": 3729,
"s": 3718,
"text": "Javascript"
},
{
"code": "// C++ program to check if a given character// is vowel or consonant.#include <iostream>using namespace std; // Function to check whether a character is// vowel or notvoid vowelOrConsonant(char x){ if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U') cout << \"Vowel\" << endl; else cout << \"Consonant\" << endl;} // Driver codeint main(){ vowelOrConsonant('c'); vowelOrConsonant('E'); return 0;}",
"e": 4235,
"s": 3729,
"text": null
},
{
"code": "// Java program to check if a given// character is vowel or consonantimport java.io.*; public class GFG { // Function to check whether a // character is vowel or not static void vowelOrConsonant(char x) { if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U') System.out.println(\"Vowel\"); else System.out.println(\"Consonant\"); } // Driver code static public void main(String[] args) { vowelOrConsonant('c'); vowelOrConsonant('E'); }} // This article is contributed by vt_m.",
"e": 4877,
"s": 4235,
"text": null
},
{
"code": "# Python3 program to check if a given# character is vowel or consonant. # Function to check whether a# character is vowel or notdef vowelOrConsonant(x): if (x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u' or x == 'A' or x == 'E' or x == 'I' or x == 'O' or x == 'U'): print(\"Vowel\") else: print(\"Consonant\") # Driver codeif __name__ == '__main__': vowelOrConsonant('c') vowelOrConsonant('E') # This code is contributed by# Sanjit_Prasad",
"e": 5369,
"s": 4877,
"text": null
},
{
"code": "// C# program to check if a given// character is vowel or consonantusing System;public class GFG { // Function to check whether a // character is vowel or not static void vowelOrConsonant(char x) { if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U') Console.WriteLine(\"Vowel\"); else Console.WriteLine(\"Consonant\"); } // Driver code static public void Main() { vowelOrConsonant('c'); vowelOrConsonant('E'); }} // This article is contributed by vt_m.",
"e": 5989,
"s": 5369,
"text": null
},
{
"code": "<?php// PHP program to check if a given character// is vowel or consonant. // Function to check whether a// character is vowel or notfunction vowelOrConsonant($x){ if ($x == 'a' || $x == 'e' || $x == 'i' || $x == 'o' || $x == 'u' || $x == 'A' || $x == 'E' || $x == 'I' || $x == 'O' || $x == 'U') echo \"Vowel\" . \"\\n\"; else echo \"Consonant\" . \"\\n\";} // Driver codevowelOrConsonant('c');vowelOrConsonant('E'); // This code is contributed// by Akanksha Rai?>",
"e": 6485,
"s": 5989,
"text": null
},
{
"code": "<script> // Javascript program to check if a// given character is vowel or consonant. // Function to check whether a character is// vowel or notfunction vowelOrConsonant(x){ if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U') document.write(\"Vowel\" + \"</br>\"); else document.write(\"Consonant\" + \"</br>\");} // Driver codevowelOrConsonant('c');vowelOrConsonant('E'); // This code is contributed by rameshtravel07 </script>",
"e": 7010,
"s": 6485,
"text": null
},
{
"code": null,
"e": 7019,
"s": 7010,
"text": "Output: "
},
{
"code": null,
"e": 7035,
"s": 7019,
"text": "Consonant\nVowel"
},
{
"code": null,
"e": 7057,
"s": 7035,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 7079,
"s": 7057,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 7097,
"s": 7079,
"text": "using switch case"
},
{
"code": null,
"e": 7101,
"s": 7097,
"text": "C++"
},
{
"code": null,
"e": 7103,
"s": 7101,
"text": "C"
},
{
"code": null,
"e": 7108,
"s": 7103,
"text": "Java"
},
{
"code": null,
"e": 7116,
"s": 7108,
"text": "Python3"
},
{
"code": null,
"e": 7119,
"s": 7116,
"text": "C#"
},
{
"code": null,
"e": 7130,
"s": 7119,
"text": "Javascript"
},
{
"code": "#include <iostream> using namespace std; int isVowel(char ch){ int check = 0; switch (ch) { case 'a': case 'e': case 'i': case 'o': case 'u': case 'A': case 'E': case 'I': case 'O': case 'U': check = 1; } return check;} // Driver Codeint main(){ cout << \"a is \" << isVowel('a') << endl; // 1 means Vowel cout << \"x is \" << isVowel('x') << endl; // 0 means Consonant return 0;}",
"e": 7582,
"s": 7130,
"text": null
},
{
"code": "#include <stdio.h> int isVowel(char ch){ int check = 0; switch (ch) { case 'a': case 'e': case 'i': case 'o': case 'u': case 'A': case 'E': case 'I': case 'O': case 'U': check = 1; } return check;} int main(){ printf(\"a is %d\\n\", isVowel('a')); // 1 means Vowel printf(\"x is %d\\n\", isVowel('x')); // 0 means Consonant return 0;}",
"e": 7990,
"s": 7582,
"text": null
},
{
"code": "/*package whatever //do not write package name here */ import java.io.*; class GFG { static int isVowel(char ch) { int check = 0; switch (ch) { case 'a': case 'e': case 'i': case 'o': case 'u': case 'A': case 'E': case 'I': case 'O': case 'U': check = 1; } return check; } // Driver Code public static void main(String[] args) { System.out.println(\"a is \" + isVowel('a')); System.out.println(\"x is \" + isVowel('x')); }}",
"e": 8558,
"s": 7990,
"text": null
},
{
"code": "def isVowel(ch): switcher = { 'a': \"Vowel\", 'e': \"Vowel\", 'i': \"Vowel\", 'o': \"Vowel\", 'u': \"Vowel\", 'A': \"Vowel\", 'E': \"Vowel\", 'I': \"Vowel\", 'O': \"Vowel\", 'U': \"Vowel\" } return switcher.get(ch, \"Consonant\") # Driver Codeprint('a is '+isVowel('a'))print('x is '+isVowel('x'))",
"e": 8913,
"s": 8558,
"text": null
},
{
"code": "using System; class GFG{ static int isVowel(char ch) { int check = 0; switch (ch) { case 'a': check = 1; break; case 'e': check = 1; break; case 'i': check = 1; break; case 'o': check = 1; break; case 'u': check = 1; break; case 'A': check = 1; break; case 'E': check = 1; break; case 'I': check = 1; break; case 'O': check = 1; break; case 'U': check = 1; break; } return check; } // Driver code static public void Main () { Console.WriteLine(\"a is \" + isVowel('a')); Console.WriteLine(\"x is \" + isVowel('x')); }} // This code is contributed by rag2127",
"e": 9683,
"s": 8913,
"text": null
},
{
"code": "<script> function isVowel(ch){ var check = 0; switch (ch) { case 'a': case 'e': case 'i': case 'o': case 'u': case 'A': case 'E': case 'I': case 'O': case 'U': check = 1; } return check;} // Driver Code // 1 means Voweldocument.write(\"a is \" + isVowel('a') + \"<br>\"); // 0 means Consonantdocument.write(\"x is \" + isVowel('x') + \"<br>\"); // This code is contributed by Shivani </script>",
"e": 10118,
"s": 9683,
"text": null
},
{
"code": null,
"e": 10132,
"s": 10118,
"text": "a is 1\nx is 0"
},
{
"code": null,
"e": 10154,
"s": 10132,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 10176,
"s": 10154,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 10251,
"s": 10176,
"text": "Another way is to find() the character in a string containing only Vowels."
},
{
"code": null,
"e": 10255,
"s": 10251,
"text": "C++"
},
{
"code": null,
"e": 10257,
"s": 10255,
"text": "C"
},
{
"code": null,
"e": 10262,
"s": 10257,
"text": "Java"
},
{
"code": null,
"e": 10270,
"s": 10262,
"text": "Python3"
},
{
"code": null,
"e": 10273,
"s": 10270,
"text": "C#"
},
{
"code": null,
"e": 10284,
"s": 10273,
"text": "Javascript"
},
{
"code": "#include <iostream>#include <string> using namespace std; int isVowel(char ch){ // Make the list of vowels string str = \"aeiouAEIOU\"; return (str.find(ch) != string::npos);} // Driver codeint main(){ cout << \"a is \" << isVowel('a') << endl; cout << \"x is \" << isVowel('x') << endl; return 0;}",
"e": 10596,
"s": 10284,
"text": null
},
{
"code": "#include <stdio.h>#include <string.h> int isVowel(char ch){ // Make the list of vowels char str[] = \"aeiouAEIOU\"; return (strchr(str, ch) != NULL);} // Driver Codeint main(){ printf(\"a is %d\\n\", isVowel('a')); printf(\"x is %d\\n\", isVowel('x')); return 0;}",
"e": 10870,
"s": 10596,
"text": null
},
{
"code": "/*package whatever //do not write package name here */ import java.io.*; class GFG { static int isVowel(char ch) { // Make the list of vowels String str = \"aeiouAEIOU\"; return (str.indexOf(ch) != -1) ? 1 : 0; } // Driver Code public static void main(String[] args) { System.out.println(\"a is \" + isVowel('a')); System.out.println(\"x is \" + isVowel('x')); }}",
"e": 11287,
"s": 10870,
"text": null
},
{
"code": "def isVowel(ch): # Make the list of vowels str = \"aeiouAEIOU\" return (str.find(ch) != -1) # Driver Codeprint('a is '+str(isVowel('a')))print('x is '+str(isVowel('x')))",
"e": 11465,
"s": 11287,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;class GFG{ static int isVowel(char ch){ // Make the list of vowels string str = \"aeiouAEIOU\"; return (str.IndexOf(ch) != -1) ? 1 : 0;} // Driver code static void Main(){ Console.WriteLine(\"a is \" + isVowel('a')); Console.WriteLine(\"x is \" + isVowel('x'));}} // This code is contributed by divyeshrabadiya07",
"e": 11851,
"s": 11465,
"text": null
},
{
"code": "<script>/*package whatever //do not write package name here */ function isVowel(ch) { // Make the list of vowels let str = \"aeiouAEIOU\"; return (str.indexOf(ch) != -1) ? 1 : 0; } // Driver Code document.write(\"a is \" + isVowel('a')+\"<br>\"); document.write(\"x is \" + isVowel('x')+\"<br>\"); // This code is contributed by patel2127</script>",
"e": 12243,
"s": 11851,
"text": null
},
{
"code": null,
"e": 12257,
"s": 12243,
"text": "a is 1\nx is 0"
},
{
"code": null,
"e": 12279,
"s": 12257,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 12353,
"s": 12279,
"text": "Auxiliary Space: O(1) Most efficient way to check Vowel using bit shift :"
},
{
"code": null,
"e": 12439,
"s": 12353,
"text": "In ASCII these is the respective values of every vowel both in lower and upper cases."
},
{
"code": null,
"e": 12441,
"s": 12439,
"text": "a"
},
{
"code": null,
"e": 12443,
"s": 12441,
"text": "e"
},
{
"code": null,
"e": 12445,
"s": 12443,
"text": "i"
},
{
"code": null,
"e": 12447,
"s": 12445,
"text": "o"
},
{
"code": null,
"e": 12449,
"s": 12447,
"text": "u"
},
{
"code": null,
"e": 12453,
"s": 12451,
"text": "A"
},
{
"code": null,
"e": 12455,
"s": 12453,
"text": "E"
},
{
"code": null,
"e": 12457,
"s": 12455,
"text": "I"
},
{
"code": null,
"e": 12459,
"s": 12457,
"text": "O"
},
{
"code": null,
"e": 12461,
"s": 12459,
"text": "U"
},
{
"code": null,
"e": 12665,
"s": 12463,
"text": "As very lower and upper case vowels have the same 5 LSBs. We need a number 0x208222 which gives 1 in its LSB after right-shift 1, 5, 19, 15 otherwise gives 0. The numbers depend on character encoding."
},
{
"code": null,
"e": 12673,
"s": 12669,
"text": "C++"
},
{
"code": null,
"e": 12675,
"s": 12673,
"text": "C"
},
{
"code": null,
"e": 12680,
"s": 12675,
"text": "Java"
},
{
"code": null,
"e": 12688,
"s": 12680,
"text": "Python3"
},
{
"code": null,
"e": 12691,
"s": 12688,
"text": "C#"
},
{
"code": null,
"e": 12702,
"s": 12691,
"text": "Javascript"
},
{
"code": "#include <iostream>using namespace std; int isVowel(char ch){ return (0x208222 >> (ch & 0x1f)) & 1; // same as (2130466 >> (ch & 31)) & 1;} // Driver Codeint main(){ cout << \"a is \" << isVowel('a') << endl; cout << \"x is \" << isVowel('x') << endl; return 0;}",
"e": 12977,
"s": 12702,
"text": null
},
{
"code": "#include <stdio.h> int isVowel(char ch){ return (0x208222 >> (ch & 0x1f)) & 1; // same as (2130466 >> (ch & 31)) & 1;} // Driver Codeint main(){ printf(\"a is %d\\n\", isVowel('a')); printf(\"x is %d\\n\", isVowel('x')); return 0;}",
"e": 13219,
"s": 12977,
"text": null
},
{
"code": "/*package whatever //do not write package name here */ import java.io.*; class GFG{ static int isVowel(char ch) { return (0x208222 >> (ch & 0x1f)) & 1; // same as (2130466 >> (ch & 31)) & 1; } // Driver Code public static void main(String[] args) { System.out.println(\"a is \" + isVowel('a')); System.out.println(\"x is \" + isVowel('x')); }}",
"e": 13611,
"s": 13219,
"text": null
},
{
"code": "def isVowel(ch): return (0x208222 >> (ord(ch) & 0x1f)) & 1 # same as (2130466 >> (ord(ch) & 31)) & 1; # Driver Codeprint('a is '+str(isVowel('a')))print('x is '+str(isVowel('x')))",
"e": 13798,
"s": 13611,
"text": null
},
{
"code": "// C# implementation of above approachusing System;class GFG { static int isVowel(char ch) { return (0x208222 >> (ch & 0x1f)) & 1; // same as (2130466 >> (ch & 31)) & 1; } // Driver code static void Main() { Console.WriteLine(\"a is \" + isVowel('a')); Console.WriteLine(\"x is \" + isVowel('x')); }} // This code is contributed by divesh072019",
"e": 14188,
"s": 13798,
"text": null
},
{
"code": "<script> function isVowel(ch) { return (0x208222 >> (ch.charCodeAt(0) & 0x1f)) & 1; // same as (2130466 >> (ch & 31)) & 1; } // Driver Code document.write(\"a is \" + isVowel('a')+\"<br>\"); document.write(\"x is \" + isVowel('x')+\"<br>\"); // This code is contributed by unknown2108</script>",
"e": 14517,
"s": 14188,
"text": null
},
{
"code": null,
"e": 14531,
"s": 14517,
"text": "a is 1\nx is 0"
},
{
"code": null,
"e": 14553,
"s": 14531,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 14696,
"s": 14553,
"text": "Auxiliary Space: O(1)*We can omit the ( ch & 0x1f ) part on X86 machines as the result of SHR/SAR (which is >> ) masked to 0x1f automatically."
},
{
"code": null,
"e": 14821,
"s": 14696,
"text": "*For machines bitmap check is faster than table check, but if the ch variable stored in register than it may perform faster."
},
{
"code": null,
"e": 14828,
"s": 14823,
"text": "vt_m"
},
{
"code": null,
"e": 14843,
"s": 14828,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 14856,
"s": 14843,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 14870,
"s": 14856,
"text": "Sanjit_Prasad"
},
{
"code": null,
"e": 14885,
"s": 14870,
"text": "meghnagupta812"
},
{
"code": null,
"e": 14900,
"s": 14885,
"text": "scorchingeagle"
},
{
"code": null,
"e": 14918,
"s": 14900,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 14932,
"s": 14918,
"text": "divyesh072019"
},
{
"code": null,
"e": 14940,
"s": 14932,
"text": "rag2127"
},
{
"code": null,
"e": 14949,
"s": 14940,
"text": "mukesh07"
},
{
"code": null,
"e": 14964,
"s": 14949,
"text": "rameshtravel07"
},
{
"code": null,
"e": 14974,
"s": 14964,
"text": "patel2127"
},
{
"code": null,
"e": 14986,
"s": 14974,
"text": "unknown2108"
},
{
"code": null,
"e": 15005,
"s": 14986,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 15021,
"s": 15005,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 15037,
"s": 15021,
"text": "vowel-consonant"
},
{
"code": null,
"e": 15056,
"s": 15037,
"text": "School Programming"
},
{
"code": null,
"e": 15154,
"s": 15056,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15177,
"s": 15154,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 15196,
"s": 15177,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 15220,
"s": 15196,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 15235,
"s": 15220,
"text": "C++ Data Types"
},
{
"code": null,
"e": 15262,
"s": 15235,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 15290,
"s": 15262,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 15310,
"s": 15290,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 15331,
"s": 15310,
"text": "Constructors in Java"
},
{
"code": null,
"e": 15351,
"s": 15331,
"text": "Constructors in C++"
}
] |
SQL Query to Select all Records From Employee Table Where Name is Not Specified | 14 May, 2021
Here, we are going to see how to find the names of the persons other than a person with a particular name SQL. In this article, we will be making use of the MSSQL Server as our database.
For example, if the employee name is Pradeep you need to show the table of employees excluding that employee with the name Pradeep. So let us execute this query in detail step-by-step.
Creating a database employee by using the following SQL query as follows.
CREATE DATABASE employee;
Output :
Using the database employee using the following SQL query as follows.
USE employee;
Output :
Creating a table employee_details with 4 columns using the following SQL query as follows.
CREATE TABLE employee_details(
emp_id VARCHAR(8),
emp_name VARCHAR(20),
emp_designation VARCHAR(20),
emp_age INT);
Output :
To view the description of the tables in the database using the following SQL query as follows.
EXEC sp_columns employee_details;
Output :
Inserting rows into employee_details table using the following SQL query as follows.
INSERT INTO employee_details VALUES('E40001','PRADEEP','H.R',36),
('E40002','ASHOK','MANAGER',28),
('E40003','PAVAN KUMAR','ASST MANAGER',28),
('E40004','SANTHOSH','STORE MANAGER',25),
('E40005','THAMAN','GENERAL MANAGER',26);
Output :
Viewing the table employee_details after inserting rows by using the following SQL query as follows.
SELECT * FROM employee_details;
Output :
Query to find an employee whose name is not Pradeep.
Since we need to display the names other than Pradeep we can use not equal to (<>) operator with the where clause to get the required query executed, In the WHERE clause we can use any other conditions also using other operators such as >,<, AND, OR, NOT etc..,
SYNTAX:
SELECT *
FROM table_name
WHERE condition1 ,condition 2,....;
For the above we can do it in two ways:
1) USING <> operator
SELECT* FROM employee_details
WHERE emp_name <>'PRADEEP';
Output :
2) USING NOT operator
SELECT* FROM employee_details
WHERE NOT emp_name='PRADEEP';
Output :
Query to find the employee whose designation is not of General Manager and Store Manager.
Using AND operator we can merge different conditions here AND is used to execute the following query.
SELECT* FROM employee_details
WHERE emp_designation<> 'GENERAL MANAGER' AND
emp_designation <> 'STORE MANAGER';
Output :
Picked
SQL-Query
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 May, 2021"
},
{
"code": null,
"e": 242,
"s": 54,
"text": "Here, we are going to see how to find the names of the persons other than a person with a particular name SQL. In this article, we will be making use of the MSSQL Server as our database."
},
{
"code": null,
"e": 427,
"s": 242,
"text": "For example, if the employee name is Pradeep you need to show the table of employees excluding that employee with the name Pradeep. So let us execute this query in detail step-by-step."
},
{
"code": null,
"e": 501,
"s": 427,
"text": "Creating a database employee by using the following SQL query as follows."
},
{
"code": null,
"e": 527,
"s": 501,
"text": "CREATE DATABASE employee;"
},
{
"code": null,
"e": 536,
"s": 527,
"text": "Output :"
},
{
"code": null,
"e": 606,
"s": 536,
"text": "Using the database employee using the following SQL query as follows."
},
{
"code": null,
"e": 620,
"s": 606,
"text": "USE employee;"
},
{
"code": null,
"e": 629,
"s": 620,
"text": "Output :"
},
{
"code": null,
"e": 721,
"s": 629,
"text": "Creating a table employee_details with 4 columns using the following SQL query as follows."
},
{
"code": null,
"e": 858,
"s": 721,
"text": " CREATE TABLE employee_details(\n emp_id VARCHAR(8),\n emp_name VARCHAR(20),\n emp_designation VARCHAR(20),\n emp_age INT);"
},
{
"code": null,
"e": 867,
"s": 858,
"text": "Output :"
},
{
"code": null,
"e": 963,
"s": 867,
"text": "To view the description of the tables in the database using the following SQL query as follows."
},
{
"code": null,
"e": 997,
"s": 963,
"text": "EXEC sp_columns employee_details;"
},
{
"code": null,
"e": 1006,
"s": 997,
"text": "Output :"
},
{
"code": null,
"e": 1091,
"s": 1006,
"text": "Inserting rows into employee_details table using the following SQL query as follows."
},
{
"code": null,
"e": 1334,
"s": 1091,
"text": "INSERT INTO employee_details VALUES('E40001','PRADEEP','H.R',36),\n ('E40002','ASHOK','MANAGER',28),\n ('E40003','PAVAN KUMAR','ASST MANAGER',28),\n ('E40004','SANTHOSH','STORE MANAGER',25),\n ('E40005','THAMAN','GENERAL MANAGER',26);"
},
{
"code": null,
"e": 1343,
"s": 1334,
"text": "Output :"
},
{
"code": null,
"e": 1444,
"s": 1343,
"text": "Viewing the table employee_details after inserting rows by using the following SQL query as follows."
},
{
"code": null,
"e": 1476,
"s": 1444,
"text": "SELECT * FROM employee_details;"
},
{
"code": null,
"e": 1485,
"s": 1476,
"text": "Output :"
},
{
"code": null,
"e": 1538,
"s": 1485,
"text": "Query to find an employee whose name is not Pradeep."
},
{
"code": null,
"e": 1800,
"s": 1538,
"text": "Since we need to display the names other than Pradeep we can use not equal to (<>) operator with the where clause to get the required query executed, In the WHERE clause we can use any other conditions also using other operators such as >,<, AND, OR, NOT etc..,"
},
{
"code": null,
"e": 1870,
"s": 1800,
"text": "SYNTAX:\nSELECT * \nFROM table_name\nWHERE condition1 ,condition 2,....;"
},
{
"code": null,
"e": 1910,
"s": 1870,
"text": "For the above we can do it in two ways:"
},
{
"code": null,
"e": 1931,
"s": 1910,
"text": "1) USING <> operator"
},
{
"code": null,
"e": 1991,
"s": 1931,
"text": " SELECT* FROM employee_details\n WHERE emp_name <>'PRADEEP';"
},
{
"code": null,
"e": 2000,
"s": 1991,
"text": "Output :"
},
{
"code": null,
"e": 2022,
"s": 2000,
"text": "2) USING NOT operator"
},
{
"code": null,
"e": 2086,
"s": 2022,
"text": " SELECT* FROM employee_details\n WHERE NOT emp_name='PRADEEP';"
},
{
"code": null,
"e": 2095,
"s": 2086,
"text": "Output :"
},
{
"code": null,
"e": 2185,
"s": 2095,
"text": "Query to find the employee whose designation is not of General Manager and Store Manager."
},
{
"code": null,
"e": 2287,
"s": 2185,
"text": "Using AND operator we can merge different conditions here AND is used to execute the following query."
},
{
"code": null,
"e": 2406,
"s": 2287,
"text": " SELECT* FROM employee_details\n WHERE emp_designation<> 'GENERAL MANAGER' AND\n emp_designation <> 'STORE MANAGER';"
},
{
"code": null,
"e": 2415,
"s": 2406,
"text": "Output :"
},
{
"code": null,
"e": 2422,
"s": 2415,
"text": "Picked"
},
{
"code": null,
"e": 2432,
"s": 2422,
"text": "SQL-Query"
},
{
"code": null,
"e": 2436,
"s": 2432,
"text": "SQL"
},
{
"code": null,
"e": 2440,
"s": 2436,
"text": "SQL"
}
] |
How to make a blinking text using jQuery ? | 05 Sep, 2019
Given an HTML document and the task is to blink the certain text of an element using jQuery. There are few techniques to solve this problem which are discussed below:
Approach 1:
Select a particular element from the document.
Toggle its visibility property from hidden to visible and vice-versa after a particular period of time.
Example 1: This example implements the above approach.
<!DOCTYPE HTML> <html> <head> <title> How to make a blinking text using jQuery ? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body align = "center"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "font-size: 20px; font-weight: bold; color:green;"> </p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = "Click on the button to start " + "the text blinking."; el_down.innerHTML = "Binking Text"; function GFG_Fun() { $('#GFG_DOWN').each(function() { var elem = $(this); setInterval(function() { if (elem.css('visibility') == 'hidden') { elem.css('visibility', 'visible'); } else { elem.css('visibility', 'hidden'); } }, 100); }); } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Approach 2:
Select a particular element from the document.
Animate its opacity property from 0 to 1 and vice-versa after a particular period of time.
Example 2: This example implements the above approach.
<!DOCTYPE HTML> <html> <head> <title> How to make a blinking text using jQuery ? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body align = "center"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "font-size: 20px; font-weight: bold; color:green;"> </p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = "Click on the button to start " + "the text blinking."; el_down.innerHTML = "Binking Text"; function blink(selector) { $(selector).animate({opacity:0}, 50, "linear", function() { $(this).delay(100); $(this).animate({opacity:1}, 50, function(){ blink(this); }); $(this).delay(100); }); } function GFG_Fun() { blink('#GFG_DOWN'); } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
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
Roadmap to Learn JavaScript For Beginners
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": "\n05 Sep, 2019"
},
{
"code": null,
"e": 195,
"s": 28,
"text": "Given an HTML document and the task is to blink the certain text of an element using jQuery. There are few techniques to solve this problem which are discussed below:"
},
{
"code": null,
"e": 207,
"s": 195,
"text": "Approach 1:"
},
{
"code": null,
"e": 254,
"s": 207,
"text": "Select a particular element from the document."
},
{
"code": null,
"e": 358,
"s": 254,
"text": "Toggle its visibility property from hidden to visible and vice-versa after a particular period of time."
},
{
"code": null,
"e": 413,
"s": 358,
"text": "Example 1: This example implements the above approach."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> How to make a blinking text using jQuery ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body align = \"center\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"font-size: 20px; font-weight: bold; color:green;\"> </p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = \"Click on the button to start \" + \"the text blinking.\"; el_down.innerHTML = \"Binking Text\"; function GFG_Fun() { $('#GFG_DOWN').each(function() { var elem = $(this); setInterval(function() { if (elem.css('visibility') == 'hidden') { elem.css('visibility', 'visible'); } else { elem.css('visibility', 'hidden'); } }, 100); }); } </script> </body> </html>",
"e": 1761,
"s": 413,
"text": null
},
{
"code": null,
"e": 1769,
"s": 1761,
"text": "Output:"
},
{
"code": null,
"e": 1800,
"s": 1769,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 1830,
"s": 1800,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 1842,
"s": 1830,
"text": "Approach 2:"
},
{
"code": null,
"e": 1889,
"s": 1842,
"text": "Select a particular element from the document."
},
{
"code": null,
"e": 1980,
"s": 1889,
"text": "Animate its opacity property from 0 to 1 and vice-versa after a particular period of time."
},
{
"code": null,
"e": 2035,
"s": 1980,
"text": "Example 2: This example implements the above approach."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> How to make a blinking text using jQuery ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body align = \"center\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"font-size: 20px; font-weight: bold; color:green;\"> </p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = \"Click on the button to start \" + \"the text blinking.\"; el_down.innerHTML = \"Binking Text\"; function blink(selector) { $(selector).animate({opacity:0}, 50, \"linear\", function() { $(this).delay(100); $(this).animate({opacity:1}, 50, function(){ blink(this); }); $(this).delay(100); }); } function GFG_Fun() { blink('#GFG_DOWN'); } </script> </body> </html>",
"e": 3349,
"s": 2035,
"text": null
},
{
"code": null,
"e": 3357,
"s": 3349,
"text": "Output:"
},
{
"code": null,
"e": 3388,
"s": 3357,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 3418,
"s": 3388,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 3429,
"s": 3418,
"text": "JavaScript"
},
{
"code": null,
"e": 3446,
"s": 3429,
"text": "Web Technologies"
},
{
"code": null,
"e": 3473,
"s": 3446,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3571,
"s": 3473,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3632,
"s": 3571,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3704,
"s": 3632,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3744,
"s": 3704,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3785,
"s": 3744,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3827,
"s": 3785,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 3860,
"s": 3827,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3922,
"s": 3860,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3983,
"s": 3922,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4033,
"s": 3983,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Use of na_values parameter in read_csv() function of Pandas in Python | 28 Jul, 2020
read_csv() is an important pandas function to read CSV files. But there are many other things one can do through this function only to change the returned object completely. In this post, we will see the use of the na_values parameter.
na_values: This is used to create a string that considers pandas as NaN (Not a Number). by-default pandas consider #N/A, -NaN, -n/a, N/A, NULL etc as NaN value. let’s see the example for better understanding.
so this is our dataframe it has three column names, class, and total marks. now import the dataframe in python pandas.
Refer the link to the data set used from here.
Example 1: see pandas consider #N/A as NaN.
Python3
# import pandas libraryimport pandas as pd # read a csv filedf = pd.read_csv('Example.csv') # show the dataframeprint(df)
Output:
Example 2: Now the na_values parameter is used to tell pandas they consider “not available” as NaN value and print NaN at the place of “not available”.
Python3
# import pandas libraryimport pandas as pd # read a csv filedf = pd.read_csv('Example.csv', na_values = "not available") # show the dataframeprint(df)
Output:
Python-pandas
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
Iterate over a list in Python
Convert integer to string in Python | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n28 Jul, 2020"
},
{
"code": null,
"e": 289,
"s": 53,
"text": "read_csv() is an important pandas function to read CSV files. But there are many other things one can do through this function only to change the returned object completely. In this post, we will see the use of the na_values parameter."
},
{
"code": null,
"e": 498,
"s": 289,
"text": "na_values: This is used to create a string that considers pandas as NaN (Not a Number). by-default pandas consider #N/A, -NaN, -n/a, N/A, NULL etc as NaN value. let’s see the example for better understanding."
},
{
"code": null,
"e": 617,
"s": 498,
"text": "so this is our dataframe it has three column names, class, and total marks. now import the dataframe in python pandas."
},
{
"code": null,
"e": 664,
"s": 617,
"text": "Refer the link to the data set used from here."
},
{
"code": null,
"e": 708,
"s": 664,
"text": "Example 1: see pandas consider #N/A as NaN."
},
{
"code": null,
"e": 716,
"s": 708,
"text": "Python3"
},
{
"code": "# import pandas libraryimport pandas as pd # read a csv filedf = pd.read_csv('Example.csv') # show the dataframeprint(df)",
"e": 840,
"s": 716,
"text": null
},
{
"code": null,
"e": 849,
"s": 840,
"text": " Output:"
},
{
"code": null,
"e": 1001,
"s": 849,
"text": "Example 2: Now the na_values parameter is used to tell pandas they consider “not available” as NaN value and print NaN at the place of “not available”."
},
{
"code": null,
"e": 1009,
"s": 1001,
"text": "Python3"
},
{
"code": "# import pandas libraryimport pandas as pd # read a csv filedf = pd.read_csv('Example.csv', na_values = \"not available\") # show the dataframeprint(df)",
"e": 1179,
"s": 1009,
"text": null
},
{
"code": null,
"e": 1187,
"s": 1179,
"text": "Output:"
},
{
"code": null,
"e": 1201,
"s": 1187,
"text": "Python-pandas"
},
{
"code": null,
"e": 1208,
"s": 1201,
"text": "Python"
},
{
"code": null,
"e": 1306,
"s": 1208,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1324,
"s": 1306,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1366,
"s": 1324,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1388,
"s": 1366,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1423,
"s": 1388,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1449,
"s": 1423,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1481,
"s": 1449,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1510,
"s": 1481,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1537,
"s": 1510,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1567,
"s": 1537,
"text": "Iterate over a list in Python"
}
] |
Right Click menu using Tkinter | 20 Apr, 2020
Python 3.x comes bundled with the Tkinter module that is useful for making GUI based applications. Of all the other frameworks supported by Python Tkinter is the simplest and fastest. Tkinter offers a plethora of widgets that can be used to build GUI applications along with the main event loop that keeps running in the background until the application is closed manually.
Note: For more information, refer to Python GUI – tkinter
Tkinter provides a mechanism to deal with events. The event is any action that must be handled by a piece of code inside the program. Events include mouse clicks, mouse movements or a keystroke of a user. Tkinter uses event sequences that allow the users to bind events to handlers for each widget.Syntax:
widget.bind(event, handler)
Tkinter widget is capable of capturing a variety of events such as Button, ButtonRelease, Motion, Double-Button, FocusIn, FocusOut, Key and many more. The code in this article basically deals with event handling where a popup menu with various options is displayed as soon as right-click is encountered on the parent widget. The Menu widget of Tkinter is used to implement toplevel, pulldown, and popup menus.
Import tkinter moduleimport tkinterImport tkinter sub-modulefrom tkinter import *Creating the parent widgetroot = Tk()Syntax: Tk(screenName=None, baseName=None, className=’Tk’, useTk=1)Parameter: In this example, Tk class is instantiated without arguments.Explanation:The Tk() method creates a blank parent widget with close, maximize, and minimize buttons on the top.Creating the label to be displayedL = Label(root, text="Right-click to display menu", width=40, height=20)Syntax: Label(master, **options)Parameter:master: The parent window (root) acts as the master.options: Label() method supports the following options – text, anchor, bg, bitmap, bd, cursor, font, fg, height, width, image, justify, relief, padx, pady, textvariable, underline and wraplength. Here the text option is used display informative text to the user and width and height specifies the position of the Label Widget in the parent window .Explanation:The Label widget is used to display text or images corresponding to a widget.The text displayed on the screen can further be formatted using the other options available under Label widget.Positioning the labelL.pack()Syntax: pack(options)Parameter:options: The options supported by pack() method are expand, fill and side which are used to position the widget on the parent window. However, pack() method is sued without any options here.Explanation:The pack() method is used to position the child widget in the parent widget.Creating the menum = Menu(root, tearoff=0)Syntax: Menu(master, options)Parameter:master: root is the master or parent widget.options: The options supported by Menu widget are title, tearoff, selectcolor, font, fg, postcommand, relief, image, bg, bd, cursor, activeforeground, activeborderwidth and activebackground. The ‘tearoff’ option is used here.Explanation:The tearoff is used to detach menus from the main window creating floating menus. If tearoff=1, it creates a menu with dotted lines at the top which when clicked the menu tears off the parent window and becomes floating. To restrict the menu in the main window tearoff=0 here.Adding options to the menum.add_command(label="Cut")
m.add_command(label="Copy")
m.add_command(label="Paste")
m.add_command(label="Reload")
m.add_separator()
m.add_command(label="Rename")Syntax: add_command(options)Parameter:options: The options available are label, command, underline and accelerator. The label option is used here to specify names of the menu items.Explanation:The add_command() method adds menu items to the menu. The add_separator() creates a thin line between the menu items.def do_popup(event):
try:
m.tk_popup(event.x_root, event.y_root)
finally:
m.grab_release()
Syntax: tk_popup(x_root, y_root)Parameter: This procedure posts a menu at a given position on the screen, x_root and y_root is the current mouse position relative to the upper left corner of the screen.Explanation:This method is the event handler. When the event(right click) happens the method is called and the menu appears on the parent widget at the position where the event occurs. The finally block ensures that the grab_release() method releases the event grab.L.bind("<Button-3>", do_popup)Syntax: bind(event, handler)Parameter:event: Here, right click is the event and it is denoted by <Button-3>.handler: The handler is a piece of code that performs some particular task when the event triggered.Explanation:The right mouse button is pressed with the mouse pointer over the widget and this triggers an event which is handled by the event handler( do_popup() function ). The do_popup() function displays the menu.Run the applicationmainloop()Syntax: mainloop()Parameter: Takes no arguments.Explanation:It acts like an infinite loop which keeps the application running until the main window is closed manually.
Import tkinter moduleimport tkinter
import tkinter
Import tkinter sub-modulefrom tkinter import *
from tkinter import *
Creating the parent widgetroot = Tk()Syntax: Tk(screenName=None, baseName=None, className=’Tk’, useTk=1)Parameter: In this example, Tk class is instantiated without arguments.Explanation:The Tk() method creates a blank parent widget with close, maximize, and minimize buttons on the top.
root = Tk()
Syntax: Tk(screenName=None, baseName=None, className=’Tk’, useTk=1)Parameter: In this example, Tk class is instantiated without arguments.Explanation:The Tk() method creates a blank parent widget with close, maximize, and minimize buttons on the top.
Creating the label to be displayedL = Label(root, text="Right-click to display menu", width=40, height=20)Syntax: Label(master, **options)Parameter:master: The parent window (root) acts as the master.options: Label() method supports the following options – text, anchor, bg, bitmap, bd, cursor, font, fg, height, width, image, justify, relief, padx, pady, textvariable, underline and wraplength. Here the text option is used display informative text to the user and width and height specifies the position of the Label Widget in the parent window .Explanation:The Label widget is used to display text or images corresponding to a widget.The text displayed on the screen can further be formatted using the other options available under Label widget.
L = Label(root, text="Right-click to display menu", width=40, height=20)
Syntax: Label(master, **options)Parameter:
master: The parent window (root) acts as the master.
options: Label() method supports the following options – text, anchor, bg, bitmap, bd, cursor, font, fg, height, width, image, justify, relief, padx, pady, textvariable, underline and wraplength. Here the text option is used display informative text to the user and width and height specifies the position of the Label Widget in the parent window .
Explanation:The Label widget is used to display text or images corresponding to a widget.The text displayed on the screen can further be formatted using the other options available under Label widget.
Positioning the labelL.pack()Syntax: pack(options)Parameter:options: The options supported by pack() method are expand, fill and side which are used to position the widget on the parent window. However, pack() method is sued without any options here.Explanation:The pack() method is used to position the child widget in the parent widget.
L.pack()
Syntax: pack(options)Parameter:
options: The options supported by pack() method are expand, fill and side which are used to position the widget on the parent window. However, pack() method is sued without any options here.
Explanation:The pack() method is used to position the child widget in the parent widget.
Creating the menum = Menu(root, tearoff=0)Syntax: Menu(master, options)Parameter:master: root is the master or parent widget.options: The options supported by Menu widget are title, tearoff, selectcolor, font, fg, postcommand, relief, image, bg, bd, cursor, activeforeground, activeborderwidth and activebackground. The ‘tearoff’ option is used here.Explanation:The tearoff is used to detach menus from the main window creating floating menus. If tearoff=1, it creates a menu with dotted lines at the top which when clicked the menu tears off the parent window and becomes floating. To restrict the menu in the main window tearoff=0 here.
m = Menu(root, tearoff=0)
Syntax: Menu(master, options)Parameter:
master: root is the master or parent widget.
options: The options supported by Menu widget are title, tearoff, selectcolor, font, fg, postcommand, relief, image, bg, bd, cursor, activeforeground, activeborderwidth and activebackground. The ‘tearoff’ option is used here.
Explanation:The tearoff is used to detach menus from the main window creating floating menus. If tearoff=1, it creates a menu with dotted lines at the top which when clicked the menu tears off the parent window and becomes floating. To restrict the menu in the main window tearoff=0 here.
Adding options to the menum.add_command(label="Cut")
m.add_command(label="Copy")
m.add_command(label="Paste")
m.add_command(label="Reload")
m.add_separator()
m.add_command(label="Rename")Syntax: add_command(options)Parameter:options: The options available are label, command, underline and accelerator. The label option is used here to specify names of the menu items.Explanation:The add_command() method adds menu items to the menu. The add_separator() creates a thin line between the menu items.
m.add_command(label="Cut")
m.add_command(label="Copy")
m.add_command(label="Paste")
m.add_command(label="Reload")
m.add_separator()
m.add_command(label="Rename")
Syntax: add_command(options)Parameter:
options: The options available are label, command, underline and accelerator. The label option is used here to specify names of the menu items.
Explanation:The add_command() method adds menu items to the menu. The add_separator() creates a thin line between the menu items.
def do_popup(event):
try:
m.tk_popup(event.x_root, event.y_root)
finally:
m.grab_release()
Syntax: tk_popup(x_root, y_root)Parameter: This procedure posts a menu at a given position on the screen, x_root and y_root is the current mouse position relative to the upper left corner of the screen.Explanation:This method is the event handler. When the event(right click) happens the method is called and the menu appears on the parent widget at the position where the event occurs. The finally block ensures that the grab_release() method releases the event grab.
def do_popup(event):
try:
m.tk_popup(event.x_root, event.y_root)
finally:
m.grab_release()
Syntax: tk_popup(x_root, y_root)Parameter: This procedure posts a menu at a given position on the screen, x_root and y_root is the current mouse position relative to the upper left corner of the screen.Explanation:This method is the event handler. When the event(right click) happens the method is called and the menu appears on the parent widget at the position where the event occurs. The finally block ensures that the grab_release() method releases the event grab.
L.bind("<Button-3>", do_popup)Syntax: bind(event, handler)Parameter:event: Here, right click is the event and it is denoted by <Button-3>.handler: The handler is a piece of code that performs some particular task when the event triggered.Explanation:The right mouse button is pressed with the mouse pointer over the widget and this triggers an event which is handled by the event handler( do_popup() function ). The do_popup() function displays the menu.
L.bind("<Button-3>", do_popup)
Syntax: bind(event, handler)Parameter:
event: Here, right click is the event and it is denoted by <Button-3>.
handler: The handler is a piece of code that performs some particular task when the event triggered.
Explanation:The right mouse button is pressed with the mouse pointer over the widget and this triggers an event which is handled by the event handler( do_popup() function ). The do_popup() function displays the menu.
Run the applicationmainloop()Syntax: mainloop()Parameter: Takes no arguments.Explanation:It acts like an infinite loop which keeps the application running until the main window is closed manually.
mainloop()
Syntax: mainloop()Parameter: Takes no arguments.Explanation:It acts like an infinite loop which keeps the application running until the main window is closed manually.
import tkinterfrom tkinter import * root = Tk() L = Label(root, text ="Right-click to display menu", width = 40, height = 20)L.pack() m = Menu(root, tearoff = 0)m.add_command(label ="Cut")m.add_command(label ="Copy")m.add_command(label ="Paste")m.add_command(label ="Reload")m.add_separator()m.add_command(label ="Rename") def do_popup(event): try: m.tk_popup(event.x_root, event.y_root) finally: m.grab_release() L.bind("<Button-3>", do_popup) mainloop()
Output
ExplanationWhen a right-click is done on the parent window the popup menu appears and displays a list of choices.
Python-tkinter
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
Iterate over a list in Python
Python OOPs Concepts | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Apr, 2020"
},
{
"code": null,
"e": 402,
"s": 28,
"text": "Python 3.x comes bundled with the Tkinter module that is useful for making GUI based applications. Of all the other frameworks supported by Python Tkinter is the simplest and fastest. Tkinter offers a plethora of widgets that can be used to build GUI applications along with the main event loop that keeps running in the background until the application is closed manually."
},
{
"code": null,
"e": 460,
"s": 402,
"text": "Note: For more information, refer to Python GUI – tkinter"
},
{
"code": null,
"e": 766,
"s": 460,
"text": "Tkinter provides a mechanism to deal with events. The event is any action that must be handled by a piece of code inside the program. Events include mouse clicks, mouse movements or a keystroke of a user. Tkinter uses event sequences that allow the users to bind events to handlers for each widget.Syntax:"
},
{
"code": null,
"e": 794,
"s": 766,
"text": "widget.bind(event, handler)"
},
{
"code": null,
"e": 1204,
"s": 794,
"text": "Tkinter widget is capable of capturing a variety of events such as Button, ButtonRelease, Motion, Double-Button, FocusIn, FocusOut, Key and many more. The code in this article basically deals with event handling where a popup menu with various options is displayed as soon as right-click is encountered on the parent widget. The Menu widget of Tkinter is used to implement toplevel, pulldown, and popup menus."
},
{
"code": null,
"e": 5027,
"s": 1204,
"text": "Import tkinter moduleimport tkinterImport tkinter sub-modulefrom tkinter import *Creating the parent widgetroot = Tk()Syntax: Tk(screenName=None, baseName=None, className=’Tk’, useTk=1)Parameter: In this example, Tk class is instantiated without arguments.Explanation:The Tk() method creates a blank parent widget with close, maximize, and minimize buttons on the top.Creating the label to be displayedL = Label(root, text=\"Right-click to display menu\", width=40, height=20)Syntax: Label(master, **options)Parameter:master: The parent window (root) acts as the master.options: Label() method supports the following options – text, anchor, bg, bitmap, bd, cursor, font, fg, height, width, image, justify, relief, padx, pady, textvariable, underline and wraplength. Here the text option is used display informative text to the user and width and height specifies the position of the Label Widget in the parent window .Explanation:The Label widget is used to display text or images corresponding to a widget.The text displayed on the screen can further be formatted using the other options available under Label widget.Positioning the labelL.pack()Syntax: pack(options)Parameter:options: The options supported by pack() method are expand, fill and side which are used to position the widget on the parent window. However, pack() method is sued without any options here.Explanation:The pack() method is used to position the child widget in the parent widget.Creating the menum = Menu(root, tearoff=0)Syntax: Menu(master, options)Parameter:master: root is the master or parent widget.options: The options supported by Menu widget are title, tearoff, selectcolor, font, fg, postcommand, relief, image, bg, bd, cursor, activeforeground, activeborderwidth and activebackground. The ‘tearoff’ option is used here.Explanation:The tearoff is used to detach menus from the main window creating floating menus. If tearoff=1, it creates a menu with dotted lines at the top which when clicked the menu tears off the parent window and becomes floating. To restrict the menu in the main window tearoff=0 here.Adding options to the menum.add_command(label=\"Cut\")\nm.add_command(label=\"Copy\")\nm.add_command(label=\"Paste\")\nm.add_command(label=\"Reload\")\nm.add_separator()\nm.add_command(label=\"Rename\")Syntax: add_command(options)Parameter:options: The options available are label, command, underline and accelerator. The label option is used here to specify names of the menu items.Explanation:The add_command() method adds menu items to the menu. The add_separator() creates a thin line between the menu items.def do_popup(event):\n try:\n m.tk_popup(event.x_root, event.y_root)\n finally:\n m.grab_release()\nSyntax: tk_popup(x_root, y_root)Parameter: This procedure posts a menu at a given position on the screen, x_root and y_root is the current mouse position relative to the upper left corner of the screen.Explanation:This method is the event handler. When the event(right click) happens the method is called and the menu appears on the parent widget at the position where the event occurs. The finally block ensures that the grab_release() method releases the event grab.L.bind(\"<Button-3>\", do_popup)Syntax: bind(event, handler)Parameter:event: Here, right click is the event and it is denoted by <Button-3>.handler: The handler is a piece of code that performs some particular task when the event triggered.Explanation:The right mouse button is pressed with the mouse pointer over the widget and this triggers an event which is handled by the event handler( do_popup() function ). The do_popup() function displays the menu.Run the applicationmainloop()Syntax: mainloop()Parameter: Takes no arguments.Explanation:It acts like an infinite loop which keeps the application running until the main window is closed manually."
},
{
"code": null,
"e": 5063,
"s": 5027,
"text": "Import tkinter moduleimport tkinter"
},
{
"code": null,
"e": 5078,
"s": 5063,
"text": "import tkinter"
},
{
"code": null,
"e": 5125,
"s": 5078,
"text": "Import tkinter sub-modulefrom tkinter import *"
},
{
"code": null,
"e": 5147,
"s": 5125,
"text": "from tkinter import *"
},
{
"code": null,
"e": 5435,
"s": 5147,
"text": "Creating the parent widgetroot = Tk()Syntax: Tk(screenName=None, baseName=None, className=’Tk’, useTk=1)Parameter: In this example, Tk class is instantiated without arguments.Explanation:The Tk() method creates a blank parent widget with close, maximize, and minimize buttons on the top."
},
{
"code": null,
"e": 5447,
"s": 5435,
"text": "root = Tk()"
},
{
"code": null,
"e": 5698,
"s": 5447,
"text": "Syntax: Tk(screenName=None, baseName=None, className=’Tk’, useTk=1)Parameter: In this example, Tk class is instantiated without arguments.Explanation:The Tk() method creates a blank parent widget with close, maximize, and minimize buttons on the top."
},
{
"code": null,
"e": 6447,
"s": 5698,
"text": "Creating the label to be displayedL = Label(root, text=\"Right-click to display menu\", width=40, height=20)Syntax: Label(master, **options)Parameter:master: The parent window (root) acts as the master.options: Label() method supports the following options – text, anchor, bg, bitmap, bd, cursor, font, fg, height, width, image, justify, relief, padx, pady, textvariable, underline and wraplength. Here the text option is used display informative text to the user and width and height specifies the position of the Label Widget in the parent window .Explanation:The Label widget is used to display text or images corresponding to a widget.The text displayed on the screen can further be formatted using the other options available under Label widget."
},
{
"code": null,
"e": 6520,
"s": 6447,
"text": "L = Label(root, text=\"Right-click to display menu\", width=40, height=20)"
},
{
"code": null,
"e": 6563,
"s": 6520,
"text": "Syntax: Label(master, **options)Parameter:"
},
{
"code": null,
"e": 6616,
"s": 6563,
"text": "master: The parent window (root) acts as the master."
},
{
"code": null,
"e": 6965,
"s": 6616,
"text": "options: Label() method supports the following options – text, anchor, bg, bitmap, bd, cursor, font, fg, height, width, image, justify, relief, padx, pady, textvariable, underline and wraplength. Here the text option is used display informative text to the user and width and height specifies the position of the Label Widget in the parent window ."
},
{
"code": null,
"e": 7166,
"s": 6965,
"text": "Explanation:The Label widget is used to display text or images corresponding to a widget.The text displayed on the screen can further be formatted using the other options available under Label widget."
},
{
"code": null,
"e": 7505,
"s": 7166,
"text": "Positioning the labelL.pack()Syntax: pack(options)Parameter:options: The options supported by pack() method are expand, fill and side which are used to position the widget on the parent window. However, pack() method is sued without any options here.Explanation:The pack() method is used to position the child widget in the parent widget."
},
{
"code": null,
"e": 7514,
"s": 7505,
"text": "L.pack()"
},
{
"code": null,
"e": 7546,
"s": 7514,
"text": "Syntax: pack(options)Parameter:"
},
{
"code": null,
"e": 7737,
"s": 7546,
"text": "options: The options supported by pack() method are expand, fill and side which are used to position the widget on the parent window. However, pack() method is sued without any options here."
},
{
"code": null,
"e": 7826,
"s": 7737,
"text": "Explanation:The pack() method is used to position the child widget in the parent widget."
},
{
"code": null,
"e": 8465,
"s": 7826,
"text": "Creating the menum = Menu(root, tearoff=0)Syntax: Menu(master, options)Parameter:master: root is the master or parent widget.options: The options supported by Menu widget are title, tearoff, selectcolor, font, fg, postcommand, relief, image, bg, bd, cursor, activeforeground, activeborderwidth and activebackground. The ‘tearoff’ option is used here.Explanation:The tearoff is used to detach menus from the main window creating floating menus. If tearoff=1, it creates a menu with dotted lines at the top which when clicked the menu tears off the parent window and becomes floating. To restrict the menu in the main window tearoff=0 here."
},
{
"code": null,
"e": 8491,
"s": 8465,
"text": "m = Menu(root, tearoff=0)"
},
{
"code": null,
"e": 8531,
"s": 8491,
"text": "Syntax: Menu(master, options)Parameter:"
},
{
"code": null,
"e": 8576,
"s": 8531,
"text": "master: root is the master or parent widget."
},
{
"code": null,
"e": 8802,
"s": 8576,
"text": "options: The options supported by Menu widget are title, tearoff, selectcolor, font, fg, postcommand, relief, image, bg, bd, cursor, activeforeground, activeborderwidth and activebackground. The ‘tearoff’ option is used here."
},
{
"code": null,
"e": 9091,
"s": 8802,
"text": "Explanation:The tearoff is used to detach menus from the main window creating floating menus. If tearoff=1, it creates a menu with dotted lines at the top which when clicked the menu tears off the parent window and becomes floating. To restrict the menu in the main window tearoff=0 here."
},
{
"code": null,
"e": 9589,
"s": 9091,
"text": "Adding options to the menum.add_command(label=\"Cut\")\nm.add_command(label=\"Copy\")\nm.add_command(label=\"Paste\")\nm.add_command(label=\"Reload\")\nm.add_separator()\nm.add_command(label=\"Rename\")Syntax: add_command(options)Parameter:options: The options available are label, command, underline and accelerator. The label option is used here to specify names of the menu items.Explanation:The add_command() method adds menu items to the menu. The add_separator() creates a thin line between the menu items."
},
{
"code": null,
"e": 9751,
"s": 9589,
"text": "m.add_command(label=\"Cut\")\nm.add_command(label=\"Copy\")\nm.add_command(label=\"Paste\")\nm.add_command(label=\"Reload\")\nm.add_separator()\nm.add_command(label=\"Rename\")"
},
{
"code": null,
"e": 9790,
"s": 9751,
"text": "Syntax: add_command(options)Parameter:"
},
{
"code": null,
"e": 9934,
"s": 9790,
"text": "options: The options available are label, command, underline and accelerator. The label option is used here to specify names of the menu items."
},
{
"code": null,
"e": 10064,
"s": 9934,
"text": "Explanation:The add_command() method adds menu items to the menu. The add_separator() creates a thin line between the menu items."
},
{
"code": null,
"e": 10648,
"s": 10064,
"text": "def do_popup(event):\n try:\n m.tk_popup(event.x_root, event.y_root)\n finally:\n m.grab_release()\nSyntax: tk_popup(x_root, y_root)Parameter: This procedure posts a menu at a given position on the screen, x_root and y_root is the current mouse position relative to the upper left corner of the screen.Explanation:This method is the event handler. When the event(right click) happens the method is called and the menu appears on the parent widget at the position where the event occurs. The finally block ensures that the grab_release() method releases the event grab."
},
{
"code": null,
"e": 10764,
"s": 10648,
"text": "def do_popup(event):\n try:\n m.tk_popup(event.x_root, event.y_root)\n finally:\n m.grab_release()\n"
},
{
"code": null,
"e": 11233,
"s": 10764,
"text": "Syntax: tk_popup(x_root, y_root)Parameter: This procedure posts a menu at a given position on the screen, x_root and y_root is the current mouse position relative to the upper left corner of the screen.Explanation:This method is the event handler. When the event(right click) happens the method is called and the menu appears on the parent widget at the position where the event occurs. The finally block ensures that the grab_release() method releases the event grab."
},
{
"code": null,
"e": 11688,
"s": 11233,
"text": "L.bind(\"<Button-3>\", do_popup)Syntax: bind(event, handler)Parameter:event: Here, right click is the event and it is denoted by <Button-3>.handler: The handler is a piece of code that performs some particular task when the event triggered.Explanation:The right mouse button is pressed with the mouse pointer over the widget and this triggers an event which is handled by the event handler( do_popup() function ). The do_popup() function displays the menu."
},
{
"code": null,
"e": 11719,
"s": 11688,
"text": "L.bind(\"<Button-3>\", do_popup)"
},
{
"code": null,
"e": 11758,
"s": 11719,
"text": "Syntax: bind(event, handler)Parameter:"
},
{
"code": null,
"e": 11829,
"s": 11758,
"text": "event: Here, right click is the event and it is denoted by <Button-3>."
},
{
"code": null,
"e": 11930,
"s": 11829,
"text": "handler: The handler is a piece of code that performs some particular task when the event triggered."
},
{
"code": null,
"e": 12147,
"s": 11930,
"text": "Explanation:The right mouse button is pressed with the mouse pointer over the widget and this triggers an event which is handled by the event handler( do_popup() function ). The do_popup() function displays the menu."
},
{
"code": null,
"e": 12344,
"s": 12147,
"text": "Run the applicationmainloop()Syntax: mainloop()Parameter: Takes no arguments.Explanation:It acts like an infinite loop which keeps the application running until the main window is closed manually."
},
{
"code": null,
"e": 12355,
"s": 12344,
"text": "mainloop()"
},
{
"code": null,
"e": 12523,
"s": 12355,
"text": "Syntax: mainloop()Parameter: Takes no arguments.Explanation:It acts like an infinite loop which keeps the application running until the main window is closed manually."
},
{
"code": "import tkinterfrom tkinter import * root = Tk() L = Label(root, text =\"Right-click to display menu\", width = 40, height = 20)L.pack() m = Menu(root, tearoff = 0)m.add_command(label =\"Cut\")m.add_command(label =\"Copy\")m.add_command(label =\"Paste\")m.add_command(label =\"Reload\")m.add_separator()m.add_command(label =\"Rename\") def do_popup(event): try: m.tk_popup(event.x_root, event.y_root) finally: m.grab_release() L.bind(\"<Button-3>\", do_popup) mainloop()",
"e": 13014,
"s": 12523,
"text": null
},
{
"code": null,
"e": 13021,
"s": 13014,
"text": "Output"
},
{
"code": null,
"e": 13135,
"s": 13021,
"text": "ExplanationWhen a right-click is done on the parent window the popup menu appears and displays a list of choices."
},
{
"code": null,
"e": 13150,
"s": 13135,
"text": "Python-tkinter"
},
{
"code": null,
"e": 13157,
"s": 13150,
"text": "Python"
},
{
"code": null,
"e": 13255,
"s": 13157,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13273,
"s": 13255,
"text": "Python Dictionary"
},
{
"code": null,
"e": 13315,
"s": 13273,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 13337,
"s": 13315,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 13372,
"s": 13337,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 13398,
"s": 13372,
"text": "Python String | replace()"
},
{
"code": null,
"e": 13430,
"s": 13398,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 13459,
"s": 13430,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 13486,
"s": 13459,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 13516,
"s": 13486,
"text": "Iterate over a list in Python"
}
] |
HTTP headers | Location | 07 Nov, 2019
The HTTP Location header is a response header that is used under 2 circumstances to ask a browser to redirect a URL (status code 3xx) or provide information about the location of a newly created resource (status code of 201). Its usage is often confused with another HTTP Header which is HTTP Content-Location header. The main difference between them is that Location gives the URL of the resource where the redirection of the page happens while HTTP Content-Location is used to indicate the URL of a transmitted resource.
Syntax:
Location: <url>
Directives: This header accepts a single directive mentioned above and described below:
<url>: This directive holds the relative or absolute URL that gives access to a resource.
Examples:
These URLs include a scheme/host and conform to scheme-specific syntax and semantics, this is an Absolute URL:Location: https://www.geeksforgeeks.org/index.php
Location: https://www.geeksforgeeks.org/index.php
These URLs don’t include a scheme or a host. It must be combined with the URLs of the original request, Relative URL:Location: /blogs/
Location: /blogs/
To check this Location in action go to Inspect Element -> Network check the response header for Location like below, Location is highlighted you can see.Supported Browsers: The browsers are compatible with the HTTP Location header are listed below:
Google Chrome
Internet Explorer
Microsoft Edge
Firefox
Opera
Safari
HTTP-headers
Picked
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
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
REST API (Introduction)
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
How to create footer to stay at the bottom of a Web page?
How to set input type date in dd-mm-yyyy format using HTML ?
Roadmap to Learn JavaScript For Beginners | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Nov, 2019"
},
{
"code": null,
"e": 551,
"s": 28,
"text": "The HTTP Location header is a response header that is used under 2 circumstances to ask a browser to redirect a URL (status code 3xx) or provide information about the location of a newly created resource (status code of 201). Its usage is often confused with another HTTP Header which is HTTP Content-Location header. The main difference between them is that Location gives the URL of the resource where the redirection of the page happens while HTTP Content-Location is used to indicate the URL of a transmitted resource."
},
{
"code": null,
"e": 559,
"s": 551,
"text": "Syntax:"
},
{
"code": null,
"e": 575,
"s": 559,
"text": "Location: <url>"
},
{
"code": null,
"e": 663,
"s": 575,
"text": "Directives: This header accepts a single directive mentioned above and described below:"
},
{
"code": null,
"e": 753,
"s": 663,
"text": "<url>: This directive holds the relative or absolute URL that gives access to a resource."
},
{
"code": null,
"e": 763,
"s": 753,
"text": "Examples:"
},
{
"code": null,
"e": 923,
"s": 763,
"text": "These URLs include a scheme/host and conform to scheme-specific syntax and semantics, this is an Absolute URL:Location: https://www.geeksforgeeks.org/index.php"
},
{
"code": null,
"e": 973,
"s": 923,
"text": "Location: https://www.geeksforgeeks.org/index.php"
},
{
"code": null,
"e": 1108,
"s": 973,
"text": "These URLs don’t include a scheme or a host. It must be combined with the URLs of the original request, Relative URL:Location: /blogs/"
},
{
"code": null,
"e": 1126,
"s": 1108,
"text": "Location: /blogs/"
},
{
"code": null,
"e": 1375,
"s": 1126,
"text": "To check this Location in action go to Inspect Element -> Network check the response header for Location like below, Location is highlighted you can see.Supported Browsers: The browsers are compatible with the HTTP Location header are listed below:"
},
{
"code": null,
"e": 1389,
"s": 1375,
"text": "Google Chrome"
},
{
"code": null,
"e": 1407,
"s": 1389,
"text": "Internet Explorer"
},
{
"code": null,
"e": 1422,
"s": 1407,
"text": "Microsoft Edge"
},
{
"code": null,
"e": 1430,
"s": 1422,
"text": "Firefox"
},
{
"code": null,
"e": 1436,
"s": 1430,
"text": "Opera"
},
{
"code": null,
"e": 1443,
"s": 1436,
"text": "Safari"
},
{
"code": null,
"e": 1456,
"s": 1443,
"text": "HTTP-headers"
},
{
"code": null,
"e": 1463,
"s": 1456,
"text": "Picked"
},
{
"code": null,
"e": 1480,
"s": 1463,
"text": "Web Technologies"
},
{
"code": null,
"e": 1578,
"s": 1480,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1639,
"s": 1578,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1682,
"s": 1639,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 1754,
"s": 1682,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1794,
"s": 1754,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1818,
"s": 1794,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1851,
"s": 1818,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 1911,
"s": 1851,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 1969,
"s": 1911,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 2030,
"s": 1969,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Stack clone() method in Java with Example | 24 Dec, 2018
The clone() method of Stack class is used to return a shallow copy of this Stack. It just creates a copy of the Stack. The copy will have a reference to a clone of the internal data array but not a reference to the original internal data array.
Syntax:
Stack.clone()
Parameters: The method does not take any parameter.
Return Value: The method returns an Object which is just the copy of the Stack.
Exception: This method throws CloneNotSupportedException if the object’s class does not support the Cloneable interface.
Below programs illustrate the Java.util.Stack.clone() method:
Program 1:
// Java code to illustrate clone() import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<String> stack = new Stack<String>(); // Use add() method to add elements into the Stack stack.add("Welcome"); stack.add("To"); stack.add("Geeks"); stack.add("4"); stack.add("Geeks"); // Displaying the Stack System.out.println("Stack: " + stack); // Creating another Stack to copy Object copy_Stack = stack.clone(); // Displaying the copy of Stack System.out.println("The cloned Stack is: " + copy_Stack); }}
Stack: [Welcome, To, Geeks, 4, Geeks]
The cloned Stack is: [Welcome, To, Geeks, 4, Geeks]
Program 2:
// Java code to illustrate clone() import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<Integer> stack = new Stack<Integer>(); // Use add() method to add elements into the Queue stack.add(10); stack.add(15); stack.add(30); stack.add(20); stack.add(5); // Displaying the Stack System.out.println("Stack: " + stack); // Creating another Stack to copy Object copy_Stack = (Stack)stack.clone(); // Displaying the copy of Stack System.out.println("The cloned Stack is: " + copy_Stack); }}
Stack: [10, 15, 30, 20, 5]
The cloned Stack is: [10, 15, 30, 20, 5]
Java - util package
Java-Collections
Java-Functions
Java-Stack
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
For-each loop in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Dec, 2018"
},
{
"code": null,
"e": 273,
"s": 28,
"text": "The clone() method of Stack class is used to return a shallow copy of this Stack. It just creates a copy of the Stack. The copy will have a reference to a clone of the internal data array but not a reference to the original internal data array."
},
{
"code": null,
"e": 281,
"s": 273,
"text": "Syntax:"
},
{
"code": null,
"e": 295,
"s": 281,
"text": "Stack.clone()"
},
{
"code": null,
"e": 347,
"s": 295,
"text": "Parameters: The method does not take any parameter."
},
{
"code": null,
"e": 427,
"s": 347,
"text": "Return Value: The method returns an Object which is just the copy of the Stack."
},
{
"code": null,
"e": 548,
"s": 427,
"text": "Exception: This method throws CloneNotSupportedException if the object’s class does not support the Cloneable interface."
},
{
"code": null,
"e": 610,
"s": 548,
"text": "Below programs illustrate the Java.util.Stack.clone() method:"
},
{
"code": null,
"e": 621,
"s": 610,
"text": "Program 1:"
},
{
"code": "// Java code to illustrate clone() import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<String> stack = new Stack<String>(); // Use add() method to add elements into the Stack stack.add(\"Welcome\"); stack.add(\"To\"); stack.add(\"Geeks\"); stack.add(\"4\"); stack.add(\"Geeks\"); // Displaying the Stack System.out.println(\"Stack: \" + stack); // Creating another Stack to copy Object copy_Stack = stack.clone(); // Displaying the copy of Stack System.out.println(\"The cloned Stack is: \" + copy_Stack); }}",
"e": 1326,
"s": 621,
"text": null
},
{
"code": null,
"e": 1417,
"s": 1326,
"text": "Stack: [Welcome, To, Geeks, 4, Geeks]\nThe cloned Stack is: [Welcome, To, Geeks, 4, Geeks]\n"
},
{
"code": null,
"e": 1428,
"s": 1417,
"text": "Program 2:"
},
{
"code": "// Java code to illustrate clone() import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<Integer> stack = new Stack<Integer>(); // Use add() method to add elements into the Queue stack.add(10); stack.add(15); stack.add(30); stack.add(20); stack.add(5); // Displaying the Stack System.out.println(\"Stack: \" + stack); // Creating another Stack to copy Object copy_Stack = (Stack)stack.clone(); // Displaying the copy of Stack System.out.println(\"The cloned Stack is: \" + copy_Stack); }}",
"e": 2121,
"s": 1428,
"text": null
},
{
"code": null,
"e": 2190,
"s": 2121,
"text": "Stack: [10, 15, 30, 20, 5]\nThe cloned Stack is: [10, 15, 30, 20, 5]\n"
},
{
"code": null,
"e": 2210,
"s": 2190,
"text": "Java - util package"
},
{
"code": null,
"e": 2227,
"s": 2210,
"text": "Java-Collections"
},
{
"code": null,
"e": 2242,
"s": 2227,
"text": "Java-Functions"
},
{
"code": null,
"e": 2253,
"s": 2242,
"text": "Java-Stack"
},
{
"code": null,
"e": 2258,
"s": 2253,
"text": "Java"
},
{
"code": null,
"e": 2263,
"s": 2258,
"text": "Java"
},
{
"code": null,
"e": 2280,
"s": 2263,
"text": "Java-Collections"
},
{
"code": null,
"e": 2378,
"s": 2280,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2393,
"s": 2378,
"text": "Arrays in Java"
},
{
"code": null,
"e": 2437,
"s": 2393,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 2473,
"s": 2437,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 2498,
"s": 2473,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 2549,
"s": 2498,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 2571,
"s": 2549,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 2602,
"s": 2571,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 2621,
"s": 2602,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 2651,
"s": 2621,
"text": "HashMap in Java with Examples"
}
] |
Python | Add tuple to front of list | 18 Oct, 2019
Sometimes, while working with Python list, we can have a problem in which we need to add a new tuple to existing list. Append at rear is usually easier than addition at front. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using insert()This is one of the way in which the element can be added to front in one-liner. It is used to add any element in front of list. The behaviour is the same for tuple as well.
# Python3 code to demonstrate working of# Adding tuple to front of list# using insert() # Initializing list test_list = [('is', 2), ('best', 3)] # printing original list print("The original list is : " + str(test_list)) # Initializing tuple to add add_tuple = ('gfg', 1) # Adding tuple to front of list# using insert()test_list.insert(0, add_tuple) # printing resultprint("The tuple after adding is : " + str(test_list))
The original list is : [('is', 2), ('best', 3)]
The tuple after adding is : [('gfg', 1), ('is', 2), ('best', 3)]
Method #2 : Using deque() + appendleft()The combination of above functions can be used to perform this particular task. In this, we just need to convert the list into a deque so that we can perform the append at front using appendleft()
# Python3 code to demonstrate working of# Adding tuple to front of list# using deque() + appendleft()from collections import deque # Initializing list test_list = [('is', 2), ('best', 3)] # printing original list print("The original list is : " + str(test_list)) # Initializing tuple to add add_tuple = ('gfg', 1) # Adding tuple to front of list# using deque() + appendleft()res = deque(test_list)res.appendleft(add_tuple) # printing resultprint("The tuple after adding is : " + str(list(res)))
The original list is : [('is', 2), ('best', 3)]
The tuple after adding is : [('gfg', 1), ('is', 2), ('best', 3)]
Python list-programs
Python
Python Programs
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
Python String | replace()
How to Install PIP on Windows ?
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Oct, 2019"
},
{
"code": null,
"e": 268,
"s": 28,
"text": "Sometimes, while working with Python list, we can have a problem in which we need to add a new tuple to existing list. Append at rear is usually easier than addition at front. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 467,
"s": 268,
"text": "Method #1 : Using insert()This is one of the way in which the element can be added to front in one-liner. It is used to add any element in front of list. The behaviour is the same for tuple as well."
},
{
"code": "# Python3 code to demonstrate working of# Adding tuple to front of list# using insert() # Initializing list test_list = [('is', 2), ('best', 3)] # printing original list print(\"The original list is : \" + str(test_list)) # Initializing tuple to add add_tuple = ('gfg', 1) # Adding tuple to front of list# using insert()test_list.insert(0, add_tuple) # printing resultprint(\"The tuple after adding is : \" + str(test_list))",
"e": 893,
"s": 467,
"text": null
},
{
"code": null,
"e": 1007,
"s": 893,
"text": "The original list is : [('is', 2), ('best', 3)]\nThe tuple after adding is : [('gfg', 1), ('is', 2), ('best', 3)]\n"
},
{
"code": null,
"e": 1246,
"s": 1009,
"text": "Method #2 : Using deque() + appendleft()The combination of above functions can be used to perform this particular task. In this, we just need to convert the list into a deque so that we can perform the append at front using appendleft()"
},
{
"code": "# Python3 code to demonstrate working of# Adding tuple to front of list# using deque() + appendleft()from collections import deque # Initializing list test_list = [('is', 2), ('best', 3)] # printing original list print(\"The original list is : \" + str(test_list)) # Initializing tuple to add add_tuple = ('gfg', 1) # Adding tuple to front of list# using deque() + appendleft()res = deque(test_list)res.appendleft(add_tuple) # printing resultprint(\"The tuple after adding is : \" + str(list(res)))",
"e": 1746,
"s": 1246,
"text": null
},
{
"code": null,
"e": 1860,
"s": 1746,
"text": "The original list is : [('is', 2), ('best', 3)]\nThe tuple after adding is : [('gfg', 1), ('is', 2), ('best', 3)]\n"
},
{
"code": null,
"e": 1881,
"s": 1860,
"text": "Python list-programs"
},
{
"code": null,
"e": 1888,
"s": 1881,
"text": "Python"
},
{
"code": null,
"e": 1904,
"s": 1888,
"text": "Python Programs"
},
{
"code": null,
"e": 2002,
"s": 1904,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2020,
"s": 2002,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2062,
"s": 2020,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2084,
"s": 2062,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2110,
"s": 2084,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2142,
"s": 2110,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2164,
"s": 2142,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2203,
"s": 2164,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2241,
"s": 2203,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2290,
"s": 2241,
"text": "Python | Convert string dictionary to dictionary"
}
] |
How to create a drag and drop feature for reordering the images using HTML CSS and jQueryUI ? | 03 Aug, 2021
Given an images gallery and the task is to re-arrange the order of images in the list or grid by dragging and dropping. The jQuery UI framework provides a sortable() function which helps in re-ordering list items by using the mouse. With this functionality, the list items become interchangeable. The jQuery UI provides a sortable() function with default draggable properties. All the list elements in the HTML document are interchangeable and re-ordered for displaying. The user can drag and drop elements to a new position with the help of the mouse. Other elements adjust themselves to fit in the list.
Creating structure: In this section, we normally include the required jQueryUI link and libraries. Also, we will create a basic image gallery where we will perform the drag and drop functionality to reorder the gallery list.
Including all the required jQuery and jQuery UI libraries:<link href = “https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css” rel = “stylesheet”><script src = “https://code.jquery.com/jquery-1.10.2.js”></script><script src = “https://code.jquery.com/ui/1.10.4/jquery-ui.js”></script>
<link href = “https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css” rel = “stylesheet”><script src = “https://code.jquery.com/jquery-1.10.2.js”></script><script src = “https://code.jquery.com/ui/1.10.4/jquery-ui.js”></script>
HTML code to create structure:<!DOCTYPE html><html><head> <title> How to create drag and drop features for images reorder using HTML CSS and jQueryUI? </title></head> <body> <h1 style="color:green">GeeksforGeeks</h1> <b>Drag and drop using jQuery UI Sortable</b> <div class="height"></div><br> <div id = "imageListId"> <div id="imageNo1" class = "listitemClass"> <img src="images/geeksimage1.png" alt=""> </div> <div id="imageNo2" class = "listitemClass"> <img src="images/geeksimage2.png" alt=""> </div> <div id="imageNo3" class = "listitemClass"> <img src="images/geeksimage3.png" alt=""> </div> <div id="imageNo4" class = "listitemClass"> <img src="images/geeksimage4.png" alt=""> </div> <div id="imageNo5" class = "listitemClass"> <img src="images/geeksimage5.png" alt=""> </div> <div id="imageNo6" class = "listitemClass"> <img src="images/geeksimage6.png" alt=""> </div> </div> <div id="outputDiv"> <b>Output of ID's of images : </b> <input id="outputvalues" type="text" value="" /> </div></body> </html>
<!DOCTYPE html><html><head> <title> How to create drag and drop features for images reorder using HTML CSS and jQueryUI? </title></head> <body> <h1 style="color:green">GeeksforGeeks</h1> <b>Drag and drop using jQuery UI Sortable</b> <div class="height"></div><br> <div id = "imageListId"> <div id="imageNo1" class = "listitemClass"> <img src="images/geeksimage1.png" alt=""> </div> <div id="imageNo2" class = "listitemClass"> <img src="images/geeksimage2.png" alt=""> </div> <div id="imageNo3" class = "listitemClass"> <img src="images/geeksimage3.png" alt=""> </div> <div id="imageNo4" class = "listitemClass"> <img src="images/geeksimage4.png" alt=""> </div> <div id="imageNo5" class = "listitemClass"> <img src="images/geeksimage5.png" alt=""> </div> <div id="imageNo6" class = "listitemClass"> <img src="images/geeksimage6.png" alt=""> </div> </div> <div id="outputDiv"> <b>Output of ID's of images : </b> <input id="outputvalues" type="text" value="" /> </div></body> </html>
Design the structure: In this section, we will design the pre-created structure and add the drag and drop feature by adding JavaScript code.
CSS code to design the structure:<style> /* text align for the body */ body { text-align: center; } /* image dimension */ img { height: 200px; width: 350px; } /* imagelistId styling */ #imageListId { margin: 0; padding: 0; list-style-type: none; } #imageListId div { margin: 0 4px 4px 4px; padding: 0.4em; display: inline-block; } /* Output order styling */ #outputvalues { margin: 0 2px 2px 2px; padding: 0.4em; padding-left: 1.5em; width: 250px; border: 2px solid dark-green; background: gray; } .listitemClass { border: 1px solid #006400; width: 350px; } .height { height: 10px; }</style>
<style> /* text align for the body */ body { text-align: center; } /* image dimension */ img { height: 200px; width: 350px; } /* imagelistId styling */ #imageListId { margin: 0; padding: 0; list-style-type: none; } #imageListId div { margin: 0 4px 4px 4px; padding: 0.4em; display: inline-block; } /* Output order styling */ #outputvalues { margin: 0 2px 2px 2px; padding: 0.4em; padding-left: 1.5em; width: 250px; border: 2px solid dark-green; background: gray; } .listitemClass { border: 1px solid #006400; width: 350px; } .height { height: 10px; }</style>
JS code to add the functionality:<script> $(function() { $("#imageListId").sortable({ update: function(event, ui) { getIdsOfImages(); } //end update }); }); function getIdsOfImages() { var values = []; $('.listitemClass').each(function(index) { values.push($(this).attr("id") .replace("imageNo", "")); }); $('#outputvalues').val(values); } </script>
<script> $(function() { $("#imageListId").sortable({ update: function(event, ui) { getIdsOfImages(); } //end update }); }); function getIdsOfImages() { var values = []; $('.listitemClass').each(function(index) { values.push($(this).attr("id") .replace("imageNo", "")); }); $('#outputvalues').val(values); } </script>
Final solution: In this section, we will combine all the above sections codes and achieve our task where you can perform the drag and drop to re-order the images in the image gallery.
Program:<!DOCTYPE html><html> <head> <title> How to create drag and drop features for images reorder using HTML CSS and jQueryUI? </title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"> </script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"> </script> <style> /* text align for the body */ body { text-align: center; } /* image dimension */ img{ height: 200px; width: 350px; } /* imagelistId styling */ #imageListId { margin: 0; padding: 0; list-style-type: none; } #imageListId div { margin: 0 4px 4px 4px; padding: 0.4em; display: inline-block; } /* Output order styling */ #outputvalues{ margin: 0 2px 2px 2px; padding: 0.4em; padding-left: 1.5em; width: 250px; border: 2px solid dark-green; background : gray; } .listitemClass { border: 1px solid #006400; width: 350px; } .height{ height: 10px; } </style> <script> $(function() { $( "#imageListId" ).sortable({ update: function(event, ui) { getIdsOfImages(); }//end update }); }); function getIdsOfImages() { var values = []; $('.listitemClass').each(function (index) { values.push($(this).attr("id") .replace("imageNo", "")); }); $('#outputvalues').val(values); } </script></head> <body> <h1 style="color:green">GeeksforGeeks</h1> <b>Drag and drop using jQuery UI Sortable</b> <div class="height"></div><br> <div id = "imageListId"> <div id="imageNo1" class = "listitemClass"> <img src="images/geeksimage1.png" alt=""> </div> <div id="imageNo2" class = "listitemClass"> <img src="images/geeksimage2.png" alt=""> </div> <div id="imageNo3" class = "listitemClass"> <img src="images/geeksimage3.png" alt=""> </div> <div id="imageNo4" class = "listitemClass"> <img src="images/geeksimage4.png" alt=""> </div> <div id="imageNo5" class = "listitemClass"> <img src="images/geeksimage5.png" alt=""> </div> <div id="imageNo6" class = "listitemClass"> <img src="images/geeksimage6.png" alt=""> </div> </div> <div id="outputDiv"> <b>Output of ID's of images : </b> <input id="outputvalues" type="text" value="" /> </div></body> </html>
<!DOCTYPE html><html> <head> <title> How to create drag and drop features for images reorder using HTML CSS and jQueryUI? </title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"> </script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"> </script> <style> /* text align for the body */ body { text-align: center; } /* image dimension */ img{ height: 200px; width: 350px; } /* imagelistId styling */ #imageListId { margin: 0; padding: 0; list-style-type: none; } #imageListId div { margin: 0 4px 4px 4px; padding: 0.4em; display: inline-block; } /* Output order styling */ #outputvalues{ margin: 0 2px 2px 2px; padding: 0.4em; padding-left: 1.5em; width: 250px; border: 2px solid dark-green; background : gray; } .listitemClass { border: 1px solid #006400; width: 350px; } .height{ height: 10px; } </style> <script> $(function() { $( "#imageListId" ).sortable({ update: function(event, ui) { getIdsOfImages(); }//end update }); }); function getIdsOfImages() { var values = []; $('.listitemClass').each(function (index) { values.push($(this).attr("id") .replace("imageNo", "")); }); $('#outputvalues').val(values); } </script></head> <body> <h1 style="color:green">GeeksforGeeks</h1> <b>Drag and drop using jQuery UI Sortable</b> <div class="height"></div><br> <div id = "imageListId"> <div id="imageNo1" class = "listitemClass"> <img src="images/geeksimage1.png" alt=""> </div> <div id="imageNo2" class = "listitemClass"> <img src="images/geeksimage2.png" alt=""> </div> <div id="imageNo3" class = "listitemClass"> <img src="images/geeksimage3.png" alt=""> </div> <div id="imageNo4" class = "listitemClass"> <img src="images/geeksimage4.png" alt=""> </div> <div id="imageNo5" class = "listitemClass"> <img src="images/geeksimage5.png" alt=""> </div> <div id="imageNo6" class = "listitemClass"> <img src="images/geeksimage6.png" alt=""> </div> </div> <div id="outputDiv"> <b>Output of ID's of images : </b> <input id="outputvalues" type="text" value="" /> </div></body> </html>
Output:
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.
CSS-Misc
HTML-Misc
JavaScript-Misc
jQuery-Misc
CSS
HTML
JavaScript
JQuery
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Form validation using jQuery
Design a web page using HTML and CSS
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
HTTP headers | Content-Type | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 658,
"s": 52,
"text": "Given an images gallery and the task is to re-arrange the order of images in the list or grid by dragging and dropping. The jQuery UI framework provides a sortable() function which helps in re-ordering list items by using the mouse. With this functionality, the list items become interchangeable. The jQuery UI provides a sortable() function with default draggable properties. All the list elements in the HTML document are interchangeable and re-ordered for displaying. The user can drag and drop elements to a new position with the help of the mouse. Other elements adjust themselves to fit in the list."
},
{
"code": null,
"e": 883,
"s": 658,
"text": "Creating structure: In this section, we normally include the required jQueryUI link and libraries. Also, we will create a basic image gallery where we will perform the drag and drop functionality to reorder the gallery list."
},
{
"code": null,
"e": 1182,
"s": 883,
"text": "Including all the required jQuery and jQuery UI libraries:<link href = “https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css” rel = “stylesheet”><script src = “https://code.jquery.com/jquery-1.10.2.js”></script><script src = “https://code.jquery.com/ui/1.10.4/jquery-ui.js”></script>"
},
{
"code": null,
"e": 1423,
"s": 1182,
"text": "<link href = “https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css” rel = “stylesheet”><script src = “https://code.jquery.com/jquery-1.10.2.js”></script><script src = “https://code.jquery.com/ui/1.10.4/jquery-ui.js”></script>"
},
{
"code": null,
"e": 2728,
"s": 1423,
"text": "HTML code to create structure:<!DOCTYPE html><html><head> <title> How to create drag and drop features for images reorder using HTML CSS and jQueryUI? </title></head> <body> <h1 style=\"color:green\">GeeksforGeeks</h1> <b>Drag and drop using jQuery UI Sortable</b> <div class=\"height\"></div><br> <div id = \"imageListId\"> <div id=\"imageNo1\" class = \"listitemClass\"> <img src=\"images/geeksimage1.png\" alt=\"\"> </div> <div id=\"imageNo2\" class = \"listitemClass\"> <img src=\"images/geeksimage2.png\" alt=\"\"> </div> <div id=\"imageNo3\" class = \"listitemClass\"> <img src=\"images/geeksimage3.png\" alt=\"\"> </div> <div id=\"imageNo4\" class = \"listitemClass\"> <img src=\"images/geeksimage4.png\" alt=\"\"> </div> <div id=\"imageNo5\" class = \"listitemClass\"> <img src=\"images/geeksimage5.png\" alt=\"\"> </div> <div id=\"imageNo6\" class = \"listitemClass\"> <img src=\"images/geeksimage6.png\" alt=\"\"> </div> </div> <div id=\"outputDiv\"> <b>Output of ID's of images : </b> <input id=\"outputvalues\" type=\"text\" value=\"\" /> </div></body> </html>"
},
{
"code": "<!DOCTYPE html><html><head> <title> How to create drag and drop features for images reorder using HTML CSS and jQueryUI? </title></head> <body> <h1 style=\"color:green\">GeeksforGeeks</h1> <b>Drag and drop using jQuery UI Sortable</b> <div class=\"height\"></div><br> <div id = \"imageListId\"> <div id=\"imageNo1\" class = \"listitemClass\"> <img src=\"images/geeksimage1.png\" alt=\"\"> </div> <div id=\"imageNo2\" class = \"listitemClass\"> <img src=\"images/geeksimage2.png\" alt=\"\"> </div> <div id=\"imageNo3\" class = \"listitemClass\"> <img src=\"images/geeksimage3.png\" alt=\"\"> </div> <div id=\"imageNo4\" class = \"listitemClass\"> <img src=\"images/geeksimage4.png\" alt=\"\"> </div> <div id=\"imageNo5\" class = \"listitemClass\"> <img src=\"images/geeksimage5.png\" alt=\"\"> </div> <div id=\"imageNo6\" class = \"listitemClass\"> <img src=\"images/geeksimage6.png\" alt=\"\"> </div> </div> <div id=\"outputDiv\"> <b>Output of ID's of images : </b> <input id=\"outputvalues\" type=\"text\" value=\"\" /> </div></body> </html>",
"e": 4003,
"s": 2728,
"text": null
},
{
"code": null,
"e": 4144,
"s": 4003,
"text": "Design the structure: In this section, we will design the pre-created structure and add the drag and drop feature by adding JavaScript code."
},
{
"code": null,
"e": 4957,
"s": 4144,
"text": "CSS code to design the structure:<style> /* text align for the body */ body { text-align: center; } /* image dimension */ img { height: 200px; width: 350px; } /* imagelistId styling */ #imageListId { margin: 0; padding: 0; list-style-type: none; } #imageListId div { margin: 0 4px 4px 4px; padding: 0.4em; display: inline-block; } /* Output order styling */ #outputvalues { margin: 0 2px 2px 2px; padding: 0.4em; padding-left: 1.5em; width: 250px; border: 2px solid dark-green; background: gray; } .listitemClass { border: 1px solid #006400; width: 350px; } .height { height: 10px; }</style>"
},
{
"code": "<style> /* text align for the body */ body { text-align: center; } /* image dimension */ img { height: 200px; width: 350px; } /* imagelistId styling */ #imageListId { margin: 0; padding: 0; list-style-type: none; } #imageListId div { margin: 0 4px 4px 4px; padding: 0.4em; display: inline-block; } /* Output order styling */ #outputvalues { margin: 0 2px 2px 2px; padding: 0.4em; padding-left: 1.5em; width: 250px; border: 2px solid dark-green; background: gray; } .listitemClass { border: 1px solid #006400; width: 350px; } .height { height: 10px; }</style>",
"e": 5737,
"s": 4957,
"text": null
},
{
"code": null,
"e": 6231,
"s": 5737,
"text": "JS code to add the functionality:<script> $(function() { $(\"#imageListId\").sortable({ update: function(event, ui) { getIdsOfImages(); } //end update }); }); function getIdsOfImages() { var values = []; $('.listitemClass').each(function(index) { values.push($(this).attr(\"id\") .replace(\"imageNo\", \"\")); }); $('#outputvalues').val(values); } </script>"
},
{
"code": "<script> $(function() { $(\"#imageListId\").sortable({ update: function(event, ui) { getIdsOfImages(); } //end update }); }); function getIdsOfImages() { var values = []; $('.listitemClass').each(function(index) { values.push($(this).attr(\"id\") .replace(\"imageNo\", \"\")); }); $('#outputvalues').val(values); } </script>",
"e": 6692,
"s": 6231,
"text": null
},
{
"code": null,
"e": 6876,
"s": 6692,
"text": "Final solution: In this section, we will combine all the above sections codes and achieve our task where you can perform the drag and drop to re-order the images in the image gallery."
},
{
"code": null,
"e": 9878,
"s": 6876,
"text": "Program:<!DOCTYPE html><html> <head> <title> How to create drag and drop features for images reorder using HTML CSS and jQueryUI? </title> <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\" rel = \"stylesheet\"> <script src = \"https://code.jquery.com/jquery-1.10.2.js\"> </script> <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"> </script> <style> /* text align for the body */ body { text-align: center; } /* image dimension */ img{ height: 200px; width: 350px; } /* imagelistId styling */ #imageListId { margin: 0; padding: 0; list-style-type: none; } #imageListId div { margin: 0 4px 4px 4px; padding: 0.4em; display: inline-block; } /* Output order styling */ #outputvalues{ margin: 0 2px 2px 2px; padding: 0.4em; padding-left: 1.5em; width: 250px; border: 2px solid dark-green; background : gray; } .listitemClass { border: 1px solid #006400; width: 350px; } .height{ height: 10px; } </style> <script> $(function() { $( \"#imageListId\" ).sortable({ update: function(event, ui) { getIdsOfImages(); }//end update }); }); function getIdsOfImages() { var values = []; $('.listitemClass').each(function (index) { values.push($(this).attr(\"id\") .replace(\"imageNo\", \"\")); }); $('#outputvalues').val(values); } </script></head> <body> <h1 style=\"color:green\">GeeksforGeeks</h1> <b>Drag and drop using jQuery UI Sortable</b> <div class=\"height\"></div><br> <div id = \"imageListId\"> <div id=\"imageNo1\" class = \"listitemClass\"> <img src=\"images/geeksimage1.png\" alt=\"\"> </div> <div id=\"imageNo2\" class = \"listitemClass\"> <img src=\"images/geeksimage2.png\" alt=\"\"> </div> <div id=\"imageNo3\" class = \"listitemClass\"> <img src=\"images/geeksimage3.png\" alt=\"\"> </div> <div id=\"imageNo4\" class = \"listitemClass\"> <img src=\"images/geeksimage4.png\" alt=\"\"> </div> <div id=\"imageNo5\" class = \"listitemClass\"> <img src=\"images/geeksimage5.png\" alt=\"\"> </div> <div id=\"imageNo6\" class = \"listitemClass\"> <img src=\"images/geeksimage6.png\" alt=\"\"> </div> </div> <div id=\"outputDiv\"> <b>Output of ID's of images : </b> <input id=\"outputvalues\" type=\"text\" value=\"\" /> </div></body> </html>"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to create drag and drop features for images reorder using HTML CSS and jQueryUI? </title> <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\" rel = \"stylesheet\"> <script src = \"https://code.jquery.com/jquery-1.10.2.js\"> </script> <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"> </script> <style> /* text align for the body */ body { text-align: center; } /* image dimension */ img{ height: 200px; width: 350px; } /* imagelistId styling */ #imageListId { margin: 0; padding: 0; list-style-type: none; } #imageListId div { margin: 0 4px 4px 4px; padding: 0.4em; display: inline-block; } /* Output order styling */ #outputvalues{ margin: 0 2px 2px 2px; padding: 0.4em; padding-left: 1.5em; width: 250px; border: 2px solid dark-green; background : gray; } .listitemClass { border: 1px solid #006400; width: 350px; } .height{ height: 10px; } </style> <script> $(function() { $( \"#imageListId\" ).sortable({ update: function(event, ui) { getIdsOfImages(); }//end update }); }); function getIdsOfImages() { var values = []; $('.listitemClass').each(function (index) { values.push($(this).attr(\"id\") .replace(\"imageNo\", \"\")); }); $('#outputvalues').val(values); } </script></head> <body> <h1 style=\"color:green\">GeeksforGeeks</h1> <b>Drag and drop using jQuery UI Sortable</b> <div class=\"height\"></div><br> <div id = \"imageListId\"> <div id=\"imageNo1\" class = \"listitemClass\"> <img src=\"images/geeksimage1.png\" alt=\"\"> </div> <div id=\"imageNo2\" class = \"listitemClass\"> <img src=\"images/geeksimage2.png\" alt=\"\"> </div> <div id=\"imageNo3\" class = \"listitemClass\"> <img src=\"images/geeksimage3.png\" alt=\"\"> </div> <div id=\"imageNo4\" class = \"listitemClass\"> <img src=\"images/geeksimage4.png\" alt=\"\"> </div> <div id=\"imageNo5\" class = \"listitemClass\"> <img src=\"images/geeksimage5.png\" alt=\"\"> </div> <div id=\"imageNo6\" class = \"listitemClass\"> <img src=\"images/geeksimage6.png\" alt=\"\"> </div> </div> <div id=\"outputDiv\"> <b>Output of ID's of images : </b> <input id=\"outputvalues\" type=\"text\" value=\"\" /> </div></body> </html>",
"e": 12872,
"s": 9878,
"text": null
},
{
"code": null,
"e": 12880,
"s": 12872,
"text": "Output:"
},
{
"code": null,
"e": 13148,
"s": 12880,
"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": 13157,
"s": 13148,
"text": "CSS-Misc"
},
{
"code": null,
"e": 13167,
"s": 13157,
"text": "HTML-Misc"
},
{
"code": null,
"e": 13183,
"s": 13167,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 13195,
"s": 13183,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 13199,
"s": 13195,
"text": "CSS"
},
{
"code": null,
"e": 13204,
"s": 13199,
"text": "HTML"
},
{
"code": null,
"e": 13215,
"s": 13204,
"text": "JavaScript"
},
{
"code": null,
"e": 13222,
"s": 13215,
"text": "JQuery"
},
{
"code": null,
"e": 13239,
"s": 13222,
"text": "Web Technologies"
},
{
"code": null,
"e": 13266,
"s": 13239,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 13271,
"s": 13266,
"text": "HTML"
},
{
"code": null,
"e": 13369,
"s": 13271,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13408,
"s": 13369,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 13447,
"s": 13408,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 13486,
"s": 13447,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 13515,
"s": 13486,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 13552,
"s": 13515,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 13576,
"s": 13552,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 13629,
"s": 13576,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 13689,
"s": 13629,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 13750,
"s": 13689,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
String in Switch Case in Java | 11 Jul, 2022
The switch statement is a multi-way branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. Basically, the expression can be a byte, short, char, and int primitive data types. Beginning with JDK7, it also works with enumerated types ( Enums in java), the String class, and Wrapper classes.
Hence the concept of string in switch statement arises into play in JDK 7 as we can use a string literal or constant to control a switch statement, which is not possible in C/C++. Using a string-based switch is an improvement over using the equivalent sequence of if/else statements. We now declare a string as a String class object only as depicted below:
Illustration:
String geeks = "GeeksforGeeks" ; // Valid from JDK7 and onwards
Object geeks = "GeeksforGeeks" ; // Invalid from JDK7 and onwards
There are certain key points that are needed to be remembered while using switch statement as it does provide convenience but at the same time acts as a double sword, hence we better go through traits as listed:
1. Expensive operation: Switching on strings can be more expensive in terms of execution than switching on primitive data types. Therefore, it is best to switch on strings only in cases in which the controlling data is already in string form.
2. String should not be NULL: Ensure that the expression in any switch statement is not null while working with strings to prevent a NullPointerException from being thrown at run-time.
3. Case Sensitive Comparison: The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the equals() method of String class consequently, the comparison of String objects in switch statements is case sensitive.
4. Better than if-else: The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.
Example 1:
Java
// Java Program to Demonstrate use of String to// Control a Switch Statement // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Custom input string String str = "two"; // Switch statement over above string switch (str) { // Case 1 case "one": // Print statement corresponding case System.out.println("one"); // break keyword terminates the // code execution here itself break; // Case 2 case "two": // Print statement corresponding case System.out.println("two"); break; // Case 3 case "three": // Print statement corresponding case System.out.println("three"); break; // Case 4 // Default case default: // Print statement corresponding case System.out.println("no match"); } }}
two
Example 2:
Java
// Java Program to Demonstrate use of String to// Control a Switch Statement // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Custom input string // Null string is passed String str = ""; // Switch statement over above string switch (str) { // Case 1 case "one": // Print statement corresponding case System.out.println("one"); // break keyword terminates the // code execution here itself break; // Case 2 case "two": // Print statement corresponding case System.out.println("two"); break; // Case 3 case "three": // Print statement corresponding case System.out.println("three"); break; // Case 4 // Default case default: // Print statement corresponding case System.out.println("no match"); } }}
no match
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
arjun_dandagi
solankimayank
varshagumber28
simmytarika5
hardikkoriintern
Java
School Programming
Strings
Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n11 Jul, 2022"
},
{
"code": null,
"e": 416,
"s": 53,
"text": "The switch statement is a multi-way branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. Basically, the expression can be a byte, short, char, and int primitive data types. Beginning with JDK7, it also works with enumerated types ( Enums in java), the String class, and Wrapper classes."
},
{
"code": null,
"e": 773,
"s": 416,
"text": "Hence the concept of string in switch statement arises into play in JDK 7 as we can use a string literal or constant to control a switch statement, which is not possible in C/C++. Using a string-based switch is an improvement over using the equivalent sequence of if/else statements. We now declare a string as a String class object only as depicted below:"
},
{
"code": null,
"e": 787,
"s": 773,
"text": "Illustration:"
},
{
"code": null,
"e": 919,
"s": 787,
"text": "String geeks = \"GeeksforGeeks\" ; // Valid from JDK7 and onwards \nObject geeks = \"GeeksforGeeks\" ; // Invalid from JDK7 and onwards "
},
{
"code": null,
"e": 1132,
"s": 919,
"text": "There are certain key points that are needed to be remembered while using switch statement as it does provide convenience but at the same time acts as a double sword, hence we better go through traits as listed: "
},
{
"code": null,
"e": 1375,
"s": 1132,
"text": "1. Expensive operation: Switching on strings can be more expensive in terms of execution than switching on primitive data types. Therefore, it is best to switch on strings only in cases in which the controlling data is already in string form."
},
{
"code": null,
"e": 1560,
"s": 1375,
"text": "2. String should not be NULL: Ensure that the expression in any switch statement is not null while working with strings to prevent a NullPointerException from being thrown at run-time."
},
{
"code": null,
"e": 1852,
"s": 1560,
"text": "3. Case Sensitive Comparison: The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the equals() method of String class consequently, the comparison of String objects in switch statements is case sensitive."
},
{
"code": null,
"e": 2028,
"s": 1852,
"text": "4. Better than if-else: The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements."
},
{
"code": null,
"e": 2039,
"s": 2028,
"text": "Example 1:"
},
{
"code": null,
"e": 2044,
"s": 2039,
"text": "Java"
},
{
"code": "// Java Program to Demonstrate use of String to// Control a Switch Statement // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Custom input string String str = \"two\"; // Switch statement over above string switch (str) { // Case 1 case \"one\": // Print statement corresponding case System.out.println(\"one\"); // break keyword terminates the // code execution here itself break; // Case 2 case \"two\": // Print statement corresponding case System.out.println(\"two\"); break; // Case 3 case \"three\": // Print statement corresponding case System.out.println(\"three\"); break; // Case 4 // Default case default: // Print statement corresponding case System.out.println(\"no match\"); } }}",
"e": 3035,
"s": 2044,
"text": null
},
{
"code": null,
"e": 3040,
"s": 3035,
"text": "two\n"
},
{
"code": null,
"e": 3051,
"s": 3040,
"text": "Example 2:"
},
{
"code": null,
"e": 3056,
"s": 3051,
"text": "Java"
},
{
"code": "// Java Program to Demonstrate use of String to// Control a Switch Statement // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Custom input string // Null string is passed String str = \"\"; // Switch statement over above string switch (str) { // Case 1 case \"one\": // Print statement corresponding case System.out.println(\"one\"); // break keyword terminates the // code execution here itself break; // Case 2 case \"two\": // Print statement corresponding case System.out.println(\"two\"); break; // Case 3 case \"three\": // Print statement corresponding case System.out.println(\"three\"); break; // Case 4 // Default case default: // Print statement corresponding case System.out.println(\"no match\"); } }}",
"e": 4076,
"s": 3056,
"text": null
},
{
"code": null,
"e": 4086,
"s": 4076,
"text": "no match\n"
},
{
"code": null,
"e": 4509,
"s": 4086,
"text": "This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 4523,
"s": 4509,
"text": "arjun_dandagi"
},
{
"code": null,
"e": 4537,
"s": 4523,
"text": "solankimayank"
},
{
"code": null,
"e": 4552,
"s": 4537,
"text": "varshagumber28"
},
{
"code": null,
"e": 4565,
"s": 4552,
"text": "simmytarika5"
},
{
"code": null,
"e": 4582,
"s": 4565,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 4587,
"s": 4582,
"text": "Java"
},
{
"code": null,
"e": 4606,
"s": 4587,
"text": "School Programming"
},
{
"code": null,
"e": 4614,
"s": 4606,
"text": "Strings"
},
{
"code": null,
"e": 4622,
"s": 4614,
"text": "Strings"
},
{
"code": null,
"e": 4627,
"s": 4622,
"text": "Java"
}
] |
Multiset in C++ Standard Template Library (STL) | 16 Jun, 2022
Multisets are a type of associative containers similar to the set, with the exception that multiple elements can have the same values. Some Basic Functions associated with multiset:
begin() – Returns an iterator to the first element in the multiset –> O(1)
end() – Returns an iterator to the theoretical element that follows the last element in the multiset –> O(1)
size() – Returns the number of elements in the multiset –> O(1)
max_size() – Returns the maximum number of elements that the multiset can hold –> O(1)
empty() – Returns whether the multiset is empty –> O(1)
insert (x) – Inserts the element x in the multiset –> O(log n)
clear () – Removes all the elements from the multiset –> O(n)
erase(x) – Removes all the occurrences of x –> O(log n)
Implementation:
CPP
// CPP Program to demonstrate the// implementation of multiset#include <iostream>#include <iterator>#include <set> using namespace std; int main(){ // empty multiset container multiset<int, greater<int> > gquiz1; // insert elements in random order gquiz1.insert(40); gquiz1.insert(30); gquiz1.insert(60); gquiz1.insert(20); gquiz1.insert(50); // 50 will be added again to // the multiset unlike set gquiz1.insert(50); gquiz1.insert(10); // printing multiset gquiz1 multiset<int, greater<int> >::iterator itr; cout << "\nThe multiset gquiz1 is : \n"; for (itr = gquiz1.begin(); itr != gquiz1.end(); ++itr) { cout << *itr << " "; } cout << endl; // assigning the elements from gquiz1 to gquiz2 multiset<int> gquiz2(gquiz1.begin(), gquiz1.end()); // print all elements of the multiset gquiz2 cout << "\nThe multiset gquiz2 \n" "after assign from gquiz1 is : \n"; for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << *itr << " "; } cout << endl; // remove all elements up to element // with value 30 in gquiz2 cout << "\ngquiz2 after removal \n" "of elements less than 30 : \n"; gquiz2.erase(gquiz2.begin(), gquiz2.find(30)); for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << *itr << " "; } // remove all elements with value 50 in gquiz2 int num; num = gquiz2.erase(50); cout << "\ngquiz2.erase(50) : \n"; cout << num << " removed \n"; for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << *itr << " "; } cout << endl; // lower bound and upper bound for multiset gquiz1 cout << "\ngquiz1.lower_bound(40) : \n" << *gquiz1.lower_bound(40) << endl; cout << "gquiz1.upper_bound(40) : \n" << *gquiz1.upper_bound(40) << endl; // lower bound and upper bound for multiset gquiz2 cout << "gquiz2.lower_bound(40) : \n" << *gquiz2.lower_bound(40) << endl; cout << "gquiz2.upper_bound(40) : \n" << *gquiz2.upper_bound(40) << endl; return 0;}
The multiset gquiz1 is :
60 50 50 40 30 20 10
The multiset gquiz2
after assign from gquiz1 is :
10 20 30 40 50 50 60
gquiz2 after removal
of elements less than 30 :
30 40 50 50 60
gquiz2.erase(50) :
2 removed
30 40 60
gquiz1.lower_bound(40) :
40
gquiz1.upper_bound(40) :
30
gquiz2.lower_bound(40) :
40
gquiz2.upper_bound(40) :
60
Removing Element From Multiset Which Have Same Value:
a.erase() – Remove all instances of element from multiset having the same value
a.erase(a.find()) – Remove only one instance of element from multiset having same value
The time complexities for doing various operations on Multisets are –
Insertion of Elements- O(log N)
Accessing Elements – O(log N)
Deleting Elements- O(log N)
C++
// CPP Code to remove an element from multiset which have// same value#include <bits/stdc++.h>using namespace std; int main(){ multiset<int> a; a.insert(10); a.insert(10); a.insert(10); // it will give output 3 cout << a.count(10) << endl; // removing single instance from multiset // it will remove only one value of // 10 from multiset a.erase(a.find(10)); // it will give output 2 cout << a.count(10) << endl; // removing all instance of element from multiset // it will remove all instance of value 10 a.erase(10); // it will give output 0 because all // instance of value is removed from // multiset cout << a.count(10) << endl; return 0;}
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
3
2
0
Function
Definition
Recent Articles on Multiset
C++ Programming Language Tutorial | Multiset in C++ STL | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersC++ Programming Language Tutorial | Multiset in C++ STL | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:35•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=xelzlR_OGnI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
samridhzor23
striver02
gabaa406
anshikajain26
utkarshgupta110092
divyanshmishra101010
sweetyty
cpp-containers-library
cpp-multiset
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vector in C++ STL
Initialize a vector in C++ (7 different ways)
std::sort() in C++ STL
Bitwise Operators in C/C++
unordered_map in C++ STL
Writing First C++ Program - Hello World Example
Templates in C++ with Examples
Virtual Function in C++
vector erase() and clear() in C++
Socket Programming in C/C++ | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Jun, 2022"
},
{
"code": null,
"e": 235,
"s": 52,
"text": "Multisets are a type of associative containers similar to the set, with the exception that multiple elements can have the same values. Some Basic Functions associated with multiset: "
},
{
"code": null,
"e": 311,
"s": 235,
"text": "begin() – Returns an iterator to the first element in the multiset –> O(1)"
},
{
"code": null,
"e": 420,
"s": 311,
"text": "end() – Returns an iterator to the theoretical element that follows the last element in the multiset –> O(1)"
},
{
"code": null,
"e": 484,
"s": 420,
"text": "size() – Returns the number of elements in the multiset –> O(1)"
},
{
"code": null,
"e": 571,
"s": 484,
"text": "max_size() – Returns the maximum number of elements that the multiset can hold –> O(1)"
},
{
"code": null,
"e": 627,
"s": 571,
"text": "empty() – Returns whether the multiset is empty –> O(1)"
},
{
"code": null,
"e": 690,
"s": 627,
"text": "insert (x) – Inserts the element x in the multiset –> O(log n)"
},
{
"code": null,
"e": 752,
"s": 690,
"text": "clear () – Removes all the elements from the multiset –> O(n)"
},
{
"code": null,
"e": 809,
"s": 752,
"text": " erase(x) – Removes all the occurrences of x –> O(log n)"
},
{
"code": null,
"e": 826,
"s": 809,
"text": "Implementation: "
},
{
"code": null,
"e": 830,
"s": 826,
"text": "CPP"
},
{
"code": "// CPP Program to demonstrate the// implementation of multiset#include <iostream>#include <iterator>#include <set> using namespace std; int main(){ // empty multiset container multiset<int, greater<int> > gquiz1; // insert elements in random order gquiz1.insert(40); gquiz1.insert(30); gquiz1.insert(60); gquiz1.insert(20); gquiz1.insert(50); // 50 will be added again to // the multiset unlike set gquiz1.insert(50); gquiz1.insert(10); // printing multiset gquiz1 multiset<int, greater<int> >::iterator itr; cout << \"\\nThe multiset gquiz1 is : \\n\"; for (itr = gquiz1.begin(); itr != gquiz1.end(); ++itr) { cout << *itr << \" \"; } cout << endl; // assigning the elements from gquiz1 to gquiz2 multiset<int> gquiz2(gquiz1.begin(), gquiz1.end()); // print all elements of the multiset gquiz2 cout << \"\\nThe multiset gquiz2 \\n\" \"after assign from gquiz1 is : \\n\"; for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << *itr << \" \"; } cout << endl; // remove all elements up to element // with value 30 in gquiz2 cout << \"\\ngquiz2 after removal \\n\" \"of elements less than 30 : \\n\"; gquiz2.erase(gquiz2.begin(), gquiz2.find(30)); for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << *itr << \" \"; } // remove all elements with value 50 in gquiz2 int num; num = gquiz2.erase(50); cout << \"\\ngquiz2.erase(50) : \\n\"; cout << num << \" removed \\n\"; for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << *itr << \" \"; } cout << endl; // lower bound and upper bound for multiset gquiz1 cout << \"\\ngquiz1.lower_bound(40) : \\n\" << *gquiz1.lower_bound(40) << endl; cout << \"gquiz1.upper_bound(40) : \\n\" << *gquiz1.upper_bound(40) << endl; // lower bound and upper bound for multiset gquiz2 cout << \"gquiz2.lower_bound(40) : \\n\" << *gquiz2.lower_bound(40) << endl; cout << \"gquiz2.upper_bound(40) : \\n\" << *gquiz2.upper_bound(40) << endl; return 0;}",
"e": 2925,
"s": 830,
"text": null
},
{
"code": null,
"e": 3273,
"s": 2925,
"text": "The multiset gquiz1 is : \n60 50 50 40 30 20 10 \n\nThe multiset gquiz2 \nafter assign from gquiz1 is : \n10 20 30 40 50 50 60 \n\ngquiz2 after removal \nof elements less than 30 : \n30 40 50 50 60 \ngquiz2.erase(50) : \n2 removed \n30 40 60 \n\ngquiz1.lower_bound(40) : \n40\ngquiz1.upper_bound(40) : \n30\ngquiz2.lower_bound(40) : \n40\ngquiz2.upper_bound(40) : \n60"
},
{
"code": null,
"e": 3328,
"s": 3273,
"text": " Removing Element From Multiset Which Have Same Value:"
},
{
"code": null,
"e": 3408,
"s": 3328,
"text": "a.erase() – Remove all instances of element from multiset having the same value"
},
{
"code": null,
"e": 3496,
"s": 3408,
"text": "a.erase(a.find()) – Remove only one instance of element from multiset having same value"
},
{
"code": null,
"e": 3566,
"s": 3496,
"text": "The time complexities for doing various operations on Multisets are –"
},
{
"code": null,
"e": 3598,
"s": 3566,
"text": "Insertion of Elements- O(log N)"
},
{
"code": null,
"e": 3628,
"s": 3598,
"text": "Accessing Elements – O(log N)"
},
{
"code": null,
"e": 3656,
"s": 3628,
"text": "Deleting Elements- O(log N)"
},
{
"code": null,
"e": 3660,
"s": 3656,
"text": "C++"
},
{
"code": "// CPP Code to remove an element from multiset which have// same value#include <bits/stdc++.h>using namespace std; int main(){ multiset<int> a; a.insert(10); a.insert(10); a.insert(10); // it will give output 3 cout << a.count(10) << endl; // removing single instance from multiset // it will remove only one value of // 10 from multiset a.erase(a.find(10)); // it will give output 2 cout << a.count(10) << endl; // removing all instance of element from multiset // it will remove all instance of value 10 a.erase(10); // it will give output 0 because all // instance of value is removed from // multiset cout << a.count(10) << endl; return 0;}",
"e": 4372,
"s": 3660,
"text": null
},
{
"code": null,
"e": 4381,
"s": 4372,
"text": "Chapters"
},
{
"code": null,
"e": 4408,
"s": 4381,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 4458,
"s": 4408,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 4481,
"s": 4458,
"text": "captions off, selected"
},
{
"code": null,
"e": 4489,
"s": 4481,
"text": "English"
},
{
"code": null,
"e": 4513,
"s": 4489,
"text": "This is a modal window."
},
{
"code": null,
"e": 4582,
"s": 4513,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 4604,
"s": 4582,
"text": "End of dialog window."
},
{
"code": null,
"e": 4610,
"s": 4604,
"text": "3\n2\n0"
},
{
"code": null,
"e": 4619,
"s": 4610,
"text": "Function"
},
{
"code": null,
"e": 4630,
"s": 4619,
"text": "Definition"
},
{
"code": null,
"e": 4660,
"s": 4630,
"text": "Recent Articles on Multiset "
},
{
"code": null,
"e": 5588,
"s": 4660,
"text": "C++ Programming Language Tutorial | Multiset in C++ STL | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersC++ Programming Language Tutorial | Multiset in C++ STL | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:35•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=xelzlR_OGnI\" 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": 5713,
"s": 5588,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 5726,
"s": 5713,
"text": "samridhzor23"
},
{
"code": null,
"e": 5736,
"s": 5726,
"text": "striver02"
},
{
"code": null,
"e": 5745,
"s": 5736,
"text": "gabaa406"
},
{
"code": null,
"e": 5759,
"s": 5745,
"text": "anshikajain26"
},
{
"code": null,
"e": 5778,
"s": 5759,
"text": "utkarshgupta110092"
},
{
"code": null,
"e": 5799,
"s": 5778,
"text": "divyanshmishra101010"
},
{
"code": null,
"e": 5808,
"s": 5799,
"text": "sweetyty"
},
{
"code": null,
"e": 5831,
"s": 5808,
"text": "cpp-containers-library"
},
{
"code": null,
"e": 5844,
"s": 5831,
"text": "cpp-multiset"
},
{
"code": null,
"e": 5848,
"s": 5844,
"text": "STL"
},
{
"code": null,
"e": 5852,
"s": 5848,
"text": "C++"
},
{
"code": null,
"e": 5856,
"s": 5852,
"text": "STL"
},
{
"code": null,
"e": 5860,
"s": 5856,
"text": "CPP"
},
{
"code": null,
"e": 5958,
"s": 5860,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5976,
"s": 5958,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 6022,
"s": 5976,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 6045,
"s": 6022,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 6072,
"s": 6045,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 6097,
"s": 6072,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 6145,
"s": 6097,
"text": "Writing First C++ Program - Hello World Example"
},
{
"code": null,
"e": 6176,
"s": 6145,
"text": "Templates in C++ with Examples"
},
{
"code": null,
"e": 6200,
"s": 6176,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 6234,
"s": 6200,
"text": "vector erase() and clear() in C++"
}
] |
JavaScript Array splice() Method | 27 May, 2022
Below is the example of Array splice() method.
Example:
Javascript
<script> var webDvlop = ["HTML", "CSS", "JS", "Bootstrap"]; document.write(webDvlop + "<br>"); // Add 'React_Native' and 'Php' after removing 'JS'. var removed = webDvlop.splice(2, 1, 'PHP', 'React_Native') document.write(webDvlop + "<br>"); document.write(removed + "<br>"); // No Removing only Insertion from 2nd // index from the ending webDvlop.splice(-2, 0, 'React') document.write(webDvlop)</script>
Output:
HTML,CSS,JS,Bootstrap
HTML,CSS,PHP,React_Native,Bootstrap
JS
HTML,CSS,PHP,React,React_Native,Bootstrap
The arr.splice() method is an inbuilt method in JavaScript which is used to modify the contents of an array by removing the existing elements and/or by adding new elements.
Syntax:
Array.splice( index, remove_count, item_list )
Parameter: This method accepts many parameters some of them are described below:
index: It is a required parameter. This parameter is the index which start modifying the array (with origin at 0). This can be negative also, which begins after that many elements counting from the end.
remove_count: The number of elements to be removed from the starting index.
items_list: The list of new items separated by comma operator that is to be inserted from the starting index.
Return Value: While it mutates the original array in-place, still it returns the list of removed items. In case there is no removed array it returns an empty array.
Below example illustrates the Array.splice() method in JavaScript:
Example:
Javascript
<script>var languages = ['C++', 'Java', 'Html', 'Python', 'C']; document.write(languages + "<br>"); // Add 'Julia' and 'Php' after removing 'Html'.var removed = languages.splice(2, 1, 'Julia', 'Php') document.write(languages + "<br>");document.write(removed + "<br>"); // No Removing only Insertion from 2nd index from the endinglanguages.splice(-2, 0, 'Pascal')document.write(languages)</script>
Output:
C++,Java,Html,Python,C
C++,Java,Julia,Php,Python,C
Html
C++,Java,Julia,Php,Pascal,Python,C
Supported Browser:
Google Chrome 1 and above
Internet Explorer 5.5 and above
Firefox 1 and above
Opera 4 and above
Safari 1 and above
bhattapoorv10
ysachin2314
tabishnadeem50
javascript-array
JavaScript-Methods
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
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": 53,
"s": 25,
"text": "\n27 May, 2022"
},
{
"code": null,
"e": 101,
"s": 53,
"text": "Below is the example of Array splice() method. "
},
{
"code": null,
"e": 111,
"s": 101,
"text": "Example: "
},
{
"code": null,
"e": 122,
"s": 111,
"text": "Javascript"
},
{
"code": "<script> var webDvlop = [\"HTML\", \"CSS\", \"JS\", \"Bootstrap\"]; document.write(webDvlop + \"<br>\"); // Add 'React_Native' and 'Php' after removing 'JS'. var removed = webDvlop.splice(2, 1, 'PHP', 'React_Native') document.write(webDvlop + \"<br>\"); document.write(removed + \"<br>\"); // No Removing only Insertion from 2nd // index from the ending webDvlop.splice(-2, 0, 'React') document.write(webDvlop)</script> ",
"e": 577,
"s": 122,
"text": null
},
{
"code": null,
"e": 586,
"s": 577,
"text": "Output: "
},
{
"code": null,
"e": 689,
"s": 586,
"text": "HTML,CSS,JS,Bootstrap\nHTML,CSS,PHP,React_Native,Bootstrap\nJS\nHTML,CSS,PHP,React,React_Native,Bootstrap"
},
{
"code": null,
"e": 862,
"s": 689,
"text": "The arr.splice() method is an inbuilt method in JavaScript which is used to modify the contents of an array by removing the existing elements and/or by adding new elements."
},
{
"code": null,
"e": 872,
"s": 862,
"text": "Syntax: "
},
{
"code": null,
"e": 919,
"s": 872,
"text": "Array.splice( index, remove_count, item_list )"
},
{
"code": null,
"e": 1001,
"s": 919,
"text": "Parameter: This method accepts many parameters some of them are described below: "
},
{
"code": null,
"e": 1204,
"s": 1001,
"text": "index: It is a required parameter. This parameter is the index which start modifying the array (with origin at 0). This can be negative also, which begins after that many elements counting from the end."
},
{
"code": null,
"e": 1280,
"s": 1204,
"text": "remove_count: The number of elements to be removed from the starting index."
},
{
"code": null,
"e": 1390,
"s": 1280,
"text": "items_list: The list of new items separated by comma operator that is to be inserted from the starting index."
},
{
"code": null,
"e": 1555,
"s": 1390,
"text": "Return Value: While it mutates the original array in-place, still it returns the list of removed items. In case there is no removed array it returns an empty array."
},
{
"code": null,
"e": 1622,
"s": 1555,
"text": "Below example illustrates the Array.splice() method in JavaScript:"
},
{
"code": null,
"e": 1633,
"s": 1622,
"text": "Example: "
},
{
"code": null,
"e": 1644,
"s": 1633,
"text": "Javascript"
},
{
"code": "<script>var languages = ['C++', 'Java', 'Html', 'Python', 'C']; document.write(languages + \"<br>\"); // Add 'Julia' and 'Php' after removing 'Html'.var removed = languages.splice(2, 1, 'Julia', 'Php') document.write(languages + \"<br>\");document.write(removed + \"<br>\"); // No Removing only Insertion from 2nd index from the endinglanguages.splice(-2, 0, 'Pascal')document.write(languages)</script> ",
"e": 2060,
"s": 1644,
"text": null
},
{
"code": null,
"e": 2069,
"s": 2060,
"text": "Output: "
},
{
"code": null,
"e": 2161,
"s": 2069,
"text": "C++,Java,Html,Python,C\nC++,Java,Julia,Php,Python,C\nHtml\nC++,Java,Julia,Php,Pascal,Python,C "
},
{
"code": null,
"e": 2181,
"s": 2161,
"text": " Supported Browser:"
},
{
"code": null,
"e": 2207,
"s": 2181,
"text": "Google Chrome 1 and above"
},
{
"code": null,
"e": 2239,
"s": 2207,
"text": "Internet Explorer 5.5 and above"
},
{
"code": null,
"e": 2259,
"s": 2239,
"text": "Firefox 1 and above"
},
{
"code": null,
"e": 2277,
"s": 2259,
"text": "Opera 4 and above"
},
{
"code": null,
"e": 2296,
"s": 2277,
"text": "Safari 1 and above"
},
{
"code": null,
"e": 2310,
"s": 2296,
"text": "bhattapoorv10"
},
{
"code": null,
"e": 2322,
"s": 2310,
"text": "ysachin2314"
},
{
"code": null,
"e": 2337,
"s": 2322,
"text": "tabishnadeem50"
},
{
"code": null,
"e": 2354,
"s": 2337,
"text": "javascript-array"
},
{
"code": null,
"e": 2373,
"s": 2354,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 2384,
"s": 2373,
"text": "JavaScript"
},
{
"code": null,
"e": 2401,
"s": 2384,
"text": "Web Technologies"
},
{
"code": null,
"e": 2499,
"s": 2401,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2560,
"s": 2499,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2632,
"s": 2560,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2673,
"s": 2632,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2725,
"s": 2673,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 2771,
"s": 2725,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 2804,
"s": 2771,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2866,
"s": 2804,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2927,
"s": 2866,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2977,
"s": 2927,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python program to print the Inverted heart pattern | 04 Oct, 2021
Let us see how to print an inverted heart pattern in Python.
Example:
Input: 11
Output:
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
*********************
********* ********
******* ******
***** ****
Input: 15
Output:
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
*********************
***********************
*************************
***************************
*****************************
************* ************
*********** **********
********* ********
******* ******
Approach:
Determine the size of the heart.Print an inverted triangle with size number of rows.Print the rest of the heart in 4 segments inside another loop.Print the white space right-triangle at the beginning.Print the first trapezium with stars.Print the white space triangle.Print the second trapezium with stars.
Determine the size of the heart.
Print an inverted triangle with size number of rows.
Print the rest of the heart in 4 segments inside another loop.
Print the white space right-triangle at the beginning.
Print the first trapezium with stars.
Print the white space triangle.
Print the second trapezium with stars.
Python3
# determining the size of the heartsize = 15 # printing the inverted trianglefor a in range(0, size): for b in range(a, size): print(" ", end = "") for b in range(1, (a * 2)): print("*", end = "") print("") # printing rest of the heartfor a in range(size, int(size / 2) - 1 , -2): # printing the white space right-triangle for b in range(1, size - a, 2): print(" ", end = "") # printing the first trapezium for b in range(1, a + 1): print("*", end = "") # printing the white space triangle for b in range(1, (size - a) + 1): print(" ", end = "") # printing the second trapezium for b in range(1, a): print("*", end = "") # new line print("")
Output:
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
*********************
***********************
*************************
***************************
*****************************
************* ************
*********** **********
********* ********
******* ******
anikakapoor
pattern-printing
Python Pattern-printing
Python
Python Programs
pattern-printing
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Split string into list of characters | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n04 Oct, 2021"
},
{
"code": null,
"e": 115,
"s": 54,
"text": "Let us see how to print an inverted heart pattern in Python."
},
{
"code": null,
"e": 124,
"s": 115,
"text": "Example:"
},
{
"code": null,
"e": 868,
"s": 124,
"text": "Input: 11\nOutput:\n\n *\n ***\n *****\n *******\n *********\n ***********\n *************\n ***************\n *****************\n *******************\n*********************\n ********* ********\n ******* ******\n ***** **** \n \nInput: 15\nOutput:\n *\n ***\n *****\n *******\n *********\n ***********\n *************\n ***************\n *****************\n *******************\n *********************\n ***********************\n *************************\n ***************************\n*****************************\n ************* ************\n *********** **********\n ********* ********\n ******* ******"
},
{
"code": null,
"e": 878,
"s": 868,
"text": "Approach:"
},
{
"code": null,
"e": 1185,
"s": 878,
"text": "Determine the size of the heart.Print an inverted triangle with size number of rows.Print the rest of the heart in 4 segments inside another loop.Print the white space right-triangle at the beginning.Print the first trapezium with stars.Print the white space triangle.Print the second trapezium with stars."
},
{
"code": null,
"e": 1218,
"s": 1185,
"text": "Determine the size of the heart."
},
{
"code": null,
"e": 1271,
"s": 1218,
"text": "Print an inverted triangle with size number of rows."
},
{
"code": null,
"e": 1334,
"s": 1271,
"text": "Print the rest of the heart in 4 segments inside another loop."
},
{
"code": null,
"e": 1389,
"s": 1334,
"text": "Print the white space right-triangle at the beginning."
},
{
"code": null,
"e": 1427,
"s": 1389,
"text": "Print the first trapezium with stars."
},
{
"code": null,
"e": 1459,
"s": 1427,
"text": "Print the white space triangle."
},
{
"code": null,
"e": 1498,
"s": 1459,
"text": "Print the second trapezium with stars."
},
{
"code": null,
"e": 1506,
"s": 1498,
"text": "Python3"
},
{
"code": "# determining the size of the heartsize = 15 # printing the inverted trianglefor a in range(0, size): for b in range(a, size): print(\" \", end = \"\") for b in range(1, (a * 2)): print(\"*\", end = \"\") print(\"\") # printing rest of the heartfor a in range(size, int(size / 2) - 1 , -2): # printing the white space right-triangle for b in range(1, size - a, 2): print(\" \", end = \"\") # printing the first trapezium for b in range(1, a + 1): print(\"*\", end = \"\") # printing the white space triangle for b in range(1, (size - a) + 1): print(\" \", end = \"\") # printing the second trapezium for b in range(1, a): print(\"*\", end = \"\") # new line print(\"\")",
"e": 2235,
"s": 1506,
"text": null
},
{
"code": null,
"e": 2243,
"s": 2235,
"text": "Output:"
},
{
"code": null,
"e": 2698,
"s": 2243,
"text": " *\n ***\n *****\n *******\n *********\n ***********\n *************\n ***************\n *****************\n *******************\n *********************\n ***********************\n *************************\n ***************************\n*****************************\n ************* ************\n *********** **********\n ********* ********\n ******* ******"
},
{
"code": null,
"e": 2712,
"s": 2700,
"text": "anikakapoor"
},
{
"code": null,
"e": 2729,
"s": 2712,
"text": "pattern-printing"
},
{
"code": null,
"e": 2753,
"s": 2729,
"text": "Python Pattern-printing"
},
{
"code": null,
"e": 2760,
"s": 2753,
"text": "Python"
},
{
"code": null,
"e": 2776,
"s": 2760,
"text": "Python Programs"
},
{
"code": null,
"e": 2793,
"s": 2776,
"text": "pattern-printing"
},
{
"code": null,
"e": 2891,
"s": 2793,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2923,
"s": 2891,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2950,
"s": 2923,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2971,
"s": 2950,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2994,
"s": 2971,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3050,
"s": 2994,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3072,
"s": 3050,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3111,
"s": 3072,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 3149,
"s": 3111,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 3186,
"s": 3149,
"text": "Python Program for Fibonacci numbers"
}
] |
Useful IPython magic commands. Towards becoming a Jupyter Notebook... | by Zolzaya Luvsandorj | Towards Data Science | When using Jupyter Notebook with IPython kernel, IPython magic commands come in handy. These magic commands make it easier to complete certain tasks. You can think of them as an extra set of helpful syntax in addition to Python syntax. In this post, we will get familiar with a few useful magic commands that you could use in Jupyter Notebook.
If you aren’t familiar with magic commands, it’s very likely that you may have been using some unknowingly. Does this syntax: %matplotlib inline look familiar to you? Probably, yes? %matplotlib is a IPython magic command. You see how this command start with %? This is a common characteristic of magic commands: they start with %. There are two kinds of magic commands:
line magic commands (start with %)
cell magic commands (start with %%)
For a line magic command, inputs are provided following the command in the same line. For a cell magic command, contents in the entire cell become its inputs. If you are not too sure what we mean by this, an example in section 3 will hopefully clarify.
Now we know a little bit about them, it’s time to explore a handful of useful magic commands and familiarise with their example usage! ✨
We can load code from an external source into a cell in Jupyter Notebook using this magic command. Here’s one useful application of this:
For most data science projects, you may find yourself importing the same set of libraries over and over again across different notebooks. To make this process quicker, we can prepare a standard setup script for a Jupyter Notebook and import this script at the beginning of each notebook to reduce the repetitive typing. Let’s look at an example to illustrate what we mean by this.
Imagine that we are working in magic_commands.ipynb that is located in project1 folder and setup.py contained the following setup script:
# Contents in setup.py# Data manipulationimport numpy as npimport pandas as pdpd.options.display.max_columns=Nonepd.options.display.float_format='{:.2f}'.format# Visualisationimport matplotlib.pyplot as pltimport seaborn as snssns.set(style='whitegrid', context='talk', palette='rainbow')
We could import the contents in setup.py with the following one liner without leaving the notebook:
%load setup.py
As we can see from this example, when we run the command, it inserts the code from setup.py and comments itself. Since standard imports can be used across most projects, you may prefer to save the script in Desktop (the parent directory) and have a project specific setup in the project folder only when needed (for instance, NLP projects will need additional set of imports).
If we wanted to load setup.py from the parent folder in the same notebook, we can update the file path to reflect the change:
%load ..\setup.py
Although this example case may seem trivial, it is a small change you could start practicing and it will hopefully inspire other applications.
Before we move on to the next command, it’s worth mentioning that while importing code from .py file is common, you can also import content from other files such as .txt and .md. In addition, you can also import code from URL like this:
%load https://gist.githubusercontent.com/zluvsand/74a6d88e401c4e3f76c2ae783a18689b/raw/5c9fd80a7bed839ba555bf4636e47572bd5c7e6d/pickle.py
This command lets us do the opposite of the previous command. We can save code to an external source from a cell in Jupyter Notebook using this magic command. If we imagine ourselves still being inside magic_commands.ipynb, this is how we would create setup.py to Desktop without leaving the notebook:
%%writefile ..\setup.py# Data manipulationimport numpy as npimport pandas as pdpd.options.display.max_columns=Nonepd.options.display.float_format='{:.2f}'.format# Visualisationimport matplotlib.pyplot as pltimport seaborn as snssns.set(style='whitegrid', context='talk', palette='rainbow')
This will create a setup.py file if doesn’t exist. Otherwise, it will overwrite the contents in the existing file.
There are often multiple ways to accomplish the same task. One important consideration when choosing between the options is speed. Or sometimes you just want to time your code to understand its performance. Whatever your use case might be, it’s useful to know how to time your code. Fortunately, timing code is easy with %[%]timeit.
Firstly, we will prepare some dummy data:
import numpy as npnp.random.seed(seed=123)numbers = np.random.randint(100, size=1000000)
Let’s imagine we wanted to time this code: mean = np.mean(numbers). We can do so with the following one liner:
%timeit mean = np.mean(numbers)
Output shows mean and standard deviation of the speed across multiple runs & loops. This is more rigorous way to time your code compared to timing based on a single run.
Now let’s understand the difference between %timeit and %%timeit (the following guideline is true for most line and cell magic commands):◼ ️️To use %timeit, a line magic command, the code you want to time should consist of a single line and be written in the same line following the magic command. Although this is a good general rule, multiple lines is possible with tweaks according to the documentation (see documentation for details). ◼ To use %%timeit, a cell magic command, the code you want to time can consist of any number of lines and written in the next line(s) following the magic command.
Here’s the equivalent of the previous code using %%timeit:
%%timeitmean = np.mean(numbers)
It’s likely that the code you want to time will consist of multiple lines, in which case %%timeit will come in handy.
Here’s a quick quiz to test your understanding. What do you think is the difference between the outputs of the following two cells? Try to think of the answer before proceeding. 💭
##### Cell A start #####%timeit mean = np.mean(numbers)np.mean(numbers)##### Cell A end ########## Cell B start #####%%timeit mean = np.mean(numbers)np.mean(numbers)##### Cell B start #####
Here comes the answer. In cell A, first we time the first line of code: mean = np.mean(numbers) then we find the average whereas in cell B, we time two lines of code:
You can see that cell B’s mean speed is about twice as cell A’s. This makes sense because we are essentially timing the same code twice (one with assignment and one without assignment) in cell B.
%[%]timeit automatically adjusts the number of loops depending on how long it takes to execute the code. This means that the longer the runtime, the less number of repetitions and vice versa so that it will always take about the same amount of time to time regardless of the complexity of the code. However, you can control the number of runs and loops by tweaking the optional arguments. Here’s an example:
%timeit -n500 -r5 np.mean(numbers)
Here, we have specified 5 runs and 500 loops.
These sets of commands are very useful if you experimented with a bunch of things and it’s already starting to get messy so it’s hard to remember exactly what you did. We can check the history of commands we ran in the current session with %history. Of note, %hist can be used instead of %history.
Let’s imagine we started a new session in section 3. We can see session history with:
%history
This is great but a little hard to see where one command ends and the other starts. Here’s how to check the history with each command numbered:
%history -n
This is easier to work with. Now, let’s learn how to export the history. If we want to write the history to a file named history.py in the same directory as the notebook, then we could use:
%history -f history.py
If we want to write the history to a Jupyter Notebook called history.ipynb in the same directory as the current notebook, then we use %notebook:
%notebook history.ipynb
This will insert each command into a separate cell. Quite convenient isn’t it?
Sometimes, we may want to recall a section of commands from the history to tweak it or rerun it. In this case, we can use %recall. When using %recall, we need to pass the corresponding numbers for the section of commands from history like this example:
%recall 1-2
The code above inserts first two commands from history into the next cell.
We have only covered a small subset of commands in this post. So in this section, I want to provide a simple guide on how to explore more magic commands on your own. ◼️ To see all available magic commands, run %lsmagic. ◼️ To access documentation for all commands, either check the documentation page or run %magic. ◼️ To access documentation of a magic command, you can run the magic command followed by ?. For example: %load?.
Lastly, try running the following one liner in your Jupyter Notebook:
%config MagicsManager
If you get the same output, even if we don’t write % or %% at the beginning of a magic command, it will still be recognised. For instance, if you try running the following syntax, you will see the same output as before:
config MagicsManager
While I think it is a convenient feature, writing the prefix makes the code more readable as it’s easy to tell it’s a magic command by the prefix.
Voila❕ We have covered a few useful magic commands and you are equipped to explore more on your own.✨ As Stephen R Covey once said “to learn and not to do is really not to learn. To know and not to do is really not to know”, I hope you will practice these magic commands to consolidate what we have learned today.
Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me.
Thank you for reading my post. If you are interested, here are links to some of my posts:◼️ Introduction to Python Virtual Environment for Data Science◼️ Introduction to Git for Data Science◼️ Organise your Jupyter Notebook with these tips◼️ Simple data visualisations in Python that you will find useful◼️ 6 simple tips for prettier and customised plots in Seaborn (Python)◼️️ 5 tips for pandas users◼️️ Writing 5 common SQL queries in pandas
Bye for now 🏃💨 | [
{
"code": null,
"e": 516,
"s": 172,
"text": "When using Jupyter Notebook with IPython kernel, IPython magic commands come in handy. These magic commands make it easier to complete certain tasks. You can think of them as an extra set of helpful syntax in addition to Python syntax. In this post, we will get familiar with a few useful magic commands that you could use in Jupyter Notebook."
},
{
"code": null,
"e": 886,
"s": 516,
"text": "If you aren’t familiar with magic commands, it’s very likely that you may have been using some unknowingly. Does this syntax: %matplotlib inline look familiar to you? Probably, yes? %matplotlib is a IPython magic command. You see how this command start with %? This is a common characteristic of magic commands: they start with %. There are two kinds of magic commands:"
},
{
"code": null,
"e": 921,
"s": 886,
"text": "line magic commands (start with %)"
},
{
"code": null,
"e": 957,
"s": 921,
"text": "cell magic commands (start with %%)"
},
{
"code": null,
"e": 1210,
"s": 957,
"text": "For a line magic command, inputs are provided following the command in the same line. For a cell magic command, contents in the entire cell become its inputs. If you are not too sure what we mean by this, an example in section 3 will hopefully clarify."
},
{
"code": null,
"e": 1347,
"s": 1210,
"text": "Now we know a little bit about them, it’s time to explore a handful of useful magic commands and familiarise with their example usage! ✨"
},
{
"code": null,
"e": 1485,
"s": 1347,
"text": "We can load code from an external source into a cell in Jupyter Notebook using this magic command. Here’s one useful application of this:"
},
{
"code": null,
"e": 1866,
"s": 1485,
"text": "For most data science projects, you may find yourself importing the same set of libraries over and over again across different notebooks. To make this process quicker, we can prepare a standard setup script for a Jupyter Notebook and import this script at the beginning of each notebook to reduce the repetitive typing. Let’s look at an example to illustrate what we mean by this."
},
{
"code": null,
"e": 2004,
"s": 1866,
"text": "Imagine that we are working in magic_commands.ipynb that is located in project1 folder and setup.py contained the following setup script:"
},
{
"code": null,
"e": 2293,
"s": 2004,
"text": "# Contents in setup.py# Data manipulationimport numpy as npimport pandas as pdpd.options.display.max_columns=Nonepd.options.display.float_format='{:.2f}'.format# Visualisationimport matplotlib.pyplot as pltimport seaborn as snssns.set(style='whitegrid', context='talk', palette='rainbow')"
},
{
"code": null,
"e": 2393,
"s": 2293,
"text": "We could import the contents in setup.py with the following one liner without leaving the notebook:"
},
{
"code": null,
"e": 2408,
"s": 2393,
"text": "%load setup.py"
},
{
"code": null,
"e": 2785,
"s": 2408,
"text": "As we can see from this example, when we run the command, it inserts the code from setup.py and comments itself. Since standard imports can be used across most projects, you may prefer to save the script in Desktop (the parent directory) and have a project specific setup in the project folder only when needed (for instance, NLP projects will need additional set of imports)."
},
{
"code": null,
"e": 2911,
"s": 2785,
"text": "If we wanted to load setup.py from the parent folder in the same notebook, we can update the file path to reflect the change:"
},
{
"code": null,
"e": 2929,
"s": 2911,
"text": "%load ..\\setup.py"
},
{
"code": null,
"e": 3072,
"s": 2929,
"text": "Although this example case may seem trivial, it is a small change you could start practicing and it will hopefully inspire other applications."
},
{
"code": null,
"e": 3309,
"s": 3072,
"text": "Before we move on to the next command, it’s worth mentioning that while importing code from .py file is common, you can also import content from other files such as .txt and .md. In addition, you can also import code from URL like this:"
},
{
"code": null,
"e": 3447,
"s": 3309,
"text": "%load https://gist.githubusercontent.com/zluvsand/74a6d88e401c4e3f76c2ae783a18689b/raw/5c9fd80a7bed839ba555bf4636e47572bd5c7e6d/pickle.py"
},
{
"code": null,
"e": 3749,
"s": 3447,
"text": "This command lets us do the opposite of the previous command. We can save code to an external source from a cell in Jupyter Notebook using this magic command. If we imagine ourselves still being inside magic_commands.ipynb, this is how we would create setup.py to Desktop without leaving the notebook:"
},
{
"code": null,
"e": 4039,
"s": 3749,
"text": "%%writefile ..\\setup.py# Data manipulationimport numpy as npimport pandas as pdpd.options.display.max_columns=Nonepd.options.display.float_format='{:.2f}'.format# Visualisationimport matplotlib.pyplot as pltimport seaborn as snssns.set(style='whitegrid', context='talk', palette='rainbow')"
},
{
"code": null,
"e": 4154,
"s": 4039,
"text": "This will create a setup.py file if doesn’t exist. Otherwise, it will overwrite the contents in the existing file."
},
{
"code": null,
"e": 4487,
"s": 4154,
"text": "There are often multiple ways to accomplish the same task. One important consideration when choosing between the options is speed. Or sometimes you just want to time your code to understand its performance. Whatever your use case might be, it’s useful to know how to time your code. Fortunately, timing code is easy with %[%]timeit."
},
{
"code": null,
"e": 4529,
"s": 4487,
"text": "Firstly, we will prepare some dummy data:"
},
{
"code": null,
"e": 4618,
"s": 4529,
"text": "import numpy as npnp.random.seed(seed=123)numbers = np.random.randint(100, size=1000000)"
},
{
"code": null,
"e": 4729,
"s": 4618,
"text": "Let’s imagine we wanted to time this code: mean = np.mean(numbers). We can do so with the following one liner:"
},
{
"code": null,
"e": 4761,
"s": 4729,
"text": "%timeit mean = np.mean(numbers)"
},
{
"code": null,
"e": 4931,
"s": 4761,
"text": "Output shows mean and standard deviation of the speed across multiple runs & loops. This is more rigorous way to time your code compared to timing based on a single run."
},
{
"code": null,
"e": 5533,
"s": 4931,
"text": "Now let’s understand the difference between %timeit and %%timeit (the following guideline is true for most line and cell magic commands):◼ ️️To use %timeit, a line magic command, the code you want to time should consist of a single line and be written in the same line following the magic command. Although this is a good general rule, multiple lines is possible with tweaks according to the documentation (see documentation for details). ◼ To use %%timeit, a cell magic command, the code you want to time can consist of any number of lines and written in the next line(s) following the magic command."
},
{
"code": null,
"e": 5592,
"s": 5533,
"text": "Here’s the equivalent of the previous code using %%timeit:"
},
{
"code": null,
"e": 5624,
"s": 5592,
"text": "%%timeitmean = np.mean(numbers)"
},
{
"code": null,
"e": 5742,
"s": 5624,
"text": "It’s likely that the code you want to time will consist of multiple lines, in which case %%timeit will come in handy."
},
{
"code": null,
"e": 5922,
"s": 5742,
"text": "Here’s a quick quiz to test your understanding. What do you think is the difference between the outputs of the following two cells? Try to think of the answer before proceeding. 💭"
},
{
"code": null,
"e": 6112,
"s": 5922,
"text": "##### Cell A start #####%timeit mean = np.mean(numbers)np.mean(numbers)##### Cell A end ########## Cell B start #####%%timeit mean = np.mean(numbers)np.mean(numbers)##### Cell B start #####"
},
{
"code": null,
"e": 6279,
"s": 6112,
"text": "Here comes the answer. In cell A, first we time the first line of code: mean = np.mean(numbers) then we find the average whereas in cell B, we time two lines of code:"
},
{
"code": null,
"e": 6475,
"s": 6279,
"text": "You can see that cell B’s mean speed is about twice as cell A’s. This makes sense because we are essentially timing the same code twice (one with assignment and one without assignment) in cell B."
},
{
"code": null,
"e": 6883,
"s": 6475,
"text": "%[%]timeit automatically adjusts the number of loops depending on how long it takes to execute the code. This means that the longer the runtime, the less number of repetitions and vice versa so that it will always take about the same amount of time to time regardless of the complexity of the code. However, you can control the number of runs and loops by tweaking the optional arguments. Here’s an example:"
},
{
"code": null,
"e": 6918,
"s": 6883,
"text": "%timeit -n500 -r5 np.mean(numbers)"
},
{
"code": null,
"e": 6964,
"s": 6918,
"text": "Here, we have specified 5 runs and 500 loops."
},
{
"code": null,
"e": 7262,
"s": 6964,
"text": "These sets of commands are very useful if you experimented with a bunch of things and it’s already starting to get messy so it’s hard to remember exactly what you did. We can check the history of commands we ran in the current session with %history. Of note, %hist can be used instead of %history."
},
{
"code": null,
"e": 7348,
"s": 7262,
"text": "Let’s imagine we started a new session in section 3. We can see session history with:"
},
{
"code": null,
"e": 7357,
"s": 7348,
"text": "%history"
},
{
"code": null,
"e": 7501,
"s": 7357,
"text": "This is great but a little hard to see where one command ends and the other starts. Here’s how to check the history with each command numbered:"
},
{
"code": null,
"e": 7513,
"s": 7501,
"text": "%history -n"
},
{
"code": null,
"e": 7703,
"s": 7513,
"text": "This is easier to work with. Now, let’s learn how to export the history. If we want to write the history to a file named history.py in the same directory as the notebook, then we could use:"
},
{
"code": null,
"e": 7726,
"s": 7703,
"text": "%history -f history.py"
},
{
"code": null,
"e": 7871,
"s": 7726,
"text": "If we want to write the history to a Jupyter Notebook called history.ipynb in the same directory as the current notebook, then we use %notebook:"
},
{
"code": null,
"e": 7895,
"s": 7871,
"text": "%notebook history.ipynb"
},
{
"code": null,
"e": 7974,
"s": 7895,
"text": "This will insert each command into a separate cell. Quite convenient isn’t it?"
},
{
"code": null,
"e": 8227,
"s": 7974,
"text": "Sometimes, we may want to recall a section of commands from the history to tweak it or rerun it. In this case, we can use %recall. When using %recall, we need to pass the corresponding numbers for the section of commands from history like this example:"
},
{
"code": null,
"e": 8239,
"s": 8227,
"text": "%recall 1-2"
},
{
"code": null,
"e": 8314,
"s": 8239,
"text": "The code above inserts first two commands from history into the next cell."
},
{
"code": null,
"e": 8743,
"s": 8314,
"text": "We have only covered a small subset of commands in this post. So in this section, I want to provide a simple guide on how to explore more magic commands on your own. ◼️ To see all available magic commands, run %lsmagic. ◼️ To access documentation for all commands, either check the documentation page or run %magic. ◼️ To access documentation of a magic command, you can run the magic command followed by ?. For example: %load?."
},
{
"code": null,
"e": 8813,
"s": 8743,
"text": "Lastly, try running the following one liner in your Jupyter Notebook:"
},
{
"code": null,
"e": 8835,
"s": 8813,
"text": "%config MagicsManager"
},
{
"code": null,
"e": 9055,
"s": 8835,
"text": "If you get the same output, even if we don’t write % or %% at the beginning of a magic command, it will still be recognised. For instance, if you try running the following syntax, you will see the same output as before:"
},
{
"code": null,
"e": 9076,
"s": 9055,
"text": "config MagicsManager"
},
{
"code": null,
"e": 9223,
"s": 9076,
"text": "While I think it is a convenient feature, writing the prefix makes the code more readable as it’s easy to tell it’s a magic command by the prefix."
},
{
"code": null,
"e": 9537,
"s": 9223,
"text": "Voila❕ We have covered a few useful magic commands and you are equipped to explore more on your own.✨ As Stephen R Covey once said “to learn and not to do is really not to learn. To know and not to do is really not to know”, I hope you will practice these magic commands to consolidate what we have learned today."
},
{
"code": null,
"e": 9761,
"s": 9537,
"text": "Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me."
},
{
"code": null,
"e": 10205,
"s": 9761,
"text": "Thank you for reading my post. If you are interested, here are links to some of my posts:◼️ Introduction to Python Virtual Environment for Data Science◼️ Introduction to Git for Data Science◼️ Organise your Jupyter Notebook with these tips◼️ Simple data visualisations in Python that you will find useful◼️ 6 simple tips for prettier and customised plots in Seaborn (Python)◼️️ 5 tips for pandas users◼️️ Writing 5 common SQL queries in pandas"
}
] |
Maximum value of unsigned short int in C++ - GeeksforGeeks | 28 Dec, 2020
In this article, we will discuss the unsigned short int data type in C++. It is the smallest (16 bit) integer data type in C++.
Some properties of the unsigned short int data type are:
Being an unsigned data type, it can store only positive values.Takes a size of 16 bits.A maximum integer value that can be stored in an unsigned short int data type is typically 65535, around 216 – 1(but is compiler dependent).The maximum value that can be stored in unsigned short int is stored as a constant in <climits> header file whose value can be used as USHRT_MAX.The minimum value that can be stored in unsigned short int is zero.In case of overflow or underflow of data type, the value is wrapped around. For example, if 0 is stored in an unsigned short int data type and 1 is subtracted from it, the value in that variable will become equal to 65535. Similarly, in the case of overflow, the value will round back to zero.
Being an unsigned data type, it can store only positive values.
Takes a size of 16 bits.
A maximum integer value that can be stored in an unsigned short int data type is typically 65535, around 216 – 1(but is compiler dependent).
The maximum value that can be stored in unsigned short int is stored as a constant in <climits> header file whose value can be used as USHRT_MAX.
The minimum value that can be stored in unsigned short int is zero.
In case of overflow or underflow of data type, the value is wrapped around. For example, if 0 is stored in an unsigned short int data type and 1 is subtracted from it, the value in that variable will become equal to 65535. Similarly, in the case of overflow, the value will round back to zero.
Below is the program to get the highest value that can be stored in unsigned short int in C++:
C++
// C++ program to obtain the maximum// value that we can store in an// unsigned short int#include <climits>#include <iostream>using namespace std; int main(){ // From the constant of climits // header file unsigned short int valueFromLimits = USHRT_MAX; cout << "Value from climits " << "constant: " << valueFromLimits << "\n"; // using the wrap around property // of data types // Initialize variable with value 0 unsigned short int value = 0; // subtract 1 from the value since // unsigned data type cannot store // negative number, the value will // wrap around and store the maximum // value that can store in it value = value - 1; cout << "Value using the wrap " << "around property: " << value << "\n"; return 0;}
Value from climits constant: 65535
Value using the wrap around property: 65535
Data Type
Data Types
C++
C++ Programs
Data Type
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++
Header files in C/C++ and its uses
C++ Program for QuickSort
How to return multiple values from a function in C or C++?
CSV file management using C++
Program to print ASCII Value of a character | [
{
"code": null,
"e": 24018,
"s": 23990,
"text": "\n28 Dec, 2020"
},
{
"code": null,
"e": 24147,
"s": 24018,
"text": "In this article, we will discuss the unsigned short int data type in C++. It is the smallest (16 bit) integer data type in C++. "
},
{
"code": null,
"e": 24204,
"s": 24147,
"text": "Some properties of the unsigned short int data type are:"
},
{
"code": null,
"e": 24937,
"s": 24204,
"text": "Being an unsigned data type, it can store only positive values.Takes a size of 16 bits.A maximum integer value that can be stored in an unsigned short int data type is typically 65535, around 216 – 1(but is compiler dependent).The maximum value that can be stored in unsigned short int is stored as a constant in <climits> header file whose value can be used as USHRT_MAX.The minimum value that can be stored in unsigned short int is zero.In case of overflow or underflow of data type, the value is wrapped around. For example, if 0 is stored in an unsigned short int data type and 1 is subtracted from it, the value in that variable will become equal to 65535. Similarly, in the case of overflow, the value will round back to zero."
},
{
"code": null,
"e": 25001,
"s": 24937,
"text": "Being an unsigned data type, it can store only positive values."
},
{
"code": null,
"e": 25026,
"s": 25001,
"text": "Takes a size of 16 bits."
},
{
"code": null,
"e": 25167,
"s": 25026,
"text": "A maximum integer value that can be stored in an unsigned short int data type is typically 65535, around 216 – 1(but is compiler dependent)."
},
{
"code": null,
"e": 25313,
"s": 25167,
"text": "The maximum value that can be stored in unsigned short int is stored as a constant in <climits> header file whose value can be used as USHRT_MAX."
},
{
"code": null,
"e": 25381,
"s": 25313,
"text": "The minimum value that can be stored in unsigned short int is zero."
},
{
"code": null,
"e": 25675,
"s": 25381,
"text": "In case of overflow or underflow of data type, the value is wrapped around. For example, if 0 is stored in an unsigned short int data type and 1 is subtracted from it, the value in that variable will become equal to 65535. Similarly, in the case of overflow, the value will round back to zero."
},
{
"code": null,
"e": 25770,
"s": 25675,
"text": "Below is the program to get the highest value that can be stored in unsigned short int in C++:"
},
{
"code": null,
"e": 25774,
"s": 25770,
"text": "C++"
},
{
"code": "// C++ program to obtain the maximum// value that we can store in an// unsigned short int#include <climits>#include <iostream>using namespace std; int main(){ // From the constant of climits // header file unsigned short int valueFromLimits = USHRT_MAX; cout << \"Value from climits \" << \"constant: \" << valueFromLimits << \"\\n\"; // using the wrap around property // of data types // Initialize variable with value 0 unsigned short int value = 0; // subtract 1 from the value since // unsigned data type cannot store // negative number, the value will // wrap around and store the maximum // value that can store in it value = value - 1; cout << \"Value using the wrap \" << \"around property: \" << value << \"\\n\"; return 0;}",
"e": 26585,
"s": 25774,
"text": null
},
{
"code": null,
"e": 26665,
"s": 26585,
"text": "Value from climits constant: 65535\nValue using the wrap around property: 65535\n"
},
{
"code": null,
"e": 26675,
"s": 26665,
"text": "Data Type"
},
{
"code": null,
"e": 26686,
"s": 26675,
"text": "Data Types"
},
{
"code": null,
"e": 26690,
"s": 26686,
"text": "C++"
},
{
"code": null,
"e": 26703,
"s": 26690,
"text": "C++ Programs"
},
{
"code": null,
"e": 26713,
"s": 26703,
"text": "Data Type"
},
{
"code": null,
"e": 26717,
"s": 26713,
"text": "CPP"
},
{
"code": null,
"e": 26815,
"s": 26717,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26824,
"s": 26815,
"text": "Comments"
},
{
"code": null,
"e": 26837,
"s": 26824,
"text": "Old Comments"
},
{
"code": null,
"e": 26865,
"s": 26837,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 26886,
"s": 26865,
"text": "Iterators in C++ STL"
},
{
"code": null,
"e": 26919,
"s": 26886,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 26939,
"s": 26919,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 26963,
"s": 26939,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 26998,
"s": 26963,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 27024,
"s": 26998,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 27083,
"s": 27024,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 27113,
"s": 27083,
"text": "CSV file management using C++"
}
] |
How to Design For Panic Resilience in Rust | by Luke Wilson | Towards Data Science | Try to imagine using some software and WHAM, a bunch of text, and visual garbage the brain can’t help but ignore. Or better yet, your user is piloting a commercial airliner when they press two buttons at the same time and the plane turns off. What we need is clear feedback, and to prevent halting execution. In this story, we discuss methods for panic resilience in Rust applications, to make quality software users can rely upon.
If you consider your software a car driving at about 60 miles per hour, a panic is like hitting a brick wall.
In 1990, a software update caused all 114 of AT&T’s nationwide Electronic Switching Systems to fail. When a tower failed, it would send a message to its neighboring towers that it was halting traffic. The message received by other towers caused them to enter a similar fail-state, perpetuating the message through the entire AT&T long-distance network.1
Poor logic is the cause of most harmful software bugs.2 Faults may be more discreet in C because ignored errors do not create warnings. Rust could have prevented some nasty software bugs that have happened in the past, but only if software developers make use of the vital error handling logic provided by the Rust language.
In the C language, number values are the idiomatic method of conveying “an error has occurred”. A function call returns an integer representing an error code. If the code is zero, then no error occurred. Otherwise, the code can be compared against values to determine what fault occurred.
The issue with that method of error handling in C is that it is not an error nor warning to ignore the return value of function calls. Failures may go unheard and unhandled.
The number one goal of error handling is to prevent crashes.
Some newer languages designed after C use exceptions for error handling, which is a high-level abstraction to error codes. Calling a function which may fail and cause an exception requires a try and catch block — to execute code that may cause an exception, and to handle the error signaled by the exception. Exceptions are still not always explicitly handled, and thus some lazy programmers handle exceptions the same way as .unwrap() handles errors in Rust — print the error and fail.
In Rust, errors are explicit. Errors in Rust are, by idiom, Result and Option types. Because errors are explicit, programmers get tired of dealing with them and eventually prefer to .unwrap() every one, which does nothing in the name of panic resilience. Unwrap encourages “best hopes” and blindly dives into whatever data may exist, and if at any case it fails, it’s a hard crash — a panic.
The number one goal of error handling is to prevent crashes.
Let’s look at three crucial sections about handling errors in Rust:
When to Panic,Handling Errors,And the additional section: Error Handling in a Library.
When to Panic,
Handling Errors,
And the additional section: Error Handling in a Library.
It is always better to exit with an error code than to panic. In the best situation, no software you write will ever panic. A panic is a controlled crash, and must be avoided to build reliable software.
A crash is not ever “appropriate” behavior, but it’s better than allowing your system to cause physical damage. If at any time it may be believed that the software could cause something deadly, expensive, or destructive to happen, it’s probably best to shut it down.
If you consider your software a car driving at about 60 miles per hour, a panic is like hitting a brick wall.
A panic unwinds the call stack, hopping out of every function call and returning from program execution, destroying objects as it goes. It is not considered a safe nor clean shutdown. Avoid panics.
The best way to end a program’s execution is to allow it to run until the last closing brace. Somehow, some way, program for that behavior. It allows all objects to safely destroy themselves. See the Drop trait.
Panic is a last-resort, not a nifty built-in that makes it easy to exit with a message!
Result, Option, std::io::Result, and other some other types can represent the success of an operation. In idiomatic Rust, if something can fail, it returns a Result which encodes two possible values: either a success value (Ok) or an error value (Err). Result<T, E> where T is the success value type, and E is the error value type.
We match our Results against the success and error values. If it is a success then we just take our value and progress in our software. But if the value produces an error, we must have an effective backup plan based on these questions:
Can we try again?Is the data absolutely mandatory to proceed, or can it be generated, adjusted, or assumed?
Can we try again?
Is the data absolutely mandatory to proceed, or can it be generated, adjusted, or assumed?
If the data is required to proceed, then we need to bubble the error up to the caller.3 We absolutely cannot panic in any function but main. Otherwise, you’ve got self-entitled functions running around believing they’re god objects. Proper error handling does all it can, and when in doubt, lets the caller handle the issue.
The following example applies the first question: Can we try again?
fn open_config() -> Result<std::fs::File, std::io::Error> { use std::fs::File; match File::open("config.toml") { Ok(f) => Ok(f), // If not found, search in second location: Err(e) => match File::open("data/config.toml") { Ok(f) => Ok(f), // Otherwise, bubble first error up to caller _ => Err(e), } }}fn main() { let mut result = open_config(); if result.is_err() { // If failed the first time // Try again in about 5 seconds ... std::thread::sleep(std::time::Duration::from_secs(5)); // Reattempt result = open_config(); } match result { // Proceed as usual ... Ok(cfg) => println!("Opened the config file"), // Print the cause to stderr, and DONT PANIC Err(e) => { eprintln!("File could not be opened: {:?}", e.kind()); std::process::exit(1); // Exit with code 1 (fail) }}
This code attempts to find a config file at “config.toml”. If it fails, it attempts to find the same configuration file in a specific subfolder. Only once the second attempt fails does it bubble the error up to the caller. The caller is main, and it is willing to reattempt a failure the first time after a 5 second pause. Notice how even main is not going to panic because while this is a fatal error, it is possible to resume the normal exiting process. It is always better to exit with an error code than to panic.
But same with panics, std::process:exit can prevent the destruction of objects, so only use it while nothing requiring the Drop trait is still owned. So panic is a last-resort, not a nifty built-in that makes it easy to exit with a message!
This last example applies the second question: Is the data absolutely mandatory to proceed?
/// Get the username from the config if it is present.fn read_username_from_config() -> Option<String> { // Implementation hidden}/// Get the username if present. Otherwise returns the/// default username "unnamed".fn get_username() -> String { read_username_from_config() .unwrap_or(String::from("unnamed"))}fn main() { let username = get_username(); println!("Username is: {}", username);}
In the above example, main is only requesting a username. get_username returns String which means there is zero capacity for it to fail. It attempts to read a username from the config file using read_username_from_config, but if one cannot be retrieved, it uses the default string “unnamed”.
It is important to weigh the value of data you can fail to get. Consider whether it’s possible to return to the input loop, or resume with a warning. Stay concerned about the usability of your software and how well it can overcome lack of data.4
Enums are the way to go when representing error values as codes.
#[derive(Debug, PartialEq)] // Use derivesenum SafeDivideError { // Define a custom error type DivideByZero,}fn safe_divide(dividend: i32, divisor: i32) -> Result<i32, SafeDivideError> { if divisor == 0 { // If the dividend is zero ... Err(SafeDivideError::DivideByZero) // Return the error value } else { // Otherwise ... Ok(dividend / divisor) // Return the success value }}assert_eq!(safe_divide(4, 2), Ok(4/2));assert_eq!(safe_divide(4, 0), Err(SafeDivideError::DivideByZero));
In the above example, we use a custom enum as the error return type. This makes it easy to see what we produced the error for, but a divide by zero is the only reason we would need to report an error in this situation. So, the better type to use is likely an Option<i32>.
Creating custom error types is valuable. When you use a bare enum as an error type, the data footprint can be tiny. This matters because regardless of using the success or error value of a Result<i32, String>, for example, it consumes as much memory as its largest member. In this case, a String, which is 16 bytes larger than an i32 on the stack. On the contrary, the SafeDivideError enum consumes “zero” bytes of memory.
println!("String: {}B", std::mem::size_of::<String>());println!("SafeDivideError: {}B", std::mem::size_of::<SafeDivideError>());// String: 24B// SafeDivideError: 0B
And when two or more values are used, it becomes the size of a u8 and can represent as much as 256 different error values, before gaining another byte. Enums are the way to go when representing error values as codes.
It is important to make use of documentation comments to explain why a function may return an error, and especially what different error values mean. If a function returns Result<i32, String> , then someone using your library would definitely want to know what different Strings can be returned by a failure of the function.
The older rules still apply to creating a library: never panic and allow the caller of the function to handle errors only when you cannot — bubble errors when necessary. Designing a good error resilient library requires putting emphasis on robust error types and their documentation. Take some genius from std::io::Error.
Rust empowers anyone to build highly robust, reliable, and efficient software. So don’t panic! Use the correct methods for writing reliable software with Rust.
Source: http://www.phworld.org/history/attcrash.htmThere’s a really good list of them: https://en.wikipedia.org/wiki/List_of_software_bugsError bubbling is when code passes an error upstream, because it decidedly won’t handle it. AKA error propagation.But don’t perform silent data manipulation.
Source: http://www.phworld.org/history/attcrash.htm
There’s a really good list of them: https://en.wikipedia.org/wiki/List_of_software_bugs
Error bubbling is when code passes an error upstream, because it decidedly won’t handle it. AKA error propagation.
But don’t perform silent data manipulation.
Some rights reserved | [
{
"code": null,
"e": 603,
"s": 171,
"text": "Try to imagine using some software and WHAM, a bunch of text, and visual garbage the brain can’t help but ignore. Or better yet, your user is piloting a commercial airliner when they press two buttons at the same time and the plane turns off. What we need is clear feedback, and to prevent halting execution. In this story, we discuss methods for panic resilience in Rust applications, to make quality software users can rely upon."
},
{
"code": null,
"e": 713,
"s": 603,
"text": "If you consider your software a car driving at about 60 miles per hour, a panic is like hitting a brick wall."
},
{
"code": null,
"e": 1067,
"s": 713,
"text": "In 1990, a software update caused all 114 of AT&T’s nationwide Electronic Switching Systems to fail. When a tower failed, it would send a message to its neighboring towers that it was halting traffic. The message received by other towers caused them to enter a similar fail-state, perpetuating the message through the entire AT&T long-distance network.1"
},
{
"code": null,
"e": 1392,
"s": 1067,
"text": "Poor logic is the cause of most harmful software bugs.2 Faults may be more discreet in C because ignored errors do not create warnings. Rust could have prevented some nasty software bugs that have happened in the past, but only if software developers make use of the vital error handling logic provided by the Rust language."
},
{
"code": null,
"e": 1681,
"s": 1392,
"text": "In the C language, number values are the idiomatic method of conveying “an error has occurred”. A function call returns an integer representing an error code. If the code is zero, then no error occurred. Otherwise, the code can be compared against values to determine what fault occurred."
},
{
"code": null,
"e": 1855,
"s": 1681,
"text": "The issue with that method of error handling in C is that it is not an error nor warning to ignore the return value of function calls. Failures may go unheard and unhandled."
},
{
"code": null,
"e": 1916,
"s": 1855,
"text": "The number one goal of error handling is to prevent crashes."
},
{
"code": null,
"e": 2403,
"s": 1916,
"text": "Some newer languages designed after C use exceptions for error handling, which is a high-level abstraction to error codes. Calling a function which may fail and cause an exception requires a try and catch block — to execute code that may cause an exception, and to handle the error signaled by the exception. Exceptions are still not always explicitly handled, and thus some lazy programmers handle exceptions the same way as .unwrap() handles errors in Rust — print the error and fail."
},
{
"code": null,
"e": 2795,
"s": 2403,
"text": "In Rust, errors are explicit. Errors in Rust are, by idiom, Result and Option types. Because errors are explicit, programmers get tired of dealing with them and eventually prefer to .unwrap() every one, which does nothing in the name of panic resilience. Unwrap encourages “best hopes” and blindly dives into whatever data may exist, and if at any case it fails, it’s a hard crash — a panic."
},
{
"code": null,
"e": 2856,
"s": 2795,
"text": "The number one goal of error handling is to prevent crashes."
},
{
"code": null,
"e": 2924,
"s": 2856,
"text": "Let’s look at three crucial sections about handling errors in Rust:"
},
{
"code": null,
"e": 3011,
"s": 2924,
"text": "When to Panic,Handling Errors,And the additional section: Error Handling in a Library."
},
{
"code": null,
"e": 3026,
"s": 3011,
"text": "When to Panic,"
},
{
"code": null,
"e": 3043,
"s": 3026,
"text": "Handling Errors,"
},
{
"code": null,
"e": 3100,
"s": 3043,
"text": "And the additional section: Error Handling in a Library."
},
{
"code": null,
"e": 3303,
"s": 3100,
"text": "It is always better to exit with an error code than to panic. In the best situation, no software you write will ever panic. A panic is a controlled crash, and must be avoided to build reliable software."
},
{
"code": null,
"e": 3570,
"s": 3303,
"text": "A crash is not ever “appropriate” behavior, but it’s better than allowing your system to cause physical damage. If at any time it may be believed that the software could cause something deadly, expensive, or destructive to happen, it’s probably best to shut it down."
},
{
"code": null,
"e": 3680,
"s": 3570,
"text": "If you consider your software a car driving at about 60 miles per hour, a panic is like hitting a brick wall."
},
{
"code": null,
"e": 3878,
"s": 3680,
"text": "A panic unwinds the call stack, hopping out of every function call and returning from program execution, destroying objects as it goes. It is not considered a safe nor clean shutdown. Avoid panics."
},
{
"code": null,
"e": 4090,
"s": 3878,
"text": "The best way to end a program’s execution is to allow it to run until the last closing brace. Somehow, some way, program for that behavior. It allows all objects to safely destroy themselves. See the Drop trait."
},
{
"code": null,
"e": 4178,
"s": 4090,
"text": "Panic is a last-resort, not a nifty built-in that makes it easy to exit with a message!"
},
{
"code": null,
"e": 4510,
"s": 4178,
"text": "Result, Option, std::io::Result, and other some other types can represent the success of an operation. In idiomatic Rust, if something can fail, it returns a Result which encodes two possible values: either a success value (Ok) or an error value (Err). Result<T, E> where T is the success value type, and E is the error value type."
},
{
"code": null,
"e": 4746,
"s": 4510,
"text": "We match our Results against the success and error values. If it is a success then we just take our value and progress in our software. But if the value produces an error, we must have an effective backup plan based on these questions:"
},
{
"code": null,
"e": 4854,
"s": 4746,
"text": "Can we try again?Is the data absolutely mandatory to proceed, or can it be generated, adjusted, or assumed?"
},
{
"code": null,
"e": 4872,
"s": 4854,
"text": "Can we try again?"
},
{
"code": null,
"e": 4963,
"s": 4872,
"text": "Is the data absolutely mandatory to proceed, or can it be generated, adjusted, or assumed?"
},
{
"code": null,
"e": 5288,
"s": 4963,
"text": "If the data is required to proceed, then we need to bubble the error up to the caller.3 We absolutely cannot panic in any function but main. Otherwise, you’ve got self-entitled functions running around believing they’re god objects. Proper error handling does all it can, and when in doubt, lets the caller handle the issue."
},
{
"code": null,
"e": 5356,
"s": 5288,
"text": "The following example applies the first question: Can we try again?"
},
{
"code": null,
"e": 6294,
"s": 5356,
"text": "fn open_config() -> Result<std::fs::File, std::io::Error> { use std::fs::File; match File::open(\"config.toml\") { Ok(f) => Ok(f), // If not found, search in second location: Err(e) => match File::open(\"data/config.toml\") { Ok(f) => Ok(f), // Otherwise, bubble first error up to caller _ => Err(e), } }}fn main() { let mut result = open_config(); if result.is_err() { // If failed the first time // Try again in about 5 seconds ... std::thread::sleep(std::time::Duration::from_secs(5)); // Reattempt result = open_config(); } match result { // Proceed as usual ... Ok(cfg) => println!(\"Opened the config file\"), // Print the cause to stderr, and DONT PANIC Err(e) => { eprintln!(\"File could not be opened: {:?}\", e.kind()); std::process::exit(1); // Exit with code 1 (fail) }}"
},
{
"code": null,
"e": 6812,
"s": 6294,
"text": "This code attempts to find a config file at “config.toml”. If it fails, it attempts to find the same configuration file in a specific subfolder. Only once the second attempt fails does it bubble the error up to the caller. The caller is main, and it is willing to reattempt a failure the first time after a 5 second pause. Notice how even main is not going to panic because while this is a fatal error, it is possible to resume the normal exiting process. It is always better to exit with an error code than to panic."
},
{
"code": null,
"e": 7053,
"s": 6812,
"text": "But same with panics, std::process:exit can prevent the destruction of objects, so only use it while nothing requiring the Drop trait is still owned. So panic is a last-resort, not a nifty built-in that makes it easy to exit with a message!"
},
{
"code": null,
"e": 7145,
"s": 7053,
"text": "This last example applies the second question: Is the data absolutely mandatory to proceed?"
},
{
"code": null,
"e": 7556,
"s": 7145,
"text": "/// Get the username from the config if it is present.fn read_username_from_config() -> Option<String> { // Implementation hidden}/// Get the username if present. Otherwise returns the/// default username \"unnamed\".fn get_username() -> String { read_username_from_config() .unwrap_or(String::from(\"unnamed\"))}fn main() { let username = get_username(); println!(\"Username is: {}\", username);}"
},
{
"code": null,
"e": 7848,
"s": 7556,
"text": "In the above example, main is only requesting a username. get_username returns String which means there is zero capacity for it to fail. It attempts to read a username from the config file using read_username_from_config, but if one cannot be retrieved, it uses the default string “unnamed”."
},
{
"code": null,
"e": 8094,
"s": 7848,
"text": "It is important to weigh the value of data you can fail to get. Consider whether it’s possible to return to the input loop, or resume with a warning. Stay concerned about the usability of your software and how well it can overcome lack of data.4"
},
{
"code": null,
"e": 8159,
"s": 8094,
"text": "Enums are the way to go when representing error values as codes."
},
{
"code": null,
"e": 8651,
"s": 8159,
"text": "#[derive(Debug, PartialEq)] // Use derivesenum SafeDivideError { // Define a custom error type DivideByZero,}fn safe_divide(dividend: i32, divisor: i32) -> Result<i32, SafeDivideError> { if divisor == 0 { // If the dividend is zero ... Err(SafeDivideError::DivideByZero) // Return the error value } else { // Otherwise ... Ok(dividend / divisor) // Return the success value }}assert_eq!(safe_divide(4, 2), Ok(4/2));assert_eq!(safe_divide(4, 0), Err(SafeDivideError::DivideByZero));"
},
{
"code": null,
"e": 8923,
"s": 8651,
"text": "In the above example, we use a custom enum as the error return type. This makes it easy to see what we produced the error for, but a divide by zero is the only reason we would need to report an error in this situation. So, the better type to use is likely an Option<i32>."
},
{
"code": null,
"e": 9346,
"s": 8923,
"text": "Creating custom error types is valuable. When you use a bare enum as an error type, the data footprint can be tiny. This matters because regardless of using the success or error value of a Result<i32, String>, for example, it consumes as much memory as its largest member. In this case, a String, which is 16 bytes larger than an i32 on the stack. On the contrary, the SafeDivideError enum consumes “zero” bytes of memory."
},
{
"code": null,
"e": 9529,
"s": 9346,
"text": "println!(\"String: {}B\", std::mem::size_of::<String>());println!(\"SafeDivideError: {}B\", std::mem::size_of::<SafeDivideError>());// String: 24B// SafeDivideError: 0B"
},
{
"code": null,
"e": 9746,
"s": 9529,
"text": "And when two or more values are used, it becomes the size of a u8 and can represent as much as 256 different error values, before gaining another byte. Enums are the way to go when representing error values as codes."
},
{
"code": null,
"e": 10071,
"s": 9746,
"text": "It is important to make use of documentation comments to explain why a function may return an error, and especially what different error values mean. If a function returns Result<i32, String> , then someone using your library would definitely want to know what different Strings can be returned by a failure of the function."
},
{
"code": null,
"e": 10393,
"s": 10071,
"text": "The older rules still apply to creating a library: never panic and allow the caller of the function to handle errors only when you cannot — bubble errors when necessary. Designing a good error resilient library requires putting emphasis on robust error types and their documentation. Take some genius from std::io::Error."
},
{
"code": null,
"e": 10553,
"s": 10393,
"text": "Rust empowers anyone to build highly robust, reliable, and efficient software. So don’t panic! Use the correct methods for writing reliable software with Rust."
},
{
"code": null,
"e": 10849,
"s": 10553,
"text": "Source: http://www.phworld.org/history/attcrash.htmThere’s a really good list of them: https://en.wikipedia.org/wiki/List_of_software_bugsError bubbling is when code passes an error upstream, because it decidedly won’t handle it. AKA error propagation.But don’t perform silent data manipulation."
},
{
"code": null,
"e": 10901,
"s": 10849,
"text": "Source: http://www.phworld.org/history/attcrash.htm"
},
{
"code": null,
"e": 10989,
"s": 10901,
"text": "There’s a really good list of them: https://en.wikipedia.org/wiki/List_of_software_bugs"
},
{
"code": null,
"e": 11104,
"s": 10989,
"text": "Error bubbling is when code passes an error upstream, because it decidedly won’t handle it. AKA error propagation."
},
{
"code": null,
"e": 11148,
"s": 11104,
"text": "But don’t perform silent data manipulation."
}
] |
How to subset a data frame by excluding the column names that are stored in a vector in R? | Subsetting of a data frame can be done in many ways and one such say is selecting the columns that are stored in a vector. Suppose we have a data frame df that has columns x, y, and z and the column names y and z are stored in a vector called V then we can subset df by excluding column names in V as select(df,-all_of(V)).
Consider the below data frame:
Live Demo
> x1<-rpois(20,5)
> x2<-rpois(20,2)
> x3<-rpois(20,3)
> x4<-rpois(20,5)
> df1<-data.frame(x1,x2,x3,x4)
> df1
x1 x2 x3 x4
1 3 4 0 5
2 4 1 2 6
3 4 1 2 3
4 8 1 7 6
5 4 2 3 8
6 4 4 1 0
7 4 1 1 2
8 7 2 4 4
9 4 3 6 5
10 4 3 5 7
11 3 2 3 5
12 4 2 3 5
13 3 1 2 5
14 4 2 5 7
15 4 3 7 2
16 2 1 3 6
17 5 1 8 3
18 4 0 4 6
19 5 2 4 9
20 9 0 4 7
Vector containing columns x1 and x4:
> v1<-c("x1","x4")
Subsetting df1 by excluding x1 and x4:
> select(df1,-all_of(v1))
x2 x3
1 4 0
2 1 2
3 1 2
4 1 7
5 2 3
6 4 1
7 1 1
8 2 4
9 3 6
10 3 5
11 2 3
12 2 3
13 1 2
14 2 5
15 3 7
16 1 3
17 1 8
18 0 4
19 2 4
20 0 4
Let’s have a look at another example:
Live Demo
> y1<-rnorm(20,1,0.098)
> y2<-rnorm(20,100,10)
> y3<-rnorm(20,5,0.97)
> y4<-rnorm(20,5275,30.5)
> df2<-data.frame(y1,y2,y3,y4)
> df2
y1 y2 y3 y4
1 1.0004066 95.44217 4.436526 5302.802
2 0.8704272 103.72030 4.459705 5279.560
3 1.0010894 96.78478 4.979246 5250.222
4 1.0856458 100.94359 5.480827 5261.604
5 0.9609981 98.62898 4.427267 5230.762
6 0.9497958 90.31327 4.332123 5204.725
7 0.9598390 95.87049 4.557982 5273.675
8 0.7686893 95.67384 5.747136 5232.587
9 0.8447364 97.65526 5.012912 5282.668
10 1.1740212 105.39359 4.088489 5300.367
11 0.9476001 115.77728 5.490385 5315.523
12 0.9824041 89.73841 4.703173 5256.286
13 0.9139366 112.73522 5.676117 5279.863
14 1.0712399 83.89056 4.510641 5275.326
15 1.1097967 91.60747 4.391030 5269.570
16 1.0449168 90.27042 3.793536 5210.164
17 0.8880382 74.78750 5.876453 5284.542
18 0.9304634 112.05254 5.410632 5330.084
19 1.1660059 108.03871 5.982188 5303.685
20 0.7662319 104.80364 5.518754 5283.069
> v2<-c("y2","y3")
Subsetting df2 by excluding y2 and y3:
> select(df2,-all_of(v2))
y1 y4
1 1.0004066 5302.802
2 0.8704272 5279.560
3 1.0010894 5250.222
4 1.0856458 5261.604
5 0.9609981 5230.762
6 0.9497958 5204.725
7 0.9598390 5273.675
8 0.7686893 5232.587
9 0.8447364 5282.668
10 1.1740212 5300.367
11 0.9476001 5315.523
12 0.9824041 5256.286
13 0.9139366 5279.863
14 1.0712399 5275.326
15 1.1097967 5269.570
16 1.0449168 5210.164
17 0.8880382 5284.542
18 0.9304634 5330.084
19 1.1660059 5303.685
20 0.7662319 5283.069 | [
{
"code": null,
"e": 1386,
"s": 1062,
"text": "Subsetting of a data frame can be done in many ways and one such say is selecting the columns that are stored in a vector. Suppose we have a data frame df that has columns x, y, and z and the column names y and z are stored in a vector called V then we can subset df by excluding column names in V as select(df,-all_of(V))."
},
{
"code": null,
"e": 1417,
"s": 1386,
"text": "Consider the below data frame:"
},
{
"code": null,
"e": 1427,
"s": 1417,
"text": "Live Demo"
},
{
"code": null,
"e": 1536,
"s": 1427,
"text": "> x1<-rpois(20,5)\n> x2<-rpois(20,2)\n> x3<-rpois(20,3)\n> x4<-rpois(20,5)\n> df1<-data.frame(x1,x2,x3,x4)\n> df1"
},
{
"code": null,
"e": 1759,
"s": 1536,
"text": "x1 x2 x3 x4\n1 3 4 0 5\n2 4 1 2 6\n3 4 1 2 3\n4 8 1 7 6\n5 4 2 3 8\n6 4 4 1 0\n7 4 1 1 2\n8 7 2 4 4\n9 4 3 6 5\n10 4 3 5 7\n11 3 2 3 5\n12 4 2 3 5\n13 3 1 2 5\n14 4 2 5 7\n15 4 3 7 2\n16 2 1 3 6\n17 5 1 8 3\n18 4 0 4 6\n19 5 2 4 9\n20 9 0 4 7"
},
{
"code": null,
"e": 1796,
"s": 1759,
"text": "Vector containing columns x1 and x4:"
},
{
"code": null,
"e": 1815,
"s": 1796,
"text": "> v1<-c(\"x1\",\"x4\")"
},
{
"code": null,
"e": 1854,
"s": 1815,
"text": "Subsetting df1 by excluding x1 and x4:"
},
{
"code": null,
"e": 1880,
"s": 1854,
"text": "> select(df1,-all_of(v1))"
},
{
"code": null,
"e": 2018,
"s": 1880,
"text": " x2 x3\n1 4 0\n2 1 2\n3 1 2\n4 1 7\n5 2 3\n6 4 1\n7 1 1\n8 2 4\n9 3 6\n10 3 5\n11 2 3\n12 2 3\n13 1 2\n14 2 5\n15 3 7\n16 1 3\n17 1 8\n18 0 4\n19 2 4\n20 0 4"
},
{
"code": null,
"e": 2056,
"s": 2018,
"text": "Let’s have a look at another example:"
},
{
"code": null,
"e": 2066,
"s": 2056,
"text": "Live Demo"
},
{
"code": null,
"e": 2199,
"s": 2066,
"text": "> y1<-rnorm(20,1,0.098)\n> y2<-rnorm(20,100,10)\n> y3<-rnorm(20,5,0.97)\n> y4<-rnorm(20,5275,30.5)\n> df2<-data.frame(y1,y2,y3,y4)\n> df2"
},
{
"code": null,
"e": 3034,
"s": 2199,
"text": " y1 y2 y3 y4\n1 1.0004066 95.44217 4.436526 5302.802\n2 0.8704272 103.72030 4.459705 5279.560\n3 1.0010894 96.78478 4.979246 5250.222\n4 1.0856458 100.94359 5.480827 5261.604\n5 0.9609981 98.62898 4.427267 5230.762\n6 0.9497958 90.31327 4.332123 5204.725\n7 0.9598390 95.87049 4.557982 5273.675\n8 0.7686893 95.67384 5.747136 5232.587\n9 0.8447364 97.65526 5.012912 5282.668\n10 1.1740212 105.39359 4.088489 5300.367\n11 0.9476001 115.77728 5.490385 5315.523\n12 0.9824041 89.73841 4.703173 5256.286\n13 0.9139366 112.73522 5.676117 5279.863\n14 1.0712399 83.89056 4.510641 5275.326\n15 1.1097967 91.60747 4.391030 5269.570\n16 1.0449168 90.27042 3.793536 5210.164\n17 0.8880382 74.78750 5.876453 5284.542\n18 0.9304634 112.05254 5.410632 5330.084\n19 1.1660059 108.03871 5.982188 5303.685\n20 0.7662319 104.80364 5.518754 5283.069"
},
{
"code": null,
"e": 3053,
"s": 3034,
"text": "> v2<-c(\"y2\",\"y3\")"
},
{
"code": null,
"e": 3092,
"s": 3053,
"text": "Subsetting df2 by excluding y2 and y3:"
},
{
"code": null,
"e": 3118,
"s": 3092,
"text": "> select(df2,-all_of(v2))"
},
{
"code": null,
"e": 3567,
"s": 3118,
"text": " y1 y4\n1 1.0004066 5302.802\n2 0.8704272 5279.560\n3 1.0010894 5250.222\n4 1.0856458 5261.604\n5 0.9609981 5230.762\n6 0.9497958 5204.725\n7 0.9598390 5273.675\n8 0.7686893 5232.587\n9 0.8447364 5282.668\n10 1.1740212 5300.367\n11 0.9476001 5315.523\n12 0.9824041 5256.286\n13 0.9139366 5279.863\n14 1.0712399 5275.326\n15 1.1097967 5269.570\n16 1.0449168 5210.164\n17 0.8880382 5284.542\n18 0.9304634 5330.084\n19 1.1660059 5303.685\n20 0.7662319 5283.069"
}
] |
KeyPairGenerator generateKeyPair() method in Java | A key pair can be generated using the generateKeyPair() method in the class java.security.KeyPairGenerator. This method requires no parameters and it returns the key pair that is generated. Every time the generateKeyPair() method is called, it generates a new key pair.
A program that demonstrates this is given as follows −
Live Demo
import java.security.*;
import java.util.*;
public class Demo {
public static void main(String[] argv) throws Exception {
try {
KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance("RSA");
KeyPair keyPair = kpGenerator.generateKeyPair();
System.out.println(keyPair);
} catch (NoSuchAlgorithmException e) {
System.out.println("Error!!! NoSuchAlgorithmException");
}
}
}
java.security.KeyPair@12a3a380
Now let us understand the above program.
A key pair is generated using the generateKeyPair() method and then this key pair is displayed. If the algorithm is wrong, then the exception of NoSuchAlgorithmException is thrown. A code snippet that demonstrates is given as follows −
try {
KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance("RSA");
KeyPair keyPair = kpGenerator.generateKeyPair();
System.out.println(keyPair);
} catch (NoSuchAlgorithmException e) {
System.out.println("Error!!! NoSuchAlgorithmException");
} | [
{
"code": null,
"e": 1332,
"s": 1062,
"text": "A key pair can be generated using the generateKeyPair() method in the class java.security.KeyPairGenerator. This method requires no parameters and it returns the key pair that is generated. Every time the generateKeyPair() method is called, it generates a new key pair."
},
{
"code": null,
"e": 1387,
"s": 1332,
"text": "A program that demonstrates this is given as follows −"
},
{
"code": null,
"e": 1398,
"s": 1387,
"text": " Live Demo"
},
{
"code": null,
"e": 1834,
"s": 1398,
"text": "import java.security.*;\nimport java.util.*;\npublic class Demo {\n public static void main(String[] argv) throws Exception {\n try {\n KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance(\"RSA\");\n KeyPair keyPair = kpGenerator.generateKeyPair();\n System.out.println(keyPair);\n } catch (NoSuchAlgorithmException e) {\n System.out.println(\"Error!!! NoSuchAlgorithmException\");\n }\n }\n}"
},
{
"code": null,
"e": 1865,
"s": 1834,
"text": "java.security.KeyPair@12a3a380"
},
{
"code": null,
"e": 1906,
"s": 1865,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 2142,
"s": 1906,
"text": "A key pair is generated using the generateKeyPair() method and then this key pair is displayed. If the algorithm is wrong, then the exception of NoSuchAlgorithmException is thrown. A code snippet that demonstrates is given as follows −"
},
{
"code": null,
"e": 2404,
"s": 2142,
"text": "try {\n KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance(\"RSA\");\n KeyPair keyPair = kpGenerator.generateKeyPair();\n System.out.println(keyPair);\n} catch (NoSuchAlgorithmException e) {\n System.out.println(\"Error!!! NoSuchAlgorithmException\");\n}"
}
] |
Minimize operations to transform A to B by multiplying by 2 or appending 1 to it - GeeksforGeeks | 17 Dec, 2021
Given two numbers A and B, the task is to find the minimum number of the following operations to transform A to B:
Multiply the current number by 2 (i.e. replace the number X by 2X)Append the digit 1 to the right of the current number (i.e. replace the number X by 10X + 1).
Multiply the current number by 2 (i.e. replace the number X by 2X)
Append the digit 1 to the right of the current number (i.e. replace the number X by 10X + 1).
Print -1 if it is not possible to transform A to B.
Examples:
Input: A = 2, B = 162Output: 4Explanation: Operation 1: Change A to 2*A, so A=2*2=4Operation 2: Change A to 2*A, so A=2*4=8.Operation 3: Change A to 10*A+1, so A=10*8+1=81Operation 4: Change A to 2*A, so A=2*81=162
Input: A = 4, B = 42Output: -1
Approach: This problem can be solved by recursively generating all possible solutions and then choosing the minimum out of those. Now, to solve this problem, follow the below steps:
Create a recursive function minOperation which will accept three parameters that are current number (cur), target number (B) and a map (dp) to memoise the returned result. This function will return the number of minimum operations required to transform the current number to the target number.Initially pass A as cur, B and a empty map dp in minOperations.Now in each recursive call:Check if cur is greater than B, if it is then return INT_MAX as it is not possible to transform the current number to B.Check if cur is equal to B, if it is then return 0.Also check if the result of this function call is already stored in map dp. If it is, then return it from there.Otherwise, call this function again for (cur* 2) and (cur*10+1) and return the minimum result out of these two after memoising.Now, if the initial call returns INT_MAX, then print -1 as it is not possible to transform A to B. Otherwise the answer is the integer returned from this function call.
Create a recursive function minOperation which will accept three parameters that are current number (cur), target number (B) and a map (dp) to memoise the returned result. This function will return the number of minimum operations required to transform the current number to the target number.
Initially pass A as cur, B and a empty map dp in minOperations.
Now in each recursive call:Check if cur is greater than B, if it is then return INT_MAX as it is not possible to transform the current number to B.Check if cur is equal to B, if it is then return 0.Also check if the result of this function call is already stored in map dp. If it is, then return it from there.Otherwise, call this function again for (cur* 2) and (cur*10+1) and return the minimum result out of these two after memoising.
Check if cur is greater than B, if it is then return INT_MAX as it is not possible to transform the current number to B.Check if cur is equal to B, if it is then return 0.Also check if the result of this function call is already stored in map dp. If it is, then return it from there.Otherwise, call this function again for (cur* 2) and (cur*10+1) and return the minimum result out of these two after memoising.
Check if cur is greater than B, if it is then return INT_MAX as it is not possible to transform the current number to B.
Check if cur is equal to B, if it is then return 0.
Also check if the result of this function call is already stored in map dp. If it is, then return it from there.
Otherwise, call this function again for (cur* 2) and (cur*10+1) and return the minimum result out of these two after memoising.
Now, if the initial call returns INT_MAX, then print -1 as it is not possible to transform A to B. Otherwise the answer is the integer returned from this function call.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ code for the above approach #include <bits/stdc++.h>using namespace std; // Function to find// the minimum number of operations// needed to transform A to Bint minOperations(int cur, int B, unordered_map<int, int>& dp){ // If current number // is greater than target if (cur > B) { return INT_MAX; } // if current number // is equal to the target if (cur == B) { return 0; } // If the number of minimum // operations required to // change the current number // to the target number // is already memoised if (dp.count(cur)) { return dp[cur]; } // Minimum number of operations // required if the current element // gets multiplied by 2 int ans1 = minOperations(cur * 2, B, dp); // Minimum number of operations // required if the 1 is appended to // the right of the current element int ans2 = minOperations(cur * 10 + 1, B, dp); // If it is not possible // to reach the target value // from the current element if (min(ans1, ans2) == INT_MAX) { return dp[cur] = INT_MAX; } // Returning the minimum // number of operations return dp[cur] = min(ans1, ans2) + 1;} // Driver Codeint main(){ int A = 2, B = 162; unordered_map<int, int> dp; int ans = minOperations(A, B, dp); // If A cannot be transformed to B if (ans == INT_MAX) { cout << -1; } else { cout << ans; }}
// Java code for the above approachimport java.util.HashMap;class GFG { // Function to find // the minimum number of operations // needed to transform A to B static int minOperations(int cur, int B, HashMap<Integer, Integer> dp) { // If current number // is greater than target if (cur > B) { return Integer.MAX_VALUE; } // if current number // is equal to the target if (cur == B) { return 0; } // If the number of minimum // operations required to // change the current number // to the target number // is already memoised if (dp.containsKey(cur)) { return dp.get(cur); } // Minimum number of operations // required if the current element // gets multiplied by 2 int ans1 = minOperations(cur * 2, B, dp); // Minimum number of operations // required if the 1 is appended to // the right of the current element int ans2 = minOperations(cur * 10 + 1, B, dp); // If it is not possible // to reach the target value // from the current element if (Math.min(ans1, ans2) == Integer.MAX_VALUE) { dp.put(cur, Integer.MAX_VALUE); return dp.get(cur); } // Returning the minimum // number of operations dp.put(cur, Math.min(ans1, ans2) + 1); return dp.get(cur); } // Driver Code public static void main(String args[]) { int A = 2, B = 162; HashMap<Integer, Integer> dp = new HashMap<Integer, Integer>(); int ans = minOperations(A, B, dp); // If A cannot be transformed to B if (ans == Integer.MAX_VALUE) { System.out.println(-1); } else { System.out.println(ans); } }} // This code is contributed by gfgking.
# Python 3 code for the above approachimport sys# Function to find# the minimum number of operations# needed to transform A to B def minOperations(cur, B, dp): # If current number # is greater than target if (cur > B): return sys.maxsize # if current number # is equal to the target if (cur == B): return 0 # If the number of minimum # operations required to # change the current number # to the target number # is already memoised if (cur in dp): return dp[cur] # Minimum number of operations # required if the current element # gets multiplied by 2 ans1 = minOperations(cur * 2, B, dp) # Minimum number of operations # required if the 1 is appended to # the right of the current element ans2 = minOperations(cur * 10 + 1, B, dp) # If it is not possible # to reach the target value # from the current element if (min(ans1, ans2) == sys.maxsize): dp[cur] = sys.maxsize return dp[cur] # Returning the minimum # number of operations dp[cur] = min(ans1, ans2) + 1 return dp[cur] # Driver Codeif __name__ == "__main__": A = 2 B = 162 dp = {} ans = minOperations(A, B, dp) # If A cannot be transformed to B if (ans == sys.maxsize): print(-1) else: print(ans) # This code is contributed by ukasp.
// C# code for the above approachusing System;using System.Collections.Generic;class GFG { // Function to find // the minimum number of operations // needed to transform A to B static int minOperations(int cur, int B, Dictionary<int, int> dp) { // If current number // is greater than target if (cur > B) { return Int32.MaxValue; } // if current number // is equal to the target if (cur == B) { return 0; } // If the number of minimum // operations required to // change the current number // to the target number // is already memoised if (dp.ContainsKey(cur)) { return dp[cur]; } // Minimum number of operations // required if the current element // gets multiplied by 2 int ans1 = minOperations(cur * 2, B, dp); // Minimum number of operations // required if the 1 is appended to // the right of the current element int ans2 = minOperations(cur * 10 + 1, B, dp); // If it is not possible // to reach the target value // from the current element if (Math.Min(ans1, ans2) == Int32.MaxValue) { dp[cur] = Int32.MaxValue; return dp[cur]; } // Returning the minimum // number of operations dp[cur] = Math.Min(ans1, ans2) + 1; return dp[cur]; } // Driver Code public static void Main(string[] args) { int A = 2, B = 162; Dictionary<int, int> dp = new Dictionary<int, int>(); int ans = minOperations(A, B, dp); // If A cannot be transformed to B if (ans == Int32.MaxValue) { Console.WriteLine(-1); } else { Console.WriteLine(ans); } }} // This code is contributed by gaurav01.
<script> // JavaScript code for the above approach // Function to find // the minimum number of operations // needed to transform A to B function minOperations(cur, B, dp) { // If current number // is greater than target if (cur > B) { return Number.MAX_VALUE; } // if current number // is equal to the target if (cur == B) { return 0; } // If the number of minimum // operations required to // change the current number // to the target number // is already memoised if (dp[cur] != 0) { return dp[cur]; } // Minimum number of operations // required if the current element // gets multiplied by 2 let ans1 = minOperations(cur * 2, B, dp); // Minimum number of operations // required if the 1 is appended to // the right of the current element let ans2 = minOperations(cur * 10 + 1, B, dp); // If it is not possible // to reach the target value // from the current element if (Math.min(ans1, ans2) == Number.MAX_VALUE) { return dp[cur] = Number.MAX_VALUE; } // Returning the minimum // number of operations return dp[cur] = Math.min(ans1, ans2) + 1; } // Driver Code let A = 2, B = 162; let dp = new Array(100000).fill(0); let ans = minOperations(A, B, dp); // If A cannot be transformed to B if (ans == Number.MAX_VALUE) { document.write(-1); } else { document.write(ans); } // This code is contributed by Potta Lokesh </script>
4
Time Complexity: O(log2 B*log10 B) Auxiliary Space: O(max(log2 B, log10 B))
lokeshpotta20
ukasp
gfgking
gaurav01
Game Theory
Mathematical
Recursion
Mathematical
Recursion
Game Theory
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Find winner when players remove multiples of A or B from Array in each turn
Find the player who will win by choosing a number in range [1, K] with sum total N
Minimum number of moves to make M and N equal by repeatedly adding any divisor of number to itself except 1 and the number
Classification of Algorithms with Examples
Find the player who will win the Coin game
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 24869,
"s": 24841,
"text": "\n17 Dec, 2021"
},
{
"code": null,
"e": 24984,
"s": 24869,
"text": "Given two numbers A and B, the task is to find the minimum number of the following operations to transform A to B:"
},
{
"code": null,
"e": 25144,
"s": 24984,
"text": "Multiply the current number by 2 (i.e. replace the number X by 2X)Append the digit 1 to the right of the current number (i.e. replace the number X by 10X + 1)."
},
{
"code": null,
"e": 25211,
"s": 25144,
"text": "Multiply the current number by 2 (i.e. replace the number X by 2X)"
},
{
"code": null,
"e": 25305,
"s": 25211,
"text": "Append the digit 1 to the right of the current number (i.e. replace the number X by 10X + 1)."
},
{
"code": null,
"e": 25357,
"s": 25305,
"text": "Print -1 if it is not possible to transform A to B."
},
{
"code": null,
"e": 25367,
"s": 25357,
"text": "Examples:"
},
{
"code": null,
"e": 25582,
"s": 25367,
"text": "Input: A = 2, B = 162Output: 4Explanation: Operation 1: Change A to 2*A, so A=2*2=4Operation 2: Change A to 2*A, so A=2*4=8.Operation 3: Change A to 10*A+1, so A=10*8+1=81Operation 4: Change A to 2*A, so A=2*81=162"
},
{
"code": null,
"e": 25613,
"s": 25582,
"text": "Input: A = 4, B = 42Output: -1"
},
{
"code": null,
"e": 25795,
"s": 25613,
"text": "Approach: This problem can be solved by recursively generating all possible solutions and then choosing the minimum out of those. Now, to solve this problem, follow the below steps:"
},
{
"code": null,
"e": 26757,
"s": 25795,
"text": "Create a recursive function minOperation which will accept three parameters that are current number (cur), target number (B) and a map (dp) to memoise the returned result. This function will return the number of minimum operations required to transform the current number to the target number.Initially pass A as cur, B and a empty map dp in minOperations.Now in each recursive call:Check if cur is greater than B, if it is then return INT_MAX as it is not possible to transform the current number to B.Check if cur is equal to B, if it is then return 0.Also check if the result of this function call is already stored in map dp. If it is, then return it from there.Otherwise, call this function again for (cur* 2) and (cur*10+1) and return the minimum result out of these two after memoising.Now, if the initial call returns INT_MAX, then print -1 as it is not possible to transform A to B. Otherwise the answer is the integer returned from this function call."
},
{
"code": null,
"e": 27051,
"s": 26757,
"text": "Create a recursive function minOperation which will accept three parameters that are current number (cur), target number (B) and a map (dp) to memoise the returned result. This function will return the number of minimum operations required to transform the current number to the target number."
},
{
"code": null,
"e": 27115,
"s": 27051,
"text": "Initially pass A as cur, B and a empty map dp in minOperations."
},
{
"code": null,
"e": 27553,
"s": 27115,
"text": "Now in each recursive call:Check if cur is greater than B, if it is then return INT_MAX as it is not possible to transform the current number to B.Check if cur is equal to B, if it is then return 0.Also check if the result of this function call is already stored in map dp. If it is, then return it from there.Otherwise, call this function again for (cur* 2) and (cur*10+1) and return the minimum result out of these two after memoising."
},
{
"code": null,
"e": 27964,
"s": 27553,
"text": "Check if cur is greater than B, if it is then return INT_MAX as it is not possible to transform the current number to B.Check if cur is equal to B, if it is then return 0.Also check if the result of this function call is already stored in map dp. If it is, then return it from there.Otherwise, call this function again for (cur* 2) and (cur*10+1) and return the minimum result out of these two after memoising."
},
{
"code": null,
"e": 28085,
"s": 27964,
"text": "Check if cur is greater than B, if it is then return INT_MAX as it is not possible to transform the current number to B."
},
{
"code": null,
"e": 28137,
"s": 28085,
"text": "Check if cur is equal to B, if it is then return 0."
},
{
"code": null,
"e": 28250,
"s": 28137,
"text": "Also check if the result of this function call is already stored in map dp. If it is, then return it from there."
},
{
"code": null,
"e": 28378,
"s": 28250,
"text": "Otherwise, call this function again for (cur* 2) and (cur*10+1) and return the minimum result out of these two after memoising."
},
{
"code": null,
"e": 28547,
"s": 28378,
"text": "Now, if the initial call returns INT_MAX, then print -1 as it is not possible to transform A to B. Otherwise the answer is the integer returned from this function call."
},
{
"code": null,
"e": 28598,
"s": 28547,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28602,
"s": 28598,
"text": "C++"
},
{
"code": null,
"e": 28607,
"s": 28602,
"text": "Java"
},
{
"code": null,
"e": 28615,
"s": 28607,
"text": "Python3"
},
{
"code": null,
"e": 28618,
"s": 28615,
"text": "C#"
},
{
"code": null,
"e": 28629,
"s": 28618,
"text": "Javascript"
},
{
"code": "// C++ code for the above approach #include <bits/stdc++.h>using namespace std; // Function to find// the minimum number of operations// needed to transform A to Bint minOperations(int cur, int B, unordered_map<int, int>& dp){ // If current number // is greater than target if (cur > B) { return INT_MAX; } // if current number // is equal to the target if (cur == B) { return 0; } // If the number of minimum // operations required to // change the current number // to the target number // is already memoised if (dp.count(cur)) { return dp[cur]; } // Minimum number of operations // required if the current element // gets multiplied by 2 int ans1 = minOperations(cur * 2, B, dp); // Minimum number of operations // required if the 1 is appended to // the right of the current element int ans2 = minOperations(cur * 10 + 1, B, dp); // If it is not possible // to reach the target value // from the current element if (min(ans1, ans2) == INT_MAX) { return dp[cur] = INT_MAX; } // Returning the minimum // number of operations return dp[cur] = min(ans1, ans2) + 1;} // Driver Codeint main(){ int A = 2, B = 162; unordered_map<int, int> dp; int ans = minOperations(A, B, dp); // If A cannot be transformed to B if (ans == INT_MAX) { cout << -1; } else { cout << ans; }}",
"e": 30084,
"s": 28629,
"text": null
},
{
"code": "// Java code for the above approachimport java.util.HashMap;class GFG { // Function to find // the minimum number of operations // needed to transform A to B static int minOperations(int cur, int B, HashMap<Integer, Integer> dp) { // If current number // is greater than target if (cur > B) { return Integer.MAX_VALUE; } // if current number // is equal to the target if (cur == B) { return 0; } // If the number of minimum // operations required to // change the current number // to the target number // is already memoised if (dp.containsKey(cur)) { return dp.get(cur); } // Minimum number of operations // required if the current element // gets multiplied by 2 int ans1 = minOperations(cur * 2, B, dp); // Minimum number of operations // required if the 1 is appended to // the right of the current element int ans2 = minOperations(cur * 10 + 1, B, dp); // If it is not possible // to reach the target value // from the current element if (Math.min(ans1, ans2) == Integer.MAX_VALUE) { dp.put(cur, Integer.MAX_VALUE); return dp.get(cur); } // Returning the minimum // number of operations dp.put(cur, Math.min(ans1, ans2) + 1); return dp.get(cur); } // Driver Code public static void main(String args[]) { int A = 2, B = 162; HashMap<Integer, Integer> dp = new HashMap<Integer, Integer>(); int ans = minOperations(A, B, dp); // If A cannot be transformed to B if (ans == Integer.MAX_VALUE) { System.out.println(-1); } else { System.out.println(ans); } }} // This code is contributed by gfgking.",
"e": 31758,
"s": 30084,
"text": null
},
{
"code": "# Python 3 code for the above approachimport sys# Function to find# the minimum number of operations# needed to transform A to B def minOperations(cur, B, dp): # If current number # is greater than target if (cur > B): return sys.maxsize # if current number # is equal to the target if (cur == B): return 0 # If the number of minimum # operations required to # change the current number # to the target number # is already memoised if (cur in dp): return dp[cur] # Minimum number of operations # required if the current element # gets multiplied by 2 ans1 = minOperations(cur * 2, B, dp) # Minimum number of operations # required if the 1 is appended to # the right of the current element ans2 = minOperations(cur * 10 + 1, B, dp) # If it is not possible # to reach the target value # from the current element if (min(ans1, ans2) == sys.maxsize): dp[cur] = sys.maxsize return dp[cur] # Returning the minimum # number of operations dp[cur] = min(ans1, ans2) + 1 return dp[cur] # Driver Codeif __name__ == \"__main__\": A = 2 B = 162 dp = {} ans = minOperations(A, B, dp) # If A cannot be transformed to B if (ans == sys.maxsize): print(-1) else: print(ans) # This code is contributed by ukasp.",
"e": 33139,
"s": 31758,
"text": null
},
{
"code": "// C# code for the above approachusing System;using System.Collections.Generic;class GFG { // Function to find // the minimum number of operations // needed to transform A to B static int minOperations(int cur, int B, Dictionary<int, int> dp) { // If current number // is greater than target if (cur > B) { return Int32.MaxValue; } // if current number // is equal to the target if (cur == B) { return 0; } // If the number of minimum // operations required to // change the current number // to the target number // is already memoised if (dp.ContainsKey(cur)) { return dp[cur]; } // Minimum number of operations // required if the current element // gets multiplied by 2 int ans1 = minOperations(cur * 2, B, dp); // Minimum number of operations // required if the 1 is appended to // the right of the current element int ans2 = minOperations(cur * 10 + 1, B, dp); // If it is not possible // to reach the target value // from the current element if (Math.Min(ans1, ans2) == Int32.MaxValue) { dp[cur] = Int32.MaxValue; return dp[cur]; } // Returning the minimum // number of operations dp[cur] = Math.Min(ans1, ans2) + 1; return dp[cur]; } // Driver Code public static void Main(string[] args) { int A = 2, B = 162; Dictionary<int, int> dp = new Dictionary<int, int>(); int ans = minOperations(A, B, dp); // If A cannot be transformed to B if (ans == Int32.MaxValue) { Console.WriteLine(-1); } else { Console.WriteLine(ans); } }} // This code is contributed by gaurav01.",
"e": 35048,
"s": 33139,
"text": null
},
{
"code": "<script> // JavaScript code for the above approach // Function to find // the minimum number of operations // needed to transform A to B function minOperations(cur, B, dp) { // If current number // is greater than target if (cur > B) { return Number.MAX_VALUE; } // if current number // is equal to the target if (cur == B) { return 0; } // If the number of minimum // operations required to // change the current number // to the target number // is already memoised if (dp[cur] != 0) { return dp[cur]; } // Minimum number of operations // required if the current element // gets multiplied by 2 let ans1 = minOperations(cur * 2, B, dp); // Minimum number of operations // required if the 1 is appended to // the right of the current element let ans2 = minOperations(cur * 10 + 1, B, dp); // If it is not possible // to reach the target value // from the current element if (Math.min(ans1, ans2) == Number.MAX_VALUE) { return dp[cur] = Number.MAX_VALUE; } // Returning the minimum // number of operations return dp[cur] = Math.min(ans1, ans2) + 1; } // Driver Code let A = 2, B = 162; let dp = new Array(100000).fill(0); let ans = minOperations(A, B, dp); // If A cannot be transformed to B if (ans == Number.MAX_VALUE) { document.write(-1); } else { document.write(ans); } // This code is contributed by Potta Lokesh </script>",
"e": 36822,
"s": 35048,
"text": null
},
{
"code": null,
"e": 36824,
"s": 36822,
"text": "4"
},
{
"code": null,
"e": 36902,
"s": 36824,
"text": " Time Complexity: O(log2 B*log10 B) Auxiliary Space: O(max(log2 B, log10 B))"
},
{
"code": null,
"e": 36918,
"s": 36904,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 36924,
"s": 36918,
"text": "ukasp"
},
{
"code": null,
"e": 36932,
"s": 36924,
"text": "gfgking"
},
{
"code": null,
"e": 36941,
"s": 36932,
"text": "gaurav01"
},
{
"code": null,
"e": 36953,
"s": 36941,
"text": "Game Theory"
},
{
"code": null,
"e": 36966,
"s": 36953,
"text": "Mathematical"
},
{
"code": null,
"e": 36976,
"s": 36966,
"text": "Recursion"
},
{
"code": null,
"e": 36989,
"s": 36976,
"text": "Mathematical"
},
{
"code": null,
"e": 36999,
"s": 36989,
"text": "Recursion"
},
{
"code": null,
"e": 37011,
"s": 36999,
"text": "Game Theory"
},
{
"code": null,
"e": 37109,
"s": 37011,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37118,
"s": 37109,
"text": "Comments"
},
{
"code": null,
"e": 37131,
"s": 37118,
"text": "Old Comments"
},
{
"code": null,
"e": 37207,
"s": 37131,
"text": "Find winner when players remove multiples of A or B from Array in each turn"
},
{
"code": null,
"e": 37290,
"s": 37207,
"text": "Find the player who will win by choosing a number in range [1, K] with sum total N"
},
{
"code": null,
"e": 37413,
"s": 37290,
"text": "Minimum number of moves to make M and N equal by repeatedly adding any divisor of number to itself except 1 and the number"
},
{
"code": null,
"e": 37456,
"s": 37413,
"text": "Classification of Algorithms with Examples"
},
{
"code": null,
"e": 37499,
"s": 37456,
"text": "Find the player who will win the Coin game"
},
{
"code": null,
"e": 37529,
"s": 37499,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 37544,
"s": 37529,
"text": "C++ Data Types"
},
{
"code": null,
"e": 37604,
"s": 37544,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 37647,
"s": 37604,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Maximum and Minimum element of a linked list which is divisible by a given number k in C++ | A linked list is a linear data structure in which elements are linked via pointers. Each element or node of a linked list has a data part and link, or we can say pointer to the next element in sequence. The elements can take noncontiguous locations in memory.
We are given a singly linked list in which there is a data part and link to the next element. The other input is a number K. Task is to find the Maximum and Minimum element of a linked list which is divisible by the number K. The linear linked list can only be traversed in one direction. At each node we will check the divisibility of it’s data part with K. If that number is maximum or minimum found so far then we will update the values of MaxD and MinD.
Input
SList : 5-->2-->10-->12-->3-->20-->7, K=5
Output
Maximum element which is divisible by K : 20
Maximum element which is divisible by K : 5
Explanation − Traversing from the Head node, keep on dividing the data part with K and check if its completely divisible, that is remainder comes 0.
Only 5, 10 and 20 are divisible by 5 out of which 5 is minimum and 20 is maximum.
Input
SList : 12-->2-->5-->18-->3-->144-->7, K=4
Output
Maximum element which is divisible by K : 144
Maximum element which is divisible by K : 12
Explanation − Traversing from the Head node, keep on dividing the data part with K and check if its completely divisible, that is remainder comes 0.
Only 12, and 144 are divisible by 4 out of which 12 is minimum and 144 is maximum.
Create a linked list node. Here we have created a class SLLnode, which has info part and next pointer.
Create a linked list node. Here we have created a class SLLnode, which has info part and next pointer.
Create a linked list. Here we have created a class SLList with SLLnode object as it’s member. So SLList consists of SLLnodes.
Create a linked list. Here we have created a class SLList with SLLnode object as it’s member. So SLList consists of SLLnodes.
The function addtohead(int) is adding nodes to this list.
The function addtohead(int) is adding nodes to this list.
To add elements to SLList we are calling addtohead(int) using SLList object named LIST.
To add elements to SLList we are calling addtohead(int) using SLList object named LIST.
Once the SLList is created we call the function Divisible(SLLnode,int) which takes two input parameters head of list and integer K.
Once the SLList is created we call the function Divisible(SLLnode,int) which takes two input parameters head of list and integer K.
Now inside Divisible we take two variables maxD and minD to store Maximum and Minimum element of a linked list which is divisible by a given number K.
Now inside Divisible we take two variables maxD and minD to store Maximum and Minimum element of a linked list which is divisible by a given number K.
maxD is initialized with -1 and minD is initialized 9999. This is supposed as range in which input lies.
maxD is initialized with -1 and minD is initialized 9999. This is supposed as range in which input lies.
Inside for loop we traverse the linked list starting from head. For this variable start is pointing to head.
Inside for loop we traverse the linked list starting from head. For this variable start is pointing to head.
Compare the info part of each node with maxD and minD and it’s divisibility with K. If current node’s info is divisible and less than minD update minD with current info part.
Compare the info part of each node with maxD and minD and it’s divisibility with K. If current node’s info is divisible and less than minD update minD with current info part.
If current node’s info is divisible by K and greater than maxD, update maxD with current info part.
If current node’s info is divisible by K and greater than maxD, update maxD with current info part.
Print the result obtained in minD and maxD.
Print the result obtained in minD and maxD.
#include<iostream.h>
#include<process.h>
#include<conio.h>
class SLLnode{
public:
int info;
SLLnode *next;
SLLnode(int e1,SLLnode *ptr=0){
info=e1;
next=ptr;
}
};
class SLList{
public:
SLLnode *head;
SLList()
{ head=0; }
void addtohead(int); };
void SLList::addtohead(int el)
{ head=new SLLnode(el,head); }
void Divisible(SLLnode* head, int K){
int minD=9999;
int maxD=-1;
SLLnode* start=head;
for(start;start->next!=NULL;start=start->next){
if ((start->info < minD) && (start->info % K == 0))
minD = start->info;
if ((start->info > maxD) && (start->info % K == 0))
maxD = start->info;
}
cout << "Max Element divisible by K: " << maxD << endl;
cout << "Min Element divisible by K: " << minD;
}
// Driver Code
int main(){
clrscr();
// Start with empty list
SLList LIST;
LIST.addtohead(50);
LIST.addtohead(21);
LIST.addtohead(32);
LIST.addtohead(45);
LIST.addtohead(11);
LIST.addtohead(23);
LIST.addtohead(90);
LIST.addtohead(56);
int K = 5;
Divisible(LIST.head, K);
getch();
return 0;
}
If we run the above code it will generate the following output −
Max Element divisible by K: 90
Min Element divisible by K: 45 | [
{
"code": null,
"e": 1322,
"s": 1062,
"text": "A linked list is a linear data structure in which elements are linked via pointers. Each element or node of a linked list has a data part and link, or we can say pointer to the next element in sequence. The elements can take noncontiguous locations in memory."
},
{
"code": null,
"e": 1780,
"s": 1322,
"text": "We are given a singly linked list in which there is a data part and link to the next element. The other input is a number K. Task is to find the Maximum and Minimum element of a linked list which is divisible by the number K. The linear linked list can only be traversed in one direction. At each node we will check the divisibility of it’s data part with K. If that number is maximum or minimum found so far then we will update the values of MaxD and MinD."
},
{
"code": null,
"e": 1787,
"s": 1780,
"text": "Input "
},
{
"code": null,
"e": 1829,
"s": 1787,
"text": "SList : 5-->2-->10-->12-->3-->20-->7, K=5"
},
{
"code": null,
"e": 1837,
"s": 1829,
"text": "Output "
},
{
"code": null,
"e": 1926,
"s": 1837,
"text": "Maximum element which is divisible by K : 20\nMaximum element which is divisible by K : 5"
},
{
"code": null,
"e": 2075,
"s": 1926,
"text": "Explanation − Traversing from the Head node, keep on dividing the data part with K and check if its completely divisible, that is remainder comes 0."
},
{
"code": null,
"e": 2157,
"s": 2075,
"text": "Only 5, 10 and 20 are divisible by 5 out of which 5 is minimum and 20 is maximum."
},
{
"code": null,
"e": 2164,
"s": 2157,
"text": "Input "
},
{
"code": null,
"e": 2207,
"s": 2164,
"text": "SList : 12-->2-->5-->18-->3-->144-->7, K=4"
},
{
"code": null,
"e": 2215,
"s": 2207,
"text": "Output "
},
{
"code": null,
"e": 2306,
"s": 2215,
"text": "Maximum element which is divisible by K : 144\nMaximum element which is divisible by K : 12"
},
{
"code": null,
"e": 2455,
"s": 2306,
"text": "Explanation − Traversing from the Head node, keep on dividing the data part with K and check if its completely divisible, that is remainder comes 0."
},
{
"code": null,
"e": 2538,
"s": 2455,
"text": "Only 12, and 144 are divisible by 4 out of which 12 is minimum and 144 is maximum."
},
{
"code": null,
"e": 2641,
"s": 2538,
"text": "Create a linked list node. Here we have created a class SLLnode, which has info part and next pointer."
},
{
"code": null,
"e": 2744,
"s": 2641,
"text": "Create a linked list node. Here we have created a class SLLnode, which has info part and next pointer."
},
{
"code": null,
"e": 2870,
"s": 2744,
"text": "Create a linked list. Here we have created a class SLList with SLLnode object as it’s member. So SLList consists of SLLnodes."
},
{
"code": null,
"e": 2996,
"s": 2870,
"text": "Create a linked list. Here we have created a class SLList with SLLnode object as it’s member. So SLList consists of SLLnodes."
},
{
"code": null,
"e": 3054,
"s": 2996,
"text": "The function addtohead(int) is adding nodes to this list."
},
{
"code": null,
"e": 3112,
"s": 3054,
"text": "The function addtohead(int) is adding nodes to this list."
},
{
"code": null,
"e": 3200,
"s": 3112,
"text": "To add elements to SLList we are calling addtohead(int) using SLList object named LIST."
},
{
"code": null,
"e": 3288,
"s": 3200,
"text": "To add elements to SLList we are calling addtohead(int) using SLList object named LIST."
},
{
"code": null,
"e": 3420,
"s": 3288,
"text": "Once the SLList is created we call the function Divisible(SLLnode,int) which takes two input parameters head of list and integer K."
},
{
"code": null,
"e": 3552,
"s": 3420,
"text": "Once the SLList is created we call the function Divisible(SLLnode,int) which takes two input parameters head of list and integer K."
},
{
"code": null,
"e": 3703,
"s": 3552,
"text": "Now inside Divisible we take two variables maxD and minD to store Maximum and Minimum element of a linked list which is divisible by a given number K."
},
{
"code": null,
"e": 3854,
"s": 3703,
"text": "Now inside Divisible we take two variables maxD and minD to store Maximum and Minimum element of a linked list which is divisible by a given number K."
},
{
"code": null,
"e": 3959,
"s": 3854,
"text": "maxD is initialized with -1 and minD is initialized 9999. This is supposed as range in which input lies."
},
{
"code": null,
"e": 4064,
"s": 3959,
"text": "maxD is initialized with -1 and minD is initialized 9999. This is supposed as range in which input lies."
},
{
"code": null,
"e": 4173,
"s": 4064,
"text": "Inside for loop we traverse the linked list starting from head. For this variable start is pointing to head."
},
{
"code": null,
"e": 4282,
"s": 4173,
"text": "Inside for loop we traverse the linked list starting from head. For this variable start is pointing to head."
},
{
"code": null,
"e": 4457,
"s": 4282,
"text": "Compare the info part of each node with maxD and minD and it’s divisibility with K. If current node’s info is divisible and less than minD update minD with current info part."
},
{
"code": null,
"e": 4632,
"s": 4457,
"text": "Compare the info part of each node with maxD and minD and it’s divisibility with K. If current node’s info is divisible and less than minD update minD with current info part."
},
{
"code": null,
"e": 4732,
"s": 4632,
"text": "If current node’s info is divisible by K and greater than maxD, update maxD with current info part."
},
{
"code": null,
"e": 4832,
"s": 4732,
"text": "If current node’s info is divisible by K and greater than maxD, update maxD with current info part."
},
{
"code": null,
"e": 4876,
"s": 4832,
"text": "Print the result obtained in minD and maxD."
},
{
"code": null,
"e": 4920,
"s": 4876,
"text": "Print the result obtained in minD and maxD."
},
{
"code": null,
"e": 6086,
"s": 4920,
"text": "#include<iostream.h>\n#include<process.h>\n#include<conio.h>\nclass SLLnode{\n public:\n int info;\n SLLnode *next;\n SLLnode(int e1,SLLnode *ptr=0){\n info=e1;\n next=ptr;\n }\n};\nclass SLList{\n public:\n SLLnode *head;\n SLList()\n { head=0; }\n void addtohead(int); };\n void SLList::addtohead(int el)\n { head=new SLLnode(el,head); }\n void Divisible(SLLnode* head, int K){\n int minD=9999;\n int maxD=-1;\n SLLnode* start=head;\n for(start;start->next!=NULL;start=start->next){\n if ((start->info < minD) && (start->info % K == 0))\n minD = start->info;\n if ((start->info > maxD) && (start->info % K == 0))\n maxD = start->info;\n }\n cout << \"Max Element divisible by K: \" << maxD << endl;\n cout << \"Min Element divisible by K: \" << minD;\n}\n// Driver Code\nint main(){\n clrscr();\n // Start with empty list\n SLList LIST;\n LIST.addtohead(50);\n LIST.addtohead(21);\n LIST.addtohead(32);\n LIST.addtohead(45);\n LIST.addtohead(11);\n LIST.addtohead(23);\n LIST.addtohead(90);\n LIST.addtohead(56);\n int K = 5;\n Divisible(LIST.head, K);\n getch();\n return 0;\n}"
},
{
"code": null,
"e": 6151,
"s": 6086,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 6213,
"s": 6151,
"text": "Max Element divisible by K: 90\nMin Element divisible by K: 45"
}
] |
AWT FlowLayout Class | The class FlowLayout components in a left-to-right flow.
Following is the declaration for java.awt.FlowLayout class:
public class FlowLayout
extends Object
implements LayoutManager, Serializable
Following are the fields for java.awt.BorderLayout class:
static int CENTER -- This value indicates that each row of components should be centered.
static int CENTER -- This value indicates that each row of components should be centered.
static int LEADING -- This value indicates that each row of components should be justified to the leading edge of the container's orientation, for example, to the left in left-to-right orientations.
static int LEADING -- This value indicates that each row of components should be justified to the leading edge of the container's orientation, for example, to the left in left-to-right orientations.
static int LEFT -- This value indicates that each row of components should be left-justified.
static int LEFT -- This value indicates that each row of components should be left-justified.
static int RIGHT -- This value indicates that each row of components should be right-justified.
static int RIGHT -- This value indicates that each row of components should be right-justified.
static int TRAILING -- This value indicates that each row of components should be justified to the trailing edge of the container's orientation, for example, to the right in left-to-right orientations.
static int TRAILING -- This value indicates that each row of components should be justified to the trailing edge of the container's orientation, for example, to the right in left-to-right orientations.
FlowLayout()
Constructs a new FlowLayout with a centered alignment and a default 5-unit horizontal and vertical gap.
FlowLayout(int align)
Constructs a new FlowLayout with the specified alignment and a default 5-unit horizontal and vertical gap.
FlowLayout(int align, int hgap, int vgap)
Creates a new flow layout manager with the indicated alignment and the indicated horizontal and vertical gaps.
void addLayoutComponent(String name, Component comp)
Adds the specified component to the layout.
int getAlignment()
Gets the alignment for this layout.
int getHgap()
Gets the horizontal gap between components.
int getVgap()
Gets the vertical gap between components.
void layoutContainer(Container target)
Lays out the container.
Dimension minimumLayoutSize(Container target)
Returns the minimum dimensions needed to layout the visible components contained in the specified target container.
Dimension preferredLayoutSize(Container target)
Returns the preferred dimensions for this layout given the visible components in the specified target container.
void removeLayoutComponent(Component comp)
Removes the specified component from the layout.
void setAlignment(int align)
Sets the alignment for this layout.
void setHgap(int hgap)
Sets the horizontal gap between components.
void setVgap(int vgap)
Sets the vertical gap between components.
String toString()
Returns a string representation of this FlowLayout object and its values.
This class inherits methods from the following classes:
java.lang.Object
java.lang.Object
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtLayoutDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
private Label msglabel;
public AwtLayoutDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtLayoutDemo awtLayoutDemo = new AwtLayoutDemo();
awtLayoutDemo.showFlowLayoutDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
msglabel = new Label();
msglabel.setAlignment(Label.CENTER);
msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showFlowLayoutDemo(){
headerLabel.setText("Layout in action: FlowLayout");
Panel panel = new Panel();
panel.setBackground(Color.darkGray);
panel.setSize(200,200);
FlowLayout layout = new FlowLayout();
layout.setHgap(10);
layout.setVgap(10);
panel.setLayout(layout);
panel.add(new Button("OK"));
panel.add(new Button("Cancel"));
controlPanel.add(panel);
mainFrame.setVisible(true);
}
}
Compile the program using command prompt. Go to D:/ > AWT and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtlayoutDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtlayoutDemo
Verify the following output
13 Lectures
2 hours
EduOLC
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1804,
"s": 1747,
"text": "The class FlowLayout components in a left-to-right flow."
},
{
"code": null,
"e": 1864,
"s": 1804,
"text": "Following is the declaration for java.awt.FlowLayout class:"
},
{
"code": null,
"e": 1951,
"s": 1864,
"text": "public class FlowLayout\n extends Object\n implements LayoutManager, Serializable"
},
{
"code": null,
"e": 2009,
"s": 1951,
"text": "Following are the fields for java.awt.BorderLayout class:"
},
{
"code": null,
"e": 2100,
"s": 2009,
"text": "static int CENTER -- This value indicates that each row of components should be centered."
},
{
"code": null,
"e": 2191,
"s": 2100,
"text": "static int CENTER -- This value indicates that each row of components should be centered."
},
{
"code": null,
"e": 2391,
"s": 2191,
"text": "static int LEADING -- This value indicates that each row of components should be justified to the leading edge of the container's orientation, for example, to the left in left-to-right orientations."
},
{
"code": null,
"e": 2591,
"s": 2391,
"text": "static int LEADING -- This value indicates that each row of components should be justified to the leading edge of the container's orientation, for example, to the left in left-to-right orientations."
},
{
"code": null,
"e": 2686,
"s": 2591,
"text": "static int LEFT -- This value indicates that each row of components should be left-justified."
},
{
"code": null,
"e": 2781,
"s": 2686,
"text": "static int LEFT -- This value indicates that each row of components should be left-justified."
},
{
"code": null,
"e": 2878,
"s": 2781,
"text": "static int RIGHT -- This value indicates that each row of components should be right-justified."
},
{
"code": null,
"e": 2975,
"s": 2878,
"text": "static int RIGHT -- This value indicates that each row of components should be right-justified."
},
{
"code": null,
"e": 3178,
"s": 2975,
"text": "static int TRAILING -- This value indicates that each row of components should be justified to the trailing edge of the container's orientation, for example, to the right in left-to-right orientations."
},
{
"code": null,
"e": 3381,
"s": 3178,
"text": "static int TRAILING -- This value indicates that each row of components should be justified to the trailing edge of the container's orientation, for example, to the right in left-to-right orientations."
},
{
"code": null,
"e": 3395,
"s": 3381,
"text": "FlowLayout() "
},
{
"code": null,
"e": 3499,
"s": 3395,
"text": "Constructs a new FlowLayout with a centered alignment and a default 5-unit horizontal and vertical gap."
},
{
"code": null,
"e": 3522,
"s": 3499,
"text": "FlowLayout(int align) "
},
{
"code": null,
"e": 3629,
"s": 3522,
"text": "Constructs a new FlowLayout with the specified alignment and a default 5-unit horizontal and vertical gap."
},
{
"code": null,
"e": 3672,
"s": 3629,
"text": "FlowLayout(int align, int hgap, int vgap) "
},
{
"code": null,
"e": 3783,
"s": 3672,
"text": "Creates a new flow layout manager with the indicated alignment and the indicated horizontal and vertical gaps."
},
{
"code": null,
"e": 3836,
"s": 3783,
"text": "void addLayoutComponent(String name, Component comp)"
},
{
"code": null,
"e": 3880,
"s": 3836,
"text": "Adds the specified component to the layout."
},
{
"code": null,
"e": 3899,
"s": 3880,
"text": "int getAlignment()"
},
{
"code": null,
"e": 3935,
"s": 3899,
"text": "Gets the alignment for this layout."
},
{
"code": null,
"e": 3949,
"s": 3935,
"text": "int getHgap()"
},
{
"code": null,
"e": 3993,
"s": 3949,
"text": "Gets the horizontal gap between components."
},
{
"code": null,
"e": 4009,
"s": 3993,
"text": "int getVgap() "
},
{
"code": null,
"e": 4051,
"s": 4009,
"text": "Gets the vertical gap between components."
},
{
"code": null,
"e": 4092,
"s": 4051,
"text": "void layoutContainer(Container target) "
},
{
"code": null,
"e": 4117,
"s": 4092,
"text": " Lays out the container."
},
{
"code": null,
"e": 4165,
"s": 4117,
"text": "Dimension minimumLayoutSize(Container target) "
},
{
"code": null,
"e": 4281,
"s": 4165,
"text": "Returns the minimum dimensions needed to layout the visible components contained in the specified target container."
},
{
"code": null,
"e": 4331,
"s": 4281,
"text": "Dimension preferredLayoutSize(Container target) "
},
{
"code": null,
"e": 4445,
"s": 4331,
"text": " Returns the preferred dimensions for this layout given the visible components in the specified target container."
},
{
"code": null,
"e": 4490,
"s": 4445,
"text": "void removeLayoutComponent(Component comp) "
},
{
"code": null,
"e": 4539,
"s": 4490,
"text": "Removes the specified component from the layout."
},
{
"code": null,
"e": 4570,
"s": 4539,
"text": "void setAlignment(int align) "
},
{
"code": null,
"e": 4606,
"s": 4570,
"text": "Sets the alignment for this layout."
},
{
"code": null,
"e": 4631,
"s": 4606,
"text": "void setHgap(int hgap) "
},
{
"code": null,
"e": 4675,
"s": 4631,
"text": "Sets the horizontal gap between components."
},
{
"code": null,
"e": 4700,
"s": 4675,
"text": "void setVgap(int vgap) "
},
{
"code": null,
"e": 4742,
"s": 4700,
"text": "Sets the vertical gap between components."
},
{
"code": null,
"e": 4762,
"s": 4742,
"text": "String toString() "
},
{
"code": null,
"e": 4836,
"s": 4762,
"text": "Returns a string representation of this FlowLayout object and its values."
},
{
"code": null,
"e": 4892,
"s": 4836,
"text": "This class inherits methods from the following classes:"
},
{
"code": null,
"e": 4909,
"s": 4892,
"text": "java.lang.Object"
},
{
"code": null,
"e": 4926,
"s": 4909,
"text": "java.lang.Object"
},
{
"code": null,
"e": 5040,
"s": 4926,
"text": "Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >"
},
{
"code": null,
"e": 6940,
"s": 5040,
"text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class AwtLayoutDemo {\n private Frame mainFrame;\n private Label headerLabel;\n private Label statusLabel;\n private Panel controlPanel;\n private Label msglabel;\n\n public AwtLayoutDemo(){\n prepareGUI();\n }\n\n public static void main(String[] args){\n AwtLayoutDemo awtLayoutDemo = new AwtLayoutDemo(); \n awtLayoutDemo.showFlowLayoutDemo(); \n }\n \n private void prepareGUI(){\n mainFrame = new Frame(\"Java AWT Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n headerLabel = new Label();\n headerLabel.setAlignment(Label.CENTER);\n statusLabel = new Label(); \n statusLabel.setAlignment(Label.CENTER);\n statusLabel.setSize(350,100);\n\n msglabel = new Label();\n msglabel.setAlignment(Label.CENTER);\n msglabel.setText(\"Welcome to TutorialsPoint AWT Tutorial.\");\n\n controlPanel = new Panel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n\n private void showFlowLayoutDemo(){\n headerLabel.setText(\"Layout in action: FlowLayout\"); \n\n Panel panel = new Panel();\n panel.setBackground(Color.darkGray);\n panel.setSize(200,200);\n FlowLayout layout = new FlowLayout();\n layout.setHgap(10); \n layout.setVgap(10);\n panel.setLayout(layout); \n panel.add(new Button(\"OK\"));\n panel.add(new Button(\"Cancel\")); \n\n controlPanel.add(panel);\n\n mainFrame.setVisible(true); \n }\n}"
},
{
"code": null,
"e": 7031,
"s": 6940,
"text": "Compile the program using command prompt. Go to D:/ > AWT and type the following command."
},
{
"code": null,
"e": 7086,
"s": 7031,
"text": "D:\\AWT>javac com\\tutorialspoint\\gui\\AwtlayoutDemo.java"
},
{
"code": null,
"e": 7183,
"s": 7086,
"text": "If no error comes that means compilation is successful. Run the program using following command."
},
{
"code": null,
"e": 7232,
"s": 7183,
"text": "D:\\AWT>java com.tutorialspoint.gui.AwtlayoutDemo"
},
{
"code": null,
"e": 7260,
"s": 7232,
"text": "Verify the following output"
},
{
"code": null,
"e": 7293,
"s": 7260,
"text": "\n 13 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7301,
"s": 7293,
"text": " EduOLC"
},
{
"code": null,
"e": 7308,
"s": 7301,
"text": " Print"
},
{
"code": null,
"e": 7319,
"s": 7308,
"text": " Add Notes"
}
] |
How to show image in alert box using JavaScript? | To show an image in alert box, try to run the following code. Here, an alert image is added to the custom alert box −
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
function functionAlert(msg, myYes) {
var confirmBox = $("#confirm");
confirmBox.find(".message").text(msg);
confirmBox.find(".yes").unbind().click(function() {
confirmBox.hide();
});
confirmBox.find(".yes").click(myYes);
confirmBox.show();
}
</script>
<style>
#confirm {
display: none;
background-color: #FFFFFF;
border: 1px solid #aaa;
position: fixed;
width: 250px;
left: 50%;
margin-left: -100px;
padding: 6px 8px 8px;
box-sizing: border-box;
text-align: center;
}
#confirm button {
background-color: #48E5DA;
display: inline-block;
border-radius: 5px;
border: 1px solid #aaa;
padding: 5px;
text-align: center;
width: 80px;
cursor: pointer;
}
#confirm .message {
text-align: left;
}
</style>
</head>
<body>
<div id="confirm">
<div class="message">This is a warning message.</div>
<button class="yes">OK</button>
<img src = "https://encrypted-tbn0.gstatic.com/images?q=
tbn:ANd9GcSNjyHBjM74KLxvROpx34zsT4zPzMWHMHz4zzJwAtemXGglsjtA"
width="120" height="70"/>
</div>
<input type="button" value="Click Me" onclick="functionAlert();" />
</body>
</html> | [
{
"code": null,
"e": 1180,
"s": 1062,
"text": "To show an image in alert box, try to run the following code. Here, an alert image is added to the custom alert box −"
},
{
"code": null,
"e": 1190,
"s": 1180,
"text": "Live Demo"
},
{
"code": null,
"e": 2893,
"s": 1190,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\">\n </script>\n <script>\n function functionAlert(msg, myYes) {\n var confirmBox = $(\"#confirm\");\n confirmBox.find(\".message\").text(msg);\n confirmBox.find(\".yes\").unbind().click(function() {\n confirmBox.hide();\n });\n confirmBox.find(\".yes\").click(myYes);\n confirmBox.show();\n }\n </script>\n <style>\n #confirm {\n display: none;\n background-color: #FFFFFF;\n border: 1px solid #aaa;\n position: fixed;\n width: 250px;\n left: 50%;\n margin-left: -100px;\n padding: 6px 8px 8px;\n box-sizing: border-box;\n text-align: center;\n }\n #confirm button {\n background-color: #48E5DA;\n display: inline-block;\n border-radius: 5px;\n border: 1px solid #aaa;\n padding: 5px;\n text-align: center;\n width: 80px;\n cursor: pointer;\n }\n #confirm .message {\n text-align: left;\n }\n </style>\n </head>\n <body>\n <div id=\"confirm\">\n <div class=\"message\">This is a warning message.</div>\n <button class=\"yes\">OK</button>\n <img src = \"https://encrypted-tbn0.gstatic.com/images?q=\n tbn:ANd9GcSNjyHBjM74KLxvROpx34zsT4zPzMWHMHz4zzJwAtemXGglsjtA\"\n width=\"120\" height=\"70\"/>\n </div>\n <input type=\"button\" value=\"Click Me\" onclick=\"functionAlert();\" />\n </body>\n</html>"
}
] |
Importance of the Collatz conjecture - GeeksforGeeks | 23 Dec, 2021
Introduction :The Collatz conjecture is an elusive problem in mathematics regarding the oneness of natural numbers when run through a specific function based on being odd or even, specifically starting that regardless of the initial number the series will eventually reach the number 1. The Collatz Conjecture has been an internationally popular problem in mathematical circles since the early part of the 20th century when the German mathematician Lothar Collatz is credited with the origination of the problem.
Description of “the conjecture” :The conjecture statement states –Take any natural number n. If n is even, divide it by 2 to get n/2, if n is odd multiply it by 3 and add 1 to obtain 3n+1. Repeat the process indefinitely. The conjecture is that no matter what number you start with, you will always eventually reach 1.
So for a natural number n, we can define the following function –
T(n) = n/2 n≡0(mod2) = (3*n) + 1 n≡1(mod2)
Some Study :The function’s progress over successive iteration while n>1 can be easily studied and visualized with the help of a graph. For this, we have this corresponding python code for simulating some runs and creating a plot.
Python3
from matplotlib import pyplot as pltn = int(input())x = []x.append(n)while(n > 1): if(n % 2 == 0): n = n//2 x.append(n) print(n) else: n = (3*n) + 1 x.append(n) print(n)plt.plot(x, '-ok')plt.show()
The above graph is for starting value of 100. You can try out the simulation code with some starting values of your own. As you can see the above graph is quite chaotic. There’s no distinct pattern other than it eventually converging to 1, As the values may become quite large very quickly. 100 takes 25 steps to converge, but others might take even more or less.
Let’s try out some more graphs, by graphing in a semi-log grid where the y-axis is logarithmic, the x-axis remains linear. The python code for the method is :
Python3
from matplotlib import pyplot as pltimport numpy as np y = []n = 100y.append(n)while(n > 1): if (n % 2 == 0): n = n//2 else: n = (3*n) + 1 y.append(n)x = range(0,len(y))plt.plot(x,np.log(y))plt.show()
The graph for the above code is:
Now we can reverse the y-axis in another graphing methodology, to study the growth from 1 and create a plot as follows:
Now to find some “patterns” on how many steps it takes for our input number to converge to 1, let’s change the x-axis of the above graphing method to log scale. The python code for the said is as follows:
Python3
from matplotlib import pyplot as pltimport numpy as np y = []n = 100y.append(n)while(n > 1): if (n % 2 == 0): n = n//2 else: n = (3*n) + 1 y.append(n)x = range(0,len(y))plt.plot(np.log(x),np.log(y[::-1]))plt.show()
The graph for the above code is as shown below, where the y-axis is the collatz value in log and the x-axis is the reversed step order.
Now with the above graphing method we can try and plot a bunch of different such series to study and compare the growth of each series.
kapoorsagar226
tinabarbararyan
Picked
Engineering Mathematics
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Activation Functions
Difference between Propositional Logic and Predicate Logic
Logic Notations in LaTeX
Proof that vertex cover is NP complete
Univariate, Bivariate and Multivariate data and its analysis
Z-test
Brackets in Latex
Betweenness Centrality (Centrality Measure)
Mathematics | Introduction of Set theory
Mathematics | Planar Graphs and Graph Coloring | [
{
"code": null,
"e": 26137,
"s": 26109,
"text": "\n23 Dec, 2021"
},
{
"code": null,
"e": 26650,
"s": 26137,
"text": "Introduction :The Collatz conjecture is an elusive problem in mathematics regarding the oneness of natural numbers when run through a specific function based on being odd or even, specifically starting that regardless of the initial number the series will eventually reach the number 1. The Collatz Conjecture has been an internationally popular problem in mathematical circles since the early part of the 20th century when the German mathematician Lothar Collatz is credited with the origination of the problem."
},
{
"code": null,
"e": 26970,
"s": 26650,
"text": "Description of “the conjecture” :The conjecture statement states –Take any natural number n. If n is even, divide it by 2 to get n/2, if n is odd multiply it by 3 and add 1 to obtain 3n+1. Repeat the process indefinitely. The conjecture is that no matter what number you start with, you will always eventually reach 1. "
},
{
"code": null,
"e": 27036,
"s": 26970,
"text": "So for a natural number n, we can define the following function –"
},
{
"code": null,
"e": 27134,
"s": 27036,
"text": "T(n) = n/2 n≡0(mod2) = (3*n) + 1 n≡1(mod2)"
},
{
"code": null,
"e": 27364,
"s": 27134,
"text": "Some Study :The function’s progress over successive iteration while n>1 can be easily studied and visualized with the help of a graph. For this, we have this corresponding python code for simulating some runs and creating a plot."
},
{
"code": null,
"e": 27372,
"s": 27364,
"text": "Python3"
},
{
"code": "from matplotlib import pyplot as pltn = int(input())x = []x.append(n)while(n > 1): if(n % 2 == 0): n = n//2 x.append(n) print(n) else: n = (3*n) + 1 x.append(n) print(n)plt.plot(x, '-ok')plt.show()",
"e": 27618,
"s": 27372,
"text": null
},
{
"code": null,
"e": 27983,
"s": 27618,
"text": "The above graph is for starting value of 100. You can try out the simulation code with some starting values of your own. As you can see the above graph is quite chaotic. There’s no distinct pattern other than it eventually converging to 1, As the values may become quite large very quickly. 100 takes 25 steps to converge, but others might take even more or less. "
},
{
"code": null,
"e": 28142,
"s": 27983,
"text": "Let’s try out some more graphs, by graphing in a semi-log grid where the y-axis is logarithmic, the x-axis remains linear. The python code for the method is :"
},
{
"code": null,
"e": 28150,
"s": 28142,
"text": "Python3"
},
{
"code": "from matplotlib import pyplot as pltimport numpy as np y = []n = 100y.append(n)while(n > 1): if (n % 2 == 0): n = n//2 else: n = (3*n) + 1 y.append(n)x = range(0,len(y))plt.plot(x,np.log(y))plt.show()",
"e": 28363,
"s": 28150,
"text": null
},
{
"code": null,
"e": 28396,
"s": 28363,
"text": "The graph for the above code is:"
},
{
"code": null,
"e": 28516,
"s": 28396,
"text": "Now we can reverse the y-axis in another graphing methodology, to study the growth from 1 and create a plot as follows:"
},
{
"code": null,
"e": 28721,
"s": 28516,
"text": "Now to find some “patterns” on how many steps it takes for our input number to converge to 1, let’s change the x-axis of the above graphing method to log scale. The python code for the said is as follows:"
},
{
"code": null,
"e": 28729,
"s": 28721,
"text": "Python3"
},
{
"code": "from matplotlib import pyplot as pltimport numpy as np y = []n = 100y.append(n)while(n > 1): if (n % 2 == 0): n = n//2 else: n = (3*n) + 1 y.append(n)x = range(0,len(y))plt.plot(np.log(x),np.log(y[::-1]))plt.show()",
"e": 28956,
"s": 28729,
"text": null
},
{
"code": null,
"e": 29092,
"s": 28956,
"text": "The graph for the above code is as shown below, where the y-axis is the collatz value in log and the x-axis is the reversed step order."
},
{
"code": null,
"e": 29228,
"s": 29092,
"text": "Now with the above graphing method we can try and plot a bunch of different such series to study and compare the growth of each series."
},
{
"code": null,
"e": 29243,
"s": 29228,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 29259,
"s": 29243,
"text": "tinabarbararyan"
},
{
"code": null,
"e": 29266,
"s": 29259,
"text": "Picked"
},
{
"code": null,
"e": 29290,
"s": 29266,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 29388,
"s": 29290,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29409,
"s": 29388,
"text": "Activation Functions"
},
{
"code": null,
"e": 29468,
"s": 29409,
"text": "Difference between Propositional Logic and Predicate Logic"
},
{
"code": null,
"e": 29493,
"s": 29468,
"text": "Logic Notations in LaTeX"
},
{
"code": null,
"e": 29532,
"s": 29493,
"text": "Proof that vertex cover is NP complete"
},
{
"code": null,
"e": 29593,
"s": 29532,
"text": "Univariate, Bivariate and Multivariate data and its analysis"
},
{
"code": null,
"e": 29600,
"s": 29593,
"text": "Z-test"
},
{
"code": null,
"e": 29618,
"s": 29600,
"text": "Brackets in Latex"
},
{
"code": null,
"e": 29662,
"s": 29618,
"text": "Betweenness Centrality (Centrality Measure)"
},
{
"code": null,
"e": 29703,
"s": 29662,
"text": "Mathematics | Introduction of Set theory"
}
] |
How to define colors as variables in CSS ? - GeeksforGeeks | 27 Apr, 2020
In CSS, we can define custom properties (often known as CSS variables), that offers us great flexibility to define a set of rules and avoid rewriting them again and again. We can also use custom properties to define colors.
Example 1:
<!DOCTYPE html><html> <head> <title> How to define colors as variables in CSS? </title> <style> :root { --primary-color: rgb(15, 157, 88); --secondary-color: rgb(255, 255, 255); } .first { width: 50%; padding: 40px 0px; margin: 10px 0px; text-align: center; /* Apply color using CSS var */ background-color: var(--primary-color); color: var(--secondary-color); } .second { width: 50%; padding: 40px 0px; text-align: center; /* Apply color using CSS var */ background-color: var(--primary-color); color: var(--secondary-color); } </style></head> <body> <div class="first"> <h1>GeeksforGeeks</h1> </div> <div class="second"> <h1>GeeksforGeeks</h1> </div></body> </html>
Output:
Explanation: In the above example, we have defined two variable having scope of root (It can be used across the whole page), --primary-color and --secondary-color. Then, we have used them on class first and second, using CSS var() function.
Note: :root selector can be replaced with any local selector. Also, it will limit the scope of the defined variable within that selector only.
Example 2:
<!DOCTYPE html><html> <head> <title> How to define colors as variables in CSS? </title> <style> .first { /* The defined colors are not scoped for .first class only */ --primary-color: rgb(15, 157, 88); --secondary-color: rgb(255, 255, 255); width: 50%; padding: 40px 0px; margin: 10px 0px; text-align: center; /* Apply color using CSS var */ background-color: var(--primary-color); color: var(--secondary-color); } .second { width: 50%; padding: 40px 0px; text-align: center; /* Apply color using CSS var */ background-color: var(--primary-color); color: var(--secondary-color); } </style></head> <body> <div class="first"> <h1>GeeksforGeeks</h1> </div> <div class="second"> <h1>GeeksforGeeks</h1> </div></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Misc
HTML-Misc
Picked
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a web page using HTML and CSS
Form validation using jQuery
How to style a checkbox using CSS?
Search Bar using HTML, CSS and JavaScript
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML | [
{
"code": null,
"e": 26731,
"s": 26703,
"text": "\n27 Apr, 2020"
},
{
"code": null,
"e": 26955,
"s": 26731,
"text": "In CSS, we can define custom properties (often known as CSS variables), that offers us great flexibility to define a set of rules and avoid rewriting them again and again. We can also use custom properties to define colors."
},
{
"code": null,
"e": 26966,
"s": 26955,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to define colors as variables in CSS? </title> <style> :root { --primary-color: rgb(15, 157, 88); --secondary-color: rgb(255, 255, 255); } .first { width: 50%; padding: 40px 0px; margin: 10px 0px; text-align: center; /* Apply color using CSS var */ background-color: var(--primary-color); color: var(--secondary-color); } .second { width: 50%; padding: 40px 0px; text-align: center; /* Apply color using CSS var */ background-color: var(--primary-color); color: var(--secondary-color); } </style></head> <body> <div class=\"first\"> <h1>GeeksforGeeks</h1> </div> <div class=\"second\"> <h1>GeeksforGeeks</h1> </div></body> </html>",
"e": 27901,
"s": 26966,
"text": null
},
{
"code": null,
"e": 27909,
"s": 27901,
"text": "Output:"
},
{
"code": null,
"e": 28150,
"s": 27909,
"text": "Explanation: In the above example, we have defined two variable having scope of root (It can be used across the whole page), --primary-color and --secondary-color. Then, we have used them on class first and second, using CSS var() function."
},
{
"code": null,
"e": 28293,
"s": 28150,
"text": "Note: :root selector can be replaced with any local selector. Also, it will limit the scope of the defined variable within that selector only."
},
{
"code": null,
"e": 28304,
"s": 28293,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to define colors as variables in CSS? </title> <style> .first { /* The defined colors are not scoped for .first class only */ --primary-color: rgb(15, 157, 88); --secondary-color: rgb(255, 255, 255); width: 50%; padding: 40px 0px; margin: 10px 0px; text-align: center; /* Apply color using CSS var */ background-color: var(--primary-color); color: var(--secondary-color); } .second { width: 50%; padding: 40px 0px; text-align: center; /* Apply color using CSS var */ background-color: var(--primary-color); color: var(--secondary-color); } </style></head> <body> <div class=\"first\"> <h1>GeeksforGeeks</h1> </div> <div class=\"second\"> <h1>GeeksforGeeks</h1> </div></body> </html>",
"e": 29315,
"s": 28304,
"text": null
},
{
"code": null,
"e": 29323,
"s": 29315,
"text": "Output:"
},
{
"code": null,
"e": 29460,
"s": 29323,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 29469,
"s": 29460,
"text": "CSS-Misc"
},
{
"code": null,
"e": 29479,
"s": 29469,
"text": "HTML-Misc"
},
{
"code": null,
"e": 29486,
"s": 29479,
"text": "Picked"
},
{
"code": null,
"e": 29490,
"s": 29486,
"text": "CSS"
},
{
"code": null,
"e": 29495,
"s": 29490,
"text": "HTML"
},
{
"code": null,
"e": 29512,
"s": 29495,
"text": "Web Technologies"
},
{
"code": null,
"e": 29539,
"s": 29512,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29544,
"s": 29539,
"text": "HTML"
},
{
"code": null,
"e": 29642,
"s": 29544,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29681,
"s": 29642,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 29718,
"s": 29681,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 29747,
"s": 29718,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 29782,
"s": 29747,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 29824,
"s": 29782,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 29884,
"s": 29824,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 29937,
"s": 29884,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 29998,
"s": 29937,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 30022,
"s": 29998,
"text": "REST API (Introduction)"
}
] |
How to create hardlink of a file using Python? | The method os.link(src, dst) creates a hard link pointing to src named dst. This method is very useful to create a copy of existing file.
For example, if you have a file called photo.jpg and want to create a hard link to it called my_photo.jpg, then you could simply use:
>>> import os
>>> os.link('photo.jpg', 'my_photo.jpg')
Now if you list the files in that directory, you'll get the my_photo | [
{
"code": null,
"e": 1200,
"s": 1062,
"text": "The method os.link(src, dst) creates a hard link pointing to src named dst. This method is very useful to create a copy of existing file."
},
{
"code": null,
"e": 1335,
"s": 1200,
"text": "For example, if you have a file called photo.jpg and want to create a hard link to it called my_photo.jpg, then you could simply use:"
},
{
"code": null,
"e": 1390,
"s": 1335,
"text": ">>> import os\n>>> os.link('photo.jpg', 'my_photo.jpg')"
},
{
"code": null,
"e": 1460,
"s": 1390,
"text": " Now if you list the files in that directory, you'll get the my_photo"
}
] |
C# | BitConverter.ToString(Byte[]) Method - GeeksforGeeks | 01 Feb, 2019
This method is used to convert the numeric value of each element of a specified array of bytes to its equivalent hexadecimal string representation.
Syntax:
public static string ToString (byte[] value);
Here, the value is an array of bytes.
Return Value: This method returns a string of hexadecimal pairs separated by hyphens, where each pair represents the corresponding element in value. For example, “6E-1D-9A-00”.
Exception: This method throws ArgumentNullException if the byte array or you can say value is null.
Below programs illustrate the use of BitConverter.ToString(Byte[]) Method:
Example 1:
// C# program to demonstrate// BitConverter.ToString(Byte[]);// Methodusing System; public class GFG { // Main Method public static void Main() { try { // Define an array of byte values. byte[] array1 = {0, 1, 2, 4, 8, 16, 32, 64, 128, 255}; // Display the values of the myArr. Console.Write("Initial Array: "); // calling the PrintIndexAndValues() // method to print PrintIndexAndValues(array1); // Getting hex string of byte values string value = BitConverter.ToString(array1); // Display the string Console.Write("string: "); Console.Write("{0}", value); } catch (ArgumentNullException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } } // Defining the method // PrintIndexAndValues public static void PrintIndexAndValues(byte[] myArr) { for (int i = 0; i < myArr.Length; i++) { Console.Write("{0} ", myArr[i]); } Console.WriteLine(); Console.WriteLine(); }}
Initial Array: 0 1 2 4 8 16 32 64 128 255
string: 00-01-02-04-08-10-20-40-80-FF
Example 2: For ArgumentNullException
// C# program to demonstrate// BitConverter.ToString(Byte[]);// Methodusing System; public class GFG { // Main Method public static void Main() { try { // Define an array of byte values. byte[] array1 = null; // Getting hex string of byte values string value = BitConverter.ToString(array1); // Display the string Console.Write("string: "); Console.Write("{0}", value); } catch (ArgumentNullException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
Exception Thrown: System.ArgumentNullException
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.bitconverter.tostring?view=netframework-4.7.2#System_BitConverter_ToString_System_Byte___
CSharp-BitConverter-Class
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Abstract Class and Interface in C#
C# | IsNullOrEmpty() Method
C# Dictionary with examples
C# | How to check whether a List contains a specified element
C# | Arrays of Strings
String.Split() Method in C# with Examples
C# | Method Overriding
C# | Class and Object
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1 | [
{
"code": null,
"e": 23282,
"s": 23254,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 23430,
"s": 23282,
"text": "This method is used to convert the numeric value of each element of a specified array of bytes to its equivalent hexadecimal string representation."
},
{
"code": null,
"e": 23438,
"s": 23430,
"text": "Syntax:"
},
{
"code": null,
"e": 23484,
"s": 23438,
"text": "public static string ToString (byte[] value);"
},
{
"code": null,
"e": 23522,
"s": 23484,
"text": "Here, the value is an array of bytes."
},
{
"code": null,
"e": 23699,
"s": 23522,
"text": "Return Value: This method returns a string of hexadecimal pairs separated by hyphens, where each pair represents the corresponding element in value. For example, “6E-1D-9A-00”."
},
{
"code": null,
"e": 23799,
"s": 23699,
"text": "Exception: This method throws ArgumentNullException if the byte array or you can say value is null."
},
{
"code": null,
"e": 23874,
"s": 23799,
"text": "Below programs illustrate the use of BitConverter.ToString(Byte[]) Method:"
},
{
"code": null,
"e": 23885,
"s": 23874,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate// BitConverter.ToString(Byte[]);// Methodusing System; public class GFG { // Main Method public static void Main() { try { // Define an array of byte values. byte[] array1 = {0, 1, 2, 4, 8, 16, 32, 64, 128, 255}; // Display the values of the myArr. Console.Write(\"Initial Array: \"); // calling the PrintIndexAndValues() // method to print PrintIndexAndValues(array1); // Getting hex string of byte values string value = BitConverter.ToString(array1); // Display the string Console.Write(\"string: \"); Console.Write(\"{0}\", value); } catch (ArgumentNullException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } } // Defining the method // PrintIndexAndValues public static void PrintIndexAndValues(byte[] myArr) { for (int i = 0; i < myArr.Length; i++) { Console.Write(\"{0} \", myArr[i]); } Console.WriteLine(); Console.WriteLine(); }}",
"e": 25085,
"s": 23885,
"text": null
},
{
"code": null,
"e": 25168,
"s": 25085,
"text": "Initial Array: 0 1 2 4 8 16 32 64 128 255 \n\nstring: 00-01-02-04-08-10-20-40-80-FF\n"
},
{
"code": null,
"e": 25205,
"s": 25168,
"text": "Example 2: For ArgumentNullException"
},
{
"code": "// C# program to demonstrate// BitConverter.ToString(Byte[]);// Methodusing System; public class GFG { // Main Method public static void Main() { try { // Define an array of byte values. byte[] array1 = null; // Getting hex string of byte values string value = BitConverter.ToString(array1); // Display the string Console.Write(\"string: \"); Console.Write(\"{0}\", value); } catch (ArgumentNullException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 25851,
"s": 25205,
"text": null
},
{
"code": null,
"e": 25899,
"s": 25851,
"text": "Exception Thrown: System.ArgumentNullException\n"
},
{
"code": null,
"e": 25910,
"s": 25899,
"text": "Reference:"
},
{
"code": null,
"e": 26051,
"s": 25910,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.bitconverter.tostring?view=netframework-4.7.2#System_BitConverter_ToString_System_Byte___"
},
{
"code": null,
"e": 26077,
"s": 26051,
"text": "CSharp-BitConverter-Class"
},
{
"code": null,
"e": 26091,
"s": 26077,
"text": "CSharp-method"
},
{
"code": null,
"e": 26094,
"s": 26091,
"text": "C#"
},
{
"code": null,
"e": 26192,
"s": 26094,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26201,
"s": 26192,
"text": "Comments"
},
{
"code": null,
"e": 26214,
"s": 26201,
"text": "Old Comments"
},
{
"code": null,
"e": 26268,
"s": 26214,
"text": "Difference between Abstract Class and Interface in C#"
},
{
"code": null,
"e": 26296,
"s": 26268,
"text": "C# | IsNullOrEmpty() Method"
},
{
"code": null,
"e": 26324,
"s": 26296,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 26386,
"s": 26324,
"text": "C# | How to check whether a List contains a specified element"
},
{
"code": null,
"e": 26409,
"s": 26386,
"text": "C# | Arrays of Strings"
},
{
"code": null,
"e": 26451,
"s": 26409,
"text": "String.Split() Method in C# with Examples"
},
{
"code": null,
"e": 26474,
"s": 26451,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 26496,
"s": 26474,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 26514,
"s": 26496,
"text": "C# | Constructors"
}
] |
Grid System - Mobile, Tablet, Desktops | We have seen an example for Medium and Large Device. Now let us take it to another level, where we would want to change it for the extra small phone size as well. Say we want to add the option for the columns to be split 75%/25% for tablets, we go like this −
<div class = "col-sm-3 col-md-6 col-lg-4">....</div>
<div class = "col-sm-9 col-md-6 col-lg-8">....</div>
Now this gives us 3 different column layouts at each point. On a phone, it will be 75% on the left, and 25% on the right. On a tablet, it will be 50%/50% again, and on a large viewport, it will be 33%/66%. three different layouts for each of the three responsive sizes. Check it out in the following example. (Here styling for each column is used. You can avoid it.)
<div class = "container">
<h1>Hello, world!</h1>
<div class = "row">
<div class = "col-sm-3 col-md-6 col-lg-8" style = "background-color: #dedef8;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat.</p>
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem
accusantium doloremque laudantium, totam rem aperiam, eaque ipsa
quae ab illo inventore veritatis et quasi architecto beatae vitae
dicta sunt explicabo.</p>
</div>
<div class = "col-sm-9 col-md-6 col-lg-4" style = "background-color: #dedef8;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem
accusantium doloremque laudantium.</p>
<p>Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet,
consectetur, adipisci velit, sed quia non numquam eius modi tempora
incidunt ut labore et dolore magnam aliquam quaerat voluptatem.</p>
</div>
</div>
</div>
This will produce the following result −
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat.
Sed ut perspiciatis unde omnis iste natus error sit voluptatem
accusantium doloremque laudantium, totam rem aperiam, eaque ipsa
quae ab illo inventore veritatis et quasi architecto beatae vitae
dicta sunt explicabo.
Sed ut perspiciatis unde omnis iste natus error sit voluptatem
accusantium doloremque laudantium.
Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet,
consectetur, adipisci velit, sed quia non numquam eius modi
tempora incidunt ut labore et dolore magnam aliquam quaerat
voluptatem.
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": 3591,
"s": 3331,
"text": "We have seen an example for Medium and Large Device. Now let us take it to another level, where we would want to change it for the extra small phone size as well. Say we want to add the option for the columns to be split 75%/25% for tablets, we go like this −"
},
{
"code": null,
"e": 3697,
"s": 3591,
"text": "<div class = \"col-sm-3 col-md-6 col-lg-4\">....</div>\n<div class = \"col-sm-9 col-md-6 col-lg-8\">....</div>"
},
{
"code": null,
"e": 4064,
"s": 3697,
"text": "Now this gives us 3 different column layouts at each point. On a phone, it will be 75% on the left, and 25% on the right. On a tablet, it will be 50%/50% again, and on a large viewport, it will be 33%/66%. three different layouts for each of the three responsive sizes. Check it out in the following example. (Here styling for each column is used. You can avoid it.)"
},
{
"code": null,
"e": 5453,
"s": 4064,
"text": "<div class = \"container\">\n <h1>Hello, world!</h1>\n\n <div class = \"row\">\n <div class = \"col-sm-3 col-md-6 col-lg-8\" style = \"background-color: #dedef8; \n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n \n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do \n eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut \n enim ad minim veniam, quis nostrud exercitation ullamco laboris \n nisi ut aliquip ex ea commodo consequat.</p>\n\n <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem \n accusantium doloremque laudantium, totam rem aperiam, eaque ipsa \n quae ab illo inventore veritatis et quasi architecto beatae vitae \n dicta sunt explicabo.</p>\n </div>\n\n <div class = \"col-sm-9 col-md-6 col-lg-4\" style = \"background-color: #dedef8;\n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n \n <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem \n accusantium doloremque laudantium.</p>\n\n <p>Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, \n consectetur, adipisci velit, sed quia non numquam eius modi tempora \n incidunt ut labore et dolore magnam aliquam quaerat voluptatem.</p>\n </div>\n \n </div>\n</div>"
},
{
"code": null,
"e": 5494,
"s": 5453,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 5801,
"s": 5494,
"text": "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do \n eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut \n enim ad minim veniam, quis nostrud exercitation ullamco laboris \n nisi ut aliquip ex ea commodo consequat. \n "
},
{
"code": null,
"e": 6091,
"s": 5801,
"text": "Sed ut perspiciatis unde omnis iste natus error sit voluptatem \n accusantium doloremque laudantium, totam rem aperiam, eaque ipsa \n quae ab illo inventore veritatis et quasi architecto beatae vitae \n dicta sunt explicabo. \n "
},
{
"code": null,
"e": 6224,
"s": 6091,
"text": "Sed ut perspiciatis unde omnis iste natus error sit voluptatem \n accusantium doloremque laudantium.\n "
},
{
"code": null,
"e": 6496,
"s": 6224,
"text": " Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, \n consectetur, adipisci velit, sed quia non numquam eius modi \n tempora incidunt ut labore et dolore magnam aliquam quaerat \n voluptatem. \n "
},
{
"code": null,
"e": 6529,
"s": 6496,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6543,
"s": 6529,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6578,
"s": 6543,
"text": "\n 54 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6595,
"s": 6578,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6632,
"s": 6595,
"text": "\n 161 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 6660,
"s": 6632,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 6693,
"s": 6660,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6705,
"s": 6693,
"text": " Azaz Patel"
},
{
"code": null,
"e": 6740,
"s": 6705,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6757,
"s": 6740,
"text": " Muhammad Ismail"
},
{
"code": null,
"e": 6790,
"s": 6757,
"text": "\n 62 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 6810,
"s": 6790,
"text": " Yossef Ayman Zedan"
},
{
"code": null,
"e": 6817,
"s": 6810,
"text": " Print"
},
{
"code": null,
"e": 6828,
"s": 6817,
"text": " Add Notes"
}
] |
BooleanField - Django Models - GeeksforGeeks | 24 Aug, 2021
BooleanField is a true/false field. It is like a bool field in C/C+++. The default form widget for this field is CheckboxInput, or NullBooleanSelect if null=True. The default value of BooleanField is None when Field.default isn’t defined. One can define the default value as true or false by setting the default attribute to true/false simultaneously.
Syntax:
field_name = models.BooleanField(**options)
Illustration of BooleanField using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
Enter the following code into models.py file of geeks app.
Python3
from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.BooleanField()
Add the geeks app to INSTALLED_APPS
Python3
# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]
Now when we run makemigrations command from the terminal,
Python manage.py makemigrations
A new folder named migrations would be created in geeks directory with a file named 0001_initial.py
Python3
# Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField(auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.BooleanField()), ], ), ]
Now run,
Python manage.py migrate
Thus, an geeks_field BooleanField is created when you run migrations on the project. It is a field to store boolean value – True/False.
BooleanField is used for checking the particular condition, for example, to check if Email of a user is verified or not. One can use BooleanField to mark it True or False. We can also set it to False by using default=True.
Python3
# importing the model# from geeks appfrom geeks.models import GeeksModel # creating a instance of# GeeksModelgeek_object = GeeksModel.objects.create(geeks_field = True)geek_object.save()
Now let’s check it in admin server. We have created an instance of GeeksModel.
Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to BooleanField will enable it to store empty values for that table in a relational database. Here are the field options and attributes that a BooleanField can use.
NaveenArora
annianni
Django-models
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 25507,
"s": 25479,
"text": "\n24 Aug, 2021"
},
{
"code": null,
"e": 25860,
"s": 25507,
"text": "BooleanField is a true/false field. It is like a bool field in C/C+++. The default form widget for this field is CheckboxInput, or NullBooleanSelect if null=True. The default value of BooleanField is None when Field.default isn’t defined. One can define the default value as true or false by setting the default attribute to true/false simultaneously. "
},
{
"code": null,
"e": 25868,
"s": 25860,
"text": "Syntax:"
},
{
"code": null,
"e": 25912,
"s": 25868,
"text": "field_name = models.BooleanField(**options)"
},
{
"code": null,
"e": 26026,
"s": 25912,
"text": "Illustration of BooleanField using an Example. Consider a project named geeksforgeeks having an app named geeks. "
},
{
"code": null,
"e": 26114,
"s": 26026,
"text": "Refer to the following articles to check how to create a project and an app in Django. "
},
{
"code": null,
"e": 26165,
"s": 26114,
"text": "How to Create a Basic Project using MVT in Django?"
},
{
"code": null,
"e": 26198,
"s": 26165,
"text": "How to Create an App in Django ?"
},
{
"code": null,
"e": 26258,
"s": 26198,
"text": "Enter the following code into models.py file of geeks app. "
},
{
"code": null,
"e": 26266,
"s": 26258,
"text": "Python3"
},
{
"code": "from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.BooleanField()",
"e": 26419,
"s": 26266,
"text": null
},
{
"code": null,
"e": 26456,
"s": 26419,
"text": "Add the geeks app to INSTALLED_APPS "
},
{
"code": null,
"e": 26464,
"s": 26456,
"text": "Python3"
},
{
"code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]",
"e": 26701,
"s": 26464,
"text": null
},
{
"code": null,
"e": 26759,
"s": 26701,
"text": "Now when we run makemigrations command from the terminal,"
},
{
"code": null,
"e": 26791,
"s": 26759,
"text": "Python manage.py makemigrations"
},
{
"code": null,
"e": 26892,
"s": 26791,
"text": "A new folder named migrations would be created in geeks directory with a file named 0001_initial.py "
},
{
"code": null,
"e": 26900,
"s": 26892,
"text": "Python3"
},
{
"code": "# Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField(auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.BooleanField()), ], ), ]",
"e": 27464,
"s": 26900,
"text": null
},
{
"code": null,
"e": 27474,
"s": 27464,
"text": "Now run, "
},
{
"code": null,
"e": 27499,
"s": 27474,
"text": "Python manage.py migrate"
},
{
"code": null,
"e": 27635,
"s": 27499,
"text": "Thus, an geeks_field BooleanField is created when you run migrations on the project. It is a field to store boolean value – True/False."
},
{
"code": null,
"e": 27858,
"s": 27635,
"text": "BooleanField is used for checking the particular condition, for example, to check if Email of a user is verified or not. One can use BooleanField to mark it True or False. We can also set it to False by using default=True."
},
{
"code": null,
"e": 27866,
"s": 27858,
"text": "Python3"
},
{
"code": "# importing the model# from geeks appfrom geeks.models import GeeksModel # creating a instance of# GeeksModelgeek_object = GeeksModel.objects.create(geeks_field = True)geek_object.save()",
"e": 28053,
"s": 27866,
"text": null
},
{
"code": null,
"e": 28134,
"s": 28053,
"text": "Now let’s check it in admin server. We have created an instance of GeeksModel. "
},
{
"code": null,
"e": 28488,
"s": 28134,
"text": "Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to BooleanField will enable it to store empty values for that table in a relational database. Here are the field options and attributes that a BooleanField can use."
},
{
"code": null,
"e": 28500,
"s": 28488,
"text": "NaveenArora"
},
{
"code": null,
"e": 28509,
"s": 28500,
"text": "annianni"
},
{
"code": null,
"e": 28523,
"s": 28509,
"text": "Django-models"
},
{
"code": null,
"e": 28537,
"s": 28523,
"text": "Python Django"
},
{
"code": null,
"e": 28544,
"s": 28537,
"text": "Python"
},
{
"code": null,
"e": 28642,
"s": 28544,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28660,
"s": 28642,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28695,
"s": 28660,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28727,
"s": 28695,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28749,
"s": 28727,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28791,
"s": 28749,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28821,
"s": 28791,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28847,
"s": 28821,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28891,
"s": 28847,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28920,
"s": 28891,
"text": "*args and **kwargs in Python"
}
] |
Reach the target | Practice | GeeksforGeeks | Given four integers A, B, C, D. A represents the initial position of the geek on the x-axis. In each step, geek can go to X+B or X-B if he is standing at X. The tasks is to check if it is possible for the geek to reach C exactly after D steps.
Input:
1. The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
2. The first line of each test case contains four space-separated integers A, B, C, and D.
Output: For each test case, print "yes" if it is possible to reach C in exactly D steps. Otherwise, print "no" (without quotes).
Constraints:
1. 1 <= T <= 5
2. -10^9 <= A, C <= 10^9
3. 1 <= B <= 10^9
4. 1 <= D <= 15
Example:
Input:
3
2 3 8 4
-3 1 0 3
-3 1 1 3
Output:
yes
yes
no
Explanation:
Test case 1: one of the possible ways is {2, 5, 8, 11, 8}.
+1
harshit68rocking4 months ago
#include <iostream>
using namespace std;
bool solve(long long a,long long b,long long c, long long d){
if(d<0){ return false;}
if(c==a && d==0) {return true;}
return solve(a,b,c-b,d-1) || solve(a,b,c+b,d-1);
}
int main() {
//code
int t;
cin>>t;
while(t--){
long long a,b,c,d;
cin>>a>>b>>c>>d;
if(solve(a,b,c,d)) cout<<"yes \n";
else cout<<"no \n";
}
return 0;
}
+2
imranwahid6 months ago
Easy C++ solution
+3
kaalel7 months ago
An simple Iterative solution as recursive takes extra AUXs.
Time.C -→ O(T → no of testcases) with no extra space.
Scanner scanner = new Scanner(System.in);
int loop = scanner.nextInt();
while (loop != 0) {
int A = scanner.nextInt();
int B = scanner.nextInt();
int C = scanner.nextInt();
int D = scanner.nextInt();
int difference = C - A;
int minimumSteps = difference / B;
if (difference % B == 0 && minimumSteps <= D) {
if (minimumSteps == D) System.out.println("yes");
else if(((D - minimumSteps) & 1) == 0) System.out.println("yes");
else System.out.println("no");
} else System.out.println("no");
loop--;
}
The (else if) statement is to handle this test case :- (2,3,11,6).
0
AMAN RAJ8 months ago
AMAN RAJ
#include <bits stdc++.h="">using namespace std;int main() { int t; long long a,b,c,d; cin>>t; while(t--){ cin>>a>>b>>c>>d; long long k=abs(c-a); if(k%b){ cout<<"no\n"; continue; } long long s=k/b; if(s>d){ cout<<"no\n"; continue; } d-=s; if(d%2) cout<<"no\n"; else cout<<"yes\n"; } return 0;}
0
AMAN RAJ
This comment was deleted.
0
Rishabh Verma9 months ago
Rishabh Verma
#include<iostream>using namespace std;#define ll long long int;bool func(ll a,ll b,ll c,ll d){ if(d == 0 ){ return a == c; } if(a <= c)func(a + b, b, c, d - 1);elsefunc(a - b, b, c, d - 1);}int main() { ll t; cin>>t; while(t--){ ll a,b,c,d;cin>>a>>b>>c>>d;if(func(a,b,c,d)){ cout<<"yes"<<endl; }="" else{="" cout<<"no"<<endl;="" }="" }="" return="" 0;="" }="" <="" code="">
0
Devendra Yadav10 months ago
Devendra Yadav
My code is not giving right output for the below input what changes should I make in my code . Input:-729315417 750626557 -1688734020 13
Here is the Code!!bool isTrue(int a,int b,int c,int d){ bool flag = false; if(d==0){ if(a==c) return true; else return false; } return isTrue(a+b,b,c,d-1)||isTrue(a-b,b,c,d-1);}
0
ANAS MALVAT10 months ago
ANAS MALVAT
int flag;void recur(long long a, long long b , long long c, long long d){ if(d ==0) { if(a == c) { flag = 1; } return; }
recur(a + b,b,c, d - 1); recur(a - b,b,c, d- 1);}int main() {//codeint T;cin >> T;while(T--){ int a,b,c,d; flag = 0; cin>>a>>b>>c>>d; recur(a,b,c,d); if(flag) { cout<<"yes"; } else{ cout<<"no"; } cout<<"\n";}return 0;}
0
Shivam kumar_09211 months ago
Shivam kumar_092
import java.util.*;import java.lang.*;import java.io.*;class GFG{ public static void main(String[] args){
Scanner input=new Scanner(System.in); int T=input.nextInt(); for(int i=0;i<t;i++) {="" long="" a="input.nextInt();" long="" b="input.nextInt();" long="" c="input.nextInt();" long="" d="input.nextInt();" int="" m="fun(A,B,C,D);" if(m="">0) System.out.println("yes"); else System.out.println("no"); } }
public static int fun(long A,long B,long C,long D) { if(D==0) { if(A==C) return 1; else return 0; }
return (fun(A+B,B,C,D-1)+fun(A-B,B,C,D-1));
}
}
0
jack11 months ago
jack
def target(a,b,c,d): for i in range(d): if(a<c): a+="b" else:="" a-="b" if(a="=c):" return="" "yes"="" return="" "no"="" t="int(input())" for="" i="" in="" range(t):="" a,b,c,d="map(int,input().split())" print(target(a,b,c,d))="" <="" code="">
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": 482,
"s": 238,
"text": "Given four integers A, B, C, D. A represents the initial position of the geek on the x-axis. In each step, geek can go to X+B or X-B if he is standing at X. The tasks is to check if it is possible for the geek to reach C exactly after D steps."
},
{
"code": null,
"e": 980,
"s": 482,
"text": "Input: \n1. The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.\n2. The first line of each test case contains four space-separated integers A, B, C, and D.\n\nOutput: For each test case, print \"yes\" if it is possible to reach C in exactly D steps. Otherwise, print \"no\" (without quotes).\n\nConstraints:\n1. 1 <= T <= 5\n2. -10^9 <= A, C <= 10^9\n3. 1 <= B <= 10^9\n4. 1 <= D <= 15\n\nExample:\nInput:\n3\n2 3 8 4\n-3 1 0 3\n-3 1 1 3"
},
{
"code": null,
"e": 1072,
"s": 980,
"text": "Output:\nyes\nyes\nno\n\nExplanation:\nTest case 1: one of the possible ways is {2, 5, 8, 11, 8}."
},
{
"code": null,
"e": 1075,
"s": 1072,
"text": "+1"
},
{
"code": null,
"e": 1104,
"s": 1075,
"text": "harshit68rocking4 months ago"
},
{
"code": null,
"e": 1517,
"s": 1104,
"text": "#include <iostream>\nusing namespace std;\n\n\nbool solve(long long a,long long b,long long c, long long d){\n\n if(d<0){ return false;}\n if(c==a && d==0) {return true;} \n \n return solve(a,b,c-b,d-1) || solve(a,b,c+b,d-1);\n}\n\nint main() {\n\t//code\n\tint t;\n\tcin>>t;\n\twhile(t--){\n\t long long a,b,c,d;\n\t cin>>a>>b>>c>>d;\n\t if(solve(a,b,c,d)) cout<<\"yes \\n\";\n\t else cout<<\"no \\n\";\n\t}\n\treturn 0;\n}"
},
{
"code": null,
"e": 1520,
"s": 1517,
"text": "+2"
},
{
"code": null,
"e": 1543,
"s": 1520,
"text": "imranwahid6 months ago"
},
{
"code": null,
"e": 1561,
"s": 1543,
"text": "Easy C++ solution"
},
{
"code": null,
"e": 1564,
"s": 1561,
"text": "+3"
},
{
"code": null,
"e": 1583,
"s": 1564,
"text": "kaalel7 months ago"
},
{
"code": null,
"e": 1643,
"s": 1583,
"text": "An simple Iterative solution as recursive takes extra AUXs."
},
{
"code": null,
"e": 1697,
"s": 1643,
"text": "Time.C -→ O(T → no of testcases) with no extra space."
},
{
"code": null,
"e": 2376,
"s": 1699,
"text": "Scanner scanner = new Scanner(System.in);\n int loop = scanner.nextInt();\n while (loop != 0) {\n int A = scanner.nextInt();\n int B = scanner.nextInt();\n int C = scanner.nextInt();\n int D = scanner.nextInt();\n int difference = C - A;\n int minimumSteps = difference / B;\n if (difference % B == 0 && minimumSteps <= D) {\n if (minimumSteps == D) System.out.println(\"yes\");\n else if(((D - minimumSteps) & 1) == 0) System.out.println(\"yes\");\n else System.out.println(\"no\");\n } else System.out.println(\"no\");\n loop--;\n }"
},
{
"code": null,
"e": 2443,
"s": 2376,
"text": "The (else if) statement is to handle this test case :- (2,3,11,6)."
},
{
"code": null,
"e": 2445,
"s": 2443,
"text": "0"
},
{
"code": null,
"e": 2466,
"s": 2445,
"text": "AMAN RAJ8 months ago"
},
{
"code": null,
"e": 2475,
"s": 2466,
"text": "AMAN RAJ"
},
{
"code": null,
"e": 2914,
"s": 2475,
"text": "#include <bits stdc++.h=\"\">using namespace std;int main() { int t; long long a,b,c,d; cin>>t; while(t--){ cin>>a>>b>>c>>d; long long k=abs(c-a); if(k%b){ cout<<\"no\\n\"; continue; } long long s=k/b; if(s>d){ cout<<\"no\\n\"; continue; } d-=s; if(d%2) cout<<\"no\\n\"; else cout<<\"yes\\n\"; } return 0;}"
},
{
"code": null,
"e": 2916,
"s": 2914,
"text": "0"
},
{
"code": null,
"e": 2925,
"s": 2916,
"text": "AMAN RAJ"
},
{
"code": null,
"e": 2951,
"s": 2925,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2953,
"s": 2951,
"text": "0"
},
{
"code": null,
"e": 2979,
"s": 2953,
"text": "Rishabh Verma9 months ago"
},
{
"code": null,
"e": 2993,
"s": 2979,
"text": "Rishabh Verma"
},
{
"code": null,
"e": 3402,
"s": 2993,
"text": "#include<iostream>using namespace std;#define ll long long int;bool func(ll a,ll b,ll c,ll d){ if(d == 0 ){ return a == c; } if(a <= c)func(a + b, b, c, d - 1);elsefunc(a - b, b, c, d - 1);}int main() { ll t; cin>>t; while(t--){ ll a,b,c,d;cin>>a>>b>>c>>d;if(func(a,b,c,d)){ cout<<\"yes\"<<endl; }=\"\" else{=\"\" cout<<\"no\"<<endl;=\"\" }=\"\" }=\"\" return=\"\" 0;=\"\" }=\"\" <=\"\" code=\"\">"
},
{
"code": null,
"e": 3404,
"s": 3402,
"text": "0"
},
{
"code": null,
"e": 3432,
"s": 3404,
"text": "Devendra Yadav10 months ago"
},
{
"code": null,
"e": 3447,
"s": 3432,
"text": "Devendra Yadav"
},
{
"code": null,
"e": 3584,
"s": 3447,
"text": "My code is not giving right output for the below input what changes should I make in my code . Input:-729315417 750626557 -1688734020 13"
},
{
"code": null,
"e": 3816,
"s": 3584,
"text": "Here is the Code!!bool isTrue(int a,int b,int c,int d){ bool flag = false; if(d==0){ if(a==c) return true; else return false; } return isTrue(a+b,b,c,d-1)||isTrue(a-b,b,c,d-1);}"
},
{
"code": null,
"e": 3818,
"s": 3816,
"text": "0"
},
{
"code": null,
"e": 3843,
"s": 3818,
"text": "ANAS MALVAT10 months ago"
},
{
"code": null,
"e": 3855,
"s": 3843,
"text": "ANAS MALVAT"
},
{
"code": null,
"e": 4026,
"s": 3855,
"text": "int flag;void recur(long long a, long long b , long long c, long long d){ if(d ==0) { if(a == c) { flag = 1; } return; }"
},
{
"code": null,
"e": 4300,
"s": 4026,
"text": " recur(a + b,b,c, d - 1); recur(a - b,b,c, d- 1);}int main() {//codeint T;cin >> T;while(T--){ int a,b,c,d; flag = 0; cin>>a>>b>>c>>d; recur(a,b,c,d); if(flag) { cout<<\"yes\"; } else{ cout<<\"no\"; } cout<<\"\\n\";}return 0;}"
},
{
"code": null,
"e": 4302,
"s": 4300,
"text": "0"
},
{
"code": null,
"e": 4332,
"s": 4302,
"text": "Shivam kumar_09211 months ago"
},
{
"code": null,
"e": 4349,
"s": 4332,
"text": "Shivam kumar_092"
},
{
"code": null,
"e": 4458,
"s": 4349,
"text": "import java.util.*;import java.lang.*;import java.io.*;class GFG{ public static void main(String[] args){"
},
{
"code": null,
"e": 4818,
"s": 4458,
"text": " Scanner input=new Scanner(System.in); int T=input.nextInt(); for(int i=0;i<t;i++) {=\"\" long=\"\" a=\"input.nextInt();\" long=\"\" b=\"input.nextInt();\" long=\"\" c=\"input.nextInt();\" long=\"\" d=\"input.nextInt();\" int=\"\" m=\"fun(A,B,C,D);\" if(m=\"\">0) System.out.println(\"yes\"); else System.out.println(\"no\"); } }"
},
{
"code": null,
"e": 4973,
"s": 4818,
"text": " public static int fun(long A,long B,long C,long D) { if(D==0) { if(A==C) return 1; else return 0; }"
},
{
"code": null,
"e": 5023,
"s": 4973,
"text": " return (fun(A+B,B,C,D-1)+fun(A-B,B,C,D-1));"
},
{
"code": null,
"e": 5026,
"s": 5023,
"text": " }"
},
{
"code": null,
"e": 5028,
"s": 5026,
"text": "}"
},
{
"code": null,
"e": 5030,
"s": 5028,
"text": "0"
},
{
"code": null,
"e": 5048,
"s": 5030,
"text": "jack11 months ago"
},
{
"code": null,
"e": 5053,
"s": 5048,
"text": "jack"
},
{
"code": null,
"e": 5307,
"s": 5053,
"text": "def target(a,b,c,d): for i in range(d): if(a<c): a+=\"b\" else:=\"\" a-=\"b\" if(a=\"=c):\" return=\"\" \"yes\"=\"\" return=\"\" \"no\"=\"\" t=\"int(input())\" for=\"\" i=\"\" in=\"\" range(t):=\"\" a,b,c,d=\"map(int,input().split())\" print(target(a,b,c,d))=\"\" <=\"\" code=\"\">"
},
{
"code": null,
"e": 5453,
"s": 5307,
"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": 5489,
"s": 5453,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5499,
"s": 5489,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5509,
"s": 5499,
"text": "\nContest\n"
},
{
"code": null,
"e": 5572,
"s": 5509,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5720,
"s": 5572,
"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": 5928,
"s": 5720,
"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": 6034,
"s": 5928,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
JDBC PreparedStatement Example | PreparedStatement in JDBC Exampl | PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorials, we are going to discuss JDBC preparedstatement example. In JDBC PreparedStatement is an interface coming from java.sql package. It extends the Statement interface. As we already discussed in step by step JDBC example, we have 3 types of statements.
Statement
PreparedStatement
CallableStatement
Here are the some important points about JDBC PreparedStatement object.
In an application if we want to run a same query for multiple times with different parameters (values) then we can go with PreparedStatement.
If we use the normal Statement, it compiles the sql command for each time before going to execute.
If the same command is compiled again and again then the performance of an application is going to be decreased.
In case of PreparedStatement, first a command will be sent to database for compilation, then the compiled code will be stored in PreparedStatement object.
Now the code can be executed for any number of times by without recompiling the command again and again.
Another important limitation of the Statement object is, it can only transfer the data of type text format only. Where as PreparedStatement can transfer binary format also.
We can obtain the PreparedStatement object by calling the prepareStatement() method on connection object.
PreparedStatement pstmt = connection.prepareStatement("insert into student values(?,?,?)");
In the above example, at first the insert command will be sent to database and compiles the command and then the compiled code will assigned into PreparedStatement object.
In the syntax, we used “?” symbol in place of values in insert command. “?” symbol is called as index parameter or replace operator or place resolution operator.
We can use only “?” symbols in the place of values. No other symbols are allowed here.
“?” symbol is not allowed for DDL commands.
“?” symbol is not allowed to replace table names and column names.
Example :
select ?,? from emp; illegal
select * from emp where ? = ?; --illegal
select * from emp where empId = : ?; --legal
update ? set sal = ? where empId = ?; --illegal
Before we run the compiled code (stored in the PreparedStatement object), we need to set the values to the compiled code by calling setXxx() methods.
Here is the complete example for JDBC PreparedStatement.
package com.onlinetutorialspoint.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
public class Jdbc_PreparedStatement_Example {
public static void main(String[] args) throws Exception {
Connection connection = null;
PreparedStatement pstatement = null;
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
int n = 0;
System.out.println("Enter no. of Students to insert");
n = scanner.nextInt();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/onlinetutorialspoint", "root", "123456");
if (connection != null)
pstatement = connection.prepareStatement("insert into student values(?,?,?,?)");
if (pstatement != null) {
for (int i = 1; i <= n; i++) {
System.out.println("Enter " + i + " Student Details");
System.out.println("Enter Student No : ");
int studentNo = scanner.nextInt();
System.out.println("Enter Student Name : ");
String studentName = scanner.next();
System.out.println("Enter Student Address : ");
String studentAddress = scanner.next();
System.out.println("Enter Student Age : ");
int studentAge = scanner.nextInt();
pstatement.setInt(1, studentNo);
pstatement.setString(2, studentName);
pstatement.setString(3, studentAddress);
pstatement.setInt(4, studentAge);
int result = pstatement.executeUpdate();
if (result == 0) {
System.out.println("Student details: are not inserted");
} else {
System.out.println(result + " records(s) are inserted");
}
}
}
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (pstatement != null) {
pstatement.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
try {
if (connection != null) {
connection.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}
Output :
Enter no. of Students to insert
2
Enter 1 Student Details
Enter Student No :
3005
Enter Student Name :
Rahul
Enter Student Address :
Banglore
Enter Student Age :
29
1 records(s) are inserted
Enter 2 Student Details
Enter Student No :
3006
Enter Student Name :
Bharat
Enter Student Address :
Hyderabad
Enter Student Age :
32
1 records(s) are inserted
Happy Learning:)
JDBC Interview Questions and Answers
JDBC Select Program Example
JDBC Insert Program Example
JDBC Update Program Example
JDBC Delete Program Example
Step by Step JDBC Program Example
Insert an Image using JDBC in Mysql DB
Read an Image in JDBC Example
CallableStatement in jdbc Example
ResultSetMetaData in JDBC Example
DatabaseMetaData in JDBC Example
Transaction Management in JDBC Example
Batch Processing in JDBC Example
JDBC Connection with Properties file
JDBC Scrollable ResultSet Example
JDBC Interview Questions and Answers
JDBC Select Program Example
JDBC Insert Program Example
JDBC Update Program Example
JDBC Delete Program Example
Step by Step JDBC Program Example
Insert an Image using JDBC in Mysql DB
Read an Image in JDBC Example
CallableStatement in jdbc Example
ResultSetMetaData in JDBC Example
DatabaseMetaData in JDBC Example
Transaction Management in JDBC Example
Batch Processing in JDBC Example
JDBC Connection with Properties file
JDBC Scrollable ResultSet Example
Δ
JDBC Driver Types
Step by Step JDBC Program
JDBC Select Program
JDBC Insert Program
JDBC Update Program
JDBC Delete Program
JDBC Connection – Properties File
JDBC PreparedStatement Program
JDBC – CallableStatement Example
JDBC – Read an Image from DB
JDBC – Insert an Image in DB
JDBC – Updatable ResultSet
JDBC – Scrollable ResultSet
JDBC – ResultSetMetaData
JDBC – DatabaseMetaData
JDBC – Transaction Management
JDBC – Batch Processing
JDBC Interview Questions | [
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 666,
"s": 398,
"text": "In this tutorials, we are going to discuss JDBC preparedstatement example. In JDBC PreparedStatement is an interface coming from java.sql package. It extends the Statement interface. As we already discussed in step by step JDBC example, we have 3 types of statements."
},
{
"code": null,
"e": 676,
"s": 666,
"text": "Statement"
},
{
"code": null,
"e": 694,
"s": 676,
"text": "PreparedStatement"
},
{
"code": null,
"e": 712,
"s": 694,
"text": "CallableStatement"
},
{
"code": null,
"e": 784,
"s": 712,
"text": "Here are the some important points about JDBC PreparedStatement object."
},
{
"code": null,
"e": 926,
"s": 784,
"text": "In an application if we want to run a same query for multiple times with different parameters (values) then we can go with PreparedStatement."
},
{
"code": null,
"e": 1025,
"s": 926,
"text": "If we use the normal Statement, it compiles the sql command for each time before going to execute."
},
{
"code": null,
"e": 1138,
"s": 1025,
"text": "If the same command is compiled again and again then the performance of an application is going to be decreased."
},
{
"code": null,
"e": 1293,
"s": 1138,
"text": "In case of PreparedStatement, first a command will be sent to database for compilation, then the compiled code will be stored in PreparedStatement object."
},
{
"code": null,
"e": 1398,
"s": 1293,
"text": "Now the code can be executed for any number of times by without recompiling the command again and again."
},
{
"code": null,
"e": 1571,
"s": 1398,
"text": "Another important limitation of the Statement object is, it can only transfer the data of type text format only. Where as PreparedStatement can transfer binary format also."
},
{
"code": null,
"e": 1677,
"s": 1571,
"text": "We can obtain the PreparedStatement object by calling the prepareStatement() method on connection object."
},
{
"code": null,
"e": 1769,
"s": 1677,
"text": "PreparedStatement pstmt = connection.prepareStatement(\"insert into student values(?,?,?)\");"
},
{
"code": null,
"e": 1941,
"s": 1769,
"text": "In the above example, at first the insert command will be sent to database and compiles the command and then the compiled code will assigned into PreparedStatement object."
},
{
"code": null,
"e": 2103,
"s": 1941,
"text": "In the syntax, we used “?” symbol in place of values in insert command. “?” symbol is called as index parameter or replace operator or place resolution operator."
},
{
"code": null,
"e": 2190,
"s": 2103,
"text": "We can use only “?” symbols in the place of values. No other symbols are allowed here."
},
{
"code": null,
"e": 2234,
"s": 2190,
"text": "“?” symbol is not allowed for DDL commands."
},
{
"code": null,
"e": 2301,
"s": 2234,
"text": "“?” symbol is not allowed to replace table names and column names."
},
{
"code": null,
"e": 2311,
"s": 2301,
"text": "Example :"
},
{
"code": null,
"e": 2474,
"s": 2311,
"text": "select ?,? from emp; illegal\nselect * from emp where ? = ?; --illegal\nselect * from emp where empId = : ?; --legal\nupdate ? set sal = ? where empId = ?; --illegal"
},
{
"code": null,
"e": 2624,
"s": 2474,
"text": "Before we run the compiled code (stored in the PreparedStatement object), we need to set the values to the compiled code by calling setXxx() methods."
},
{
"code": null,
"e": 2681,
"s": 2624,
"text": "Here is the complete example for JDBC PreparedStatement."
},
{
"code": null,
"e": 5586,
"s": 2681,
"text": "package com.onlinetutorialspoint.jdbc; \n \nimport java.sql.Connection; \nimport java.sql.DriverManager; \nimport java.sql.PreparedStatement; \nimport java.sql.SQLException; \nimport java.util.Scanner; \n \npublic class Jdbc_PreparedStatement_Example { \n \n public static void main(String[] args) throws Exception { \n\n Connection connection = null; \n PreparedStatement pstatement = null; \n Scanner scanner = null; \n \n try { \n \n scanner = new Scanner(System.in); \n int n = 0; \n System.out.println(\"Enter no. of Students to insert\"); \n n = scanner.nextInt(); \n Class.forName(\"sun.jdbc.odbc.JdbcOdbcDriver\"); \n connection = DriverManager.getConnection(\"jdbc:mysql://localhost:3306/onlinetutorialspoint\", \"root\", \"123456\"); \n if (connection != null) \n pstatement = connection.prepareStatement(\"insert into student values(?,?,?,?)\"); \n if (pstatement != null) { \n for (int i = 1; i <= n; i++) { \n System.out.println(\"Enter \" + i + \" Student Details\"); \n System.out.println(\"Enter Student No : \"); \n int studentNo = scanner.nextInt(); \n System.out.println(\"Enter Student Name : \"); \n String studentName = scanner.next(); \n System.out.println(\"Enter Student Address : \"); \n String studentAddress = scanner.next(); \n System.out.println(\"Enter Student Age : \"); \n int studentAge = scanner.nextInt(); \n pstatement.setInt(1, studentNo); \n pstatement.setString(2, studentName); \n pstatement.setString(3, studentAddress); \n pstatement.setInt(4, studentAge); \n int result = pstatement.executeUpdate(); \n if (result == 0) { \n System.out.println(\"Student details: are not inserted\"); \n } else { \n System.out.println(result + \" records(s) are inserted\"); \n } \n } \n } \n } catch (ClassNotFoundException cnfe) { \n cnfe.printStackTrace(); \n } catch (SQLException se) { \n se.printStackTrace(); \n } catch (Exception ex) { \n ex.printStackTrace(); \n } finally { \n try { \n if (pstatement != null) { \n pstatement.close(); \n } \n } catch (SQLException se) { \n se.printStackTrace(); \n } \n try { \n if (connection != null) { \n connection.close(); \n } \n } catch (SQLException se) { \n se.printStackTrace(); \n } \n } \n } \n \n}"
},
{
"code": null,
"e": 5595,
"s": 5586,
"text": "Output :"
},
{
"code": null,
"e": 5947,
"s": 5595,
"text": "Enter no. of Students to insert\n2\nEnter 1 Student Details\nEnter Student No :\n3005\nEnter Student Name :\nRahul\nEnter Student Address :\nBanglore\nEnter Student Age :\n29\n1 records(s) are inserted\nEnter 2 Student Details\nEnter Student No :\n3006\nEnter Student Name :\nBharat\nEnter Student Address :\nHyderabad\nEnter Student Age :\n32\n1 records(s) are inserted"
},
{
"code": null,
"e": 5964,
"s": 5947,
"text": "Happy Learning:)"
},
{
"code": null,
"e": 6462,
"s": 5964,
"text": "\nJDBC Interview Questions and Answers\nJDBC Select Program Example\nJDBC Insert Program Example\nJDBC Update Program Example\nJDBC Delete Program Example\nStep by Step JDBC Program Example\nInsert an Image using JDBC in Mysql DB\nRead an Image in JDBC Example\nCallableStatement in jdbc Example\nResultSetMetaData in JDBC Example\nDatabaseMetaData in JDBC Example\nTransaction Management in JDBC Example\nBatch Processing in JDBC Example\nJDBC Connection with Properties file\nJDBC Scrollable ResultSet Example\n"
},
{
"code": null,
"e": 6499,
"s": 6462,
"text": "JDBC Interview Questions and Answers"
},
{
"code": null,
"e": 6527,
"s": 6499,
"text": "JDBC Select Program Example"
},
{
"code": null,
"e": 6555,
"s": 6527,
"text": "JDBC Insert Program Example"
},
{
"code": null,
"e": 6583,
"s": 6555,
"text": "JDBC Update Program Example"
},
{
"code": null,
"e": 6611,
"s": 6583,
"text": "JDBC Delete Program Example"
},
{
"code": null,
"e": 6645,
"s": 6611,
"text": "Step by Step JDBC Program Example"
},
{
"code": null,
"e": 6684,
"s": 6645,
"text": "Insert an Image using JDBC in Mysql DB"
},
{
"code": null,
"e": 6714,
"s": 6684,
"text": "Read an Image in JDBC Example"
},
{
"code": null,
"e": 6748,
"s": 6714,
"text": "CallableStatement in jdbc Example"
},
{
"code": null,
"e": 6782,
"s": 6748,
"text": "ResultSetMetaData in JDBC Example"
},
{
"code": null,
"e": 6815,
"s": 6782,
"text": "DatabaseMetaData in JDBC Example"
},
{
"code": null,
"e": 6854,
"s": 6815,
"text": "Transaction Management in JDBC Example"
},
{
"code": null,
"e": 6887,
"s": 6854,
"text": "Batch Processing in JDBC Example"
},
{
"code": null,
"e": 6924,
"s": 6887,
"text": "JDBC Connection with Properties file"
},
{
"code": null,
"e": 6958,
"s": 6924,
"text": "JDBC Scrollable ResultSet Example"
},
{
"code": null,
"e": 6964,
"s": 6962,
"text": "Δ"
},
{
"code": null,
"e": 6983,
"s": 6964,
"text": " JDBC Driver Types"
},
{
"code": null,
"e": 7010,
"s": 6983,
"text": " Step by Step JDBC Program"
},
{
"code": null,
"e": 7031,
"s": 7010,
"text": " JDBC Select Program"
},
{
"code": null,
"e": 7052,
"s": 7031,
"text": " JDBC Insert Program"
},
{
"code": null,
"e": 7073,
"s": 7052,
"text": " JDBC Update Program"
},
{
"code": null,
"e": 7094,
"s": 7073,
"text": " JDBC Delete Program"
},
{
"code": null,
"e": 7129,
"s": 7094,
"text": " JDBC Connection – Properties File"
},
{
"code": null,
"e": 7161,
"s": 7129,
"text": " JDBC PreparedStatement Program"
},
{
"code": null,
"e": 7195,
"s": 7161,
"text": " JDBC – CallableStatement Example"
},
{
"code": null,
"e": 7225,
"s": 7195,
"text": " JDBC – Read an Image from DB"
},
{
"code": null,
"e": 7255,
"s": 7225,
"text": " JDBC – Insert an Image in DB"
},
{
"code": null,
"e": 7283,
"s": 7255,
"text": " JDBC – Updatable ResultSet"
},
{
"code": null,
"e": 7312,
"s": 7283,
"text": " JDBC – Scrollable ResultSet"
},
{
"code": null,
"e": 7338,
"s": 7312,
"text": " JDBC – ResultSetMetaData"
},
{
"code": null,
"e": 7363,
"s": 7338,
"text": " JDBC – DatabaseMetaData"
},
{
"code": null,
"e": 7394,
"s": 7363,
"text": " JDBC – Transaction Management"
},
{
"code": null,
"e": 7419,
"s": 7394,
"text": " JDBC – Batch Processing"
}
] |
D3.js lineRadial() Method - GeeksforGeeks | 23 Aug, 2020
The d3.lineRadial() method is used to constructs a new Radial line generator with the default settings. The Radial line generator is then used to make a Radial line.
Syntax:
d3.lineRadial();
Parameters: This method does not accept any parameters.
Return Value: This method returns a Radial line Generator.
Example 1: The following example makes a Radial curve line using this method.
HTML
<!DOCTYPE html><html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"> </script> <script src="https://d3js.org/d3.v4.min.js"> </script></head> <body> <h1 style="text-align:center;color: green;"> GeeksforGeeks </h1> <center> <svg id="gfg" width="200" height="200"> <g transform="translate(100, 100)"></g> </svg> </center> <script> var lineRadialGenerator = d3.lineRadial(); var data = [ [0, 10], [3.14 * .5, 35], [3.14 * .75, 55], [3.14, 60], [3.14 * 1.25, 65], [3.14 * 1.5, 70], [3.14 * 1.75, 75], [3.14 * 2, 80], [3.14 * 2.25, 85], [3.14 * 2.5, 90], [3.14 * 2.75, 95], [3.14 * 3, 100], [3.14 * 3.25, 105], [3.14 * 3.5, 110]]; var a = lineRadialGenerator(data); d3.select("#gfg") .select("g") .append("path") .attr("d", a) .attr("fill", "none") .attr("stroke", "green"); </script></body> </html>
Output:
Example 2:
HTML
<!DOCTYPE html><html> <head> <meta charset="utf-8"> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"> </script> <script src= "https://d3js.org/d3.v4.min.js"> </script></head> <body> <h1 style="text-align:center; color:green;"> GeeksforGeeks</h1> <center> <svg id="gfg" width="200" height="200"> <g transform="translate(100, 100)"></g> </svg> </center> <script> var lineRadialGenerator = d3.lineRadial(); var data = [ [0, 80], [Math.PI * 0.25, 80], [Math.PI * 0.5, 80], [Math.PI * 0.75, 80], [Math.PI, 80], [Math.PI * 1.25, 80], [Math.PI * 1.5, 80], [Math.PI * 1.75, 80], [Math.PI * 2, 80] ]; var a = lineRadialGenerator(data); d3.select("#gfg") .select("g") .append("path") .attr("d", a) .attr("fill", "none") .attr("stroke", "green"); </script></body> </html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to detect browser or tab closing in JavaScript ?
How to get character array from string in JavaScript?
How to filter object array based on attributes?
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": 25220,
"s": 25192,
"text": "\n23 Aug, 2020"
},
{
"code": null,
"e": 25386,
"s": 25220,
"text": "The d3.lineRadial() method is used to constructs a new Radial line generator with the default settings. The Radial line generator is then used to make a Radial line."
},
{
"code": null,
"e": 25394,
"s": 25386,
"text": "Syntax:"
},
{
"code": null,
"e": 25411,
"s": 25394,
"text": "d3.lineRadial();"
},
{
"code": null,
"e": 25467,
"s": 25411,
"text": "Parameters: This method does not accept any parameters."
},
{
"code": null,
"e": 25526,
"s": 25467,
"text": "Return Value: This method returns a Radial line Generator."
},
{
"code": null,
"e": 25604,
"s": 25526,
"text": "Example 1: The following example makes a Radial curve line using this method."
},
{
"code": null,
"e": 25609,
"s": 25604,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js\"> </script> <script src=\"https://d3js.org/d3.v4.min.js\"> </script></head> <body> <h1 style=\"text-align:center;color: green;\"> GeeksforGeeks </h1> <center> <svg id=\"gfg\" width=\"200\" height=\"200\"> <g transform=\"translate(100, 100)\"></g> </svg> </center> <script> var lineRadialGenerator = d3.lineRadial(); var data = [ [0, 10], [3.14 * .5, 35], [3.14 * .75, 55], [3.14, 60], [3.14 * 1.25, 65], [3.14 * 1.5, 70], [3.14 * 1.75, 75], [3.14 * 2, 80], [3.14 * 2.25, 85], [3.14 * 2.5, 90], [3.14 * 2.75, 95], [3.14 * 3, 100], [3.14 * 3.25, 105], [3.14 * 3.5, 110]]; var a = lineRadialGenerator(data); d3.select(\"#gfg\") .select(\"g\") .append(\"path\") .attr(\"d\", a) .attr(\"fill\", \"none\") .attr(\"stroke\", \"green\"); </script></body> </html>",
"e": 26746,
"s": 25609,
"text": null
},
{
"code": null,
"e": 26754,
"s": 26746,
"text": "Output:"
},
{
"code": null,
"e": 26765,
"s": 26754,
"text": "Example 2:"
},
{
"code": null,
"e": 26770,
"s": 26765,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js\"> </script> <script src= \"https://d3js.org/d3.v4.min.js\"> </script></head> <body> <h1 style=\"text-align:center; color:green;\"> GeeksforGeeks</h1> <center> <svg id=\"gfg\" width=\"200\" height=\"200\"> <g transform=\"translate(100, 100)\"></g> </svg> </center> <script> var lineRadialGenerator = d3.lineRadial(); var data = [ [0, 80], [Math.PI * 0.25, 80], [Math.PI * 0.5, 80], [Math.PI * 0.75, 80], [Math.PI, 80], [Math.PI * 1.25, 80], [Math.PI * 1.5, 80], [Math.PI * 1.75, 80], [Math.PI * 2, 80] ]; var a = lineRadialGenerator(data); d3.select(\"#gfg\") .select(\"g\") .append(\"path\") .attr(\"d\", a) .attr(\"fill\", \"none\") .attr(\"stroke\", \"green\"); </script></body> </html>",
"e": 27821,
"s": 26770,
"text": null
},
{
"code": null,
"e": 27829,
"s": 27821,
"text": "Output:"
},
{
"code": null,
"e": 27835,
"s": 27829,
"text": "D3.js"
},
{
"code": null,
"e": 27846,
"s": 27835,
"text": "JavaScript"
},
{
"code": null,
"e": 27863,
"s": 27846,
"text": "Web Technologies"
},
{
"code": null,
"e": 27961,
"s": 27863,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27970,
"s": 27961,
"text": "Comments"
},
{
"code": null,
"e": 27983,
"s": 27970,
"text": "Old Comments"
},
{
"code": null,
"e": 28044,
"s": 27983,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28085,
"s": 28044,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28138,
"s": 28085,
"text": "How to detect browser or tab closing in JavaScript ?"
},
{
"code": null,
"e": 28192,
"s": 28138,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 28240,
"s": 28192,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 28282,
"s": 28240,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28315,
"s": 28282,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28377,
"s": 28315,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28420,
"s": 28377,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Difference between regular functions and arrow functions - GeeksforGeeks | 24 May, 2019
This article discusses the major differences between the regular functions and the arrow functions.
Arrow functions – a new feature introduced in ES6 – enable writing concise functions in JavaScript. While both regular and arrow functions work in a similar manner, yet there are certain interesting differences between them, as discussed below.
Syntax
Syntax of regular functions:-
let x = function function_name(parameters){ // body of the function};
Example of regular functions:-
let square = function(x){ return (x*x);};console.log(square(9));
Output:
The syntax of arrow functions:-
let x = (parameters) => { // body of the function};
Example of arrow functions:-
var square = (x) => { return (x*x);};console.log(square(9));
Output:
Use of this keyword
Unlike regular functions, arrow functions do not have their own this.For example:-
let user = { name: "GFG", gfg1:() => { console.log("hello " + this.name); // no 'this' binding here }, gfg2(){ console.log("Welcome to " + this.name); // 'this' binding works here } };user.gfg1();user.gfg2();
Output:
Availability of arguments objects
Arguments objects are not available in arrow functions, but are available in regular functions.
Example using regular ():-
let user = { show(){ console.log(arguments); }};user.show(1, 2, 3);
Output:
Example using arrow ():-
let user = { show_ar : () => { console.log(...arguments); }};user.show_ar(1, 2, 3);
Output:
Using new keyword
Regular functions created using function declarations or expressions are ‘constructible’ and ‘callable’. Since regular functions are constructible, they can be called using the ‘new’ keyword. However, the arrow functions are only ‘callable’ and not constructible. Thus, we will get a run-time error on trying to construct a non-constructible arrow functions using the new keyword.
Example using regular function:-
let x = function(){ console.log(arguments);};new x =(1,2,3);
Output:Example using arrow function:-
let x = ()=> { console.log(arguments);};new x(1,2,3);
Output:For more information on arrow functions, refer this link.
shubham_singh
javascript-functions
Web technologies
Difference Between
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Differences between IPv4 and IPv6
Difference Between Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference between DFA and NFA
Web 1.0, Web 2.0 and Web 3.0 with their difference
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
Form validation using HTML and JavaScript
File uploading in React.js | [
{
"code": null,
"e": 24012,
"s": 23984,
"text": "\n24 May, 2019"
},
{
"code": null,
"e": 24112,
"s": 24012,
"text": "This article discusses the major differences between the regular functions and the arrow functions."
},
{
"code": null,
"e": 24357,
"s": 24112,
"text": "Arrow functions – a new feature introduced in ES6 – enable writing concise functions in JavaScript. While both regular and arrow functions work in a similar manner, yet there are certain interesting differences between them, as discussed below."
},
{
"code": null,
"e": 24364,
"s": 24357,
"text": "Syntax"
},
{
"code": null,
"e": 24394,
"s": 24364,
"text": "Syntax of regular functions:-"
},
{
"code": "let x = function function_name(parameters){ // body of the function};",
"e": 24466,
"s": 24394,
"text": null
},
{
"code": null,
"e": 24497,
"s": 24466,
"text": "Example of regular functions:-"
},
{
"code": "let square = function(x){ return (x*x);};console.log(square(9));",
"e": 24563,
"s": 24497,
"text": null
},
{
"code": null,
"e": 24571,
"s": 24563,
"text": "Output:"
},
{
"code": null,
"e": 24603,
"s": 24571,
"text": "The syntax of arrow functions:-"
},
{
"code": "let x = (parameters) => { // body of the function};",
"e": 24658,
"s": 24603,
"text": null
},
{
"code": null,
"e": 24687,
"s": 24658,
"text": "Example of arrow functions:-"
},
{
"code": "var square = (x) => { return (x*x);};console.log(square(9));",
"e": 24751,
"s": 24687,
"text": null
},
{
"code": null,
"e": 24759,
"s": 24751,
"text": "Output:"
},
{
"code": null,
"e": 24779,
"s": 24759,
"text": "Use of this keyword"
},
{
"code": null,
"e": 24862,
"s": 24779,
"text": "Unlike regular functions, arrow functions do not have their own this.For example:-"
},
{
"code": "let user = { name: \"GFG\", gfg1:() => { console.log(\"hello \" + this.name); // no 'this' binding here }, gfg2(){ console.log(\"Welcome to \" + this.name); // 'this' binding works here } };user.gfg1();user.gfg2();",
"e": 25109,
"s": 24862,
"text": null
},
{
"code": null,
"e": 25117,
"s": 25109,
"text": "Output:"
},
{
"code": null,
"e": 25151,
"s": 25117,
"text": "Availability of arguments objects"
},
{
"code": null,
"e": 25247,
"s": 25151,
"text": "Arguments objects are not available in arrow functions, but are available in regular functions."
},
{
"code": null,
"e": 25274,
"s": 25247,
"text": "Example using regular ():-"
},
{
"code": "let user = { show(){ console.log(arguments); }};user.show(1, 2, 3);",
"e": 25361,
"s": 25274,
"text": null
},
{
"code": null,
"e": 25369,
"s": 25361,
"text": "Output:"
},
{
"code": null,
"e": 25394,
"s": 25369,
"text": "Example using arrow ():-"
},
{
"code": "let user = { show_ar : () => { console.log(...arguments); }};user.show_ar(1, 2, 3);",
"e": 25500,
"s": 25394,
"text": null
},
{
"code": null,
"e": 25508,
"s": 25500,
"text": "Output:"
},
{
"code": null,
"e": 25526,
"s": 25508,
"text": "Using new keyword"
},
{
"code": null,
"e": 25907,
"s": 25526,
"text": "Regular functions created using function declarations or expressions are ‘constructible’ and ‘callable’. Since regular functions are constructible, they can be called using the ‘new’ keyword. However, the arrow functions are only ‘callable’ and not constructible. Thus, we will get a run-time error on trying to construct a non-constructible arrow functions using the new keyword."
},
{
"code": null,
"e": 25940,
"s": 25907,
"text": "Example using regular function:-"
},
{
"code": "let x = function(){ console.log(arguments);};new x =(1,2,3);",
"e": 26004,
"s": 25940,
"text": null
},
{
"code": null,
"e": 26042,
"s": 26004,
"text": "Output:Example using arrow function:-"
},
{
"code": "let x = ()=> { console.log(arguments);};new x(1,2,3);",
"e": 26099,
"s": 26042,
"text": null
},
{
"code": null,
"e": 26164,
"s": 26099,
"text": "Output:For more information on arrow functions, refer this link."
},
{
"code": null,
"e": 26178,
"s": 26164,
"text": "shubham_singh"
},
{
"code": null,
"e": 26199,
"s": 26178,
"text": "javascript-functions"
},
{
"code": null,
"e": 26216,
"s": 26199,
"text": "Web technologies"
},
{
"code": null,
"e": 26235,
"s": 26216,
"text": "Difference Between"
},
{
"code": null,
"e": 26246,
"s": 26235,
"text": "JavaScript"
},
{
"code": null,
"e": 26263,
"s": 26246,
"text": "Web Technologies"
},
{
"code": null,
"e": 26361,
"s": 26263,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26370,
"s": 26361,
"text": "Comments"
},
{
"code": null,
"e": 26383,
"s": 26370,
"text": "Old Comments"
},
{
"code": null,
"e": 26417,
"s": 26383,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 26485,
"s": 26417,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 26543,
"s": 26485,
"text": "Difference between Prim's and Kruskal's algorithm for MST"
},
{
"code": null,
"e": 26574,
"s": 26543,
"text": "Difference between DFA and NFA"
},
{
"code": null,
"e": 26625,
"s": 26574,
"text": "Web 1.0, Web 2.0 and Web 3.0 with their difference"
},
{
"code": null,
"e": 26686,
"s": 26625,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26758,
"s": 26686,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 26827,
"s": 26758,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 26869,
"s": 26827,
"text": "Form validation using HTML and JavaScript"
}
] |
Kth Smallest Number in Multiplication Table in C++ | Suppose we know about one Multiplication Table. But could we find out the k-th smallest number quickly from the multiplication table? So if we have to height m and the length n of a m * n Multiplication Table, and one positive integer k, we have need to find the k-th smallest number in this table.
So if m = 3 and n = 3 and k is 6, then the output will be 4., this is because the multiplication table is like −
6th smallest element is 4 as [1,2,2,3,3,4,6,6,9]
To solve this, we will follow these steps −
Define a function ok(), this will take m, n, x,
ret := 0
for initialize i := 1, when i <= n, update (increase i by 1), do −temp := minimum of x / i and mret := ret + temp
temp := minimum of x / i and m
ret := ret + temp
return ret
From the main method, do the following −
ret := -1, low := 1, high := m * n
while low <= high, do −mid := low + (high - low) / 2cnt := ok(m, n, mid)if cnt >= k, then −high := mid - 1ret := midOtherwiselow := mid + 1
mid := low + (high - low) / 2
cnt := ok(m, n, mid)
if cnt >= k, then −high := mid - 1ret := mid
high := mid - 1
ret := mid
Otherwiselow := mid + 1
low := mid + 1
return ret
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int ok(int m, int n, int x){
int ret = 0;
for(int i = 1; i <= n; i++){
int temp = min(x / i, m);
ret += temp;
}
return ret;
}
int findKthNumber(int m, int n, int k) {
int ret = -1;
int low = 1;
int high = m * n ;
while(low <= high){
int mid = low + (high - low)/ 2;
int cnt = ok(m, n, mid);
if(cnt >= k){
high = mid - 1;
ret = mid;
}else low = mid + 1;
}
return ret;
}
};
main(){
Solution ob;
cout << (ob.findKthNumber(3,3,6));
}
“2*”
4 | [
{
"code": null,
"e": 1361,
"s": 1062,
"text": "Suppose we know about one Multiplication Table. But could we find out the k-th smallest number quickly from the multiplication table? So if we have to height m and the length n of a m * n Multiplication Table, and one positive integer k, we have need to find the k-th smallest number in this table."
},
{
"code": null,
"e": 1474,
"s": 1361,
"text": "So if m = 3 and n = 3 and k is 6, then the output will be 4., this is because the multiplication table is like −"
},
{
"code": null,
"e": 1523,
"s": 1474,
"text": "6th smallest element is 4 as [1,2,2,3,3,4,6,6,9]"
},
{
"code": null,
"e": 1567,
"s": 1523,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1615,
"s": 1567,
"text": "Define a function ok(), this will take m, n, x,"
},
{
"code": null,
"e": 1624,
"s": 1615,
"text": "ret := 0"
},
{
"code": null,
"e": 1738,
"s": 1624,
"text": "for initialize i := 1, when i <= n, update (increase i by 1), do −temp := minimum of x / i and mret := ret + temp"
},
{
"code": null,
"e": 1769,
"s": 1738,
"text": "temp := minimum of x / i and m"
},
{
"code": null,
"e": 1787,
"s": 1769,
"text": "ret := ret + temp"
},
{
"code": null,
"e": 1798,
"s": 1787,
"text": "return ret"
},
{
"code": null,
"e": 1839,
"s": 1798,
"text": "From the main method, do the following −"
},
{
"code": null,
"e": 1874,
"s": 1839,
"text": "ret := -1, low := 1, high := m * n"
},
{
"code": null,
"e": 2014,
"s": 1874,
"text": "while low <= high, do −mid := low + (high - low) / 2cnt := ok(m, n, mid)if cnt >= k, then −high := mid - 1ret := midOtherwiselow := mid + 1"
},
{
"code": null,
"e": 2044,
"s": 2014,
"text": "mid := low + (high - low) / 2"
},
{
"code": null,
"e": 2065,
"s": 2044,
"text": "cnt := ok(m, n, mid)"
},
{
"code": null,
"e": 2110,
"s": 2065,
"text": "if cnt >= k, then −high := mid - 1ret := mid"
},
{
"code": null,
"e": 2126,
"s": 2110,
"text": "high := mid - 1"
},
{
"code": null,
"e": 2137,
"s": 2126,
"text": "ret := mid"
},
{
"code": null,
"e": 2161,
"s": 2137,
"text": "Otherwiselow := mid + 1"
},
{
"code": null,
"e": 2176,
"s": 2161,
"text": "low := mid + 1"
},
{
"code": null,
"e": 2187,
"s": 2176,
"text": "return ret"
},
{
"code": null,
"e": 2257,
"s": 2187,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2268,
"s": 2257,
"text": " Live Demo"
},
{
"code": null,
"e": 2925,
"s": 2268,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n int ok(int m, int n, int x){\n int ret = 0;\n for(int i = 1; i <= n; i++){\n int temp = min(x / i, m);\n ret += temp;\n }\n return ret;\n }\n int findKthNumber(int m, int n, int k) {\n int ret = -1;\n int low = 1;\n int high = m * n ;\n while(low <= high){\n int mid = low + (high - low)/ 2;\n int cnt = ok(m, n, mid);\n if(cnt >= k){\n high = mid - 1;\n ret = mid;\n }else low = mid + 1;\n }\n return ret;\n }\n};\nmain(){\n Solution ob;\n cout << (ob.findKthNumber(3,3,6));\n}"
},
{
"code": null,
"e": 2930,
"s": 2925,
"text": "“2*”"
},
{
"code": null,
"e": 2932,
"s": 2930,
"text": "4"
}
] |
Implementation of K-Nearest Neighbors from Scratch using Python - GeeksforGeeks | 14 Oct, 2020
K Nearest Neighbors Classification is one of the classification techniques based on instance-based learning. Models based on instance-based learning to generalize beyond the training examples. To do so, they store the training examples first. When it encounters a new instance (or test example), then they instantly build a relationship between stored training examples and this new instant to assign a target function value for this new instance. Instance-based methods are sometimes called lazy learning methods because they postponed learning until the new instance is encountered for prediction.
Instead of estimating the hypothetical function (or target function) once for the entire space, these methods will estimate it locally and differently for each new instance to be predicted.
Basic Assumption:
All instances correspond to points in the n-dimensional space where n represents the number of features in any instance.The nearest neighbors of an instance are defined in terms of the Euclidean distance.
All instances correspond to points in the n-dimensional space where n represents the number of features in any instance.
The nearest neighbors of an instance are defined in terms of the Euclidean distance.
An instance can be represented by < x1, x2, .............., xn >.
Euclidean distance between two instances xa and xb is given by d( xa, xb ) :
How does it work?
K-Nearest Neighbors Classifier first stores the training examples. During prediction, when it encounters a new instance (or test example) to predict, it finds the K number of training instances nearest to this new instance. Then assigns the most common class among the K-Nearest training instances to this test instance.
The optimal choice for K is by validating errors on test data. K can also be chosen by the square root of m, where m is the number of examples in the dataset.
KNN Graphical Working Representation
In the above figure, “+” denotes training instances labelled with 1. “-” denotes training instances with 0. Here we classified for the test instance xt as the most common class among K-Nearest training instances to it. Here we choose K = 3, so xt is classified as “-” or 0.
Store all training examples.Repeat steps 3, 4, and 5 for each test example.Find the K number of training examples nearest to the current test example.y_pred for current test example = most common class among K-Nearest training instances.Go to step 2.
Store all training examples.
Repeat steps 3, 4, and 5 for each test example.
Find the K number of training examples nearest to the current test example.
y_pred for current test example = most common class among K-Nearest training instances.
Go to step 2.
Diabetes Dataset used in this implementation can be downloaded from link.
It has 8 features columns like i.e “Age”, “Glucose” e.t.c, and the target variable “Outcome” for 108 patients. So in this, we will create a link Neighbors Classifier model to predict the presence of diabetes or not for patients with such information.
# Importing libraries import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from scipy.stats import mode from sklearn.neighbors import KNeighborsClassifier # K Nearest Neighbors Classification class K_Nearest_Neighbors_Classifier() : def __init__( self, K ) : self.K = K # Function to store training set def fit( self, X_train, Y_train ) : self.X_train = X_train self.Y_train = Y_train # no_of_training_examples, no_of_features self.m, self.n = X_train.shape # Function for prediction def predict( self, X_test ) : self.X_test = X_test # no_of_test_examples, no_of_features self.m_test, self.n = X_test.shape # initialize Y_predict Y_predict = np.zeros( self.m_test ) for i in range( self.m_test ) : x = self.X_test[i] # find the K nearest neighbors from current test example neighbors = np.zeros( self.K ) neighbors = self.find_neighbors( x ) # most frequent class in K neighbors Y_predict[i] = mode( neighbors )[0][0] return Y_predict # Function to find the K nearest neighbors to current test example def find_neighbors( self, x ) : # calculate all the euclidean distances between current # test example x and training set X_train euclidean_distances = np.zeros( self.m ) for i in range( self.m ) : d = self.euclidean( x, self.X_train[i] ) euclidean_distances[i] = d # sort Y_train according to euclidean_distance_array and # store into Y_train_sorted inds = euclidean_distances.argsort() Y_train_sorted = self.Y_train[inds] return Y_train_sorted[:self.K] # Function to calculate euclidean distance def euclidean( self, x, x_train ) : return np.sqrt( np.sum( np.square( x - x_train ) ) ) # Driver code def main() : # Importing dataset df = pd.read_csv( "diabetes.csv" ) X = df.iloc[:,:-1].values Y = df.iloc[:,-1:].values # Splitting dataset into train and test set X_train, X_test, Y_train, Y_test = train_test_split( X, Y, test_size = 1/3, random_state = 0 ) # Model training model = K_Nearest_Neighbors_Classifier( K = 3 ) model.fit( X_train, Y_train ) model1 = KNeighborsClassifier( n_neighbors = 3 ) model1.fit( X_train, Y_train ) # Prediction on test set Y_pred = model.predict( X_test ) Y_pred1 = model1.predict( X_test ) # measure performance correctly_classified = 0 correctly_classified1 = 0 # counter count = 0 for count in range( np.size( Y_pred ) ) : if Y_test[count] == Y_pred[count] : correctly_classified = correctly_classified + 1 if Y_test[count] == Y_pred1[count] : correctly_classified1 = correctly_classified1 + 1 count = count + 1 print( "Accuracy on test set by our model : ", ( correctly_classified / count ) * 100 ) print( "Accuracy on test set by sklearn model : ", ( correctly_classified1 / count ) * 100 ) if __name__ == "__main__" : main()
Accuracy on test set by our model : 63.888888888888886
Accuracy on test set by sklearn model : 63.888888888888886
The accuracy achieved by our model and sklearn is equal which indicates the correct implementation of our model.
Note: Above Implementation is for model creation from scratch, not to improve the accuracy of the diabetes dataset.
K Nearest Neighbors Regression first stores the training examples. During prediction, when it encounters a new instance ( or test example ) to predict, it finds the K number of training instances nearest to this new instance. Then predicts the target value for this instance by calculating the mean of the target values of these nearest neighbors.
The optimal choice for K is by validating errors on test data. K can also be chosen by the square root of m, where m is the number of examples in the dataset.
Store all training examples.Repeat steps 3, 4, and 5 for each test example.Find the K number of training examples nearest to the current test example.y_pred for current test example = mean of the true target values of these K neighbors.Go to step 2.
Store all training examples.
Repeat steps 3, 4, and 5 for each test example.
Find the K number of training examples nearest to the current test example.
y_pred for current test example = mean of the true target values of these K neighbors.
Go to step 2.
Dataset used in this implementation can be downloaded from link
It has 2 columns — “YearsExperience” and “Salary” for 30 employees in a company. So in this, we will create a K Nearest Neighbors Regression model to learn the correlation between the number of years of experience of each employee and their respective salary.
The model, we created predicts the same value as the sklearn model predicts for the test set.
Python3
# Importing libraries import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsRegressor # K Nearest Neighbors Regression class K_Nearest_Neighbors_Regressor() : def __init__( self, K ) : self.K = K # Function to store training set def fit( self, X_train, Y_train ) : self.X_train = X_train self.Y_train = Y_train # no_of_training_examples, no_of_features self.m, self.n = X_train.shape # Function for prediction def predict( self, X_test ) : self.X_test = X_test # no_of_test_examples, no_of_features self.m_test, self.n = X_test.shape # initialize Y_predict Y_predict = np.zeros( self.m_test ) for i in range( self.m_test ) : x = self.X_test[i] # find the K nearest neighbors from current test example neighbors = np.zeros( self.K ) neighbors = self.find_neighbors( x ) # calculate the mean of K nearest neighbors Y_predict[i] = np.mean( neighbors ) return Y_predict # Function to find the K nearest neighbors to current test example def find_neighbors( self, x ) : # calculate all the euclidean distances between current test # example x and training set X_train euclidean_distances = np.zeros( self.m ) for i in range( self.m ) : d = self.euclidean( x, self.X_train[i] ) euclidean_distances[i] = d # sort Y_train according to euclidean_distance_array and # store into Y_train_sorted inds = euclidean_distances.argsort() Y_train_sorted = self.Y_train[inds] return Y_train_sorted[:self.K] # Function to calculate euclidean distance def euclidean( self, x, x_train ) : return np.sqrt( np.sum( np.square( x - x_train ) ) ) # Driver code def main() : # Importing dataset df = pd.read_csv( "salary_data.csv" ) X = df.iloc[:,:-1].values Y = df.iloc[:,1].values # Splitting dataset into train and test set X_train, X_test, Y_train, Y_test = train_test_split( X, Y, test_size = 1/3, random_state = 0 ) # Model training model = K_Nearest_Neighbors_Regressor( K = 3 ) model.fit( X_train, Y_train ) model1 = KNeighborsRegressor( n_neighbors = 3 ) model1.fit( X_train, Y_train ) # Prediction on test set Y_pred = model.predict( X_test ) Y_pred1 = model1.predict( X_test ) print( "Predicted values by our model : ", np.round( Y_pred[:3], 2 ) ) print( "Predicted values by sklearn model : ", np.round( Y_pred1[:3], 2 ) ) print( "Real values : ", Y_test[:3] ) if __name__ == "__main__" : main()
Predicted values by our model : [ 43024.33 113755.33 58419. ]
Predicted values by sklearn model : [ 43024.33 113755.33 58419. ]
Real values : [ 37731 122391 57081]
Disadvantage: Instance Learning models are computationally very costly because all the computations are done during prediction. It also considers all the training examples for the prediction of every test example.
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
Python | Decision tree implementation
Search Algorithms in AI
Difference between Informed and Uninformed Search in AI
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": 24131,
"s": 24103,
"text": "\n14 Oct, 2020"
},
{
"code": null,
"e": 24731,
"s": 24131,
"text": "K Nearest Neighbors Classification is one of the classification techniques based on instance-based learning. Models based on instance-based learning to generalize beyond the training examples. To do so, they store the training examples first. When it encounters a new instance (or test example), then they instantly build a relationship between stored training examples and this new instant to assign a target function value for this new instance. Instance-based methods are sometimes called lazy learning methods because they postponed learning until the new instance is encountered for prediction."
},
{
"code": null,
"e": 24921,
"s": 24731,
"text": "Instead of estimating the hypothetical function (or target function) once for the entire space, these methods will estimate it locally and differently for each new instance to be predicted."
},
{
"code": null,
"e": 24939,
"s": 24921,
"text": "Basic Assumption:"
},
{
"code": null,
"e": 25144,
"s": 24939,
"text": "All instances correspond to points in the n-dimensional space where n represents the number of features in any instance.The nearest neighbors of an instance are defined in terms of the Euclidean distance."
},
{
"code": null,
"e": 25265,
"s": 25144,
"text": "All instances correspond to points in the n-dimensional space where n represents the number of features in any instance."
},
{
"code": null,
"e": 25350,
"s": 25265,
"text": "The nearest neighbors of an instance are defined in terms of the Euclidean distance."
},
{
"code": null,
"e": 25494,
"s": 25350,
"text": "An instance can be represented by < x1, x2, .............., xn >.\nEuclidean distance between two instances xa and xb is given by d( xa, xb ) :\n"
},
{
"code": null,
"e": 25512,
"s": 25494,
"text": "How does it work?"
},
{
"code": null,
"e": 25834,
"s": 25512,
"text": "K-Nearest Neighbors Classifier first stores the training examples. During prediction, when it encounters a new instance (or test example) to predict, it finds the K number of training instances nearest to this new instance. Then assigns the most common class among the K-Nearest training instances to this test instance."
},
{
"code": null,
"e": 25993,
"s": 25834,
"text": "The optimal choice for K is by validating errors on test data. K can also be chosen by the square root of m, where m is the number of examples in the dataset."
},
{
"code": null,
"e": 26030,
"s": 25993,
"text": "KNN Graphical Working Representation"
},
{
"code": null,
"e": 26304,
"s": 26030,
"text": "In the above figure, “+” denotes training instances labelled with 1. “-” denotes training instances with 0. Here we classified for the test instance xt as the most common class among K-Nearest training instances to it. Here we choose K = 3, so xt is classified as “-” or 0."
},
{
"code": null,
"e": 26556,
"s": 26304,
"text": "Store all training examples.Repeat steps 3, 4, and 5 for each test example.Find the K number of training examples nearest to the current test example.y_pred for current test example = most common class among K-Nearest training instances.Go to step 2."
},
{
"code": null,
"e": 26585,
"s": 26556,
"text": "Store all training examples."
},
{
"code": null,
"e": 26633,
"s": 26585,
"text": "Repeat steps 3, 4, and 5 for each test example."
},
{
"code": null,
"e": 26709,
"s": 26633,
"text": "Find the K number of training examples nearest to the current test example."
},
{
"code": null,
"e": 26798,
"s": 26709,
"text": "y_pred for current test example = most common class among K-Nearest training instances."
},
{
"code": null,
"e": 26812,
"s": 26798,
"text": "Go to step 2."
},
{
"code": null,
"e": 26886,
"s": 26812,
"text": "Diabetes Dataset used in this implementation can be downloaded from link."
},
{
"code": null,
"e": 27137,
"s": 26886,
"text": "It has 8 features columns like i.e “Age”, “Glucose” e.t.c, and the target variable “Outcome” for 108 patients. So in this, we will create a link Neighbors Classifier model to predict the presence of diabetes or not for patients with such information."
},
{
"code": "# Importing libraries import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from scipy.stats import mode from sklearn.neighbors import KNeighborsClassifier # K Nearest Neighbors Classification class K_Nearest_Neighbors_Classifier() : def __init__( self, K ) : self.K = K # Function to store training set def fit( self, X_train, Y_train ) : self.X_train = X_train self.Y_train = Y_train # no_of_training_examples, no_of_features self.m, self.n = X_train.shape # Function for prediction def predict( self, X_test ) : self.X_test = X_test # no_of_test_examples, no_of_features self.m_test, self.n = X_test.shape # initialize Y_predict Y_predict = np.zeros( self.m_test ) for i in range( self.m_test ) : x = self.X_test[i] # find the K nearest neighbors from current test example neighbors = np.zeros( self.K ) neighbors = self.find_neighbors( x ) # most frequent class in K neighbors Y_predict[i] = mode( neighbors )[0][0] return Y_predict # Function to find the K nearest neighbors to current test example def find_neighbors( self, x ) : # calculate all the euclidean distances between current # test example x and training set X_train euclidean_distances = np.zeros( self.m ) for i in range( self.m ) : d = self.euclidean( x, self.X_train[i] ) euclidean_distances[i] = d # sort Y_train according to euclidean_distance_array and # store into Y_train_sorted inds = euclidean_distances.argsort() Y_train_sorted = self.Y_train[inds] return Y_train_sorted[:self.K] # Function to calculate euclidean distance def euclidean( self, x, x_train ) : return np.sqrt( np.sum( np.square( x - x_train ) ) ) # Driver code def main() : # Importing dataset df = pd.read_csv( \"diabetes.csv\" ) X = df.iloc[:,:-1].values Y = df.iloc[:,-1:].values # Splitting dataset into train and test set X_train, X_test, Y_train, Y_test = train_test_split( X, Y, test_size = 1/3, random_state = 0 ) # Model training model = K_Nearest_Neighbors_Classifier( K = 3 ) model.fit( X_train, Y_train ) model1 = KNeighborsClassifier( n_neighbors = 3 ) model1.fit( X_train, Y_train ) # Prediction on test set Y_pred = model.predict( X_test ) Y_pred1 = model1.predict( X_test ) # measure performance correctly_classified = 0 correctly_classified1 = 0 # counter count = 0 for count in range( np.size( Y_pred ) ) : if Y_test[count] == Y_pred[count] : correctly_classified = correctly_classified + 1 if Y_test[count] == Y_pred1[count] : correctly_classified1 = correctly_classified1 + 1 count = count + 1 print( \"Accuracy on test set by our model : \", ( correctly_classified / count ) * 100 ) print( \"Accuracy on test set by sklearn model : \", ( correctly_classified1 / count ) * 100 ) if __name__ == \"__main__\" : main()",
"e": 30862,
"s": 27137,
"text": null
},
{
"code": null,
"e": 30989,
"s": 30862,
"text": "Accuracy on test set by our model : 63.888888888888886\nAccuracy on test set by sklearn model : 63.888888888888886\n"
},
{
"code": null,
"e": 31102,
"s": 30989,
"text": "The accuracy achieved by our model and sklearn is equal which indicates the correct implementation of our model."
},
{
"code": null,
"e": 31218,
"s": 31102,
"text": "Note: Above Implementation is for model creation from scratch, not to improve the accuracy of the diabetes dataset."
},
{
"code": null,
"e": 31567,
"s": 31218,
"text": "K Nearest Neighbors Regression first stores the training examples. During prediction, when it encounters a new instance ( or test example ) to predict, it finds the K number of training instances nearest to this new instance. Then predicts the target value for this instance by calculating the mean of the target values of these nearest neighbors."
},
{
"code": null,
"e": 31726,
"s": 31567,
"text": "The optimal choice for K is by validating errors on test data. K can also be chosen by the square root of m, where m is the number of examples in the dataset."
},
{
"code": null,
"e": 31977,
"s": 31726,
"text": "Store all training examples.Repeat steps 3, 4, and 5 for each test example.Find the K number of training examples nearest to the current test example.y_pred for current test example = mean of the true target values of these K neighbors.Go to step 2."
},
{
"code": null,
"e": 32006,
"s": 31977,
"text": "Store all training examples."
},
{
"code": null,
"e": 32054,
"s": 32006,
"text": "Repeat steps 3, 4, and 5 for each test example."
},
{
"code": null,
"e": 32130,
"s": 32054,
"text": "Find the K number of training examples nearest to the current test example."
},
{
"code": null,
"e": 32218,
"s": 32130,
"text": "y_pred for current test example = mean of the true target values of these K neighbors."
},
{
"code": null,
"e": 32232,
"s": 32218,
"text": "Go to step 2."
},
{
"code": null,
"e": 32296,
"s": 32232,
"text": "Dataset used in this implementation can be downloaded from link"
},
{
"code": null,
"e": 32556,
"s": 32296,
"text": "It has 2 columns — “YearsExperience” and “Salary” for 30 employees in a company. So in this, we will create a K Nearest Neighbors Regression model to learn the correlation between the number of years of experience of each employee and their respective salary."
},
{
"code": null,
"e": 32650,
"s": 32556,
"text": "The model, we created predicts the same value as the sklearn model predicts for the test set."
},
{
"code": null,
"e": 32658,
"s": 32650,
"text": "Python3"
},
{
"code": "# Importing libraries import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsRegressor # K Nearest Neighbors Regression class K_Nearest_Neighbors_Regressor() : def __init__( self, K ) : self.K = K # Function to store training set def fit( self, X_train, Y_train ) : self.X_train = X_train self.Y_train = Y_train # no_of_training_examples, no_of_features self.m, self.n = X_train.shape # Function for prediction def predict( self, X_test ) : self.X_test = X_test # no_of_test_examples, no_of_features self.m_test, self.n = X_test.shape # initialize Y_predict Y_predict = np.zeros( self.m_test ) for i in range( self.m_test ) : x = self.X_test[i] # find the K nearest neighbors from current test example neighbors = np.zeros( self.K ) neighbors = self.find_neighbors( x ) # calculate the mean of K nearest neighbors Y_predict[i] = np.mean( neighbors ) return Y_predict # Function to find the K nearest neighbors to current test example def find_neighbors( self, x ) : # calculate all the euclidean distances between current test # example x and training set X_train euclidean_distances = np.zeros( self.m ) for i in range( self.m ) : d = self.euclidean( x, self.X_train[i] ) euclidean_distances[i] = d # sort Y_train according to euclidean_distance_array and # store into Y_train_sorted inds = euclidean_distances.argsort() Y_train_sorted = self.Y_train[inds] return Y_train_sorted[:self.K] # Function to calculate euclidean distance def euclidean( self, x, x_train ) : return np.sqrt( np.sum( np.square( x - x_train ) ) ) # Driver code def main() : # Importing dataset df = pd.read_csv( \"salary_data.csv\" ) X = df.iloc[:,:-1].values Y = df.iloc[:,1].values # Splitting dataset into train and test set X_train, X_test, Y_train, Y_test = train_test_split( X, Y, test_size = 1/3, random_state = 0 ) # Model training model = K_Nearest_Neighbors_Regressor( K = 3 ) model.fit( X_train, Y_train ) model1 = KNeighborsRegressor( n_neighbors = 3 ) model1.fit( X_train, Y_train ) # Prediction on test set Y_pred = model.predict( X_test ) Y_pred1 = model1.predict( X_test ) print( \"Predicted values by our model : \", np.round( Y_pred[:3], 2 ) ) print( \"Predicted values by sklearn model : \", np.round( Y_pred1[:3], 2 ) ) print( \"Real values : \", Y_test[:3] ) if __name__ == \"__main__\" : main()",
"e": 35875,
"s": 32658,
"text": null
},
{
"code": null,
"e": 36076,
"s": 35875,
"text": "Predicted values by our model : [ 43024.33 113755.33 58419. ]\nPredicted values by sklearn model : [ 43024.33 113755.33 58419. ]\nReal values : [ 37731 122391 57081]"
},
{
"code": null,
"e": 36290,
"s": 36076,
"text": "Disadvantage: Instance Learning models are computationally very costly because all the computations are done during prediction. It also considers all the training examples for the prediction of every test example."
},
{
"code": null,
"e": 36307,
"s": 36290,
"text": "Machine Learning"
},
{
"code": null,
"e": 36314,
"s": 36307,
"text": "Python"
},
{
"code": null,
"e": 36331,
"s": 36314,
"text": "Machine Learning"
},
{
"code": null,
"e": 36429,
"s": 36331,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36438,
"s": 36429,
"text": "Comments"
},
{
"code": null,
"e": 36451,
"s": 36438,
"text": "Old Comments"
},
{
"code": null,
"e": 36474,
"s": 36451,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 36488,
"s": 36474,
"text": "Decision Tree"
},
{
"code": null,
"e": 36526,
"s": 36488,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 36550,
"s": 36526,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 36606,
"s": 36550,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 36634,
"s": 36606,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 36684,
"s": 36634,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 36706,
"s": 36684,
"text": "Python map() function"
}
] |
How to change the color and add grid lines to a Python Matplotlib surface plot? | To change the color and add grid lines to a Python surface plot, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create x, y and h data points using numpy.
Create x, y and h data points using numpy.
Create a new figure or activate an existing figure.
Create a new figure or activate an existing figure.
Get 3D axes object, with figure (from Step 3).
Get 3D axes object, with figure (from Step 3).
Create a surface plot, with orange color, edgecolors and linewidth.
Create a surface plot, with orange color, edgecolors and linewidth.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.arange(-5, 5, 0.25)
y = np.arange(-5, 5, 0.25)
x, y = np.meshgrid(x, y)
h = np.sin(x)*np.cos(y)
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(x, y, h, rstride=10, cstride=10, color='orangered', edgecolors='yellow', lw=0.6)
plt.show() | [
{
"code": null,
"e": 1161,
"s": 1062,
"text": "To change the color and add grid lines to a Python surface plot, we can take the following steps −"
},
{
"code": null,
"e": 1237,
"s": 1161,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1313,
"s": 1237,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1356,
"s": 1313,
"text": "Create x, y and h data points using numpy."
},
{
"code": null,
"e": 1399,
"s": 1356,
"text": "Create x, y and h data points using numpy."
},
{
"code": null,
"e": 1451,
"s": 1399,
"text": "Create a new figure or activate an existing figure."
},
{
"code": null,
"e": 1503,
"s": 1451,
"text": "Create a new figure or activate an existing figure."
},
{
"code": null,
"e": 1550,
"s": 1503,
"text": "Get 3D axes object, with figure (from Step 3)."
},
{
"code": null,
"e": 1597,
"s": 1550,
"text": "Get 3D axes object, with figure (from Step 3)."
},
{
"code": null,
"e": 1665,
"s": 1597,
"text": "Create a surface plot, with orange color, edgecolors and linewidth."
},
{
"code": null,
"e": 1733,
"s": 1665,
"text": "Create a surface plot, with orange color, edgecolors and linewidth."
},
{
"code": null,
"e": 2164,
"s": 1733,
"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nx = np.arange(-5, 5, 0.25)\ny = np.arange(-5, 5, 0.25)\n\nx, y = np.meshgrid(x, y)\nh = np.sin(x)*np.cos(y)\n\nfig = plt.figure()\n\nax = Axes3D(fig)\nax.plot_surface(x, y, h, rstride=10, cstride=10, color='orangered', edgecolors='yellow', lw=0.6)\n\nplt.show()"
}
] |
How to set the part of the Android TextView as clickable? | This example demonstrates how do I set the part of the Android textView as clickable.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I want THIS and THIS to be CLICKED!"
android:layout_centerInParent="true"
android:textSize="16sp"
android:textStyle="bold|italic"/>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
String text = "I want THIS and THIS to be CLICKED";
SpannableString spannableString = new SpannableString(text);
ClickableSpan clickableSpan1 = new ClickableSpan() {
@Override
public void onClick(View widget) {
Toast.makeText(MainActivity.this, "THIS", Toast.LENGTH_SHORT).show();
}
};
ClickableSpan clickableSpan2 = new ClickableSpan() {
@Override
public void onClick(View widget) {
Toast.makeText(MainActivity.this, "THIS", Toast.LENGTH_SHORT).show();
}
};
ClickableSpan clickableSpan3 = new ClickableSpan() {
@Override
public void onClick(View widget) {
Toast.makeText(MainActivity.this, "CLICKED", Toast.LENGTH_SHORT).show();
}
};
spannableString.setSpan(clickableSpan1, 7,11, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString.setSpan(clickableSpan2, 16,20, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString.setSpan(clickableSpan3, 27,34, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString);
textView.setMovementMethod(LinkMovementMethod.getInstance());
}
}
Step 4 - Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code. | [
{
"code": null,
"e": 1148,
"s": 1062,
"text": "This example demonstrates how do I set the part of the Android textView as clickable."
},
{
"code": null,
"e": 1277,
"s": 1148,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1342,
"s": 1277,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1938,
"s": 1342,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"I want THIS and THIS to be CLICKED!\"\n android:layout_centerInParent=\"true\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold|italic\"/>\n</RelativeLayout>"
},
{
"code": null,
"e": 1995,
"s": 1938,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3769,
"s": 1995,
"text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.text.SpannableString;\nimport android.text.Spanned;\nimport android.text.method.LinkMovementMethod;\nimport android.text.style.ClickableSpan;\nimport android.view.View;\nimport android.widget.TextView;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.textView);\n String text = \"I want THIS and THIS to be CLICKED\";\n SpannableString spannableString = new SpannableString(text);\n ClickableSpan clickableSpan1 = new ClickableSpan() {\n @Override\n public void onClick(View widget) {\n Toast.makeText(MainActivity.this, \"THIS\", Toast.LENGTH_SHORT).show();\n }\n };\n ClickableSpan clickableSpan2 = new ClickableSpan() {\n @Override\n public void onClick(View widget) {\n Toast.makeText(MainActivity.this, \"THIS\", Toast.LENGTH_SHORT).show();\n }\n };\n ClickableSpan clickableSpan3 = new ClickableSpan() {\n @Override\n public void onClick(View widget) {\n Toast.makeText(MainActivity.this, \"CLICKED\", Toast.LENGTH_SHORT).show();\n }\n };\n spannableString.setSpan(clickableSpan1, 7,11, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);\n spannableString.setSpan(clickableSpan2, 16,20, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);\n spannableString.setSpan(clickableSpan3, 27,34, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);\n textView.setText(spannableString);\n textView.setMovementMethod(LinkMovementMethod.getInstance());\n }\n}"
},
{
"code": null,
"e": 3824,
"s": 3769,
"text": "Step 4 - Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4494,
"s": 3824,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4841,
"s": 4494,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
},
{
"code": null,
"e": 4882,
"s": 4841,
"text": "Click here to download the project code."
}
] |
Apache Presto - current_date() | presto:default> select current_date as date;
Date
------------
2016-07-06
The query returns the current date.
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2051,
"s": 2006,
"text": "presto:default> select current_date as date;"
},
{
"code": null,
"e": 2088,
"s": 2051,
"text": " Date \n------------ \n 2016-07-06 \n"
},
{
"code": null,
"e": 2124,
"s": 2088,
"text": "The query returns the current date."
},
{
"code": null,
"e": 2159,
"s": 2124,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 2178,
"s": 2159,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 2213,
"s": 2178,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 2234,
"s": 2213,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 2267,
"s": 2234,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 2280,
"s": 2267,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 2315,
"s": 2280,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 2333,
"s": 2315,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 2366,
"s": 2333,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 2384,
"s": 2366,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 2417,
"s": 2384,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 2435,
"s": 2417,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 2442,
"s": 2435,
"text": " Print"
},
{
"code": null,
"e": 2453,
"s": 2442,
"text": " Add Notes"
}
] |
Karger’s algorithm for Minimum Cut | Set 2 (Analysis and Applications) - GeeksforGeeks | 10 May, 2016
We have introduced and discussed below Karger’s algorithm in set 1.
1) Initialize contracted graph CG as copy of original graph
2) While there are more than 2 vertices.
a) Pick a random edge (u, v) in the contracted graph.
b) Merge (or contract) u and v into a single vertex (update
the contracted graph).
c) Remove self-loops
3) Return cut represented by two vertices.
As discussed in the previous post, Karger’s algorithm doesn’t always find min cut. In this post, the probability of finding min-cut is discussed.
Probability that the cut produced by Karger’s Algorithm is Min-Cut is greater than or equal to 1/(n2)
Proof:Let there be a unique Min-Cut of given graph and let there be C edges in the Min-Cut and the edges be {e1, e2, e3, .. ec}. The Karger’s algorithm would produce this Min-Cut if and only if none of the edges in set {e1, e2, e3, .. ec} is removed in iterations in the main while loop of above algorithm.
c is number of edges in min-cut
m is total number of edges
n is total number of vertices
S1 = Event that one of the edges in {e1, e2,
e3, .. ec} is chosen in 1st iteration.
S2 = Event that one of the edges in {e1, e2,
e3, .. ec} is chosen in 2nd iteration.
S3 = Event that one of the edges in {e1, e2,
e3, .. ec} is chosen in 3rd iteration.
..................
..................
The cut produced by Karger's algorithm would be a min-cut if none of the above
events happen.
So the required probability is P[S1' ∩ S2' ∩ S3' ∩ ............]
Probability that a min-cut edge is chosen in first iteration:
Let us calculate P[S1']
P[S1] = c/m
P[S1'] = (1 - c/m)
Above value is in terms of m (or edges), let us convert
it in terms of n (or vertices) using below 2 facts..
1) Since size of min-cut is c, degree of all vertices must be greater
than or equal to c.
2) As per Handshaking Lemma, sum of degrees of all vertices = 2m
From above two facts, we can conclude below.
n*c <= 2m
m >= nc/2
P[S1] <= c / (cn/2)
<= 2/n
P[S1] <= c / (cn/2)
<= 2/n
P[S1'] >= (1-2/n) ------------(1)
Probability that a min-cut edge is chosen in second iteration:
P[S1' ∩ S2'] = P[S2' | S1' ] * P[S1']
In the above expression, we know value of P[S1'] >= (1-2/n)
P[S2' | S1'] is conditional probability that is, a min cut is
not chosen in second iteration given that it is not chosen in first iteration
Since there are total (n-1) edges left now and number of cut edges is still c,
we can replace n by n-1 in inequality (1). So we get.
P[S2' | S1' ] >= (1 - 2/(n-1))
P[S1' ∩ S2'] >= (1-2/n) x (1-2/(n-1))
Probability that a min-cut edge is chosen in all iterations:
P[S1' ∩ S2' ∩ S3' ∩.......... ∩ Sn-2']
>= [1 - 2/n] * [1 - 2/(n-1)] * [1 - 2/(n-2)] * [1 - 2/(n-3)] *...
... * [1 - 2/(n - (n-4)] * [1 - 2/(n - (n-3)]
>= [(n-2)/n] * [(n-3)/(n-1)] * [(n-4)/(n-2)] * .... 2/4 * 2/3
>= 2/(n * (n-1))
>= 1/n2
How to increase probability of success?The above probability of success of basic algorithm is very less. For example, for a graph with 10 nodes, the probability of finding the min-cut is greater than or equal to 1/100. The probability can be increased by repeated runs of basic algorithm and return minimum of all cuts found.
Applications:1) In war situation, a party would be interested in finding minimum number of links that break communication network of enemy.
2) The min-cut problem can be used to study reliability of a network (smallest number of edges that can fail).
3) Study of network optimization (find a maximum flow).
4) Clustering problems (edges like associations rules) Matching problems (an NC algorithm for min-cut in directed graphs would result in an NC algorithm for maximum matching in bipartite graphs)
5) Matching problems (an NC algorithm for min-cut in directed graphs would result in an NC algorithm for maximum matching in bipartite graphs)
Sources:https://www.youtube.com/watch?v=-UuivvyHPashttp://disi.unal.edu.co/~gjhernandezp/psc/lectures/02/MinCut.pdf
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Graph
Randomized
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Topological Sorting
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Detect Cycle in a Directed Graph
QuickSort using Random Pivoting
K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)
Shuffle a given array using Fisher–Yates shuffle Algorithm
Reservoir Sampling
Random Walk (Implementation in Python) | [
{
"code": null,
"e": 24661,
"s": 24633,
"text": "\n10 May, 2016"
},
{
"code": null,
"e": 24729,
"s": 24661,
"text": "We have introduced and discussed below Karger’s algorithm in set 1."
},
{
"code": null,
"e": 25061,
"s": 24729,
"text": "1) Initialize contracted graph CG as copy of original graph\n2) While there are more than 2 vertices.\n a) Pick a random edge (u, v) in the contracted graph.\n b) Merge (or contract) u and v into a single vertex (update \n the contracted graph).\n c) Remove self-loops\n3) Return cut represented by two vertices."
},
{
"code": null,
"e": 25207,
"s": 25061,
"text": "As discussed in the previous post, Karger’s algorithm doesn’t always find min cut. In this post, the probability of finding min-cut is discussed."
},
{
"code": null,
"e": 25309,
"s": 25207,
"text": "Probability that the cut produced by Karger’s Algorithm is Min-Cut is greater than or equal to 1/(n2)"
},
{
"code": null,
"e": 25616,
"s": 25309,
"text": "Proof:Let there be a unique Min-Cut of given graph and let there be C edges in the Min-Cut and the edges be {e1, e2, e3, .. ec}. The Karger’s algorithm would produce this Min-Cut if and only if none of the edges in set {e1, e2, e3, .. ec} is removed in iterations in the main while loop of above algorithm."
},
{
"code": null,
"e": 26177,
"s": 25616,
"text": "c is number of edges in min-cut\nm is total number of edges\nn is total number of vertices\n\nS1 = Event that one of the edges in {e1, e2, \n e3, .. ec} is chosen in 1st iteration.\nS2 = Event that one of the edges in {e1, e2, \n e3, .. ec} is chosen in 2nd iteration.\nS3 = Event that one of the edges in {e1, e2, \n e3, .. ec} is chosen in 3rd iteration.\n\n..................\n..................\n\nThe cut produced by Karger's algorithm would be a min-cut if none of the above\nevents happen.\n\nSo the required probability is P[S1' ∩ S2' ∩ S3' ∩ ............]"
},
{
"code": null,
"e": 26239,
"s": 26177,
"text": "Probability that a min-cut edge is chosen in first iteration:"
},
{
"code": null,
"e": 26752,
"s": 26239,
"text": "Let us calculate P[S1']\nP[S1] = c/m\nP[S1'] = (1 - c/m)\n\nAbove value is in terms of m (or edges), let us convert \nit in terms of n (or vertices) using below 2 facts.. \n\n1) Since size of min-cut is c, degree of all vertices must be greater \nthan or equal to c. \n\n2) As per Handshaking Lemma, sum of degrees of all vertices = 2m\n\nFrom above two facts, we can conclude below.\n n*c <= 2m\n m >= nc/2\n\n P[S1] <= c / (cn/2)\n <= 2/n\n\n P[S1] <= c / (cn/2)\n <= 2/n\n\n P[S1'] >= (1-2/n) ------------(1)"
},
{
"code": null,
"e": 26815,
"s": 26752,
"text": "Probability that a min-cut edge is chosen in second iteration:"
},
{
"code": null,
"e": 27269,
"s": 26815,
"text": "\nP[S1' ∩ S2'] = P[S2' | S1' ] * P[S1']\n\nIn the above expression, we know value of P[S1'] >= (1-2/n)\n\nP[S2' | S1'] is conditional probability that is, a min cut is \nnot chosen in second iteration given that it is not chosen in first iteration\n\nSince there are total (n-1) edges left now and number of cut edges is still c,\nwe can replace n by n-1 in inequality (1). So we get.\n P[S2' | S1' ] >= (1 - 2/(n-1)) \n\n P[S1' ∩ S2'] >= (1-2/n) x (1-2/(n-1))"
},
{
"code": null,
"e": 27330,
"s": 27269,
"text": "Probability that a min-cut edge is chosen in all iterations:"
},
{
"code": null,
"e": 27605,
"s": 27330,
"text": "\nP[S1' ∩ S2' ∩ S3' ∩.......... ∩ Sn-2']\n\n>= [1 - 2/n] * [1 - 2/(n-1)] * [1 - 2/(n-2)] * [1 - 2/(n-3)] *...\n ... * [1 - 2/(n - (n-4)] * [1 - 2/(n - (n-3)]\n\n>= [(n-2)/n] * [(n-3)/(n-1)] * [(n-4)/(n-2)] * .... 2/4 * 2/3\n\n>= 2/(n * (n-1))\n>= 1/n2 "
},
{
"code": null,
"e": 27931,
"s": 27605,
"text": "How to increase probability of success?The above probability of success of basic algorithm is very less. For example, for a graph with 10 nodes, the probability of finding the min-cut is greater than or equal to 1/100. The probability can be increased by repeated runs of basic algorithm and return minimum of all cuts found."
},
{
"code": null,
"e": 28071,
"s": 27931,
"text": "Applications:1) In war situation, a party would be interested in finding minimum number of links that break communication network of enemy."
},
{
"code": null,
"e": 28182,
"s": 28071,
"text": "2) The min-cut problem can be used to study reliability of a network (smallest number of edges that can fail)."
},
{
"code": null,
"e": 28238,
"s": 28182,
"text": "3) Study of network optimization (find a maximum flow)."
},
{
"code": null,
"e": 28433,
"s": 28238,
"text": "4) Clustering problems (edges like associations rules) Matching problems (an NC algorithm for min-cut in directed graphs would result in an NC algorithm for maximum matching in bipartite graphs)"
},
{
"code": null,
"e": 28576,
"s": 28433,
"text": "5) Matching problems (an NC algorithm for min-cut in directed graphs would result in an NC algorithm for maximum matching in bipartite graphs)"
},
{
"code": null,
"e": 28692,
"s": 28576,
"text": "Sources:https://www.youtube.com/watch?v=-UuivvyHPashttp://disi.unal.edu.co/~gjhernandezp/psc/lectures/02/MinCut.pdf"
},
{
"code": null,
"e": 28817,
"s": 28692,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 28823,
"s": 28817,
"text": "Graph"
},
{
"code": null,
"e": 28834,
"s": 28823,
"text": "Randomized"
},
{
"code": null,
"e": 28840,
"s": 28834,
"text": "Graph"
},
{
"code": null,
"e": 28938,
"s": 28840,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28947,
"s": 28938,
"text": "Comments"
},
{
"code": null,
"e": 28960,
"s": 28947,
"text": "Old Comments"
},
{
"code": null,
"e": 29018,
"s": 28960,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 29038,
"s": 29018,
"text": "Topological Sorting"
},
{
"code": null,
"e": 29069,
"s": 29038,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 29102,
"s": 29069,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 29135,
"s": 29102,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 29167,
"s": 29135,
"text": "QuickSort using Random Pivoting"
},
{
"code": null,
"e": 29246,
"s": 29167,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)"
},
{
"code": null,
"e": 29305,
"s": 29246,
"text": "Shuffle a given array using Fisher–Yates shuffle Algorithm"
},
{
"code": null,
"e": 29324,
"s": 29305,
"text": "Reservoir Sampling"
}
] |
Containers in C++ STL | In this tutorial, we will be discussing a program to understand containers in C++ STL.
Containers are the objects used to store multiple elements of the same type or different. Depending on that they can be further classified as −
Sequence containers (array, vector, list)
Sequence containers (array, vector, list)
Associative containers (set, map, multimap)
Associative containers (set, map, multimap)
Unordered Associative containers (unordered_set, unordered_map)
Unordered Associative containers (unordered_set, unordered_map)
Container Adapters (stack, queue)
Container Adapters (stack, queue)
Live Demo
#include <iostream>
using namespace std;
int main(){
int array[10] = {1,2,3,4};
for(int i=0; i<10; i++){
cout << array[i] << " ";
}
return 0;
}
1 2 3 4 0 0 0 0 0 0 | [
{
"code": null,
"e": 1149,
"s": 1062,
"text": "In this tutorial, we will be discussing a program to understand containers in C++ STL."
},
{
"code": null,
"e": 1293,
"s": 1149,
"text": "Containers are the objects used to store multiple elements of the same type or different. Depending on that they can be further classified as −"
},
{
"code": null,
"e": 1335,
"s": 1293,
"text": "Sequence containers (array, vector, list)"
},
{
"code": null,
"e": 1377,
"s": 1335,
"text": "Sequence containers (array, vector, list)"
},
{
"code": null,
"e": 1421,
"s": 1377,
"text": "Associative containers (set, map, multimap)"
},
{
"code": null,
"e": 1465,
"s": 1421,
"text": "Associative containers (set, map, multimap)"
},
{
"code": null,
"e": 1529,
"s": 1465,
"text": "Unordered Associative containers (unordered_set, unordered_map)"
},
{
"code": null,
"e": 1593,
"s": 1529,
"text": "Unordered Associative containers (unordered_set, unordered_map)"
},
{
"code": null,
"e": 1627,
"s": 1593,
"text": "Container Adapters (stack, queue)"
},
{
"code": null,
"e": 1661,
"s": 1627,
"text": "Container Adapters (stack, queue)"
},
{
"code": null,
"e": 1672,
"s": 1661,
"text": " Live Demo"
},
{
"code": null,
"e": 1834,
"s": 1672,
"text": "#include <iostream>\nusing namespace std;\nint main(){\n int array[10] = {1,2,3,4};\n for(int i=0; i<10; i++){\n cout << array[i] << \" \";\n }\n return 0;\n}"
},
{
"code": null,
"e": 1854,
"s": 1834,
"text": "1 2 3 4 0 0 0 0 0 0"
}
] |
Maximum Weight Difference in C++ Program | In this problem, we are given an array arr[] and a number M. Our task is to
create a program to calculate the Maximum Weight Difference in C++.
We will find M elements from the array such that the absolute difference
between the sum and the sum of the rest elements is maximum.
Let’s take an example to understand the problem,
arr[] = {3, 1, 6, 9, 4} M = 3
15
We will consider 4,6,9. The sum is 19. The absolute difference with the sum
of rest numbers is
|19 − 4| = 15
A simple solution to the problem is by finding all subsequences of the array,
finding the sum elements of the subarray, and the rest. And return the
maximum difference.
A more efficient solution is found by using the fact that maximum weight
difference i.e. difference of the sum of elements and the rest is maximum if
we consider m maximum elements or m minimum elements for
subsequence.
So, we will check for the maximum sum difference for a subsequence of m
largest elements and rest array or subsequence of m smallest elements and
rest array.
And return the maximum of both.
Initialize −
maxSum , maxSumDiff, minSumDiff
Step 1 −
sort the array in descending order.
Step 2 −
Loop for i −> 0 to n
Step 2.1 −
if (i < m) −> maxSumDiff += arr[i]
Step 2.2 −
else −> maxSumDiff −= arr[i]
Step 2 −
Loop for i −> n to 0
Step 2.1 −
if (i > m) −> minSumDiff += arr[i]
Step 2.2 −
else −> minSumDiff −= arr[i]
Step 3 −
if maxSumDiff > minSumDiff −> maxSum = maxSumDiff.
Step 4 −
if maxSumDiff < minSumDiff −> maxSum = minSumDiff.
Step 5 −
return maxSum.
Program to illustrate the working of our solution,
Live Demo
#include <bits/stdc++.h>
using namespace std;
int maxWeightDifference(int arr[], int N, int M){
int maxabsDiff = −1000;
sort(arr, arr + N);
int sumMin = 0, sumMax = 0, arrSum = 0;
for(int i = 0; i < N; i++){
arrSum += arr[i];
if(i < M)
sumMin += arr[i];
if(i >= (N−M))
sumMax += arr[i];
}
maxabsDiff = max(abs(sumMax − (arrSum − sumMax)), abs(sumMin −
(arrSum − sumMin)));
return maxabsDiff;
}
int main(){
int arr[] = {3, 1, 6, 9, 4} ;
int M = 3;
int N = sizeof(arr)/sizeof(arr[0]);
cout<<"The maximum weight difference is "<<maxWeightDifference(arr,N, M);
return 0;
}
The maximum weight difference is 15 | [
{
"code": null,
"e": 1206,
"s": 1062,
"text": "In this problem, we are given an array arr[] and a number M. Our task is to\ncreate a program to calculate the Maximum Weight Difference in C++."
},
{
"code": null,
"e": 1340,
"s": 1206,
"text": "We will find M elements from the array such that the absolute difference\nbetween the sum and the sum of the rest elements is maximum."
},
{
"code": null,
"e": 1389,
"s": 1340,
"text": "Let’s take an example to understand the problem,"
},
{
"code": null,
"e": 1419,
"s": 1389,
"text": "arr[] = {3, 1, 6, 9, 4} M = 3"
},
{
"code": null,
"e": 1422,
"s": 1419,
"text": "15"
},
{
"code": null,
"e": 1517,
"s": 1422,
"text": "We will consider 4,6,9. The sum is 19. The absolute difference with the sum\nof rest numbers is"
},
{
"code": null,
"e": 1531,
"s": 1517,
"text": "|19 − 4| = 15"
},
{
"code": null,
"e": 1700,
"s": 1531,
"text": "A simple solution to the problem is by finding all subsequences of the array,\nfinding the sum elements of the subarray, and the rest. And return the\nmaximum difference."
},
{
"code": null,
"e": 1920,
"s": 1700,
"text": "A more efficient solution is found by using the fact that maximum weight\ndifference i.e. difference of the sum of elements and the rest is maximum if\nwe consider m maximum elements or m minimum elements for\nsubsequence."
},
{
"code": null,
"e": 2078,
"s": 1920,
"text": "So, we will check for the maximum sum difference for a subsequence of m\nlargest elements and rest array or subsequence of m smallest elements and\nrest array."
},
{
"code": null,
"e": 2110,
"s": 2078,
"text": "And return the maximum of both."
},
{
"code": null,
"e": 2123,
"s": 2110,
"text": "Initialize −"
},
{
"code": null,
"e": 2155,
"s": 2123,
"text": "maxSum , maxSumDiff, minSumDiff"
},
{
"code": null,
"e": 2164,
"s": 2155,
"text": "Step 1 −"
},
{
"code": null,
"e": 2200,
"s": 2164,
"text": "sort the array in descending order."
},
{
"code": null,
"e": 2209,
"s": 2200,
"text": "Step 2 −"
},
{
"code": null,
"e": 2230,
"s": 2209,
"text": "Loop for i −> 0 to n"
},
{
"code": null,
"e": 2241,
"s": 2230,
"text": "Step 2.1 −"
},
{
"code": null,
"e": 2276,
"s": 2241,
"text": "if (i < m) −> maxSumDiff += arr[i]"
},
{
"code": null,
"e": 2287,
"s": 2276,
"text": "Step 2.2 −"
},
{
"code": null,
"e": 2316,
"s": 2287,
"text": "else −> maxSumDiff −= arr[i]"
},
{
"code": null,
"e": 2325,
"s": 2316,
"text": "Step 2 −"
},
{
"code": null,
"e": 2346,
"s": 2325,
"text": "Loop for i −> n to 0"
},
{
"code": null,
"e": 2357,
"s": 2346,
"text": "Step 2.1 −"
},
{
"code": null,
"e": 2392,
"s": 2357,
"text": "if (i > m) −> minSumDiff += arr[i]"
},
{
"code": null,
"e": 2403,
"s": 2392,
"text": "Step 2.2 −"
},
{
"code": null,
"e": 2432,
"s": 2403,
"text": "else −> minSumDiff −= arr[i]"
},
{
"code": null,
"e": 2441,
"s": 2432,
"text": "Step 3 −"
},
{
"code": null,
"e": 2492,
"s": 2441,
"text": "if maxSumDiff > minSumDiff −> maxSum = maxSumDiff."
},
{
"code": null,
"e": 2501,
"s": 2492,
"text": "Step 4 −"
},
{
"code": null,
"e": 2552,
"s": 2501,
"text": "if maxSumDiff < minSumDiff −> maxSum = minSumDiff."
},
{
"code": null,
"e": 2561,
"s": 2552,
"text": "Step 5 −"
},
{
"code": null,
"e": 2576,
"s": 2561,
"text": "return maxSum."
},
{
"code": null,
"e": 2627,
"s": 2576,
"text": "Program to illustrate the working of our solution,"
},
{
"code": null,
"e": 2638,
"s": 2627,
"text": " Live Demo"
},
{
"code": null,
"e": 3282,
"s": 2638,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nint maxWeightDifference(int arr[], int N, int M){\n int maxabsDiff = −1000;\n sort(arr, arr + N);\n int sumMin = 0, sumMax = 0, arrSum = 0;\n for(int i = 0; i < N; i++){\n arrSum += arr[i];\n if(i < M)\n sumMin += arr[i];\n if(i >= (N−M))\n sumMax += arr[i];\n }\n maxabsDiff = max(abs(sumMax − (arrSum − sumMax)), abs(sumMin −\n (arrSum − sumMin)));\n return maxabsDiff;\n}\nint main(){\n int arr[] = {3, 1, 6, 9, 4} ;\n int M = 3;\n int N = sizeof(arr)/sizeof(arr[0]);\n cout<<\"The maximum weight difference is \"<<maxWeightDifference(arr,N, M);\n return 0;\n}"
},
{
"code": null,
"e": 3318,
"s": 3282,
"text": "The maximum weight difference is 15"
}
] |
Insertion Sort Program in C | This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained which is always sorted. For example, the lower part of an array is maintained to be sorted. An element which is to be 'insert'ed in this sorted sub-list, has to find its appropriate place and then it is to be inserted there. Hence the name insertion sort.
#include <stdio.h>
#include <stdbool.h>
#define MAX 7
int intArray[MAX] = {4,6,3,2,1,9,7};
void printline(int count) {
int i;
for(i = 0;i < count-1;i++) {
printf("=");
}
printf("=\n");
}
void display() {
int i;
printf("[");
// navigate through all items
for(i = 0;i < MAX;i++) {
printf("%d ",intArray[i]);
}
printf("]\n");
}
void insertionSort() {
int valueToInsert;
int holePosition;
int i;
// loop through all numbers
for(i = 1; i < MAX; i++) {
// select a value to be inserted.
valueToInsert = intArray[i];
// select the hole position where number is to be inserted
holePosition = i;
// check if previous no. is larger than value to be inserted
while (holePosition > 0 && intArray[holePosition-1] > valueToInsert) {
intArray[holePosition] = intArray[holePosition-1];
holePosition--;
printf(" item moved : %d\n" , intArray[holePosition]);
}
if(holePosition != i) {
printf(" item inserted : %d, at position : %d\n" , valueToInsert,holePosition);
// insert the number at hole position
intArray[holePosition] = valueToInsert;
}
printf("Iteration %d#:",i);
display();
}
}
void main() {
printf("Input Array: ");
display();
printline(50);
insertionSort();
printf("Output Array: ");
display();
printline(50);
}
If we compile and run the above program, it will produce the following result −
Input Array: [4 6 3 2 1 9 7 ]
==================================================
Iteration 1#:[4 6 3 2 1 9 7 ]
item moved : 6
item moved : 4
item inserted : 3, at position : 0
Iteration 2#:[3 4 6 2 1 9 7 ]
item moved : 6
item moved : 4
item moved : 3
item inserted : 2, at position : 0
Iteration 3#:[2 3 4 6 1 9 7 ]
item moved : 6
item moved : 4
item moved : 3
item moved : 2
item inserted : 1, at position : 0
Iteration 4#:[1 2 3 4 6 9 7 ]
Iteration 5#:[1 2 3 4 6 9 7 ]
item moved : 9
item inserted : 7, at position : 5
Iteration 6#:[1 2 3 4 6 7 9 ]
Output Array: [1 2 3 4 6 7 9 ]
==================================================
42 Lectures
1.5 hours
Ravi Kiran
141 Lectures
13 hours
Arnab Chakraborty
26 Lectures
8.5 hours
Parth Panjabi
65 Lectures
6 hours
Arnab Chakraborty
75 Lectures
13 hours
Eduonix Learning Solutions
64 Lectures
10.5 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2923,
"s": 2580,
"text": "This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained which is always sorted. For example, the lower part of an array is maintained to be sorted. An element which is to be 'insert'ed in this sorted sub-list, has to find its appropriate place and then it is to be inserted there. Hence the name insertion sort."
},
{
"code": null,
"e": 4370,
"s": 2923,
"text": "#include <stdio.h>\n#include <stdbool.h>\n\n#define MAX 7\n\nint intArray[MAX] = {4,6,3,2,1,9,7};\n\nvoid printline(int count) {\n int i;\n\t\n for(i = 0;i < count-1;i++) {\n printf(\"=\");\n }\n\t\n printf(\"=\\n\");\n}\n\nvoid display() {\n int i;\n printf(\"[\");\n\t\n // navigate through all items \n for(i = 0;i < MAX;i++) {\n printf(\"%d \",intArray[i]);\n }\n\t\n printf(\"]\\n\");\n}\n\nvoid insertionSort() {\n\n int valueToInsert;\n int holePosition;\n int i;\n \n // loop through all numbers \n for(i = 1; i < MAX; i++) { \n\t\n // select a value to be inserted. \n valueToInsert = intArray[i];\n\t\t\n // select the hole position where number is to be inserted \n holePosition = i;\n\t\t\n // check if previous no. is larger than value to be inserted \n while (holePosition > 0 && intArray[holePosition-1] > valueToInsert) {\n intArray[holePosition] = intArray[holePosition-1];\n holePosition--;\n printf(\" item moved : %d\\n\" , intArray[holePosition]);\n }\n\n if(holePosition != i) {\n printf(\" item inserted : %d, at position : %d\\n\" , valueToInsert,holePosition);\n // insert the number at hole position \n intArray[holePosition] = valueToInsert;\n }\n\n printf(\"Iteration %d#:\",i);\n display();\n\t\t\n } \n}\n\nvoid main() {\n printf(\"Input Array: \");\n display();\n printline(50);\n insertionSort();\n printf(\"Output Array: \");\n display();\n printline(50);\n}"
},
{
"code": null,
"e": 4450,
"s": 4370,
"text": "If we compile and run the above program, it will produce the following result −"
},
{
"code": null,
"e": 5098,
"s": 4450,
"text": "Input Array: [4 6 3 2 1 9 7 ]\n==================================================\nIteration 1#:[4 6 3 2 1 9 7 ]\n item moved : 6\n item moved : 4\n item inserted : 3, at position : 0\nIteration 2#:[3 4 6 2 1 9 7 ]\n item moved : 6\n item moved : 4\n item moved : 3\n item inserted : 2, at position : 0\nIteration 3#:[2 3 4 6 1 9 7 ]\n item moved : 6\n item moved : 4\n item moved : 3\n item moved : 2\n item inserted : 1, at position : 0\nIteration 4#:[1 2 3 4 6 9 7 ]\nIteration 5#:[1 2 3 4 6 9 7 ]\n item moved : 9\n item inserted : 7, at position : 5\nIteration 6#:[1 2 3 4 6 7 9 ]\nOutput Array: [1 2 3 4 6 7 9 ]\n==================================================\n"
},
{
"code": null,
"e": 5133,
"s": 5098,
"text": "\n 42 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5145,
"s": 5133,
"text": " Ravi Kiran"
},
{
"code": null,
"e": 5180,
"s": 5145,
"text": "\n 141 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5199,
"s": 5180,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5234,
"s": 5199,
"text": "\n 26 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 5249,
"s": 5234,
"text": " Parth Panjabi"
},
{
"code": null,
"e": 5282,
"s": 5249,
"text": "\n 65 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5301,
"s": 5282,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5335,
"s": 5301,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5363,
"s": 5335,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5399,
"s": 5363,
"text": "\n 64 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 5427,
"s": 5399,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5434,
"s": 5427,
"text": " Print"
},
{
"code": null,
"e": 5445,
"s": 5434,
"text": " Add Notes"
}
] |
C Program to Compute Quotient and Remainder? | Given two numbers dividend and divisor. The task is to write a program to find the quotient and remainder of these two numbers when the dividend is divided by the divisor.
In division, we will see the relationship between the dividend, divisor, quotient, and remainder. The number which we divide is called the dividend. The number by which we divide is called the divisor. The result obtained is called the quotient. The number left over is called the remainder.
55 ÷ 9 = 6 and 1
Dividend Divisor Quotient Remainder
Input:
Dividend = 6
Divisor = 2
Output:
Quotient = 3,
Remainder = 0
Then, the variables Dividend and Divisor are divided using the arithmetic operator / to get the quotient as result stored in the variable quotient; and using the arithmetic operator % to get the remainder as result stored in the variable remainder.
#include <stdio.h>
int main() {
int dividend, divisor, quotient, remainder;
dividend= 2;
divisor= 6;
// Computes quotient
quotient = dividend / divisor;
// Computes remainder
remainder = dividend % divisor;
printf("Quotient = %d\n", quotient);
printf("Remainder = %d", remainder);
return 0;
} | [
{
"code": null,
"e": 1234,
"s": 1062,
"text": "Given two numbers dividend and divisor. The task is to write a program to find the quotient and remainder of these two numbers when the dividend is divided by the divisor."
},
{
"code": null,
"e": 1526,
"s": 1234,
"text": "In division, we will see the relationship between the dividend, divisor, quotient, and remainder. The number which we divide is called the dividend. The number by which we divide is called the divisor. The result obtained is called the quotient. The number left over is called the remainder."
},
{
"code": null,
"e": 1579,
"s": 1526,
"text": "55 ÷ 9 = 6 and 1\nDividend Divisor Quotient Remainder"
},
{
"code": null,
"e": 1647,
"s": 1579,
"text": "Input:\nDividend = 6\nDivisor = 2\nOutput:\nQuotient = 3,\nRemainder = 0"
},
{
"code": null,
"e": 1896,
"s": 1647,
"text": "Then, the variables Dividend and Divisor are divided using the arithmetic operator / to get the quotient as result stored in the variable quotient; and using the arithmetic operator % to get the remainder as result stored in the variable remainder."
},
{
"code": null,
"e": 2219,
"s": 1896,
"text": "#include <stdio.h>\nint main() {\n int dividend, divisor, quotient, remainder;\n dividend= 2;\n divisor= 6;\n // Computes quotient\n quotient = dividend / divisor;\n // Computes remainder\n remainder = dividend % divisor;\n printf(\"Quotient = %d\\n\", quotient);\n printf(\"Remainder = %d\", remainder);\n return 0;\n}"
}
] |
wxPython - Multiple Document Interface | A typical GUI application may have multiple windows. Tabbed and stacked widgets allow to activate one such window at a time. However, many a times this approach may not be useful as view of other windows is hidden.
One way to display multiple windows simultaneously is to create them as independent windows. This is called as SDI (Single Document Interface). This requires more memory resources as each window may have its own menu system, toolbar, etc.
MDI framework in wxPython provides a wx.MDIParentFrame class. Its object acts as a container for multiple child windows, each an object of wx.MDIChildFrame class.
Child windows reside in the MDIClientWindow area of the parent frame. As soon as a child frame is added, the menu bar of the parent frame shows a Window menu containing buttons to arrange the children in a cascaded or tiled manner.
The following example illustrates the uses of MDIParentFrame as top level window. A Menu button called NewWindow adds a child window in the client area. Multiple windows can be added and then arranged in a cascaded or tiled order.
The complete code is as follows −
import wx
class MDIFrame(wx.MDIParentFrame):
def __init__(self):
wx.MDIParentFrame.__init__(self, None, -1, "MDI Parent", size = (600,400))
menu = wx.Menu()
menu.Append(5000, "&New Window")
menu.Append(5001, "&Exit")
menubar = wx.MenuBar()
menubar.Append(menu, "&File")
self.SetMenuBar(menubar)
self.Bind(wx.EVT_MENU, self.OnNewWindow, id = 5000)
self.Bind(wx.EVT_MENU, self.OnExit, id = 5001)
def OnExit(self, evt):
self.Close(True)
def OnNewWindow(self, evt):
win = wx.MDIChildFrame(self, -1, "Child Window")
win.Show(True)
app = wx.App()
frame = MDIFrame()
frame.Show()
app.MainLoop()
The above code produces the following output −
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2097,
"s": 1882,
"text": "A typical GUI application may have multiple windows. Tabbed and stacked widgets allow to activate one such window at a time. However, many a times this approach may not be useful as view of other windows is hidden."
},
{
"code": null,
"e": 2336,
"s": 2097,
"text": "One way to display multiple windows simultaneously is to create them as independent windows. This is called as SDI (Single Document Interface). This requires more memory resources as each window may have its own menu system, toolbar, etc."
},
{
"code": null,
"e": 2499,
"s": 2336,
"text": "MDI framework in wxPython provides a wx.MDIParentFrame class. Its object acts as a container for multiple child windows, each an object of wx.MDIChildFrame class."
},
{
"code": null,
"e": 2731,
"s": 2499,
"text": "Child windows reside in the MDIClientWindow area of the parent frame. As soon as a child frame is added, the menu bar of the parent frame shows a Window menu containing buttons to arrange the children in a cascaded or tiled manner."
},
{
"code": null,
"e": 2962,
"s": 2731,
"text": "The following example illustrates the uses of MDIParentFrame as top level window. A Menu button called NewWindow adds a child window in the client area. Multiple windows can be added and then arranged in a cascaded or tiled order."
},
{
"code": null,
"e": 2996,
"s": 2962,
"text": "The complete code is as follows −"
},
{
"code": null,
"e": 3699,
"s": 2996,
"text": "import wx \n \nclass MDIFrame(wx.MDIParentFrame): \n def __init__(self): \n wx.MDIParentFrame.__init__(self, None, -1, \"MDI Parent\", size = (600,400)) \n menu = wx.Menu() \n menu.Append(5000, \"&New Window\") \n menu.Append(5001, \"&Exit\") \n menubar = wx.MenuBar() \n menubar.Append(menu, \"&File\") \n\t\t\n self.SetMenuBar(menubar) \n self.Bind(wx.EVT_MENU, self.OnNewWindow, id = 5000) \n self.Bind(wx.EVT_MENU, self.OnExit, id = 5001) \n\t\t\n def OnExit(self, evt): \n self.Close(True) \n\t\t\n def OnNewWindow(self, evt): \n win = wx.MDIChildFrame(self, -1, \"Child Window\")\n win.Show(True) \n\t\t\napp = wx.App() \nframe = MDIFrame() \nframe.Show() \napp.MainLoop()"
},
{
"code": null,
"e": 3746,
"s": 3699,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 3753,
"s": 3746,
"text": " Print"
},
{
"code": null,
"e": 3764,
"s": 3753,
"text": " Add Notes"
}
] |
WPF - Resources | Resources are normally definitions connected with some object that you just anticipate to use more often than once. It is the ability to store data locally for controls or for the current window or globally for the entire applications.
Defining an object as a resource allows us to access it from another place. What it means is that the object can be reused. Resources are defined in resource dictionaries and any object can be defined as a resource effectively making it a shareable asset. A unique key is specified to an XAML resource and with that key, it can be referenced by using a StaticResource markup extension.
Resources can be of two types −
StaticResource
DynamicResource
A StaticResource is a onetime lookup, whereas a DynamicResource works more like a data binding. It remembers that a property is associated with a particular resource key. If the object associated with that key changes, dynamic resource will update the target property.
Here's a simple application for the SolidColorBrush resource.
Let’s create a new WPF project with the name WPFResouces.
Let’s create a new WPF project with the name WPFResouces.
Drag two Rectangles and set their properties as shown in the following XAML code.
Drag two Rectangles and set their properties as shown in the following XAML code.
<Window x:Class = "WPFResources.MainWindow"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local = "clr-namespace:WPFResources"
mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "525">
<Window.Resources>
<SolidColorBrush x:Key = "brushResource" Color = "Blue" />
</Window.Resources>
<StackPanel>
<Rectangle Height = "50" Margin = "20" Fill = "{StaticResource brushResource}" />
<Rectangle Height = "50" Margin = "20" Fill = "{DynamicResource brushResource}" />
<Button x:Name = "changeResourceButton"
Content = "_Change Resource" Click = "changeResourceButton_Click" />
</StackPanel>
</Window>
In the above XAML code, you can see that one rectangle has StaticResource and the other one has DynamicResource and the color of brushResource is Bisque.
In the above XAML code, you can see that one rectangle has StaticResource and the other one has DynamicResource and the color of brushResource is Bisque.
When you compile and execute the code, it will produce the following MainWindow.
When you compile and execute the code, it will produce the following MainWindow.
When you click the "Change Resource" button, you will see that the rectangle with DynamicResource will change its color to Red.
Resources are defined in resource dictionaries, but there are numerous places where a resource dictionary can be defined. In the above example, a resource dictionary is defined on Window/page level. In what dictionary a resource is defined immediately limits the scope of that resource. So the scope, i.e. where you can use the resource, depends on where you've defined it.
Define the resource in the resource dictionary of a grid and it's accessible by that grid and by its child elements only.
Define the resource in the resource dictionary of a grid and it's accessible by that grid and by its child elements only.
Define it on a window/page and it's accessible by all elements on that window/page.
Define it on a window/page and it's accessible by all elements on that window/page.
The app root can be found in App.xaml resources dictionary. It's the root of our application, so the resources defined here are scoped to the entire application.
The app root can be found in App.xaml resources dictionary. It's the root of our application, so the resources defined here are scoped to the entire application.
As far as the scope of the resource is concerned, the most often are application level, page level, and a specific element level like a Grid, StackPanel, etc.
The above application has resources in its Window/page level.
Resource dictionaries in XAML apps imply that the resource dictionaries are kept in separate files. It is followed in almost all XAML apps. Defining resources in separate files can have the following advantages −
Separation between defining resources in the resource dictionary and UI related code.
Separation between defining resources in the resource dictionary and UI related code.
Defining all the resources in a separate file such as App.xaml would make them available across the app.
Defining all the resources in a separate file such as App.xaml would make them available across the app.
So, how do we define our resources in a resource dictionary in a separate file? Well, it is very easy, just add a new resource dictionary through Visual Studio by following steps given below −
In your solution, add a new folder and name it ResourceDictionaries.
In your solution, add a new folder and name it ResourceDictionaries.
Right-click on this folder and select Resource Dictionary from Add submenu item and name it DictionaryWithBrush.xaml
Right-click on this folder and select Resource Dictionary from Add submenu item and name it DictionaryWithBrush.xaml
Let’s now take the same example, but here, we will define the resource dictionary in app level. The XAML code for MainWindow.xaml is as follows −
<Window x:Class = "WPFResources.MainWindow"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local = "clr-namespace:WPFResources"
mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "525">
<StackPanel>
<Rectangle Height = "50" Margin = "20" Fill = "{StaticResource brushResource}" />
<Rectangle Height = "50" Margin = "20" Fill = "{DynamicResource brushResource}" />
<Button x:Name = "changeResourceButton"
Content = "_Change Resource" Click = "changeResourceButton_Click" />
</StackPanel>
</Window>
Here is the implementation in DictionaryWithBrush.xaml −
<ResourceDictionary xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml">
<SolidColorBrush x:Key = "brushResource" Color = "Blue" />
</ResourceDictionary>
Here is the implementation in app.xaml −
<Application x:Class="WPFResources.App"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri = "MainWindow.xaml">
<Application.Resources>
<ResourceDictionary Source = " XAMLResources\ResourceDictionaries\DictionaryWithBrush.xaml"/>
</Application.Resources>
</Application>
When the above code is compiled and executed, it will produce the following output −
When you click the Change Resource button, the rectangle will change its color to Red.
We recommend that you execute the above code and try some more resources (for example, background color).
31 Lectures
2.5 hours
Anadi Sharma
30 Lectures
2.5 hours
Taurius Litvinavicius
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2256,
"s": 2020,
"text": "Resources are normally definitions connected with some object that you just anticipate to use more often than once. It is the ability to store data locally for controls or for the current window or globally for the entire applications."
},
{
"code": null,
"e": 2642,
"s": 2256,
"text": "Defining an object as a resource allows us to access it from another place. What it means is that the object can be reused. Resources are defined in resource dictionaries and any object can be defined as a resource effectively making it a shareable asset. A unique key is specified to an XAML resource and with that key, it can be referenced by using a StaticResource markup extension."
},
{
"code": null,
"e": 2674,
"s": 2642,
"text": "Resources can be of two types −"
},
{
"code": null,
"e": 2689,
"s": 2674,
"text": "StaticResource"
},
{
"code": null,
"e": 2705,
"s": 2689,
"text": "DynamicResource"
},
{
"code": null,
"e": 2974,
"s": 2705,
"text": "A StaticResource is a onetime lookup, whereas a DynamicResource works more like a data binding. It remembers that a property is associated with a particular resource key. If the object associated with that key changes, dynamic resource will update the target property."
},
{
"code": null,
"e": 3036,
"s": 2974,
"text": "Here's a simple application for the SolidColorBrush resource."
},
{
"code": null,
"e": 3094,
"s": 3036,
"text": "Let’s create a new WPF project with the name WPFResouces."
},
{
"code": null,
"e": 3152,
"s": 3094,
"text": "Let’s create a new WPF project with the name WPFResouces."
},
{
"code": null,
"e": 3234,
"s": 3152,
"text": "Drag two Rectangles and set their properties as shown in the following XAML code."
},
{
"code": null,
"e": 3316,
"s": 3234,
"text": "Drag two Rectangles and set their properties as shown in the following XAML code."
},
{
"code": null,
"e": 4228,
"s": 3316,
"text": "<Window x:Class = \"WPFResources.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n xmlns:local = \"clr-namespace:WPFResources\" \n mc:Ignorable = \"d\" Title = \"MainWindow\" Height = \"350\" Width = \"525\"> \n\t\n <Window.Resources> \n <SolidColorBrush x:Key = \"brushResource\" Color = \"Blue\" /> \n </Window.Resources> \n\t\n <StackPanel> \n <Rectangle Height = \"50\" Margin = \"20\" Fill = \"{StaticResource brushResource}\" /> \n <Rectangle Height = \"50\" Margin = \"20\" Fill = \"{DynamicResource brushResource}\" /> \n <Button x:Name = \"changeResourceButton\"\n Content = \"_Change Resource\" Click = \"changeResourceButton_Click\" /> \n </StackPanel> \n\t\n</Window> "
},
{
"code": null,
"e": 4382,
"s": 4228,
"text": "In the above XAML code, you can see that one rectangle has StaticResource and the other one has DynamicResource and the color of brushResource is Bisque."
},
{
"code": null,
"e": 4536,
"s": 4382,
"text": "In the above XAML code, you can see that one rectangle has StaticResource and the other one has DynamicResource and the color of brushResource is Bisque."
},
{
"code": null,
"e": 4617,
"s": 4536,
"text": "When you compile and execute the code, it will produce the following MainWindow."
},
{
"code": null,
"e": 4698,
"s": 4617,
"text": "When you compile and execute the code, it will produce the following MainWindow."
},
{
"code": null,
"e": 4826,
"s": 4698,
"text": "When you click the \"Change Resource\" button, you will see that the rectangle with DynamicResource will change its color to Red."
},
{
"code": null,
"e": 5200,
"s": 4826,
"text": "Resources are defined in resource dictionaries, but there are numerous places where a resource dictionary can be defined. In the above example, a resource dictionary is defined on Window/page level. In what dictionary a resource is defined immediately limits the scope of that resource. So the scope, i.e. where you can use the resource, depends on where you've defined it."
},
{
"code": null,
"e": 5322,
"s": 5200,
"text": "Define the resource in the resource dictionary of a grid and it's accessible by that grid and by its child elements only."
},
{
"code": null,
"e": 5444,
"s": 5322,
"text": "Define the resource in the resource dictionary of a grid and it's accessible by that grid and by its child elements only."
},
{
"code": null,
"e": 5528,
"s": 5444,
"text": "Define it on a window/page and it's accessible by all elements on that window/page."
},
{
"code": null,
"e": 5612,
"s": 5528,
"text": "Define it on a window/page and it's accessible by all elements on that window/page."
},
{
"code": null,
"e": 5774,
"s": 5612,
"text": "The app root can be found in App.xaml resources dictionary. It's the root of our application, so the resources defined here are scoped to the entire application."
},
{
"code": null,
"e": 5936,
"s": 5774,
"text": "The app root can be found in App.xaml resources dictionary. It's the root of our application, so the resources defined here are scoped to the entire application."
},
{
"code": null,
"e": 6095,
"s": 5936,
"text": "As far as the scope of the resource is concerned, the most often are application level, page level, and a specific element level like a Grid, StackPanel, etc."
},
{
"code": null,
"e": 6157,
"s": 6095,
"text": "The above application has resources in its Window/page level."
},
{
"code": null,
"e": 6370,
"s": 6157,
"text": "Resource dictionaries in XAML apps imply that the resource dictionaries are kept in separate files. It is followed in almost all XAML apps. Defining resources in separate files can have the following advantages −"
},
{
"code": null,
"e": 6456,
"s": 6370,
"text": "Separation between defining resources in the resource dictionary and UI related code."
},
{
"code": null,
"e": 6542,
"s": 6456,
"text": "Separation between defining resources in the resource dictionary and UI related code."
},
{
"code": null,
"e": 6647,
"s": 6542,
"text": "Defining all the resources in a separate file such as App.xaml would make them available across the app."
},
{
"code": null,
"e": 6752,
"s": 6647,
"text": "Defining all the resources in a separate file such as App.xaml would make them available across the app."
},
{
"code": null,
"e": 6945,
"s": 6752,
"text": "So, how do we define our resources in a resource dictionary in a separate file? Well, it is very easy, just add a new resource dictionary through Visual Studio by following steps given below −"
},
{
"code": null,
"e": 7014,
"s": 6945,
"text": "In your solution, add a new folder and name it ResourceDictionaries."
},
{
"code": null,
"e": 7083,
"s": 7014,
"text": "In your solution, add a new folder and name it ResourceDictionaries."
},
{
"code": null,
"e": 7200,
"s": 7083,
"text": "Right-click on this folder and select Resource Dictionary from Add submenu item and name it DictionaryWithBrush.xaml"
},
{
"code": null,
"e": 7317,
"s": 7200,
"text": "Right-click on this folder and select Resource Dictionary from Add submenu item and name it DictionaryWithBrush.xaml"
},
{
"code": null,
"e": 7463,
"s": 7317,
"text": "Let’s now take the same example, but here, we will define the resource dictionary in app level. The XAML code for MainWindow.xaml is as follows −"
},
{
"code": null,
"e": 8259,
"s": 7463,
"text": "<Window x:Class = \"WPFResources.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n xmlns:local = \"clr-namespace:WPFResources\" \n mc:Ignorable = \"d\" Title = \"MainWindow\" Height = \"350\" Width = \"525\"> \n\t\n <StackPanel> \n <Rectangle Height = \"50\" Margin = \"20\" Fill = \"{StaticResource brushResource}\" /> \n <Rectangle Height = \"50\" Margin = \"20\" Fill = \"{DynamicResource brushResource}\" /> \n <Button x:Name = \"changeResourceButton\"\n Content = \"_Change Resource\" Click = \"changeResourceButton_Click\" /> \n </StackPanel> \n\t\n</Window>"
},
{
"code": null,
"e": 8316,
"s": 8259,
"text": "Here is the implementation in DictionaryWithBrush.xaml −"
},
{
"code": null,
"e": 8555,
"s": 8316,
"text": "<ResourceDictionary xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\"> \n\t\n <SolidColorBrush x:Key = \"brushResource\" Color = \"Blue\" /> \n</ResourceDictionary> "
},
{
"code": null,
"e": 8596,
"s": 8555,
"text": "Here is the implementation in app.xaml −"
},
{
"code": null,
"e": 8984,
"s": 8596,
"text": "<Application x:Class=\"WPFResources.App\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n StartupUri = \"MainWindow.xaml\"> \n\t\n <Application.Resources> \n <ResourceDictionary Source = \" XAMLResources\\ResourceDictionaries\\DictionaryWithBrush.xaml\"/> \n </Application.Resources> \n\t\n</Application> "
},
{
"code": null,
"e": 9069,
"s": 8984,
"text": "When the above code is compiled and executed, it will produce the following output −"
},
{
"code": null,
"e": 9156,
"s": 9069,
"text": "When you click the Change Resource button, the rectangle will change its color to Red."
},
{
"code": null,
"e": 9262,
"s": 9156,
"text": "We recommend that you execute the above code and try some more resources (for example, background color)."
},
{
"code": null,
"e": 9297,
"s": 9262,
"text": "\n 31 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9311,
"s": 9297,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 9346,
"s": 9311,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9369,
"s": 9346,
"text": " Taurius Litvinavicius"
},
{
"code": null,
"e": 9376,
"s": 9369,
"text": " Print"
},
{
"code": null,
"e": 9387,
"s": 9376,
"text": " Add Notes"
}
] |
Can we define an abstract class with no abstract methods in Java? | Yes, we can declare an abstract class with no abstract methods in Java.
An abstract class means that hiding the implementation and showing the function definition to the user.
An abstract class having both abstract methods and non-abstract methods.
For an abstract class, we are not able to create an object directly. But Indirectly we can create an object using the subclass object.
A Java abstract class can have instance methods that implement a default behavior.
An abstract class can extend only one class or one abstract class at a time.
Declaring a class as abstract with no abstract methods means that we don't allow it to be instantiated on its own.
An abstract class used in Java signifies that we can't create an object of the class directly.
abstract class AbstractDemo { // Abstract class
private int i = 0;
public void display() { // non-abstract method
System.out.print("Welcome to Tutorials Point");
}
}
public class InheritedClassDemo extends AbstractDemo {
public static void main(String args[]) {
AbstractDemo demo = new InheritedClassDemo();
demo.display();
}
}
In the above example, we have not defined an abstract method in AbstractDemo class. The compiler doesn't throw any compile-time error.
Welcome to Tutorials Point | [
{
"code": null,
"e": 1134,
"s": 1062,
"text": "Yes, we can declare an abstract class with no abstract methods in Java."
},
{
"code": null,
"e": 1238,
"s": 1134,
"text": "An abstract class means that hiding the implementation and showing the function definition to the user."
},
{
"code": null,
"e": 1311,
"s": 1238,
"text": "An abstract class having both abstract methods and non-abstract methods."
},
{
"code": null,
"e": 1446,
"s": 1311,
"text": "For an abstract class, we are not able to create an object directly. But Indirectly we can create an object using the subclass object."
},
{
"code": null,
"e": 1529,
"s": 1446,
"text": "A Java abstract class can have instance methods that implement a default behavior."
},
{
"code": null,
"e": 1606,
"s": 1529,
"text": "An abstract class can extend only one class or one abstract class at a time."
},
{
"code": null,
"e": 1721,
"s": 1606,
"text": "Declaring a class as abstract with no abstract methods means that we don't allow it to be instantiated on its own."
},
{
"code": null,
"e": 1816,
"s": 1721,
"text": "An abstract class used in Java signifies that we can't create an object of the class directly."
},
{
"code": null,
"e": 2177,
"s": 1816,
"text": "abstract class AbstractDemo { // Abstract class\n private int i = 0;\n public void display() { // non-abstract method\n System.out.print(\"Welcome to Tutorials Point\");\n }\n}\npublic class InheritedClassDemo extends AbstractDemo {\n public static void main(String args[]) {\n AbstractDemo demo = new InheritedClassDemo();\n demo.display();\n }\n}"
},
{
"code": null,
"e": 2312,
"s": 2177,
"text": "In the above example, we have not defined an abstract method in AbstractDemo class. The compiler doesn't throw any compile-time error."
},
{
"code": null,
"e": 2339,
"s": 2312,
"text": "Welcome to Tutorials Point"
}
] |
Count subarrays with equal number of 1's and 0's - GeeksforGeeks | 24 Mar, 2022
Given an array arr[] of size n containing 0 and 1 only. The problem is to count the subarrays having an equal number of 0’s and 1’s.
Examples:
Input : arr[] = {1, 0, 0, 1, 0, 1, 1}
Output : 8
The index range for the 8 sub-arrays are:
(0, 1), (2, 3), (0, 3), (3, 4), (4, 5)
(2, 5), (0, 5), (1, 6)
The problem is closely related to the Largest subarray with an equal number of 0’s and 1’sApproach: Following are the steps:
Consider all 0’s in arr[] as -1.Create a hash table that holds the count of each sum[i] value, where sum[i] = sum(arr[0]+..+arr[i]), for i = 0 to n-1.Now start calculating the cumulative sum and then we get an incremental count of 1 for that sum represented as an index in the hash table. Arrays of each pair of positions with the same value in the cumulative sum constitute a continuous range with an equal number of 1’s and 0’s.Now traverse the hash table and get the frequency of each element in the hash table. Let frequency be denoted as freq. For each freq > 1 we can choose any two pairs of indices of a sub-array by (freq * (freq – 1)) / 2 number of ways. Do the same for all freq and sum up the result will be the number of all possible sub-arrays containing the equal number of 1’s and 0’s.Also, add freq of the sum of 0 to the hash table for the final result.
Consider all 0’s in arr[] as -1.
Create a hash table that holds the count of each sum[i] value, where sum[i] = sum(arr[0]+..+arr[i]), for i = 0 to n-1.
Now start calculating the cumulative sum and then we get an incremental count of 1 for that sum represented as an index in the hash table. Arrays of each pair of positions with the same value in the cumulative sum constitute a continuous range with an equal number of 1’s and 0’s.
Now traverse the hash table and get the frequency of each element in the hash table. Let frequency be denoted as freq. For each freq > 1 we can choose any two pairs of indices of a sub-array by (freq * (freq – 1)) / 2 number of ways. Do the same for all freq and sum up the result will be the number of all possible sub-arrays containing the equal number of 1’s and 0’s.
Also, add freq of the sum of 0 to the hash table for the final result.
Explanation: Considering all 0’s as -1, if sum[i] == sum[j], where sum[i] = sum(arr[0]+..+arr[i]) and sum[j] = sum(arr[0]+..+arr[j]) and ‘i’ is less than ‘j’, then sum(arr[i+1]+..+arr[j]) must be 0. It can only be 0 if arr(i+1, .., j) contains an equal number of 1’s and 0’s.
C++
Java
Python3
C#
Javascript
// C++ implementation to count subarrays with// equal number of 1's and 0's#include <bits/stdc++.h> using namespace std; // function to count subarrays with// equal number of 1's and 0'sint countSubarrWithEqualZeroAndOne(int arr[], int n){ // 'um' implemented as hash table to store // frequency of values obtained through // cumulative sum unordered_map<int, int> um; int curr_sum = 0; // Traverse original array and compute cumulative // sum and increase count by 1 for this sum // in 'um'. Adds '-1' when arr[i] == 0 for (int i = 0; i < n; i++) { curr_sum += (arr[i] == 0) ? -1 : arr[i]; um[curr_sum]++; } int count = 0; // traverse the hash table 'um' for (auto itr = um.begin(); itr != um.end(); itr++) { // If there are more than one prefix subarrays // with a particular sum if (itr->second > 1) count += ((itr->second * (itr->second - 1)) / 2); } // add the subarrays starting from 1st element and // have equal number of 1's and 0's if (um.find(0) != um.end()) count += um[0]; // required count of subarrays return count;} // Driver program to test aboveint main(){ int arr[] = { 1, 0, 0, 1, 0, 1, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Count = " << countSubarrWithEqualZeroAndOne(arr, n); return 0;}
// Java implementation to count subarrays with// equal number of 1's and 0'simport java.util.*; class GFG{ // function to count subarrays with// equal number of 1's and 0'sstatic int countSubarrWithEqualZeroAndOne(int arr[], int n){ // 'um' implemented as hash table to store // frequency of values obtained through // cumulative sum Map<Integer,Integer> um = new HashMap<>(); int curr_sum = 0; // Traverse original array and compute cumulative // sum and increase count by 1 for this sum // in 'um'. Adds '-1' when arr[i] == 0 for (int i = 0; i < n; i++) { curr_sum += (arr[i] == 0) ? -1 : arr[i]; um.put(curr_sum, um.get(curr_sum)==null?1:um.get(curr_sum)+1); } int count = 0; // traverse the hash table 'um' for (Map.Entry<Integer,Integer> itr : um.entrySet()) { // If there are more than one prefix subarrays // with a particular sum if (itr.getValue() > 1) count += ((itr.getValue()* (itr.getValue()- 1)) / 2); } // add the subarrays starting from 1st element and // have equal number of 1's and 0's if (um.containsKey(0)) count += um.get(0); // required count of subarrays return count;} // Driver program to test abovepublic static void main(String[] args){ int arr[] = { 1, 0, 0, 1, 0, 1, 1 }; int n = arr.length; System.out.println("Count = " + countSubarrWithEqualZeroAndOne(arr, n));}} // This code is contributed by Rajput-Ji
# Python3 implementation to count# subarrays with equal number# of 1's and 0's # function to count subarrays with# equal number of 1's and 0'sdef countSubarrWithEqualZeroAndOne (arr, n): # 'um' implemented as hash table # to store frequency of values # obtained through cumulative sum um = dict() curr_sum = 0 # Traverse original array and compute # cumulative sum and increase count # by 1 for this sum in 'um'. # Adds '-1' when arr[i] == 0 for i in range(n): curr_sum += (-1 if (arr[i] == 0) else arr[i]) if um.get(curr_sum): um[curr_sum]+=1 else: um[curr_sum]=1 count = 0 # traverse the hash table 'um' for itr in um: # If there are more than one # prefix subarrays with a # particular sum if um[itr] > 1: count += ((um[itr] * int(um[itr] - 1)) / 2) # add the subarrays starting from # 1st element and have equal # number of 1's and 0's if um.get(0): count += um[0] # required count of subarrays return int(count) # Driver code to test abovearr = [ 1, 0, 0, 1, 0, 1, 1 ]n = len(arr)print("Count =", countSubarrWithEqualZeroAndOne(arr, n)) # This code is contributed by "Sharad_Bhardwaj".
// C# implementation to count subarrays// with equal number of 1's and 0'susing System;using System.Collections.Generic; class GFG{ // function to count subarrays with// equal number of 1's and 0'sstatic int countSubarrWithEqualZeroAndOne(int []arr, int n){ // 'um' implemented as hash table to store // frequency of values obtained through // cumulative sum Dictionary<int, int> mp = new Dictionary<int, int>(); int curr_sum = 0; // Traverse original array and compute cumulative // sum and increase count by 1 for this sum // in 'um'. Adds '-1' when arr[i] == 0 for (int i = 0; i < n; i++) { curr_sum += (arr[i] == 0) ? -1 : arr[i]; if(mp.ContainsKey(curr_sum)) { var v = mp[curr_sum]; mp.Remove(curr_sum); mp.Add(curr_sum, ++v); } else mp.Add(curr_sum, 1); } int count = 0; // traverse the hash table 'um' foreach(KeyValuePair<int, int> itr in mp) { // If there are more than one prefix subarrays // with a particular sum if (itr.Value > 1) count += ((itr.Value* (itr.Value - 1)) / 2); } // add the subarrays starting from 1st element // and have equal number of 1's and 0's if (mp.ContainsKey(0)) count += mp[0]; // required count of subarrays return count;} // Driver program to test abovepublic static void Main(String[] args){ int []arr = { 1, 0, 0, 1, 0, 1, 1 }; int n = arr.Length; Console.WriteLine("Count = " + countSubarrWithEqualZeroAndOne(arr, n));}} // This code is contributed by PrinciRaj1992
<script> // Javascript implementation to count subarrays with// equal number of 1's and 0's // function to count subarrays with// equal number of 1's and 0'sfunction countSubarrWithEqualZeroAndOne(arr, n){ // 'um' implemented as hash table to store // frequency of values obtained through // cumulative sum var um = new Map(); var curr_sum = 0; // Traverse original array and compute cumulative // sum and increase count by 1 for this sum // in 'um'. Adds '-1' when arr[i] == 0 for (var i = 0; i < n; i++) { curr_sum += (arr[i] == 0) ? -1 : arr[i]; if(um.has(curr_sum)) um.set(curr_sum, um.get(curr_sum)+1); else um.set(curr_sum, 1) } var count = 0; // traverse the hash table 'um' um.forEach((value, key) => { // If there are more than one prefix subarrays // with a particular sum if (value > 1) count += ((value * (value - 1)) / 2); }); // add the subarrays starting from 1st element and // have equal number of 1's and 0's if (um.has(0)) count += um.get(0); // required count of subarrays return count;} // Driver program to test abovevar arr = [1, 0, 0, 1, 0, 1, 1];var n = arr.length;document.write( "Count = " + countSubarrWithEqualZeroAndOne(arr, n)); // This code is contributed by noob2000.</script>
Output:
Count = 8
Time Complexity: O(n). Auxiliary Space: O(n).
Another approach: This approach is very easy to understand if we simply know this question : Number of subarrays having sum exactly equal to k. We just have to make k=0 and all the zeroes in the given array to -1.
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h> using namespace std; int countSubarrWithEqualZeroAndOne(int arr[], int n){ map<int, int> mp; int sum = 0; int count = 0; for (int i = 0; i < n; i++) { // Replacing 0's in array with -1 if (arr[i] == 0) arr[i] = -1; sum += arr[i]; // If sum = 0, it implies number of 0's and 1's are // equal from arr[0]..arr[i] if (sum == 0) count++; //if mp[sum] exists then add "frequency-1" to count if (mp[sum]) count += mp[sum]; //if frequency of "sum" is zero then we initialize that frequency to 1 //if its not 0, we increment it if (mp[sum] == 0) mp[sum] = 1; else mp[sum]++; } return count;} int main(){ int arr[] = { 1, 0, 0, 1, 0, 1, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "count=" << countSubarrWithEqualZeroAndOne(arr, n);}
import java.util.HashMap;import java.util.Map; // Java implementation to count subarrays with// equal number of 1's and 0'spublic class Main { // Function that returns count of sub arrays // with equal numbers of 1's and 0's static int countSubarrWithEqualZeroAndOne(int[] arr, int n) { Map<Integer, Integer> myMap = new HashMap<>(); int sum = 0; int count = 0; for (int i = 0; i < n; i++) { // Replacing 0's in array with -1 if (arr[i] == 0) arr[i] = -1; sum += arr[i]; // If sum = 0, it implies number of 0's and 1's // are equal from arr[0]..arr[i] if (sum == 0) count++; if (myMap.containsKey(sum)) count += myMap.get(sum); if (!myMap.containsKey(sum)) myMap.put(sum, 1); else myMap.put(sum, myMap.get(sum) + 1); } return count; } // main function public static void main(String[] args) { int arr[] = { 1, 0, 0, 1, 0, 1, 1 }; int n = arr.length; System.out.println( "Count = " + countSubarrWithEqualZeroAndOne(arr, n)); }}
# Python3 implementation to count subarrays# with equal number of 1's and 0's def countSubarrWithEqualZeroAndOne(arr, n): mp = dict() Sum = 0 count = 0 for i in range(n): # Replacing 0's in array with -1 if (arr[i] == 0): arr[i] = -1 Sum += arr[i] # If Sum = 0, it implies number of # 0's and 1's are equal from arr[0]..arr[i] if (Sum == 0): count += 1 if (Sum in mp.keys()): count += mp[Sum] mp[Sum] = mp.get(Sum, 0) + 1 return count # Driver Codearr = [1, 0, 0, 1, 0, 1, 1] n = len(arr) print("count =", countSubarrWithEqualZeroAndOne(arr, n)) # This code is contributed by mohit kumar
// C# implementation to count subarrays with// equal number of 1's and 0'susing System;using System.Collections.Generic; class GFG { // Function that returns count of sub arrays // with equal numbers of 1's and 0's static int countSubarrWithEqualZeroAndOne(int[] arr, int n) { Dictionary<int, int> myMap = new Dictionary<int, int>(); int sum = 0; int count = 0; for (int i = 0; i < n; i++) { // Replacing 0's in array with -1 if (arr[i] == 0) arr[i] = -1; sum += arr[i]; // If sum = 0, it implies number of 0's and 1's // are equal from arr[0]..arr[i] if (sum == 0) count++; if (myMap.ContainsKey(sum)) count += myMap[sum]; if (!myMap.ContainsKey(sum)) myMap.Add(sum, 1); else { var v = myMap[sum] + 1; myMap.Remove(sum); myMap.Add(sum, v); } } return count; } // Driver code public static void Main(String[] args) { int[] arr = { 1, 0, 0, 1, 0, 1, 1 }; int n = arr.Length; Console.WriteLine( "Count = " + countSubarrWithEqualZeroAndOne(arr, n)); }} // This code is contributed by 29AjayKumar
<script> // Javascript implementation to count subarrays with// equal number of 1's and 0's function countSubarrWithEqualZeroAndOne(arr, n){ var mp = new Map(); var sum = 0; let count = 0; for (var i = 0; i < n; i++) { //Replacing 0's in array with -1 if (arr[i] == 0) arr[i] = -1; sum += arr[i]; //If sum = 0, it implies number of 0's and 1's are //equal from arr[0]..arr[i] if (sum == 0) count += 1; if (mp.has(sum) == true) count += mp.get(sum); if(mp.has(sum) == false) mp.set(sum, 1); else mp.set(sum, mp.get(sum)+1); } return count;} // Driver program to test abovevar arr = [1, 0, 0, 1, 0, 1, 1];var n = arr.length;document.write( "Count = " + countSubarrWithEqualZeroAndOne(arr, n)); // This code is contributed by noob2000.</script>
Output:
Count = 8
ravi_Sgo
shivamgoel009
mohit kumar 29
29AjayKumar
Rajput-Ji
princiraj1992
noob2000
shivanisinghss2110
dishantarora
superdude
binary-string
Arrays
Hash
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
Hashing | Set 3 (Open Addressing) | [
{
"code": null,
"e": 24205,
"s": 24177,
"text": "\n24 Mar, 2022"
},
{
"code": null,
"e": 24338,
"s": 24205,
"text": "Given an array arr[] of size n containing 0 and 1 only. The problem is to count the subarrays having an equal number of 0’s and 1’s."
},
{
"code": null,
"e": 24350,
"s": 24338,
"text": "Examples: "
},
{
"code": null,
"e": 24503,
"s": 24350,
"text": "Input : arr[] = {1, 0, 0, 1, 0, 1, 1}\nOutput : 8\nThe index range for the 8 sub-arrays are:\n(0, 1), (2, 3), (0, 3), (3, 4), (4, 5)\n(2, 5), (0, 5), (1, 6)"
},
{
"code": null,
"e": 24629,
"s": 24503,
"text": "The problem is closely related to the Largest subarray with an equal number of 0’s and 1’sApproach: Following are the steps: "
},
{
"code": null,
"e": 25500,
"s": 24629,
"text": "Consider all 0’s in arr[] as -1.Create a hash table that holds the count of each sum[i] value, where sum[i] = sum(arr[0]+..+arr[i]), for i = 0 to n-1.Now start calculating the cumulative sum and then we get an incremental count of 1 for that sum represented as an index in the hash table. Arrays of each pair of positions with the same value in the cumulative sum constitute a continuous range with an equal number of 1’s and 0’s.Now traverse the hash table and get the frequency of each element in the hash table. Let frequency be denoted as freq. For each freq > 1 we can choose any two pairs of indices of a sub-array by (freq * (freq – 1)) / 2 number of ways. Do the same for all freq and sum up the result will be the number of all possible sub-arrays containing the equal number of 1’s and 0’s.Also, add freq of the sum of 0 to the hash table for the final result."
},
{
"code": null,
"e": 25533,
"s": 25500,
"text": "Consider all 0’s in arr[] as -1."
},
{
"code": null,
"e": 25652,
"s": 25533,
"text": "Create a hash table that holds the count of each sum[i] value, where sum[i] = sum(arr[0]+..+arr[i]), for i = 0 to n-1."
},
{
"code": null,
"e": 25933,
"s": 25652,
"text": "Now start calculating the cumulative sum and then we get an incremental count of 1 for that sum represented as an index in the hash table. Arrays of each pair of positions with the same value in the cumulative sum constitute a continuous range with an equal number of 1’s and 0’s."
},
{
"code": null,
"e": 26304,
"s": 25933,
"text": "Now traverse the hash table and get the frequency of each element in the hash table. Let frequency be denoted as freq. For each freq > 1 we can choose any two pairs of indices of a sub-array by (freq * (freq – 1)) / 2 number of ways. Do the same for all freq and sum up the result will be the number of all possible sub-arrays containing the equal number of 1’s and 0’s."
},
{
"code": null,
"e": 26375,
"s": 26304,
"text": "Also, add freq of the sum of 0 to the hash table for the final result."
},
{
"code": null,
"e": 26652,
"s": 26375,
"text": "Explanation: Considering all 0’s as -1, if sum[i] == sum[j], where sum[i] = sum(arr[0]+..+arr[i]) and sum[j] = sum(arr[0]+..+arr[j]) and ‘i’ is less than ‘j’, then sum(arr[i+1]+..+arr[j]) must be 0. It can only be 0 if arr(i+1, .., j) contains an equal number of 1’s and 0’s. "
},
{
"code": null,
"e": 26656,
"s": 26652,
"text": "C++"
},
{
"code": null,
"e": 26661,
"s": 26656,
"text": "Java"
},
{
"code": null,
"e": 26669,
"s": 26661,
"text": "Python3"
},
{
"code": null,
"e": 26672,
"s": 26669,
"text": "C#"
},
{
"code": null,
"e": 26683,
"s": 26672,
"text": "Javascript"
},
{
"code": "// C++ implementation to count subarrays with// equal number of 1's and 0's#include <bits/stdc++.h> using namespace std; // function to count subarrays with// equal number of 1's and 0'sint countSubarrWithEqualZeroAndOne(int arr[], int n){ // 'um' implemented as hash table to store // frequency of values obtained through // cumulative sum unordered_map<int, int> um; int curr_sum = 0; // Traverse original array and compute cumulative // sum and increase count by 1 for this sum // in 'um'. Adds '-1' when arr[i] == 0 for (int i = 0; i < n; i++) { curr_sum += (arr[i] == 0) ? -1 : arr[i]; um[curr_sum]++; } int count = 0; // traverse the hash table 'um' for (auto itr = um.begin(); itr != um.end(); itr++) { // If there are more than one prefix subarrays // with a particular sum if (itr->second > 1) count += ((itr->second * (itr->second - 1)) / 2); } // add the subarrays starting from 1st element and // have equal number of 1's and 0's if (um.find(0) != um.end()) count += um[0]; // required count of subarrays return count;} // Driver program to test aboveint main(){ int arr[] = { 1, 0, 0, 1, 0, 1, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Count = \" << countSubarrWithEqualZeroAndOne(arr, n); return 0;}",
"e": 28041,
"s": 26683,
"text": null
},
{
"code": "// Java implementation to count subarrays with// equal number of 1's and 0'simport java.util.*; class GFG{ // function to count subarrays with// equal number of 1's and 0'sstatic int countSubarrWithEqualZeroAndOne(int arr[], int n){ // 'um' implemented as hash table to store // frequency of values obtained through // cumulative sum Map<Integer,Integer> um = new HashMap<>(); int curr_sum = 0; // Traverse original array and compute cumulative // sum and increase count by 1 for this sum // in 'um'. Adds '-1' when arr[i] == 0 for (int i = 0; i < n; i++) { curr_sum += (arr[i] == 0) ? -1 : arr[i]; um.put(curr_sum, um.get(curr_sum)==null?1:um.get(curr_sum)+1); } int count = 0; // traverse the hash table 'um' for (Map.Entry<Integer,Integer> itr : um.entrySet()) { // If there are more than one prefix subarrays // with a particular sum if (itr.getValue() > 1) count += ((itr.getValue()* (itr.getValue()- 1)) / 2); } // add the subarrays starting from 1st element and // have equal number of 1's and 0's if (um.containsKey(0)) count += um.get(0); // required count of subarrays return count;} // Driver program to test abovepublic static void main(String[] args){ int arr[] = { 1, 0, 0, 1, 0, 1, 1 }; int n = arr.length; System.out.println(\"Count = \" + countSubarrWithEqualZeroAndOne(arr, n));}} // This code is contributed by Rajput-Ji",
"e": 29518,
"s": 28041,
"text": null
},
{
"code": "# Python3 implementation to count# subarrays with equal number# of 1's and 0's # function to count subarrays with# equal number of 1's and 0'sdef countSubarrWithEqualZeroAndOne (arr, n): # 'um' implemented as hash table # to store frequency of values # obtained through cumulative sum um = dict() curr_sum = 0 # Traverse original array and compute # cumulative sum and increase count # by 1 for this sum in 'um'. # Adds '-1' when arr[i] == 0 for i in range(n): curr_sum += (-1 if (arr[i] == 0) else arr[i]) if um.get(curr_sum): um[curr_sum]+=1 else: um[curr_sum]=1 count = 0 # traverse the hash table 'um' for itr in um: # If there are more than one # prefix subarrays with a # particular sum if um[itr] > 1: count += ((um[itr] * int(um[itr] - 1)) / 2) # add the subarrays starting from # 1st element and have equal # number of 1's and 0's if um.get(0): count += um[0] # required count of subarrays return int(count) # Driver code to test abovearr = [ 1, 0, 0, 1, 0, 1, 1 ]n = len(arr)print(\"Count =\", countSubarrWithEqualZeroAndOne(arr, n)) # This code is contributed by \"Sharad_Bhardwaj\".",
"e": 30797,
"s": 29518,
"text": null
},
{
"code": "// C# implementation to count subarrays// with equal number of 1's and 0'susing System;using System.Collections.Generic; class GFG{ // function to count subarrays with// equal number of 1's and 0'sstatic int countSubarrWithEqualZeroAndOne(int []arr, int n){ // 'um' implemented as hash table to store // frequency of values obtained through // cumulative sum Dictionary<int, int> mp = new Dictionary<int, int>(); int curr_sum = 0; // Traverse original array and compute cumulative // sum and increase count by 1 for this sum // in 'um'. Adds '-1' when arr[i] == 0 for (int i = 0; i < n; i++) { curr_sum += (arr[i] == 0) ? -1 : arr[i]; if(mp.ContainsKey(curr_sum)) { var v = mp[curr_sum]; mp.Remove(curr_sum); mp.Add(curr_sum, ++v); } else mp.Add(curr_sum, 1); } int count = 0; // traverse the hash table 'um' foreach(KeyValuePair<int, int> itr in mp) { // If there are more than one prefix subarrays // with a particular sum if (itr.Value > 1) count += ((itr.Value* (itr.Value - 1)) / 2); } // add the subarrays starting from 1st element // and have equal number of 1's and 0's if (mp.ContainsKey(0)) count += mp[0]; // required count of subarrays return count;} // Driver program to test abovepublic static void Main(String[] args){ int []arr = { 1, 0, 0, 1, 0, 1, 1 }; int n = arr.Length; Console.WriteLine(\"Count = \" + countSubarrWithEqualZeroAndOne(arr, n));}} // This code is contributed by PrinciRaj1992",
"e": 32512,
"s": 30797,
"text": null
},
{
"code": "<script> // Javascript implementation to count subarrays with// equal number of 1's and 0's // function to count subarrays with// equal number of 1's and 0'sfunction countSubarrWithEqualZeroAndOne(arr, n){ // 'um' implemented as hash table to store // frequency of values obtained through // cumulative sum var um = new Map(); var curr_sum = 0; // Traverse original array and compute cumulative // sum and increase count by 1 for this sum // in 'um'. Adds '-1' when arr[i] == 0 for (var i = 0; i < n; i++) { curr_sum += (arr[i] == 0) ? -1 : arr[i]; if(um.has(curr_sum)) um.set(curr_sum, um.get(curr_sum)+1); else um.set(curr_sum, 1) } var count = 0; // traverse the hash table 'um' um.forEach((value, key) => { // If there are more than one prefix subarrays // with a particular sum if (value > 1) count += ((value * (value - 1)) / 2); }); // add the subarrays starting from 1st element and // have equal number of 1's and 0's if (um.has(0)) count += um.get(0); // required count of subarrays return count;} // Driver program to test abovevar arr = [1, 0, 0, 1, 0, 1, 1];var n = arr.length;document.write( \"Count = \" + countSubarrWithEqualZeroAndOne(arr, n)); // This code is contributed by noob2000.</script>",
"e": 33879,
"s": 32512,
"text": null
},
{
"code": null,
"e": 33889,
"s": 33879,
"text": "Output: "
},
{
"code": null,
"e": 33899,
"s": 33889,
"text": "Count = 8"
},
{
"code": null,
"e": 33947,
"s": 33899,
"text": "Time Complexity: O(n). Auxiliary Space: O(n). "
},
{
"code": null,
"e": 34164,
"s": 33947,
"text": "Another approach: This approach is very easy to understand if we simply know this question : Number of subarrays having sum exactly equal to k. We just have to make k=0 and all the zeroes in the given array to -1. "
},
{
"code": null,
"e": 34168,
"s": 34164,
"text": "C++"
},
{
"code": null,
"e": 34173,
"s": 34168,
"text": "Java"
},
{
"code": null,
"e": 34181,
"s": 34173,
"text": "Python3"
},
{
"code": null,
"e": 34184,
"s": 34181,
"text": "C#"
},
{
"code": null,
"e": 34195,
"s": 34184,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h> using namespace std; int countSubarrWithEqualZeroAndOne(int arr[], int n){ map<int, int> mp; int sum = 0; int count = 0; for (int i = 0; i < n; i++) { // Replacing 0's in array with -1 if (arr[i] == 0) arr[i] = -1; sum += arr[i]; // If sum = 0, it implies number of 0's and 1's are // equal from arr[0]..arr[i] if (sum == 0) count++; //if mp[sum] exists then add \"frequency-1\" to count if (mp[sum]) count += mp[sum]; //if frequency of \"sum\" is zero then we initialize that frequency to 1 //if its not 0, we increment it if (mp[sum] == 0) mp[sum] = 1; else mp[sum]++; } return count;} int main(){ int arr[] = { 1, 0, 0, 1, 0, 1, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"count=\" << countSubarrWithEqualZeroAndOne(arr, n);}",
"e": 35144,
"s": 34195,
"text": null
},
{
"code": "import java.util.HashMap;import java.util.Map; // Java implementation to count subarrays with// equal number of 1's and 0'spublic class Main { // Function that returns count of sub arrays // with equal numbers of 1's and 0's static int countSubarrWithEqualZeroAndOne(int[] arr, int n) { Map<Integer, Integer> myMap = new HashMap<>(); int sum = 0; int count = 0; for (int i = 0; i < n; i++) { // Replacing 0's in array with -1 if (arr[i] == 0) arr[i] = -1; sum += arr[i]; // If sum = 0, it implies number of 0's and 1's // are equal from arr[0]..arr[i] if (sum == 0) count++; if (myMap.containsKey(sum)) count += myMap.get(sum); if (!myMap.containsKey(sum)) myMap.put(sum, 1); else myMap.put(sum, myMap.get(sum) + 1); } return count; } // main function public static void main(String[] args) { int arr[] = { 1, 0, 0, 1, 0, 1, 1 }; int n = arr.length; System.out.println( \"Count = \" + countSubarrWithEqualZeroAndOne(arr, n)); }}",
"e": 36408,
"s": 35144,
"text": null
},
{
"code": "# Python3 implementation to count subarrays# with equal number of 1's and 0's def countSubarrWithEqualZeroAndOne(arr, n): mp = dict() Sum = 0 count = 0 for i in range(n): # Replacing 0's in array with -1 if (arr[i] == 0): arr[i] = -1 Sum += arr[i] # If Sum = 0, it implies number of # 0's and 1's are equal from arr[0]..arr[i] if (Sum == 0): count += 1 if (Sum in mp.keys()): count += mp[Sum] mp[Sum] = mp.get(Sum, 0) + 1 return count # Driver Codearr = [1, 0, 0, 1, 0, 1, 1] n = len(arr) print(\"count =\", countSubarrWithEqualZeroAndOne(arr, n)) # This code is contributed by mohit kumar",
"e": 37114,
"s": 36408,
"text": null
},
{
"code": "// C# implementation to count subarrays with// equal number of 1's and 0'susing System;using System.Collections.Generic; class GFG { // Function that returns count of sub arrays // with equal numbers of 1's and 0's static int countSubarrWithEqualZeroAndOne(int[] arr, int n) { Dictionary<int, int> myMap = new Dictionary<int, int>(); int sum = 0; int count = 0; for (int i = 0; i < n; i++) { // Replacing 0's in array with -1 if (arr[i] == 0) arr[i] = -1; sum += arr[i]; // If sum = 0, it implies number of 0's and 1's // are equal from arr[0]..arr[i] if (sum == 0) count++; if (myMap.ContainsKey(sum)) count += myMap[sum]; if (!myMap.ContainsKey(sum)) myMap.Add(sum, 1); else { var v = myMap[sum] + 1; myMap.Remove(sum); myMap.Add(sum, v); } } return count; } // Driver code public static void Main(String[] args) { int[] arr = { 1, 0, 0, 1, 0, 1, 1 }; int n = arr.Length; Console.WriteLine( \"Count = \" + countSubarrWithEqualZeroAndOne(arr, n)); }} // This code is contributed by 29AjayKumar",
"e": 38496,
"s": 37114,
"text": null
},
{
"code": "<script> // Javascript implementation to count subarrays with// equal number of 1's and 0's function countSubarrWithEqualZeroAndOne(arr, n){ var mp = new Map(); var sum = 0; let count = 0; for (var i = 0; i < n; i++) { //Replacing 0's in array with -1 if (arr[i] == 0) arr[i] = -1; sum += arr[i]; //If sum = 0, it implies number of 0's and 1's are //equal from arr[0]..arr[i] if (sum == 0) count += 1; if (mp.has(sum) == true) count += mp.get(sum); if(mp.has(sum) == false) mp.set(sum, 1); else mp.set(sum, mp.get(sum)+1); } return count;} // Driver program to test abovevar arr = [1, 0, 0, 1, 0, 1, 1];var n = arr.length;document.write( \"Count = \" + countSubarrWithEqualZeroAndOne(arr, n)); // This code is contributed by noob2000.</script>",
"e": 39412,
"s": 38496,
"text": null
},
{
"code": null,
"e": 39422,
"s": 39412,
"text": "Output: "
},
{
"code": null,
"e": 39432,
"s": 39422,
"text": "Count = 8"
},
{
"code": null,
"e": 39443,
"s": 39434,
"text": "ravi_Sgo"
},
{
"code": null,
"e": 39457,
"s": 39443,
"text": "shivamgoel009"
},
{
"code": null,
"e": 39472,
"s": 39457,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 39484,
"s": 39472,
"text": "29AjayKumar"
},
{
"code": null,
"e": 39494,
"s": 39484,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 39508,
"s": 39494,
"text": "princiraj1992"
},
{
"code": null,
"e": 39517,
"s": 39508,
"text": "noob2000"
},
{
"code": null,
"e": 39536,
"s": 39517,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 39549,
"s": 39536,
"text": "dishantarora"
},
{
"code": null,
"e": 39559,
"s": 39549,
"text": "superdude"
},
{
"code": null,
"e": 39573,
"s": 39559,
"text": "binary-string"
},
{
"code": null,
"e": 39580,
"s": 39573,
"text": "Arrays"
},
{
"code": null,
"e": 39585,
"s": 39580,
"text": "Hash"
},
{
"code": null,
"e": 39592,
"s": 39585,
"text": "Arrays"
},
{
"code": null,
"e": 39597,
"s": 39592,
"text": "Hash"
},
{
"code": null,
"e": 39695,
"s": 39597,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39704,
"s": 39695,
"text": "Comments"
},
{
"code": null,
"e": 39717,
"s": 39704,
"text": "Old Comments"
},
{
"code": null,
"e": 39765,
"s": 39717,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 39809,
"s": 39765,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 39832,
"s": 39809,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 39864,
"s": 39832,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 39878,
"s": 39864,
"text": "Linear Search"
},
{
"code": null,
"e": 39963,
"s": 39878,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 39999,
"s": 39963,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 40030,
"s": 39999,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 40057,
"s": 40030,
"text": "Count pairs with given sum"
}
] |
Django - URL Mapping | Now that we have a working view as explained in the previous chapters. We want to access that view via a URL. Django has his own way for URL mapping and it's done by editing your project url.py file (myproject/url.py). The url.py file looks like −
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
#Examples
#url(r'^$', 'myproject.view.home', name = 'home'),
#url(r'^blog/', include('blog.urls')),
url(r'^admin', include(admin.site.urls)),
)
When a user makes a request for a page on your web app, Django controller takes over to look for the corresponding view via the url.py file, and then return the HTML response or a 404 not found error, if not found. In url.py, the most important thing is the "urlpatterns" tuple. It’s where you define the mapping between URLs and views. A mapping is a tuple in URL patterns like −
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
#Examples
#url(r'^$', 'myproject.view.home', name = 'home'),
#url(r'^blog/', include('blog.urls')),
url(r'^admin', include(admin.site.urls)),
url(r'^hello/', 'myapp.views.hello', name = 'hello'),
)
The marked line maps the URL "/home" to the hello view created in myapp/view.py file. As you can see above a mapping is composed of three elements −
The pattern − A regexp matching the URL you want to be resolved and map. Everything that can work with the python 're' module is eligible for the pattern (useful when you want to pass parameters via url).
The pattern − A regexp matching the URL you want to be resolved and map. Everything that can work with the python 're' module is eligible for the pattern (useful when you want to pass parameters via url).
The python path to the view − Same as when you are importing a module.
The python path to the view − Same as when you are importing a module.
The name − In order to perform URL reversing, you’ll need to use named URL patterns as done in the examples above. Once done, just start the server to access your view via :http://127.0.0.1/hello
The name − In order to perform URL reversing, you’ll need to use named URL patterns as done in the examples above. Once done, just start the server to access your view via :http://127.0.0.1/hello
So far, we have created the URLs in “myprojects/url.py” file, however as stated earlier about Django and creating an app, the best point was to be able to reuse applications in different projects. You can easily see what the problem is, if you are saving all your URLs in the “projecturl.py” file. So best practice is to create an “url.py” per application and to include it in our main projects url.py file (we included admin URLs for admin interface before).
We need to create an url.py file in myapp using the following code −
from django.conf.urls import patterns, include, url
urlpatterns = patterns('', url(r'^hello/', 'myapp.views.hello', name = 'hello'),)
Then myproject/url.py will change to the following −
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
#Examples
#url(r'^$', 'myproject.view.home', name = 'home'),
#url(r'^blog/', include('blog.urls')),
url(r'^admin', include(admin.site.urls)),
url(r'^myapp/', include('myapp.urls')),
)
We have included all URLs from myapp application. The home.html that was accessed through “/hello” is now “/myapp/hello” which is a better and more understandable structure for the web app.
Now let's imagine we have another view in myapp “morning” and we want to map it in myapp/url.py, we will then change our myapp/url.py to −
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^hello/', 'myapp.views.hello', name = 'hello'),
url(r'^morning/', 'myapp.views.morning', name = 'morning'),
)
This can be re-factored to −
from django.conf.urls import patterns, include, url
urlpatterns = patterns('myapp.views',
url(r'^hello/', 'hello', name = 'hello'),
url(r'^morning/', 'morning', name = 'morning'),)
As you can see, we now use the first element of our urlpatterns tuple. This can be useful when you want to change your app name.
We now know how to map URL, how to organize them, now let us see how to send parameters to views. A classic sample is the article example (you want to access an article via “/articles/article_id”).
Passing parameters is done by capturing them with the regexp in the URL pattern. If we have a view like the following one in “myapp/view.py”
from django.shortcuts import render
from django.http import HttpResponse
def hello(request):
return render(request, "hello.html", {})
def viewArticle(request, articleId):
text = "Displaying article Number : %s"%articleId
return HttpResponse(text)
We want to map it in myapp/url.py so we can access it via “/myapp/article/articleId”, we need the following in “myapp/url.py” −
from django.conf.urls import patterns, include, url
urlpatterns = patterns('myapp.views',
url(r'^hello/', 'hello', name = 'hello'),
url(r'^morning/', 'morning', name = 'morning'),
url(r'^article/(\d+)/', 'viewArticle', name = 'article'),)
When Django will see the url: “/myapp/article/42” it will pass the parameters '42' to the viewArticle view, and in your browser you should get the following result −
Note that the order of parameters is important here. Suppose we want the list of articles of a month of a year, let's add a viewArticles view. Our view.py becomes −
from django.shortcuts import render
from django.http import HttpResponse
def hello(request):
return render(request, "hello.html", {})
def viewArticle(request, articleId):
text = "Displaying article Number : %s"%articleId
return HttpResponse(text)
def viewArticle(request, month, year):
text = "Displaying articles of : %s/%s"%(year, month)
return HttpResponse(text)
The corresponding url.py file will look like −
from django.conf.urls import patterns, include, url
urlpatterns = patterns('myapp.views',
url(r'^hello/', 'hello', name = 'hello'),
url(r'^morning/', 'morning', name = 'morning'),
url(r'^article/(\d+)/', 'viewArticle', name = 'article'),
url(r'^articles/(\d{2})/(\d{4})', 'viewArticles', name = 'articles'),)
Now when you go to “/myapp/articles/12/2006/” you will get 'Displaying articles of: 2006/12' but if you reverse the parameters you won’t get the same result.
To avoid that, it is possible to link a URL parameter to the view parameter. For that, our url.py will become −
from django.conf.urls import patterns, include, url
urlpatterns = patterns('myapp.views',
url(r'^hello/', 'hello', name = 'hello'),
url(r'^morning/', 'morning', name = 'morning'),
url(r'^article/(\d+)/', 'viewArticle', name = 'article'),
url(r'^articles/(?P\d{2})/(?P\d{4})', 'viewArticles', name = 'articles'),)
39 Lectures
3.5 hours
John Elder
36 Lectures
2.5 hours
John Elder
28 Lectures
2 hours
John Elder
20 Lectures
1 hours
John Elder
35 Lectures
3 hours
John Elder
79 Lectures
10 hours
Rathan Kumar
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2293,
"s": 2045,
"text": "Now that we have a working view as explained in the previous chapters. We want to access that view via a URL. Django has his own way for URL mapping and it's done by editing your project url.py file (myproject/url.py). The url.py file looks like −"
},
{
"code": null,
"e": 2584,
"s": 2293,
"text": "from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n #Examples\n #url(r'^$', 'myproject.view.home', name = 'home'),\n #url(r'^blog/', include('blog.urls')),\n\n url(r'^admin', include(admin.site.urls)),\n)"
},
{
"code": null,
"e": 2965,
"s": 2584,
"text": "When a user makes a request for a page on your web app, Django controller takes over to look for the corresponding view via the url.py file, and then return the HTML response or a 404 not found error, if not found. In url.py, the most important thing is the \"urlpatterns\" tuple. It’s where you define the mapping between URLs and views. A mapping is a tuple in URL patterns like −"
},
{
"code": null,
"e": 3313,
"s": 2965,
"text": "from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n #Examples\n #url(r'^$', 'myproject.view.home', name = 'home'),\n #url(r'^blog/', include('blog.urls')),\n\n url(r'^admin', include(admin.site.urls)),\n url(r'^hello/', 'myapp.views.hello', name = 'hello'),\n)"
},
{
"code": null,
"e": 3462,
"s": 3313,
"text": "The marked line maps the URL \"/home\" to the hello view created in myapp/view.py file. As you can see above a mapping is composed of three elements −"
},
{
"code": null,
"e": 3667,
"s": 3462,
"text": "The pattern − A regexp matching the URL you want to be resolved and map. Everything that can work with the python 're' module is eligible for the pattern (useful when you want to pass parameters via url)."
},
{
"code": null,
"e": 3872,
"s": 3667,
"text": "The pattern − A regexp matching the URL you want to be resolved and map. Everything that can work with the python 're' module is eligible for the pattern (useful when you want to pass parameters via url)."
},
{
"code": null,
"e": 3943,
"s": 3872,
"text": "The python path to the view − Same as when you are importing a module."
},
{
"code": null,
"e": 4014,
"s": 3943,
"text": "The python path to the view − Same as when you are importing a module."
},
{
"code": null,
"e": 4210,
"s": 4014,
"text": "The name − In order to perform URL reversing, you’ll need to use named URL patterns as done in the examples above. Once done, just start the server to access your view via :http://127.0.0.1/hello"
},
{
"code": null,
"e": 4406,
"s": 4210,
"text": "The name − In order to perform URL reversing, you’ll need to use named URL patterns as done in the examples above. Once done, just start the server to access your view via :http://127.0.0.1/hello"
},
{
"code": null,
"e": 4866,
"s": 4406,
"text": "So far, we have created the URLs in “myprojects/url.py” file, however as stated earlier about Django and creating an app, the best point was to be able to reuse applications in different projects. You can easily see what the problem is, if you are saving all your URLs in the “projecturl.py” file. So best practice is to create an “url.py” per application and to include it in our main projects url.py file (we included admin URLs for admin interface before)."
},
{
"code": null,
"e": 4935,
"s": 4866,
"text": "We need to create an url.py file in myapp using the following code −"
},
{
"code": null,
"e": 5070,
"s": 4935,
"text": "from django.conf.urls import patterns, include, url\n\nurlpatterns = patterns('', url(r'^hello/', 'myapp.views.hello', name = 'hello'),)"
},
{
"code": null,
"e": 5123,
"s": 5070,
"text": "Then myproject/url.py will change to the following −"
},
{
"code": null,
"e": 5457,
"s": 5123,
"text": "from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n #Examples\n #url(r'^$', 'myproject.view.home', name = 'home'),\n #url(r'^blog/', include('blog.urls')),\n\n url(r'^admin', include(admin.site.urls)),\n url(r'^myapp/', include('myapp.urls')),\n)"
},
{
"code": null,
"e": 5647,
"s": 5457,
"text": "We have included all URLs from myapp application. The home.html that was accessed through “/hello” is now “/myapp/hello” which is a better and more understandable structure for the web app."
},
{
"code": null,
"e": 5786,
"s": 5647,
"text": "Now let's imagine we have another view in myapp “morning” and we want to map it in myapp/url.py, we will then change our myapp/url.py to −"
},
{
"code": null,
"e": 5988,
"s": 5786,
"text": "from django.conf.urls import patterns, include, url\n\nurlpatterns = patterns('',\n url(r'^hello/', 'myapp.views.hello', name = 'hello'),\n url(r'^morning/', 'myapp.views.morning', name = 'morning'),\n)"
},
{
"code": null,
"e": 6017,
"s": 5988,
"text": "This can be re-factored to −"
},
{
"code": null,
"e": 6205,
"s": 6017,
"text": "from django.conf.urls import patterns, include, url\n\nurlpatterns = patterns('myapp.views',\n url(r'^hello/', 'hello', name = 'hello'),\n url(r'^morning/', 'morning', name = 'morning'),)"
},
{
"code": null,
"e": 6334,
"s": 6205,
"text": "As you can see, we now use the first element of our urlpatterns tuple. This can be useful when you want to change your app name."
},
{
"code": null,
"e": 6532,
"s": 6334,
"text": "We now know how to map URL, how to organize them, now let us see how to send parameters to views. A classic sample is the article example (you want to access an article via “/articles/article_id”)."
},
{
"code": null,
"e": 6673,
"s": 6532,
"text": "Passing parameters is done by capturing them with the regexp in the URL pattern. If we have a view like the following one in “myapp/view.py”"
},
{
"code": null,
"e": 6931,
"s": 6673,
"text": "from django.shortcuts import render\nfrom django.http import HttpResponse\n\ndef hello(request):\n return render(request, \"hello.html\", {})\n\ndef viewArticle(request, articleId):\n text = \"Displaying article Number : %s\"%articleId\n return HttpResponse(text)"
},
{
"code": null,
"e": 7059,
"s": 6931,
"text": "We want to map it in myapp/url.py so we can access it via “/myapp/article/articleId”, we need the following in “myapp/url.py” −"
},
{
"code": null,
"e": 7308,
"s": 7059,
"text": "from django.conf.urls import patterns, include, url\n\nurlpatterns = patterns('myapp.views',\n url(r'^hello/', 'hello', name = 'hello'),\n url(r'^morning/', 'morning', name = 'morning'),\n url(r'^article/(\\d+)/', 'viewArticle', name = 'article'),)"
},
{
"code": null,
"e": 7474,
"s": 7308,
"text": "When Django will see the url: “/myapp/article/42” it will pass the parameters '42' to the viewArticle view, and in your browser you should get the following result −"
},
{
"code": null,
"e": 7639,
"s": 7474,
"text": "Note that the order of parameters is important here. Suppose we want the list of articles of a month of a year, let's add a viewArticles view. Our view.py becomes −"
},
{
"code": null,
"e": 8023,
"s": 7639,
"text": "from django.shortcuts import render\nfrom django.http import HttpResponse\n\ndef hello(request):\n return render(request, \"hello.html\", {})\n\ndef viewArticle(request, articleId):\n text = \"Displaying article Number : %s\"%articleId\n return HttpResponse(text)\n\ndef viewArticle(request, month, year):\n text = \"Displaying articles of : %s/%s\"%(year, month)\n return HttpResponse(text)"
},
{
"code": null,
"e": 8070,
"s": 8023,
"text": "The corresponding url.py file will look like −"
},
{
"code": null,
"e": 8392,
"s": 8070,
"text": "from django.conf.urls import patterns, include, url\n\nurlpatterns = patterns('myapp.views',\n url(r'^hello/', 'hello', name = 'hello'),\n url(r'^morning/', 'morning', name = 'morning'),\n url(r'^article/(\\d+)/', 'viewArticle', name = 'article'),\n url(r'^articles/(\\d{2})/(\\d{4})', 'viewArticles', name = 'articles'),)"
},
{
"code": null,
"e": 8550,
"s": 8392,
"text": "Now when you go to “/myapp/articles/12/2006/” you will get 'Displaying articles of: 2006/12' but if you reverse the parameters you won’t get the same result."
},
{
"code": null,
"e": 8662,
"s": 8550,
"text": "To avoid that, it is possible to link a URL parameter to the view parameter. For that, our url.py will become −"
},
{
"code": null,
"e": 8988,
"s": 8662,
"text": "from django.conf.urls import patterns, include, url\n\nurlpatterns = patterns('myapp.views',\n url(r'^hello/', 'hello', name = 'hello'),\n url(r'^morning/', 'morning', name = 'morning'),\n url(r'^article/(\\d+)/', 'viewArticle', name = 'article'),\n url(r'^articles/(?P\\d{2})/(?P\\d{4})', 'viewArticles', name = 'articles'),)"
},
{
"code": null,
"e": 9023,
"s": 8988,
"text": "\n 39 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 9035,
"s": 9023,
"text": " John Elder"
},
{
"code": null,
"e": 9070,
"s": 9035,
"text": "\n 36 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9082,
"s": 9070,
"text": " John Elder"
},
{
"code": null,
"e": 9115,
"s": 9082,
"text": "\n 28 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 9127,
"s": 9115,
"text": " John Elder"
},
{
"code": null,
"e": 9160,
"s": 9127,
"text": "\n 20 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9172,
"s": 9160,
"text": " John Elder"
},
{
"code": null,
"e": 9205,
"s": 9172,
"text": "\n 35 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 9217,
"s": 9205,
"text": " John Elder"
},
{
"code": null,
"e": 9251,
"s": 9217,
"text": "\n 79 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 9265,
"s": 9251,
"text": " Rathan Kumar"
},
{
"code": null,
"e": 9272,
"s": 9265,
"text": " Print"
},
{
"code": null,
"e": 9283,
"s": 9272,
"text": " Add Notes"
}
] |
How to BIND a DBRM directly into a PLAN? | A DBRM is a DB2 object which is generated from the pre-compilation of the source code. It contains all the SQL statements/queries of the source code. DBRM could not be executed directly due to its format, hence it is binded into a plan first. There can be multiple DBRM which can be binded in a single plan.
Whenever there is a source code change, corresponding DBRM has to be generated again with changed SQL statements/queries. Then the entire plan (which contains the old DBRM) has to be bound again.
Using the below JCL step we can BIND a DBRM directly into a PLAN.
//BIND EXEC PGM=IKJEFT01
//STEPLIB DD DSN=DIS.TEST.LOADLIB,DISP=SHR
//SYSOUT DD SYSOUT=*
//SYSTSIN DD *
DSN SYSTEM(TB3)
BIND PLAN(PLANA) -
MEMBER(DBRM1) -
LIB(‘DIS.TEST.DBRM’)
/*
The BIND PLAN parameter has the name of the plan which needs to be binded. The MEMBER parameter is the name of the DBRM PDS member residing in the PDS DIS.TEST.DBRM. | [
{
"code": null,
"e": 1370,
"s": 1062,
"text": "A DBRM is a DB2 object which is generated from the pre-compilation of the source code. It contains all the SQL statements/queries of the source code. DBRM could not be executed directly due to its format, hence it is binded into a plan first. There can be multiple DBRM which can be binded in a single plan."
},
{
"code": null,
"e": 1566,
"s": 1370,
"text": "Whenever there is a source code change, corresponding DBRM has to be generated again with changed SQL statements/queries. Then the entire plan (which contains the old DBRM) has to be bound again."
},
{
"code": null,
"e": 1632,
"s": 1566,
"text": "Using the below JCL step we can BIND a DBRM directly into a PLAN."
},
{
"code": null,
"e": 1811,
"s": 1632,
"text": "//BIND EXEC PGM=IKJEFT01\n//STEPLIB DD DSN=DIS.TEST.LOADLIB,DISP=SHR\n//SYSOUT DD SYSOUT=*\n//SYSTSIN DD *\nDSN SYSTEM(TB3)\nBIND PLAN(PLANA) -\nMEMBER(DBRM1) -\nLIB(‘DIS.TEST.DBRM’)\n/*"
},
{
"code": null,
"e": 1977,
"s": 1811,
"text": "The BIND PLAN parameter has the name of the plan which needs to be binded. The MEMBER parameter is the name of the DBRM PDS member residing in the PDS DIS.TEST.DBRM."
}
] |
Interleave the first half of the queue with second half - GeeksforGeeks | 05 May, 2022
Given a queue of integers of even length, rearrange the elements by interleaving the first half of the queue with the second half of the queue. Only a stack can be used as an auxiliary space. Examples:
Input : 1 2 3 4
Output : 1 3 2 4
Input : 11 12 13 14 15 16 17 18 19 20
Output : 11 16 12 17 13 18 14 19 15 20
Following are the steps to solve the problem: 1.Push the first half elements of queue to stack. 2.Enqueue back the stack elements. 3.Dequeue the first half elements of the queue and enqueue them back. 4.Again push the first half elements into the stack. 5.Interleave the elements of queue and stack.
C++
Java
Python3
C#
Javascript
// C++ program to interleave the first half of the queue// with the second half#include <bits/stdc++.h>using namespace std; // Function to interleave the queuevoid interLeaveQueue(queue<int>& q){ // To check the even number of elements if (q.size() % 2 != 0) cout << "Input even number of integers." << endl; // Initialize an empty stack of int type stack<int> s; int halfSize = q.size() / 2; // Push first half elements into the stack // queue:16 17 18 19 20, stack: 15(T) 14 13 12 11 for (int i = 0; i < halfSize; i++) { s.push(q.front()); q.pop(); } // enqueue back the stack elements // queue: 16 17 18 19 20 15 14 13 12 11 while (!s.empty()) { q.push(s.top()); s.pop(); } // dequeue the first half elements of queue // and enqueue them back // queue: 15 14 13 12 11 16 17 18 19 20 for (int i = 0; i < halfSize; i++) { q.push(q.front()); q.pop(); } // Again push the first half elements into the stack // queue: 16 17 18 19 20, stack: 11(T) 12 13 14 15 for (int i = 0; i < halfSize; i++) { s.push(q.front()); q.pop(); } // interleave the elements of queue and stack // queue: 11 16 12 17 13 18 14 19 15 20 while (!s.empty()) { q.push(s.top()); s.pop(); q.push(q.front()); q.pop(); }} // Driver program to test above functionint main(){ queue<int> q; q.push(11); q.push(12); q.push(13); q.push(14); q.push(15); q.push(16); q.push(17); q.push(18); q.push(19); q.push(20); interLeaveQueue(q); int length = q.size(); for (int i = 0; i < length; i++) { cout << q.front() << " "; q.pop(); } return 0;}
// Java program to interleave// the first half of the queue// with the second halfimport java.util.*; class GFG{ // Function to interleave the queuestatic void interLeaveQueue(Queue<Integer>q){ // To check the even number of elements if (q.size() % 2 != 0) System.out.println("Input even number of integers." ); // Initialize an empty stack of int type Stack<Integer> s = new Stack<>(); int halfSize = q.size() / 2; // Push first half elements into the stack // queue:16 17 18 19 20, stack: 15(T) 14 13 12 11 for (int i = 0; i < halfSize; i++) { s.push(q.peek()); q.poll(); } // enqueue back the stack elements // queue: 16 17 18 19 20 15 14 13 12 11 while (!s.empty()) { q.add(s.peek()); s.pop(); } // dequeue the first half elements of queue // and enqueue them back // queue: 15 14 13 12 11 16 17 18 19 20 for (int i = 0; i < halfSize; i++) { q.add(q.peek()); q.poll(); } // Again push the first half elements into the stack // queue: 16 17 18 19 20, stack: 11(T) 12 13 14 15 for (int i = 0; i < halfSize; i++) { s.push(q.peek()); q.poll(); } // interleave the elements of queue and stack // queue: 11 16 12 17 13 18 14 19 15 20 while (!s.empty()) { q.add(s.peek()); s.pop(); q.add(q.peek()); q.poll(); }} // Driver codepublic static void main(String[] args){ Queue<Integer> q = new java.util.LinkedList<>(); q.add(11); q.add(12); q.add(13); q.add(14); q.add(15); q.add(16); q.add(17); q.add(18); q.add(19); q.add(20); interLeaveQueue(q); int length = q.size(); for (int i = 0; i < length; i++) { System.out.print(q.peek() + " "); q.poll(); }}} // This code contributed by Rajput-Ji
# Python3 program to interleave the first# half of the queue with the second halffrom queue import Queue # Function to interleave the queuedef interLeaveQueue(q): # To check the even number of elements if (q.qsize() % 2 != 0): print("Input even number of integers.") # Initialize an empty stack of int type s = [] halfSize = int(q.qsize() / 2) # put first half elements into # the stack queue:16 17 18 19 20, # stack: 15(T) 14 13 12 11 for i in range(halfSize): s.append(q.queue[0]) q.get() # enqueue back the stack elements # queue: 16 17 18 19 20 15 14 13 12 11 while len(s) != 0: q.put(s[-1]) s.pop() # dequeue the first half elements of # queue and enqueue them back # queue: 15 14 13 12 11 16 17 18 19 20 for i in range(halfSize): q.put(q.queue[0]) q.get() # Again put the first half elements into # the stack queue: 16 17 18 19 20, # stack: 11(T) 12 13 14 15 for i in range(halfSize): s.append(q.queue[0]) q.get() # interleave the elements of queue and stack # queue: 11 16 12 17 13 18 14 19 15 20 while len(s) != 0: q.put(s[-1]) s.pop() q.put(q.queue[0]) q.get() # Driver Codeif __name__ == '__main__': q = Queue() q.put(11) q.put(12) q.put(13) q.put(14) q.put(15) q.put(16) q.put(17) q.put(18) q.put(19) q.put(20) interLeaveQueue(q) length = q.qsize() for i in range(length): print(q.queue[0], end = " ") q.get() # This code is contributed by PranchalK
// C# program to interleave// the first half of the queue// with the second halfusing System;using System.Collections.Generic; class GFG{ // Function to interleave the queuestatic void interLeaveQueue(Queue<int>q){ // To check the even number of elements if (q.Count % 2 != 0) Console.WriteLine("Input even number of integers." ); // Initialize an empty stack of int type Stack<int> s = new Stack<int>(); int halfSize = q.Count / 2; // Push first half elements into the stack // queue:16 17 18 19 20, stack: 15(T) 14 13 12 11 for (int i = 0; i < halfSize; i++) { s.Push(q.Peek()); q.Dequeue(); } // enqueue back the stack elements // queue: 16 17 18 19 20 15 14 13 12 11 while (s.Count != 0) { q.Enqueue(s.Peek()); s.Pop(); } // dequeue the first half elements of queue // and enqueue them back // queue: 15 14 13 12 11 16 17 18 19 20 for (int i = 0; i < halfSize; i++) { q.Enqueue(q.Peek()); q.Dequeue(); } // Again push the first half elements into the stack // queue: 16 17 18 19 20, stack: 11(T) 12 13 14 15 for (int i = 0; i < halfSize; i++) { s.Push(q.Peek()); q.Dequeue(); } // interleave the elements of queue and stack // queue: 11 16 12 17 13 18 14 19 15 20 while (s.Count != 0) { q.Enqueue(s.Peek()); s.Pop(); q.Enqueue(q.Peek()); q.Dequeue(); }} // Driver codepublic static void Main(String[] args){ Queue<int> q = new Queue<int>(); q.Enqueue(11); q.Enqueue(12); q.Enqueue(13); q.Enqueue(14); q.Enqueue(15); q.Enqueue(16); q.Enqueue(17); q.Enqueue(18); q.Enqueue(19); q.Enqueue(20); interLeaveQueue(q); int length = q.Count; for (int i = 0; i < length; i++) { Console.Write(q.Peek() + " "); q.Dequeue(); }}} // This code is contributed by Princi Singh
<script> // JavaScript program to interleave the first// half of the queue with the second half // Function to interleave the queuefunction interLeaveQueue(q){ // To check the even number of elements if (q.length % 2 != 0) document.write("Inpush even number of integers.") // Initialize an empty stack of int type let s = [] let halfSize = Math.floor(q.length / 2) // push first half elements into // the stack queue:16 17 18 19 20, // stack: 15(T) 14 13 12 11 for(let i = 0; i < halfSize; i++) s.push(q.shift()) // enqueue back the stack elements // queue: 16 17 18 19 20 15 14 13 12 11 while(s.length != 0){ q.push(s[s.length-1]) s.pop() } // dequeue the first half elements of // queue and enqueue them back // queue: 15 14 13 12 11 16 17 18 19 20 for(let i = 0; i < halfSize; i++) q.push(q.shift()) // Again push the first half elements into // the stack queue: 16 17 18 19 20, // stack: 11(T) 12 13 14 15 for(let i = 0; i < halfSize; i++) s.push(q.shift()) // interleave the elements of queue and stack // queue: 11 16 12 17 13 18 14 19 15 20 while(s.length != 0){ q.push(s[s.length-1]) s.pop() q.push(q.shift()) }} // Driver Code let q =[]q.push(11)q.push(12)q.push(13)q.push(14)q.push(15)q.push(16)q.push(17)q.push(18)q.push(19)q.push(20)interLeaveQueue(q)let length = q.lengthfor(let i=0;i<length;i++) document.write(q.shift()," ") // This code is contributed by shinjanpatra </script>
Output:
11 16 12 17 13 18 14 19 15 20
Time complexity: O(n). Auxiliary Space: O(n).
YouTubeGeeksforGeeks507K subscribersInterleave the first half of the queue with second half | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:41•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=BNuXP58kAWk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Prakriti Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
PranchalKatiyar
Rajput-Ji
princi singh
shinjanpatra
Queue
Stack
Stack
Queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Queue | Set 1 (Introduction and Array Implementation)
Priority Queue | Set 1 (Introduction)
LRU Cache Implementation
Queue - Linked List Implementation
Circular Queue | Set 1 (Introduction and Array Implementation)
Stack Data Structure (Introduction and Program)
Stack Class in Java
Stack in Python
Check for Balanced Brackets in an expression (well-formedness) using Stack
Stack | Set 2 (Infix to Postfix) | [
{
"code": null,
"e": 25933,
"s": 25905,
"text": "\n05 May, 2022"
},
{
"code": null,
"e": 26135,
"s": 25933,
"text": "Given a queue of integers of even length, rearrange the elements by interleaving the first half of the queue with the second half of the queue. Only a stack can be used as an auxiliary space. Examples:"
},
{
"code": null,
"e": 26247,
"s": 26135,
"text": "Input : 1 2 3 4\nOutput : 1 3 2 4\n\nInput : 11 12 13 14 15 16 17 18 19 20\nOutput : 11 16 12 17 13 18 14 19 15 20"
},
{
"code": null,
"e": 26548,
"s": 26247,
"text": "Following are the steps to solve the problem: 1.Push the first half elements of queue to stack. 2.Enqueue back the stack elements. 3.Dequeue the first half elements of the queue and enqueue them back. 4.Again push the first half elements into the stack. 5.Interleave the elements of queue and stack. "
},
{
"code": null,
"e": 26552,
"s": 26548,
"text": "C++"
},
{
"code": null,
"e": 26557,
"s": 26552,
"text": "Java"
},
{
"code": null,
"e": 26565,
"s": 26557,
"text": "Python3"
},
{
"code": null,
"e": 26568,
"s": 26565,
"text": "C#"
},
{
"code": null,
"e": 26579,
"s": 26568,
"text": "Javascript"
},
{
"code": "// C++ program to interleave the first half of the queue// with the second half#include <bits/stdc++.h>using namespace std; // Function to interleave the queuevoid interLeaveQueue(queue<int>& q){ // To check the even number of elements if (q.size() % 2 != 0) cout << \"Input even number of integers.\" << endl; // Initialize an empty stack of int type stack<int> s; int halfSize = q.size() / 2; // Push first half elements into the stack // queue:16 17 18 19 20, stack: 15(T) 14 13 12 11 for (int i = 0; i < halfSize; i++) { s.push(q.front()); q.pop(); } // enqueue back the stack elements // queue: 16 17 18 19 20 15 14 13 12 11 while (!s.empty()) { q.push(s.top()); s.pop(); } // dequeue the first half elements of queue // and enqueue them back // queue: 15 14 13 12 11 16 17 18 19 20 for (int i = 0; i < halfSize; i++) { q.push(q.front()); q.pop(); } // Again push the first half elements into the stack // queue: 16 17 18 19 20, stack: 11(T) 12 13 14 15 for (int i = 0; i < halfSize; i++) { s.push(q.front()); q.pop(); } // interleave the elements of queue and stack // queue: 11 16 12 17 13 18 14 19 15 20 while (!s.empty()) { q.push(s.top()); s.pop(); q.push(q.front()); q.pop(); }} // Driver program to test above functionint main(){ queue<int> q; q.push(11); q.push(12); q.push(13); q.push(14); q.push(15); q.push(16); q.push(17); q.push(18); q.push(19); q.push(20); interLeaveQueue(q); int length = q.size(); for (int i = 0; i < length; i++) { cout << q.front() << \" \"; q.pop(); } return 0;}",
"e": 28316,
"s": 26579,
"text": null
},
{
"code": "// Java program to interleave// the first half of the queue// with the second halfimport java.util.*; class GFG{ // Function to interleave the queuestatic void interLeaveQueue(Queue<Integer>q){ // To check the even number of elements if (q.size() % 2 != 0) System.out.println(\"Input even number of integers.\" ); // Initialize an empty stack of int type Stack<Integer> s = new Stack<>(); int halfSize = q.size() / 2; // Push first half elements into the stack // queue:16 17 18 19 20, stack: 15(T) 14 13 12 11 for (int i = 0; i < halfSize; i++) { s.push(q.peek()); q.poll(); } // enqueue back the stack elements // queue: 16 17 18 19 20 15 14 13 12 11 while (!s.empty()) { q.add(s.peek()); s.pop(); } // dequeue the first half elements of queue // and enqueue them back // queue: 15 14 13 12 11 16 17 18 19 20 for (int i = 0; i < halfSize; i++) { q.add(q.peek()); q.poll(); } // Again push the first half elements into the stack // queue: 16 17 18 19 20, stack: 11(T) 12 13 14 15 for (int i = 0; i < halfSize; i++) { s.push(q.peek()); q.poll(); } // interleave the elements of queue and stack // queue: 11 16 12 17 13 18 14 19 15 20 while (!s.empty()) { q.add(s.peek()); s.pop(); q.add(q.peek()); q.poll(); }} // Driver codepublic static void main(String[] args){ Queue<Integer> q = new java.util.LinkedList<>(); q.add(11); q.add(12); q.add(13); q.add(14); q.add(15); q.add(16); q.add(17); q.add(18); q.add(19); q.add(20); interLeaveQueue(q); int length = q.size(); for (int i = 0; i < length; i++) { System.out.print(q.peek() + \" \"); q.poll(); }}} // This code contributed by Rajput-Ji",
"e": 30154,
"s": 28316,
"text": null
},
{
"code": "# Python3 program to interleave the first# half of the queue with the second halffrom queue import Queue # Function to interleave the queuedef interLeaveQueue(q): # To check the even number of elements if (q.qsize() % 2 != 0): print(\"Input even number of integers.\") # Initialize an empty stack of int type s = [] halfSize = int(q.qsize() / 2) # put first half elements into # the stack queue:16 17 18 19 20, # stack: 15(T) 14 13 12 11 for i in range(halfSize): s.append(q.queue[0]) q.get() # enqueue back the stack elements # queue: 16 17 18 19 20 15 14 13 12 11 while len(s) != 0: q.put(s[-1]) s.pop() # dequeue the first half elements of # queue and enqueue them back # queue: 15 14 13 12 11 16 17 18 19 20 for i in range(halfSize): q.put(q.queue[0]) q.get() # Again put the first half elements into # the stack queue: 16 17 18 19 20, # stack: 11(T) 12 13 14 15 for i in range(halfSize): s.append(q.queue[0]) q.get() # interleave the elements of queue and stack # queue: 11 16 12 17 13 18 14 19 15 20 while len(s) != 0: q.put(s[-1]) s.pop() q.put(q.queue[0]) q.get() # Driver Codeif __name__ == '__main__': q = Queue() q.put(11) q.put(12) q.put(13) q.put(14) q.put(15) q.put(16) q.put(17) q.put(18) q.put(19) q.put(20) interLeaveQueue(q) length = q.qsize() for i in range(length): print(q.queue[0], end = \" \") q.get() # This code is contributed by PranchalK",
"e": 31742,
"s": 30154,
"text": null
},
{
"code": "// C# program to interleave// the first half of the queue// with the second halfusing System;using System.Collections.Generic; class GFG{ // Function to interleave the queuestatic void interLeaveQueue(Queue<int>q){ // To check the even number of elements if (q.Count % 2 != 0) Console.WriteLine(\"Input even number of integers.\" ); // Initialize an empty stack of int type Stack<int> s = new Stack<int>(); int halfSize = q.Count / 2; // Push first half elements into the stack // queue:16 17 18 19 20, stack: 15(T) 14 13 12 11 for (int i = 0; i < halfSize; i++) { s.Push(q.Peek()); q.Dequeue(); } // enqueue back the stack elements // queue: 16 17 18 19 20 15 14 13 12 11 while (s.Count != 0) { q.Enqueue(s.Peek()); s.Pop(); } // dequeue the first half elements of queue // and enqueue them back // queue: 15 14 13 12 11 16 17 18 19 20 for (int i = 0; i < halfSize; i++) { q.Enqueue(q.Peek()); q.Dequeue(); } // Again push the first half elements into the stack // queue: 16 17 18 19 20, stack: 11(T) 12 13 14 15 for (int i = 0; i < halfSize; i++) { s.Push(q.Peek()); q.Dequeue(); } // interleave the elements of queue and stack // queue: 11 16 12 17 13 18 14 19 15 20 while (s.Count != 0) { q.Enqueue(s.Peek()); s.Pop(); q.Enqueue(q.Peek()); q.Dequeue(); }} // Driver codepublic static void Main(String[] args){ Queue<int> q = new Queue<int>(); q.Enqueue(11); q.Enqueue(12); q.Enqueue(13); q.Enqueue(14); q.Enqueue(15); q.Enqueue(16); q.Enqueue(17); q.Enqueue(18); q.Enqueue(19); q.Enqueue(20); interLeaveQueue(q); int length = q.Count; for (int i = 0; i < length; i++) { Console.Write(q.Peek() + \" \"); q.Dequeue(); }}} // This code is contributed by Princi Singh",
"e": 33658,
"s": 31742,
"text": null
},
{
"code": "<script> // JavaScript program to interleave the first// half of the queue with the second half // Function to interleave the queuefunction interLeaveQueue(q){ // To check the even number of elements if (q.length % 2 != 0) document.write(\"Inpush even number of integers.\") // Initialize an empty stack of int type let s = [] let halfSize = Math.floor(q.length / 2) // push first half elements into // the stack queue:16 17 18 19 20, // stack: 15(T) 14 13 12 11 for(let i = 0; i < halfSize; i++) s.push(q.shift()) // enqueue back the stack elements // queue: 16 17 18 19 20 15 14 13 12 11 while(s.length != 0){ q.push(s[s.length-1]) s.pop() } // dequeue the first half elements of // queue and enqueue them back // queue: 15 14 13 12 11 16 17 18 19 20 for(let i = 0; i < halfSize; i++) q.push(q.shift()) // Again push the first half elements into // the stack queue: 16 17 18 19 20, // stack: 11(T) 12 13 14 15 for(let i = 0; i < halfSize; i++) s.push(q.shift()) // interleave the elements of queue and stack // queue: 11 16 12 17 13 18 14 19 15 20 while(s.length != 0){ q.push(s[s.length-1]) s.pop() q.push(q.shift()) }} // Driver Code let q =[]q.push(11)q.push(12)q.push(13)q.push(14)q.push(15)q.push(16)q.push(17)q.push(18)q.push(19)q.push(20)interLeaveQueue(q)let length = q.lengthfor(let i=0;i<length;i++) document.write(q.shift(),\" \") // This code is contributed by shinjanpatra </script>",
"e": 35204,
"s": 33658,
"text": null
},
{
"code": null,
"e": 35212,
"s": 35204,
"text": "Output:"
},
{
"code": null,
"e": 35243,
"s": 35212,
"text": "11 16 12 17 13 18 14 19 15 20 "
},
{
"code": null,
"e": 35289,
"s": 35243,
"text": "Time complexity: O(n). Auxiliary Space: O(n)."
},
{
"code": null,
"e": 36143,
"s": 35289,
"text": "YouTubeGeeksforGeeks507K subscribersInterleave the first half of the queue with second half | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:41•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=BNuXP58kAWk\" 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": 36566,
"s": 36143,
"text": "This article is contributed by Prakriti Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 36582,
"s": 36566,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 36592,
"s": 36582,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 36605,
"s": 36592,
"text": "princi singh"
},
{
"code": null,
"e": 36618,
"s": 36605,
"text": "shinjanpatra"
},
{
"code": null,
"e": 36624,
"s": 36618,
"text": "Queue"
},
{
"code": null,
"e": 36630,
"s": 36624,
"text": "Stack"
},
{
"code": null,
"e": 36636,
"s": 36630,
"text": "Stack"
},
{
"code": null,
"e": 36642,
"s": 36636,
"text": "Queue"
},
{
"code": null,
"e": 36740,
"s": 36642,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36794,
"s": 36740,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 36832,
"s": 36794,
"text": "Priority Queue | Set 1 (Introduction)"
},
{
"code": null,
"e": 36857,
"s": 36832,
"text": "LRU Cache Implementation"
},
{
"code": null,
"e": 36892,
"s": 36857,
"text": "Queue - Linked List Implementation"
},
{
"code": null,
"e": 36955,
"s": 36892,
"text": "Circular Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 37003,
"s": 36955,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 37023,
"s": 37003,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 37039,
"s": 37023,
"text": "Stack in Python"
},
{
"code": null,
"e": 37114,
"s": 37039,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
}
] |
Minimum cost of path between given nodes containing at most K nodes in a directed and weighted graph - GeeksforGeeks | 10 Feb, 2022
Given a directed weighted graph represented by a 2-D array graph[][] of size n and 3 integers src, dst, and k representing the source point, destination point, and the available number of stops. The task is to minimize the cost of the path between two nodes containing at most K nodes in a directed and weighted graph. If there is no such route, return -1.
Examples:
Input: n=6, graph[][] = [[0, 1, 10], [1, 2, 20], [1, 3, 10], [2, 5, 30], [3, 4, 10], [4, 5, 10]], src=0, dst=5, k=2Output: 60Explanation:
Src = 0, Dst = 5 and k = 2
There can be a route marked with a green arrow that takes cost = 10+10+10+10=40 using three stops. And route marked with red arrow takes cost = 10+20+30=60 using two stops. But since there can be at most 2 stops, the answer will be 60.
Input: n=3, graph[][] = [[0, 1, 10], [0, 2, 50], [1, 2, 10], src=0, dst=2, k=1Output: 20Explanation:
Src=0 and Dst=2
Since the k is 1, then the green-colored path can be taken with a minimum cost of 20.
Approach: Increase k by 1 because on reaching the destination, k+1 stops will be consumed. Use Breadth-first search to run while loop till the queue becomes empty. At each time pop out all the elements from the queue and decrease k by 1 and check-in their adjacent list of elements and check they are not visited before or their cost is greater than the cost of parent node + cost of that node, then mark their prices by prices[parent] + cost of that node. If k becomes 0 then break the while loop because either cost is calculated or we consumed k+1 stops. Follow the steps below to solve the problem:
Increase the value of k by 1.
Initialize a vector of pair adj[n] and construct the adjacency list for the graph.
Initialize a vector prices[n] with values -1.
Initialize a queue of pair q[].
Push the pair {src, 0} into the queue and set the value of prices[0] as 0.
Traverse in a while loop until the queue becomes empty and perform the following steps:If k equals 0 then break.Initialize the variable sz as the size of the queue.Traverse in a while loop until sz is greater than 0 and perform the following tasks:Initialize the variables node as the first value of the front pair of the queue and cost as the second value of the front pair of the queue.Iterate over the range [0, adj[node].size()) using the variable it and perform the following tasks:If prices[it.first] equals -1 or cost + it.second is less than prices[it.first] then set the value of prices[it.first] as cost + it.second and push the pair {it.first, cost + it.second} into the queue.Reduce the value of k by 1.
If k equals 0 then break.
Initialize the variable sz as the size of the queue.
Traverse in a while loop until sz is greater than 0 and perform the following tasks:Initialize the variables node as the first value of the front pair of the queue and cost as the second value of the front pair of the queue.Iterate over the range [0, adj[node].size()) using the variable it and perform the following tasks:If prices[it.first] equals -1 or cost + it.second is less than prices[it.first] then set the value of prices[it.first] as cost + it.second and push the pair {it.first, cost + it.second} into the queue.
Initialize the variables node as the first value of the front pair of the queue and cost as the second value of the front pair of the queue.
Iterate over the range [0, adj[node].size()) using the variable it and perform the following tasks:If prices[it.first] equals -1 or cost + it.second is less than prices[it.first] then set the value of prices[it.first] as cost + it.second and push the pair {it.first, cost + it.second} into the queue.
If prices[it.first] equals -1 or cost + it.second is less than prices[it.first] then set the value of prices[it.first] as cost + it.second and push the pair {it.first, cost + it.second} into the queue.
Reduce the value of k by 1.
After performing the above steps, print the value of prices[dst] as the answer.
Below is the implementation of the above approach:
C++
Java
Python3
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum cost// from src to dst with at most k stopsint findCheapestCost(int n, vector<vector<int> >& graph, int src, int dst, int k){ // Increase k by 1 Because on reaching // destination, k becomes k+1 k = k + 1; // Making Adjacency List vector<pair<int, int> > adj[n]; // U->{v, wt} for (auto it : graph) { adj[it[0]].push_back({ it[1], it[2] }); } // Vector for Storing prices vector<int> prices(n, -1); // Queue for storing vertex and cost queue<pair<int, int> > q; q.push({ src, 0 }); prices[src] = 0; while (!q.empty()) { // If all the k stops are used, // then break if (k == 0) break; int sz = q.size(); while (sz--) { int node = q.front().first; int cost = q.front().second; q.pop(); for (auto it : adj[node]) { if (prices[it.first] == -1 or cost + it.second < prices[it.first]) { prices[it.first] = cost + it.second; q.push({ it.first, cost + it.second }); } } } k--; } return prices[dst];} // Driver Codeint main(){ int n = 6; vector<vector<int> > graph = { { 0, 1, 10 }, { 1, 2, 20 }, { 2, 5, 30 }, { 1, 3, 10 }, { 3, 4, 10 }, { 4, 5, 10 } }; int src = 0; int dst = 5; int k = 2; cout << findCheapestCost(n, graph, src, dst, k) << endl; return 0;}
// Java program for the above approachimport java.util.*; class GFG{ static class pair { int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } // Function to find the minimum cost // from src to dst with at most k stops static int findCheapestCost(int n, int[][] graph, int src, int dst, int k) { // Increase k by 1 Because on reaching // destination, k becomes k+1 k = k + 1; // Making Adjacency List Vector<pair> []adj = new Vector[n]; for (int i = 0; i < adj.length; i++) adj[i] = new Vector<pair>(); // U.{v, wt} for (int it[] : graph) { adj[it[0]].add(new pair( it[1], it[2] )); } // Vector for Storing prices int []prices = new int[n]; Arrays.fill(prices, -1); // Queue for storing vertex and cost Queue<pair > q = new LinkedList<>(); q.add(new pair( src, 0 )); prices[src] = 0; while (!q.isEmpty()) { // If all the k stops are used, // then break if (k == 0) break; int sz = q.size(); while (sz-- >0) { int node = q.peek().first; int cost = q.peek().second; q.remove(); for (pair it : adj[node]) { if (prices[it.first] == -1 || cost + it.second < prices[it.first]) { prices[it.first] = cost + it.second; q.add(new pair( it.first, cost + it.second )); } } } k--; } return prices[dst]; } // Driver Code public static void main(String[] args) { int n = 6; int[][] graph = { { 0, 1, 10 }, { 1, 2, 20 }, { 2, 5, 30 }, { 1, 3, 10 }, { 3, 4, 10 }, { 4, 5, 10 } }; int src = 0; int dst = 5; int k = 2; System.out.print(findCheapestCost(n, graph, src, dst, k) +"\n"); }} // This code is contributed by 29AjayKumar
# python3 program for the above approachfrom collections import deque # Function to find the minimum cost# from src to dst with at most k stopsdef findCheapestCost(n, graph, src, dst, k): # Increase k by 1 Because on reaching # destination, k becomes k+1 k = k + 1 # Making Adjacency List adj = [[] for _ in range(n)] # U->{v, wt} for it in graph: adj[it[0]].append([it[1], it[2]]) # Vector for Storing prices prices = [-1 for _ in range(n)] # Queue for storing vertex and cost q = deque() q.append([src, 0]) prices[src] = 0 while (len(q) != 0): # If all the k stops are used, # then break if (k == 0): break sz = len(q) while (True): sz -= 1 pr = q.popleft() node = pr[0] cost = pr[1] for it in adj[node]: if (prices[it[0]] == -1 or cost + it[1] < prices[it[0]]): prices[it[0]] = cost + it[1] q.append([it[0], cost + it[1]]) if sz == 0: break k -= 1 return prices[dst] # Driver Codeif __name__ == "__main__": n = 6 graph = [ [0, 1, 10], [1, 2, 20], [2, 5, 30], [1, 3, 10], [3, 4, 10], [4, 5, 10]] src = 0 dst = 5 k = 2 print(findCheapestCost(n, graph, src, dst, k)) # This code is contributed by rakeshsahni
60
Time Complexity: O(n*k)Auxiliary Space: O(n)
rakeshsahni
kk773572498
29AjayKumar
Dijkstra
Shortest Path
Graph
Mathematical
Mathematical
Graph
Shortest Path
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Best First Search (Informed Search)
Longest Path in a Directed Acyclic Graph
Graph Coloring | Set 2 (Greedy Algorithm)
Maximum Bipartite Matching
Graph Coloring | Set 1 (Introduction and Applications)
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 26311,
"s": 26283,
"text": "\n10 Feb, 2022"
},
{
"code": null,
"e": 26668,
"s": 26311,
"text": "Given a directed weighted graph represented by a 2-D array graph[][] of size n and 3 integers src, dst, and k representing the source point, destination point, and the available number of stops. The task is to minimize the cost of the path between two nodes containing at most K nodes in a directed and weighted graph. If there is no such route, return -1."
},
{
"code": null,
"e": 26678,
"s": 26668,
"text": "Examples:"
},
{
"code": null,
"e": 26816,
"s": 26678,
"text": "Input: n=6, graph[][] = [[0, 1, 10], [1, 2, 20], [1, 3, 10], [2, 5, 30], [3, 4, 10], [4, 5, 10]], src=0, dst=5, k=2Output: 60Explanation:"
},
{
"code": null,
"e": 26843,
"s": 26816,
"text": "Src = 0, Dst = 5 and k = 2"
},
{
"code": null,
"e": 27080,
"s": 26843,
"text": "There can be a route marked with a green arrow that takes cost = 10+10+10+10=40 using three stops. And route marked with red arrow takes cost = 10+20+30=60 using two stops. But since there can be at most 2 stops, the answer will be 60."
},
{
"code": null,
"e": 27182,
"s": 27080,
"text": "Input: n=3, graph[][] = [[0, 1, 10], [0, 2, 50], [1, 2, 10], src=0, dst=2, k=1Output: 20Explanation:"
},
{
"code": null,
"e": 27198,
"s": 27182,
"text": "Src=0 and Dst=2"
},
{
"code": null,
"e": 27284,
"s": 27198,
"text": "Since the k is 1, then the green-colored path can be taken with a minimum cost of 20."
},
{
"code": null,
"e": 27887,
"s": 27284,
"text": "Approach: Increase k by 1 because on reaching the destination, k+1 stops will be consumed. Use Breadth-first search to run while loop till the queue becomes empty. At each time pop out all the elements from the queue and decrease k by 1 and check-in their adjacent list of elements and check they are not visited before or their cost is greater than the cost of parent node + cost of that node, then mark their prices by prices[parent] + cost of that node. If k becomes 0 then break the while loop because either cost is calculated or we consumed k+1 stops. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 27917,
"s": 27887,
"text": "Increase the value of k by 1."
},
{
"code": null,
"e": 28000,
"s": 27917,
"text": "Initialize a vector of pair adj[n] and construct the adjacency list for the graph."
},
{
"code": null,
"e": 28046,
"s": 28000,
"text": "Initialize a vector prices[n] with values -1."
},
{
"code": null,
"e": 28078,
"s": 28046,
"text": "Initialize a queue of pair q[]."
},
{
"code": null,
"e": 28153,
"s": 28078,
"text": "Push the pair {src, 0} into the queue and set the value of prices[0] as 0."
},
{
"code": null,
"e": 28869,
"s": 28153,
"text": "Traverse in a while loop until the queue becomes empty and perform the following steps:If k equals 0 then break.Initialize the variable sz as the size of the queue.Traverse in a while loop until sz is greater than 0 and perform the following tasks:Initialize the variables node as the first value of the front pair of the queue and cost as the second value of the front pair of the queue.Iterate over the range [0, adj[node].size()) using the variable it and perform the following tasks:If prices[it.first] equals -1 or cost + it.second is less than prices[it.first] then set the value of prices[it.first] as cost + it.second and push the pair {it.first, cost + it.second} into the queue.Reduce the value of k by 1."
},
{
"code": null,
"e": 28895,
"s": 28869,
"text": "If k equals 0 then break."
},
{
"code": null,
"e": 28948,
"s": 28895,
"text": "Initialize the variable sz as the size of the queue."
},
{
"code": null,
"e": 29473,
"s": 28948,
"text": "Traverse in a while loop until sz is greater than 0 and perform the following tasks:Initialize the variables node as the first value of the front pair of the queue and cost as the second value of the front pair of the queue.Iterate over the range [0, adj[node].size()) using the variable it and perform the following tasks:If prices[it.first] equals -1 or cost + it.second is less than prices[it.first] then set the value of prices[it.first] as cost + it.second and push the pair {it.first, cost + it.second} into the queue."
},
{
"code": null,
"e": 29614,
"s": 29473,
"text": "Initialize the variables node as the first value of the front pair of the queue and cost as the second value of the front pair of the queue."
},
{
"code": null,
"e": 29915,
"s": 29614,
"text": "Iterate over the range [0, adj[node].size()) using the variable it and perform the following tasks:If prices[it.first] equals -1 or cost + it.second is less than prices[it.first] then set the value of prices[it.first] as cost + it.second and push the pair {it.first, cost + it.second} into the queue."
},
{
"code": null,
"e": 30117,
"s": 29915,
"text": "If prices[it.first] equals -1 or cost + it.second is less than prices[it.first] then set the value of prices[it.first] as cost + it.second and push the pair {it.first, cost + it.second} into the queue."
},
{
"code": null,
"e": 30145,
"s": 30117,
"text": "Reduce the value of k by 1."
},
{
"code": null,
"e": 30225,
"s": 30145,
"text": "After performing the above steps, print the value of prices[dst] as the answer."
},
{
"code": null,
"e": 30277,
"s": 30225,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 30281,
"s": 30277,
"text": "C++"
},
{
"code": null,
"e": 30286,
"s": 30281,
"text": "Java"
},
{
"code": null,
"e": 30294,
"s": 30286,
"text": "Python3"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum cost// from src to dst with at most k stopsint findCheapestCost(int n, vector<vector<int> >& graph, int src, int dst, int k){ // Increase k by 1 Because on reaching // destination, k becomes k+1 k = k + 1; // Making Adjacency List vector<pair<int, int> > adj[n]; // U->{v, wt} for (auto it : graph) { adj[it[0]].push_back({ it[1], it[2] }); } // Vector for Storing prices vector<int> prices(n, -1); // Queue for storing vertex and cost queue<pair<int, int> > q; q.push({ src, 0 }); prices[src] = 0; while (!q.empty()) { // If all the k stops are used, // then break if (k == 0) break; int sz = q.size(); while (sz--) { int node = q.front().first; int cost = q.front().second; q.pop(); for (auto it : adj[node]) { if (prices[it.first] == -1 or cost + it.second < prices[it.first]) { prices[it.first] = cost + it.second; q.push({ it.first, cost + it.second }); } } } k--; } return prices[dst];} // Driver Codeint main(){ int n = 6; vector<vector<int> > graph = { { 0, 1, 10 }, { 1, 2, 20 }, { 2, 5, 30 }, { 1, 3, 10 }, { 3, 4, 10 }, { 4, 5, 10 } }; int src = 0; int dst = 5; int k = 2; cout << findCheapestCost(n, graph, src, dst, k) << endl; return 0;}",
"e": 31933,
"s": 30294,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ static class pair { int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } // Function to find the minimum cost // from src to dst with at most k stops static int findCheapestCost(int n, int[][] graph, int src, int dst, int k) { // Increase k by 1 Because on reaching // destination, k becomes k+1 k = k + 1; // Making Adjacency List Vector<pair> []adj = new Vector[n]; for (int i = 0; i < adj.length; i++) adj[i] = new Vector<pair>(); // U.{v, wt} for (int it[] : graph) { adj[it[0]].add(new pair( it[1], it[2] )); } // Vector for Storing prices int []prices = new int[n]; Arrays.fill(prices, -1); // Queue for storing vertex and cost Queue<pair > q = new LinkedList<>(); q.add(new pair( src, 0 )); prices[src] = 0; while (!q.isEmpty()) { // If all the k stops are used, // then break if (k == 0) break; int sz = q.size(); while (sz-- >0) { int node = q.peek().first; int cost = q.peek().second; q.remove(); for (pair it : adj[node]) { if (prices[it.first] == -1 || cost + it.second < prices[it.first]) { prices[it.first] = cost + it.second; q.add(new pair( it.first, cost + it.second )); } } } k--; } return prices[dst]; } // Driver Code public static void main(String[] args) { int n = 6; int[][] graph = { { 0, 1, 10 }, { 1, 2, 20 }, { 2, 5, 30 }, { 1, 3, 10 }, { 3, 4, 10 }, { 4, 5, 10 } }; int src = 0; int dst = 5; int k = 2; System.out.print(findCheapestCost(n, graph, src, dst, k) +\"\\n\"); }} // This code is contributed by 29AjayKumar",
"e": 33854,
"s": 31933,
"text": null
},
{
"code": "# python3 program for the above approachfrom collections import deque # Function to find the minimum cost# from src to dst with at most k stopsdef findCheapestCost(n, graph, src, dst, k): # Increase k by 1 Because on reaching # destination, k becomes k+1 k = k + 1 # Making Adjacency List adj = [[] for _ in range(n)] # U->{v, wt} for it in graph: adj[it[0]].append([it[1], it[2]]) # Vector for Storing prices prices = [-1 for _ in range(n)] # Queue for storing vertex and cost q = deque() q.append([src, 0]) prices[src] = 0 while (len(q) != 0): # If all the k stops are used, # then break if (k == 0): break sz = len(q) while (True): sz -= 1 pr = q.popleft() node = pr[0] cost = pr[1] for it in adj[node]: if (prices[it[0]] == -1 or cost + it[1] < prices[it[0]]): prices[it[0]] = cost + it[1] q.append([it[0], cost + it[1]]) if sz == 0: break k -= 1 return prices[dst] # Driver Codeif __name__ == \"__main__\": n = 6 graph = [ [0, 1, 10], [1, 2, 20], [2, 5, 30], [1, 3, 10], [3, 4, 10], [4, 5, 10]] src = 0 dst = 5 k = 2 print(findCheapestCost(n, graph, src, dst, k)) # This code is contributed by rakeshsahni",
"e": 35352,
"s": 33854,
"text": null
},
{
"code": null,
"e": 35358,
"s": 35355,
"text": "60"
},
{
"code": null,
"e": 35405,
"s": 35360,
"text": "Time Complexity: O(n*k)Auxiliary Space: O(n)"
},
{
"code": null,
"e": 35419,
"s": 35407,
"text": "rakeshsahni"
},
{
"code": null,
"e": 35431,
"s": 35419,
"text": "kk773572498"
},
{
"code": null,
"e": 35443,
"s": 35431,
"text": "29AjayKumar"
},
{
"code": null,
"e": 35452,
"s": 35443,
"text": "Dijkstra"
},
{
"code": null,
"e": 35466,
"s": 35452,
"text": "Shortest Path"
},
{
"code": null,
"e": 35472,
"s": 35466,
"text": "Graph"
},
{
"code": null,
"e": 35485,
"s": 35472,
"text": "Mathematical"
},
{
"code": null,
"e": 35498,
"s": 35485,
"text": "Mathematical"
},
{
"code": null,
"e": 35504,
"s": 35498,
"text": "Graph"
},
{
"code": null,
"e": 35518,
"s": 35504,
"text": "Shortest Path"
},
{
"code": null,
"e": 35616,
"s": 35518,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35652,
"s": 35616,
"text": "Best First Search (Informed Search)"
},
{
"code": null,
"e": 35693,
"s": 35652,
"text": "Longest Path in a Directed Acyclic Graph"
},
{
"code": null,
"e": 35735,
"s": 35693,
"text": "Graph Coloring | Set 2 (Greedy Algorithm)"
},
{
"code": null,
"e": 35762,
"s": 35735,
"text": "Maximum Bipartite Matching"
},
{
"code": null,
"e": 35817,
"s": 35762,
"text": "Graph Coloring | Set 1 (Introduction and Applications)"
},
{
"code": null,
"e": 35847,
"s": 35817,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 35907,
"s": 35847,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 35922,
"s": 35907,
"text": "C++ Data Types"
},
{
"code": null,
"e": 35965,
"s": 35922,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Guidelines for asymptotic analysis - GeeksforGeeks | 09 Jul, 2021
In this article, the focus is on learning some rules that can help to determine the running time of an algorithm.
Asymptotic analysis refers to computing the running time of any operation in mathematical units of computation. In Asymptotic Analysis, the performance of an algorithm in terms of input size (we don’t measure the actual running time) is evaluated. How the time (or space) taken by an algorithm increases with the input size is also calculated.
(g(n)) = {f(n) such that g(n) is a curve which approximates f(n) at higher values of input size, n}
This curve is called asymptotic curve and the algorithm analysis for such a curve is called Asymptotic analysis.
Loops: The running time of a loop is, at most, the running time of the statements inside the loop, including tests) multiplied number of iterations.
Below is the python program that demonstrates the above concept:
Python3
# Python program to implement# the above concept# execute n times for in# range(0.00); for i in range(0, n):print ('Current Number:', i, sep = "")
#constant time
Total time a constant cx n = cn = O(n).
Nested loops: Analyze from the inside out. The total running time is the product of the sizes of all the loops.
Below is a python program that demonstrates the above concept:
Python3
# Python program to implement# the above concept# outer loop executed n timesfor i in range(0, n): # inner loop executes n times for j in range(0, n): print("i value % d and j value % d" % (i, j))
# constant time
Total time = C x n x n = cn^2 =0(n2).
Consecutive statements: Add the time complexity of each statement.
Below is a python program that demonstrates the above concept:
Python3
# Python program that implements# the above conceptn = 100 # executes n timesfor i in range (0, n): print (Current Number: i, sep = "") # outer loop executed n times for i in range (0, n): # inner loop executes n times for j in range(0, n): print(" i value % d and j value % d"%(i, j)) X
Total time = co + c1n + c2n^2 = 0(n^2).
If-then-else statements: Worst-case running time: the test, plus either the then part of the else part whichever is the largest.
Below is a python program that demonstrates the above concept:
Python3
# Python program that implements# the above conceptif n == I: print ("Incorrect Value") print (n) else: for i in range(0, n): # constant time print (CurrNumber:, i, sep = "")
Total time = co + c1*n = 0(n).
kalrap615
Algorithms
Analysis
Algorithms
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?
Difference between Algorithm, Pseudocode and Program
K means Clustering - Introduction
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Analysis of Algorithms | Set 1 (Asymptotic Analysis)
Analysis of Algorithms | Set 3 (Asymptotic Notations)
Time Complexity and Space Complexity
Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)
Practice Questions on Time Complexity Analysis | [
{
"code": null,
"e": 25943,
"s": 25915,
"text": "\n09 Jul, 2021"
},
{
"code": null,
"e": 26057,
"s": 25943,
"text": "In this article, the focus is on learning some rules that can help to determine the running time of an algorithm."
},
{
"code": null,
"e": 26401,
"s": 26057,
"text": "Asymptotic analysis refers to computing the running time of any operation in mathematical units of computation. In Asymptotic Analysis, the performance of an algorithm in terms of input size (we don’t measure the actual running time) is evaluated. How the time (or space) taken by an algorithm increases with the input size is also calculated."
},
{
"code": null,
"e": 26503,
"s": 26401,
"text": "(g(n)) = {f(n) such that g(n) is a curve which approximates f(n) at higher values of input size, n}"
},
{
"code": null,
"e": 26616,
"s": 26503,
"text": "This curve is called asymptotic curve and the algorithm analysis for such a curve is called Asymptotic analysis."
},
{
"code": null,
"e": 26765,
"s": 26616,
"text": "Loops: The running time of a loop is, at most, the running time of the statements inside the loop, including tests) multiplied number of iterations."
},
{
"code": null,
"e": 26830,
"s": 26765,
"text": "Below is the python program that demonstrates the above concept:"
},
{
"code": null,
"e": 26838,
"s": 26830,
"text": "Python3"
},
{
"code": "# Python program to implement# the above concept# execute n times for in# range(0.00); for i in range(0, n):print ('Current Number:', i, sep = \"\")",
"e": 26985,
"s": 26838,
"text": null
},
{
"code": null,
"e": 27041,
"s": 26985,
"text": "#constant time \nTotal time a constant cx n = cn = O(n)."
},
{
"code": null,
"e": 27153,
"s": 27041,
"text": "Nested loops: Analyze from the inside out. The total running time is the product of the sizes of all the loops."
},
{
"code": null,
"e": 27216,
"s": 27153,
"text": "Below is a python program that demonstrates the above concept:"
},
{
"code": null,
"e": 27224,
"s": 27216,
"text": "Python3"
},
{
"code": "# Python program to implement# the above concept# outer loop executed n timesfor i in range(0, n): # inner loop executes n times for j in range(0, n): print(\"i value % d and j value % d\" % (i, j))",
"e": 27434,
"s": 27224,
"text": null
},
{
"code": null,
"e": 27489,
"s": 27434,
"text": "# constant time \nTotal time = C x n x n = cn^2 =0(n2)."
},
{
"code": null,
"e": 27556,
"s": 27489,
"text": "Consecutive statements: Add the time complexity of each statement."
},
{
"code": null,
"e": 27619,
"s": 27556,
"text": "Below is a python program that demonstrates the above concept:"
},
{
"code": null,
"e": 27627,
"s": 27619,
"text": "Python3"
},
{
"code": "# Python program that implements# the above conceptn = 100 # executes n timesfor i in range (0, n): print (Current Number: i, sep = \"\") # outer loop executed n times for i in range (0, n): # inner loop executes n times for j in range(0, n): print(\" i value % d and j value % d\"%(i, j)) X",
"e": 27953,
"s": 27627,
"text": null
},
{
"code": null,
"e": 27996,
"s": 27956,
"text": "Total time = co + c1n + c2n^2 = 0(n^2)."
},
{
"code": null,
"e": 28128,
"s": 27998,
"text": "If-then-else statements: Worst-case running time: the test, plus either the then part of the else part whichever is the largest. "
},
{
"code": null,
"e": 28193,
"s": 28130,
"text": "Below is a python program that demonstrates the above concept:"
},
{
"code": null,
"e": 28203,
"s": 28195,
"text": "Python3"
},
{
"code": "# Python program that implements# the above conceptif n == I: print (\"Incorrect Value\") print (n) else: for i in range(0, n): # constant time print (CurrNumber:, i, sep = \"\")",
"e": 28392,
"s": 28203,
"text": null
},
{
"code": null,
"e": 28423,
"s": 28392,
"text": "Total time = co + c1*n = 0(n)."
},
{
"code": null,
"e": 28433,
"s": 28423,
"text": "kalrap615"
},
{
"code": null,
"e": 28444,
"s": 28433,
"text": "Algorithms"
},
{
"code": null,
"e": 28453,
"s": 28444,
"text": "Analysis"
},
{
"code": null,
"e": 28464,
"s": 28453,
"text": "Algorithms"
},
{
"code": null,
"e": 28562,
"s": 28464,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28587,
"s": 28562,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 28614,
"s": 28587,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 28667,
"s": 28614,
"text": "Difference between Algorithm, Pseudocode and Program"
},
{
"code": null,
"e": 28701,
"s": 28667,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 28768,
"s": 28701,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 28821,
"s": 28768,
"text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)"
},
{
"code": null,
"e": 28875,
"s": 28821,
"text": "Analysis of Algorithms | Set 3 (Asymptotic Notations)"
},
{
"code": null,
"e": 28912,
"s": 28875,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 28975,
"s": 28912,
"text": "Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)"
}
] |
CURRENT_TIMESTAMP() Function in SQL Server - GeeksforGeeks | 18 Jan, 2021
CURRENT_TIMESTAMP() function :This function in SQL Server is used to return the current date as well as time. And the format of the output is as follows.
'YYYY-MM-DD hh:mm:ss.mmm'
Features :
This function is used to find the current date and time.
This function comes under Date Functions.
This function doesn’t accept any parameter.
This function can also be used as a default value in some codes.
Syntax :
CURRENT_TIMESTAMP
Parameter :This method doesn’t accept any parameter.
Returns :It returns the current date as well as time and the format of the output returned is ‘YYYY-MM-DD hh:mm:ss.mmm’.
Example-1 :Using CURRENT_TIMESTAMP function and getting the current date as well as time.
SELECT CURRENT_TIMESTAMP
AS current_date_and_time;
Output :
current_date_and_time
--------------------------
2020-12-31 12:32:24.100
So, here the output may vary every time you run this code as this function returns the current date and time.
Example-2 :Using CURRENT_TIMESTAMP as a default value in the below example and getting the output.
CREATE TABLE current_time_stamp
(
id_num INT IDENTITY,
message VARCHAR(150) NOT NULL,
generated_at DATETIME NOT NULL
DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY(id_num)
);
Inserting data into table –
INSERT INTO current_time_stamp(message)
VALUES('Its the first message.');
INSERT INTO current_time_stamp(message)
VALUES('current_time_stamp');
Reading data from table –
SELECT
id_num,
message,
generated_at
FROM
current_time_stamp;
Output :
Here, firstly you need to create a table then insert values into it then generate the required output using CURRENT_TIMESTAMP function as a default value.
Note –For running the above code use SQL server compiler, you can also use an online compiler.
Application :This function is used to find the current date as well as time.
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL | Subquery
SQL Query to Convert VARCHAR to INT
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates | [
{
"code": null,
"e": 25513,
"s": 25485,
"text": "\n18 Jan, 2021"
},
{
"code": null,
"e": 25667,
"s": 25513,
"text": "CURRENT_TIMESTAMP() function :This function in SQL Server is used to return the current date as well as time. And the format of the output is as follows."
},
{
"code": null,
"e": 25693,
"s": 25667,
"text": "'YYYY-MM-DD hh:mm:ss.mmm'"
},
{
"code": null,
"e": 25704,
"s": 25693,
"text": "Features :"
},
{
"code": null,
"e": 25761,
"s": 25704,
"text": "This function is used to find the current date and time."
},
{
"code": null,
"e": 25803,
"s": 25761,
"text": "This function comes under Date Functions."
},
{
"code": null,
"e": 25847,
"s": 25803,
"text": "This function doesn’t accept any parameter."
},
{
"code": null,
"e": 25912,
"s": 25847,
"text": "This function can also be used as a default value in some codes."
},
{
"code": null,
"e": 25921,
"s": 25912,
"text": "Syntax :"
},
{
"code": null,
"e": 25939,
"s": 25921,
"text": "CURRENT_TIMESTAMP"
},
{
"code": null,
"e": 25992,
"s": 25939,
"text": "Parameter :This method doesn’t accept any parameter."
},
{
"code": null,
"e": 26113,
"s": 25992,
"text": "Returns :It returns the current date as well as time and the format of the output returned is ‘YYYY-MM-DD hh:mm:ss.mmm’."
},
{
"code": null,
"e": 26203,
"s": 26113,
"text": "Example-1 :Using CURRENT_TIMESTAMP function and getting the current date as well as time."
},
{
"code": null,
"e": 26255,
"s": 26203,
"text": "SELECT CURRENT_TIMESTAMP \nAS current_date_and_time;"
},
{
"code": null,
"e": 26264,
"s": 26255,
"text": "Output :"
},
{
"code": null,
"e": 26337,
"s": 26264,
"text": "current_date_and_time\n--------------------------\n2020-12-31 12:32:24.100"
},
{
"code": null,
"e": 26447,
"s": 26337,
"text": "So, here the output may vary every time you run this code as this function returns the current date and time."
},
{
"code": null,
"e": 26546,
"s": 26447,
"text": "Example-2 :Using CURRENT_TIMESTAMP as a default value in the below example and getting the output."
},
{
"code": null,
"e": 26737,
"s": 26546,
"text": "CREATE TABLE current_time_stamp\n(\n id_num INT IDENTITY, \n message VARCHAR(150) NOT NULL, \n generated_at DATETIME NOT NULL\n DEFAULT CURRENT_TIMESTAMP, \n PRIMARY KEY(id_num)\n);\n"
},
{
"code": null,
"e": 26765,
"s": 26737,
"text": "Inserting data into table –"
},
{
"code": null,
"e": 26911,
"s": 26765,
"text": "INSERT INTO current_time_stamp(message)\nVALUES('Its the first message.');\n\nINSERT INTO current_time_stamp(message)\nVALUES('current_time_stamp');\n"
},
{
"code": null,
"e": 26937,
"s": 26911,
"text": "Reading data from table –"
},
{
"code": null,
"e": 27019,
"s": 26937,
"text": "SELECT \n id_num, \n message, \n generated_at\nFROM \n current_time_stamp;"
},
{
"code": null,
"e": 27028,
"s": 27019,
"text": "Output :"
},
{
"code": null,
"e": 27183,
"s": 27028,
"text": "Here, firstly you need to create a table then insert values into it then generate the required output using CURRENT_TIMESTAMP function as a default value."
},
{
"code": null,
"e": 27278,
"s": 27183,
"text": "Note –For running the above code use SQL server compiler, you can also use an online compiler."
},
{
"code": null,
"e": 27355,
"s": 27278,
"text": "Application :This function is used to find the current date as well as time."
},
{
"code": null,
"e": 27364,
"s": 27355,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 27375,
"s": 27364,
"text": "SQL-Server"
},
{
"code": null,
"e": 27379,
"s": 27375,
"text": "SQL"
},
{
"code": null,
"e": 27383,
"s": 27379,
"text": "SQL"
},
{
"code": null,
"e": 27481,
"s": 27383,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27547,
"s": 27481,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 27604,
"s": 27547,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 27636,
"s": 27604,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 27651,
"s": 27636,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 27687,
"s": 27651,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 27765,
"s": 27687,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 27782,
"s": 27765,
"text": "SQL using Python"
},
{
"code": null,
"e": 27848,
"s": 27782,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
},
{
"code": null,
"e": 27910,
"s": 27848,
"text": "How to Select Data Between Two Dates and Times in SQL Server?"
}
] |
GATE | GATE-CS-2014-(Set-3) | Question 65 - GeeksforGeeks | 30 Sep, 2021
An instruction pipeline has five stages, namely, instruction fetch (IF), instruction decode and register fetch (ID/RF), instruction execution (EX), memory access (MEM), and register writeback (WB) with stage latencies 1 ns, 2.2 ns, 2 ns, 1 ns, and 0.75 ns, respectively (ns stands for nanoseconds). To gain in terms of frequency, the designers have decided to split the ID/RF stage into three stages (ID, RF1, RF2) each of latency 2.2/3 ns. Also, the EX stage is split into two stages (EX1, EX2) each of latency 1 ns. The new design has a total of eight pipeline stages. A program has 20% branch instructions which execute in the EX stage and produce the next instruction pointer at the end of the EX stage in the old design and at the end of the EX2 stage in the new design. The IF stage stalls after fetching a branch instruction until the next instruction pointer is computed. All instructions other than the branch instruction have an average CPI of one in both the designs. The execution times of this program on the old and the new design are P and Q nanoseconds, respectively. The value of P/Q is __________.
(A) 1.5(B) 1.4(C) 1.8(D) 2.5Answer: (A)Explanation:
Each one takes average 1CPI.
In 1st case 80% take 1 clock and 20% take 3 clocks so total time:
p = (.8*1 + .2*3)*2.2=3.08.
q = (.8*1 + 6*.2)*1=2
p/q = 1.54
YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersPipelining: Previous Year Question part-II | COA | GeeksforGeeks GATE | Harshit NigamWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0016:26 / 40:21•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=h-14CfDEprU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2014-(Set-3)
GATE-GATE-CS-2014-(Set-3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90 | [
{
"code": null,
"e": 25773,
"s": 25745,
"text": "\n30 Sep, 2021"
},
{
"code": null,
"e": 26889,
"s": 25773,
"text": "An instruction pipeline has five stages, namely, instruction fetch (IF), instruction decode and register fetch (ID/RF), instruction execution (EX), memory access (MEM), and register writeback (WB) with stage latencies 1 ns, 2.2 ns, 2 ns, 1 ns, and 0.75 ns, respectively (ns stands for nanoseconds). To gain in terms of frequency, the designers have decided to split the ID/RF stage into three stages (ID, RF1, RF2) each of latency 2.2/3 ns. Also, the EX stage is split into two stages (EX1, EX2) each of latency 1 ns. The new design has a total of eight pipeline stages. A program has 20% branch instructions which execute in the EX stage and produce the next instruction pointer at the end of the EX stage in the old design and at the end of the EX2 stage in the new design. The IF stage stalls after fetching a branch instruction until the next instruction pointer is computed. All instructions other than the branch instruction have an average CPI of one in both the designs. The execution times of this program on the old and the new design are P and Q nanoseconds, respectively. The value of P/Q is __________."
},
{
"code": null,
"e": 26941,
"s": 26889,
"text": "(A) 1.5(B) 1.4(C) 1.8(D) 2.5Answer: (A)Explanation:"
},
{
"code": null,
"e": 27100,
"s": 26941,
"text": "Each one takes average 1CPI.\n\nIn 1st case 80% take 1 clock and 20% take 3 clocks so total time:\n\np = (.8*1 + .2*3)*2.2=3.08.\nq = (.8*1 + 6*.2)*1=2\np/q = 1.54 "
},
{
"code": null,
"e": 28014,
"s": 27100,
"text": "YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersPipelining: Previous Year Question part-II | COA | GeeksforGeeks GATE | Harshit NigamWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0016:26 / 40:21•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=h-14CfDEprU\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question"
},
{
"code": null,
"e": 28035,
"s": 28014,
"text": "GATE-CS-2014-(Set-3)"
},
{
"code": null,
"e": 28061,
"s": 28035,
"text": "GATE-GATE-CS-2014-(Set-3)"
},
{
"code": null,
"e": 28066,
"s": 28061,
"text": "GATE"
},
{
"code": null,
"e": 28164,
"s": 28066,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28198,
"s": 28164,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 28232,
"s": 28198,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 28266,
"s": 28232,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 28299,
"s": 28266,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 28335,
"s": 28299,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 28369,
"s": 28335,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 28405,
"s": 28369,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 28439,
"s": 28405,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 28473,
"s": 28439,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
Building blocks of a Data Model - GeeksforGeeks | 25 Mar, 2020
A data model is a structure of the data that contains all the required details of the data like the name of the data, size of the data, relationship with other data and constraints that are applied on the data. It is a communication tool.
A data model is essential in order to store the database in a sorted manner. It will provide the interaction between the system analyst, designer and application programmer. It improves the understanding of designing of the database in which the organization is interested.
A data model constitutes of building blocks. They are:
1. Entities
2. Attributes
3. Relationships
4. Constraints
These are explained as following below in brief.
Entities:Entities are real time objects that exist.It can be a person, place, object, event, concept. Entities are represented by a rectangle box containing the entity name in it.Example: Student, employee.Attributes:It is the set of characteristics representing an entity.It is represented by a ellipse symbol with attribute name on it.Example: A student has attributes like name, roll number, age and much more.Relationship:It describes the association between two entities.It is represented using diamond symbol containing relationship name with it.The data model generally uses three kinds of relationships:one to many, many to many, one to one.Example: The relationship between two entities Student and Class has many to many relationship.Constraints:Constraints are conditions applied on the data.It provides the data integrity.Example: A student can take a maximum of 2 books from the library is applied as a constraint on the student database.
Entities:Entities are real time objects that exist.It can be a person, place, object, event, concept. Entities are represented by a rectangle box containing the entity name in it.Example: Student, employee.
Example: Student, employee.
Attributes:It is the set of characteristics representing an entity.It is represented by a ellipse symbol with attribute name on it.Example: A student has attributes like name, roll number, age and much more.
Example: A student has attributes like name, roll number, age and much more.
Relationship:It describes the association between two entities.It is represented using diamond symbol containing relationship name with it.The data model generally uses three kinds of relationships:one to many, many to many, one to one.Example: The relationship between two entities Student and Class has many to many relationship.
Example: The relationship between two entities Student and Class has many to many relationship.
Constraints:Constraints are conditions applied on the data.It provides the data integrity.Example: A student can take a maximum of 2 books from the library is applied as a constraint on the student database.
Example: A student can take a maximum of 2 books from the library is applied as a constraint on the student database.
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Deadlock in DBMS
Types of Functional dependencies in DBMS
KDD Process in Data Mining
Conflict Serializability in DBMS
Two Phase Locking Protocol
Introduction of Relational Algebra in DBMS
What is Temporary Table in SQL?
MySQL | Regular expressions (Regexp)
Difference between Where and Having Clause in SQL
Difference between File System and DBMS | [
{
"code": null,
"e": 25549,
"s": 25521,
"text": "\n25 Mar, 2020"
},
{
"code": null,
"e": 25788,
"s": 25549,
"text": "A data model is a structure of the data that contains all the required details of the data like the name of the data, size of the data, relationship with other data and constraints that are applied on the data. It is a communication tool."
},
{
"code": null,
"e": 26062,
"s": 25788,
"text": "A data model is essential in order to store the database in a sorted manner. It will provide the interaction between the system analyst, designer and application programmer. It improves the understanding of designing of the database in which the organization is interested."
},
{
"code": null,
"e": 26117,
"s": 26062,
"text": "A data model constitutes of building blocks. They are:"
},
{
"code": null,
"e": 26178,
"s": 26117,
"text": "1. Entities\n2. Attributes\n3. Relationships \n4. Constraints "
},
{
"code": null,
"e": 26227,
"s": 26178,
"text": "These are explained as following below in brief."
},
{
"code": null,
"e": 27179,
"s": 26227,
"text": "Entities:Entities are real time objects that exist.It can be a person, place, object, event, concept. Entities are represented by a rectangle box containing the entity name in it.Example: Student, employee.Attributes:It is the set of characteristics representing an entity.It is represented by a ellipse symbol with attribute name on it.Example: A student has attributes like name, roll number, age and much more.Relationship:It describes the association between two entities.It is represented using diamond symbol containing relationship name with it.The data model generally uses three kinds of relationships:one to many, many to many, one to one.Example: The relationship between two entities Student and Class has many to many relationship.Constraints:Constraints are conditions applied on the data.It provides the data integrity.Example: A student can take a maximum of 2 books from the library is applied as a constraint on the student database."
},
{
"code": null,
"e": 27386,
"s": 27179,
"text": "Entities:Entities are real time objects that exist.It can be a person, place, object, event, concept. Entities are represented by a rectangle box containing the entity name in it.Example: Student, employee."
},
{
"code": null,
"e": 27414,
"s": 27386,
"text": "Example: Student, employee."
},
{
"code": null,
"e": 27622,
"s": 27414,
"text": "Attributes:It is the set of characteristics representing an entity.It is represented by a ellipse symbol with attribute name on it.Example: A student has attributes like name, roll number, age and much more."
},
{
"code": null,
"e": 27699,
"s": 27622,
"text": "Example: A student has attributes like name, roll number, age and much more."
},
{
"code": null,
"e": 28031,
"s": 27699,
"text": "Relationship:It describes the association between two entities.It is represented using diamond symbol containing relationship name with it.The data model generally uses three kinds of relationships:one to many, many to many, one to one.Example: The relationship between two entities Student and Class has many to many relationship."
},
{
"code": null,
"e": 28127,
"s": 28031,
"text": "Example: The relationship between two entities Student and Class has many to many relationship."
},
{
"code": null,
"e": 28335,
"s": 28127,
"text": "Constraints:Constraints are conditions applied on the data.It provides the data integrity.Example: A student can take a maximum of 2 books from the library is applied as a constraint on the student database."
},
{
"code": null,
"e": 28453,
"s": 28335,
"text": "Example: A student can take a maximum of 2 books from the library is applied as a constraint on the student database."
},
{
"code": null,
"e": 28458,
"s": 28453,
"text": "DBMS"
},
{
"code": null,
"e": 28463,
"s": 28458,
"text": "DBMS"
},
{
"code": null,
"e": 28561,
"s": 28463,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28578,
"s": 28561,
"text": "Deadlock in DBMS"
},
{
"code": null,
"e": 28619,
"s": 28578,
"text": "Types of Functional dependencies in DBMS"
},
{
"code": null,
"e": 28646,
"s": 28619,
"text": "KDD Process in Data Mining"
},
{
"code": null,
"e": 28679,
"s": 28646,
"text": "Conflict Serializability in DBMS"
},
{
"code": null,
"e": 28706,
"s": 28679,
"text": "Two Phase Locking Protocol"
},
{
"code": null,
"e": 28749,
"s": 28706,
"text": "Introduction of Relational Algebra in DBMS"
},
{
"code": null,
"e": 28781,
"s": 28749,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 28818,
"s": 28781,
"text": "MySQL | Regular expressions (Regexp)"
},
{
"code": null,
"e": 28868,
"s": 28818,
"text": "Difference between Where and Having Clause in SQL"
}
] |
Solidity - View and Pure Functions - GeeksforGeeks | 11 May, 2022
The view functions are read-only function, which ensures that state variables cannot be modified after calling them. If the statements which modify state variables, emitting events, creating other contracts, using selfdestruct method, transferring ethers via calls, Calling a function which is not ‘view or pure’, using low-level calls, etc are present in view functions then the compiler throw a warning in such cases. By default, a get method is view function.
Example: In the below example, the contract Test defines a view function to calculate the product and sum of two unsigned integers.
Solidity
// Solidity program to // demonstrate view// functionspragma solidity ^0.5.0; // Defining a contractcontract Test { // Declaring state // variables uint num1 = 2; uint num2 = 4; // Defining view function to // calculate product and sum // of 2 numbers function getResult( ) public view returns( uint product, uint sum){ uint num1 = 10; uint num2 = 16; product = num1 * num2; sum = num1 + num2; }}
Output :
The pure functions do not read or modify the state variables, which returns the values only using the parameters passed to the function or local variables present in it. If the statements which read the state variables, access the address or balance, accessing any global variable block or msg, calling a function which is not pure, etc are present in pure functions then the compiler throws a warning in such cases.
Example: In the below example, the contract Test defines a pure function to calculate the product and sum of two numbers.
Solidity
// Solidity program to // demonstrate pure functionspragma solidity ^0.5.0; // Defining a contractcontract Test { // Defining pure function to // calculate product and sum // of 2 numbers function getResult( ) public pure returns( uint product, uint sum){ uint num1 = 2; uint num2 = 4; product = num1 * num2; sum = num1 + num2; }}
Output :
Solidity-Functions
Blockchain
Solidity
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Storage vs Memory in Solidity
Ethereum Blockchain - Getting Free Test Ethers For Rinkeby Test Network
How to Become a Blockchain Developer?
How to connect ReactJS with MetaMask ?
Proof of Work (PoW) Consensus
Storage vs Memory in Solidity
Mathematical Operations in Solidity
Solidity - Inheritance
How to Install Solidity in Windows?
Introduction to Solidity | [
{
"code": null,
"e": 25681,
"s": 25653,
"text": "\n11 May, 2022"
},
{
"code": null,
"e": 26144,
"s": 25681,
"text": "The view functions are read-only function, which ensures that state variables cannot be modified after calling them. If the statements which modify state variables, emitting events, creating other contracts, using selfdestruct method, transferring ethers via calls, Calling a function which is not ‘view or pure’, using low-level calls, etc are present in view functions then the compiler throw a warning in such cases. By default, a get method is view function."
},
{
"code": null,
"e": 26276,
"s": 26144,
"text": "Example: In the below example, the contract Test defines a view function to calculate the product and sum of two unsigned integers."
},
{
"code": null,
"e": 26285,
"s": 26276,
"text": "Solidity"
},
{
"code": "// Solidity program to // demonstrate view// functionspragma solidity ^0.5.0; // Defining a contractcontract Test { // Declaring state // variables uint num1 = 2; uint num2 = 4; // Defining view function to // calculate product and sum // of 2 numbers function getResult( ) public view returns( uint product, uint sum){ uint num1 = 10; uint num2 = 16; product = num1 * num2; sum = num1 + num2; }}",
"e": 26747,
"s": 26285,
"text": null
},
{
"code": null,
"e": 26758,
"s": 26747,
"text": "Output : "
},
{
"code": null,
"e": 27175,
"s": 26758,
"text": "The pure functions do not read or modify the state variables, which returns the values only using the parameters passed to the function or local variables present in it. If the statements which read the state variables, access the address or balance, accessing any global variable block or msg, calling a function which is not pure, etc are present in pure functions then the compiler throws a warning in such cases."
},
{
"code": null,
"e": 27297,
"s": 27175,
"text": "Example: In the below example, the contract Test defines a pure function to calculate the product and sum of two numbers."
},
{
"code": null,
"e": 27306,
"s": 27297,
"text": "Solidity"
},
{
"code": "// Solidity program to // demonstrate pure functionspragma solidity ^0.5.0; // Defining a contractcontract Test { // Defining pure function to // calculate product and sum // of 2 numbers function getResult( ) public pure returns( uint product, uint sum){ uint num1 = 2; uint num2 = 4; product = num1 * num2; sum = num1 + num2; }}",
"e": 27682,
"s": 27306,
"text": null
},
{
"code": null,
"e": 27693,
"s": 27682,
"text": "Output : "
},
{
"code": null,
"e": 27712,
"s": 27693,
"text": "Solidity-Functions"
},
{
"code": null,
"e": 27723,
"s": 27712,
"text": "Blockchain"
},
{
"code": null,
"e": 27732,
"s": 27723,
"text": "Solidity"
},
{
"code": null,
"e": 27830,
"s": 27732,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27860,
"s": 27830,
"text": "Storage vs Memory in Solidity"
},
{
"code": null,
"e": 27932,
"s": 27860,
"text": "Ethereum Blockchain - Getting Free Test Ethers For Rinkeby Test Network"
},
{
"code": null,
"e": 27970,
"s": 27932,
"text": "How to Become a Blockchain Developer?"
},
{
"code": null,
"e": 28009,
"s": 27970,
"text": "How to connect ReactJS with MetaMask ?"
},
{
"code": null,
"e": 28039,
"s": 28009,
"text": "Proof of Work (PoW) Consensus"
},
{
"code": null,
"e": 28069,
"s": 28039,
"text": "Storage vs Memory in Solidity"
},
{
"code": null,
"e": 28105,
"s": 28069,
"text": "Mathematical Operations in Solidity"
},
{
"code": null,
"e": 28128,
"s": 28105,
"text": "Solidity - Inheritance"
},
{
"code": null,
"e": 28164,
"s": 28128,
"text": "How to Install Solidity in Windows?"
}
] |
How to change pagefile settings from custom to system managed using PowerShell? | To change the pagefile settings to system managed, we need to set InitialSize and MaximumSize parameters to 0. In the below example, we have E: has custom pagefile, not system managed and we need to convert it to the system managed.
$pagefileset = Gwmi win32_pagefilesetting | where{$_.caption -like 'E:*'}
$pagefileset.InitialSize = 0
$pagefileset.MaximumSize = 0
$pagefileset.Put() | Out-Null
Now when you check the pagefile setting on E: it should be System managed.
To change the settings on the remote computer use -ComputerName parameter in the Get-WmiObject method. | [
{
"code": null,
"e": 1295,
"s": 1062,
"text": "To change the pagefile settings to system managed, we need to set InitialSize and MaximumSize parameters to 0. In the below example, we have E: has custom pagefile, not system managed and we need to convert it to the system managed."
},
{
"code": null,
"e": 1457,
"s": 1295,
"text": "$pagefileset = Gwmi win32_pagefilesetting | where{$_.caption -like 'E:*'}\n$pagefileset.InitialSize = 0\n$pagefileset.MaximumSize = 0\n$pagefileset.Put() | Out-Null"
},
{
"code": null,
"e": 1532,
"s": 1457,
"text": "Now when you check the pagefile setting on E: it should be System managed."
},
{
"code": null,
"e": 1635,
"s": 1532,
"text": "To change the settings on the remote computer use -ComputerName parameter in the Get-WmiObject method."
}
] |
How to detect the value change of a JSlider in Java? | A JSlider is a subclass of JComponent class and it is similar to scroll bar which allows the user to select a numeric value from a specified range of integer values. A JSlider has a knob which can slide on a range of values and can be used to select a particular value. and it can generate a ChangeListener interface.
We can detect the value changed when the slider is moved horizontally using the Graphics2D class and override paint() method.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class ValueChangeJSliderTest extends JFrame {
private JSlider slider;
public ValueChangeJSliderTest() {
setTitle("ValueChangeJSlider Test");
slider = new JSlider(JSlider.HORIZONTAL, 0, 20, 1);
slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ce) {
repaint();
}
});
setLayout(new BorderLayout());
slider.setBackground(Color.white);
slider.setMajorTickSpacing(1);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
add(slider, BorderLayout.NORTH);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setFont(new Font("Serif", Font.ITALIC, 25));
g2d.drawString(""+slider.getValue(), 200, 130);
}
public static void main(String[] args) {
new ValueChangeJSliderTest();
}
} | [
{
"code": null,
"e": 1380,
"s": 1062,
"text": "A JSlider is a subclass of JComponent class and it is similar to scroll bar which allows the user to select a numeric value from a specified range of integer values. A JSlider has a knob which can slide on a range of values and can be used to select a particular value. and it can generate a ChangeListener interface."
},
{
"code": null,
"e": 1506,
"s": 1380,
"text": "We can detect the value changed when the slider is moved horizontally using the Graphics2D class and override paint() method."
},
{
"code": null,
"e": 2631,
"s": 1506,
"text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\nimport javax.swing.event.*;\npublic class ValueChangeJSliderTest extends JFrame {\n private JSlider slider;\n public ValueChangeJSliderTest() {\n setTitle(\"ValueChangeJSlider Test\");\n slider = new JSlider(JSlider.HORIZONTAL, 0, 20, 1);\n slider.addChangeListener(new ChangeListener() {\n public void stateChanged(ChangeEvent ce) {\n repaint();\n }\n });\n setLayout(new BorderLayout());\n slider.setBackground(Color.white);\n slider.setMajorTickSpacing(1);\n slider.setPaintTicks(true);\n slider.setPaintLabels(true);\n add(slider, BorderLayout.NORTH);\n setSize(400, 300);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setLocationRelativeTo(null);\n setVisible(true);\n }\n public void paint(Graphics g) {\n super.paint(g);\n Graphics2D g2d = (Graphics2D) g;\n g2d.setFont(new Font(\"Serif\", Font.ITALIC, 25));\n g2d.drawString(\"\"+slider.getValue(), 200, 130);\n }\n public static void main(String[] args) {\n new ValueChangeJSliderTest();\n }\n}"
}
] |
Different Types of Joins in Pandas - GeeksforGeeks | 17 Dec, 2020
The pandas module contains various features to perform various operations on dataframes like join, concatenate, delete, add, etc. In this article, we are going to discuss the various types of join operations that can be performed on pandas dataframe. There are mainly five types of Joins in Pandas:
Inner Join
Left Outer Join
Right Outer Join
Full Outer Join or simply Outer Join
Index Join
To understand different types of joins, we will first make two DataFrames, namely a and b.
Dataframe a:
Python3
# importing pandas import pandas as pd # Creating dataframe aa = pd.DataFrame() # Creating Dictionaryd = {'id': [1, 2, 10, 12], 'val1': ['a', 'b', 'c', 'd']} a = pd.DataFrame(d) # printing the dataframea
Output:
DataFrame b:
Python3
# importing pandasimport pandas as pd # Creating dataframe bb = pd.DataFrame() # Creating dictionaryd = {'id': [1, 2, 9, 8], 'val1': ['p', 'q', 'r', 's']}b = pd.DataFrame(d) # printing the dataframeb
Output:
We will use these two dataframes to understand the different types of joins.
Inner Join: Inner join is the most common type of join you’ll be working with. It returns a dataframe with only those rows that have common characteristics. This is similar to the intersection of two sets.
Example:
Python3
# importing pandasimport pandas as pd # Creating dataframe aa = pd.DataFrame() # Creating Dictionaryd = {'id': [1, 2, 10, 12], 'val1': ['a', 'b', 'c', 'd']} a = pd.DataFrame(d) # Creating dataframe bb = pd.DataFrame() # Creating dictionaryd = {'id': [1, 2, 9, 8], 'val1': ['p', 'q', 'r', 's']}b = pd.DataFrame(d) # inner joindf = pd.merge(a, b, on='id', how='inner') # display dataframedf
Output:
Left Outer Join: With a left outer join, all the records from the first dataframe will be displayed, irrespective of whether the keys in the first dataframe can be found in the second dataframe. Whereas, for the second dataframe, only the records with the keys in the second dataframe that can be found in the first dataframe will be displayed.
Example:
Python3
# importing pandasimport pandas as pd # Creating dataframe aa = pd.DataFrame() # Creating Dictionaryd = {'id': [1, 2, 10, 12], 'val1': ['a', 'b', 'c', 'd']} a = pd.DataFrame(d) # Creating dataframe bb = pd.DataFrame() # Creating dictionaryd = {'id': [1, 2, 9, 8], 'val1': ['p', 'q', 'r', 's']}b = pd.DataFrame(d) # left outer joindf = pd.merge(a, b, on='id', how='left') # display dataframedf
Output:
Right Outer Join: For a right join, all the records from the second dataframe will be displayed. However, only the records with the keys in the first dataframe that can be found in the second dataframe will be displayed.
Example:
Python3
# importing pandasimport pandas as pd # Creating dataframe aa = pd.DataFrame() # Creating Dictionaryd = {'id': [1, 2, 10, 12], 'val1': ['a', 'b', 'c', 'd']} a = pd.DataFrame(d) # Creating dataframe bb = pd.DataFrame() # Creating dictionaryd = {'id': [1, 2, 9, 8], 'val1': ['p', 'q', 'r', 's']}b = pd.DataFrame(d) # right outer joindf = pd.merge(a, b, on='id', how='right') # display dataframedf
Output:
Full Outer Join: A full outer join returns all the rows from the left dataframe, all the rows from the right dataframe, and matches up rows where possible, with NaNs elsewhere. But if the dataframe is complete, then we get the same output.
Example:
Python3
# importing pandasimport pandas as pd # Creating dataframe aa = pd.DataFrame() # Creating Dictionaryd = {'id': [1, 2, 10, 12], 'val1': ['a', 'b', 'c', 'd']} a = pd.DataFrame(d) # Creating dataframe bb = pd.DataFrame() # Creating dictionaryd = {'id': [1, 2, 9, 8], 'val1': ['p', 'q', 'r', 's']}b = pd.DataFrame(d) # full outer joindf = pd.merge(a, b, on='id', how='outer') # display dataframedf
Output:
Index Join: To merge the dataframe on indices pass the left_index and right_index arguments as True i.e. both the dataframes are merged on an index using default Inner Join.
Example:
Python3
# importing pandasimport pandas as pd # Creating dataframe aa = pd.DataFrame() # Creating Dictionaryd = {'id': [1, 2, 10, 12], 'val1': ['a', 'b', 'c', 'd']} a = pd.DataFrame(d) # Creating dataframe bb = pd.DataFrame() # Creating dictionaryd = {'id': [1, 2, 9, 8], 'val1': ['p', 'q', 'r', 's']}b = pd.DataFrame(d) # index joindf = pd.merge(a, b, left_index=True, right_index=True) # display dataframedf
Output:
Picked
Python-pandas
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
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python Classes and Objects | [
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n17 Dec, 2020"
},
{
"code": null,
"e": 24511,
"s": 24212,
"text": "The pandas module contains various features to perform various operations on dataframes like join, concatenate, delete, add, etc. In this article, we are going to discuss the various types of join operations that can be performed on pandas dataframe. There are mainly five types of Joins in Pandas:"
},
{
"code": null,
"e": 24522,
"s": 24511,
"text": "Inner Join"
},
{
"code": null,
"e": 24538,
"s": 24522,
"text": "Left Outer Join"
},
{
"code": null,
"e": 24555,
"s": 24538,
"text": "Right Outer Join"
},
{
"code": null,
"e": 24592,
"s": 24555,
"text": "Full Outer Join or simply Outer Join"
},
{
"code": null,
"e": 24603,
"s": 24592,
"text": "Index Join"
},
{
"code": null,
"e": 24694,
"s": 24603,
"text": "To understand different types of joins, we will first make two DataFrames, namely a and b."
},
{
"code": null,
"e": 24707,
"s": 24694,
"text": "Dataframe a:"
},
{
"code": null,
"e": 24715,
"s": 24707,
"text": "Python3"
},
{
"code": "# importing pandas import pandas as pd # Creating dataframe aa = pd.DataFrame() # Creating Dictionaryd = {'id': [1, 2, 10, 12], 'val1': ['a', 'b', 'c', 'd']} a = pd.DataFrame(d) # printing the dataframea",
"e": 24929,
"s": 24715,
"text": null
},
{
"code": null,
"e": 24937,
"s": 24929,
"text": "Output:"
},
{
"code": null,
"e": 24953,
"s": 24940,
"text": "DataFrame b:"
},
{
"code": null,
"e": 24961,
"s": 24953,
"text": "Python3"
},
{
"code": "# importing pandasimport pandas as pd # Creating dataframe bb = pd.DataFrame() # Creating dictionaryd = {'id': [1, 2, 9, 8], 'val1': ['p', 'q', 'r', 's']}b = pd.DataFrame(d) # printing the dataframeb",
"e": 25168,
"s": 24961,
"text": null
},
{
"code": null,
"e": 25176,
"s": 25168,
"text": "Output:"
},
{
"code": null,
"e": 25258,
"s": 25181,
"text": "We will use these two dataframes to understand the different types of joins."
},
{
"code": null,
"e": 25464,
"s": 25258,
"text": "Inner Join: Inner join is the most common type of join you’ll be working with. It returns a dataframe with only those rows that have common characteristics. This is similar to the intersection of two sets."
},
{
"code": null,
"e": 25473,
"s": 25464,
"text": "Example:"
},
{
"code": null,
"e": 25481,
"s": 25473,
"text": "Python3"
},
{
"code": "# importing pandasimport pandas as pd # Creating dataframe aa = pd.DataFrame() # Creating Dictionaryd = {'id': [1, 2, 10, 12], 'val1': ['a', 'b', 'c', 'd']} a = pd.DataFrame(d) # Creating dataframe bb = pd.DataFrame() # Creating dictionaryd = {'id': [1, 2, 9, 8], 'val1': ['p', 'q', 'r', 's']}b = pd.DataFrame(d) # inner joindf = pd.merge(a, b, on='id', how='inner') # display dataframedf",
"e": 25885,
"s": 25481,
"text": null
},
{
"code": null,
"e": 25893,
"s": 25885,
"text": "Output:"
},
{
"code": null,
"e": 26238,
"s": 25893,
"text": "Left Outer Join: With a left outer join, all the records from the first dataframe will be displayed, irrespective of whether the keys in the first dataframe can be found in the second dataframe. Whereas, for the second dataframe, only the records with the keys in the second dataframe that can be found in the first dataframe will be displayed."
},
{
"code": null,
"e": 26247,
"s": 26238,
"text": "Example:"
},
{
"code": null,
"e": 26255,
"s": 26247,
"text": "Python3"
},
{
"code": "# importing pandasimport pandas as pd # Creating dataframe aa = pd.DataFrame() # Creating Dictionaryd = {'id': [1, 2, 10, 12], 'val1': ['a', 'b', 'c', 'd']} a = pd.DataFrame(d) # Creating dataframe bb = pd.DataFrame() # Creating dictionaryd = {'id': [1, 2, 9, 8], 'val1': ['p', 'q', 'r', 's']}b = pd.DataFrame(d) # left outer joindf = pd.merge(a, b, on='id', how='left') # display dataframedf",
"e": 26663,
"s": 26255,
"text": null
},
{
"code": null,
"e": 26671,
"s": 26663,
"text": "Output:"
},
{
"code": null,
"e": 26892,
"s": 26671,
"text": "Right Outer Join: For a right join, all the records from the second dataframe will be displayed. However, only the records with the keys in the first dataframe that can be found in the second dataframe will be displayed."
},
{
"code": null,
"e": 26901,
"s": 26892,
"text": "Example:"
},
{
"code": null,
"e": 26909,
"s": 26901,
"text": "Python3"
},
{
"code": "# importing pandasimport pandas as pd # Creating dataframe aa = pd.DataFrame() # Creating Dictionaryd = {'id': [1, 2, 10, 12], 'val1': ['a', 'b', 'c', 'd']} a = pd.DataFrame(d) # Creating dataframe bb = pd.DataFrame() # Creating dictionaryd = {'id': [1, 2, 9, 8], 'val1': ['p', 'q', 'r', 's']}b = pd.DataFrame(d) # right outer joindf = pd.merge(a, b, on='id', how='right') # display dataframedf",
"e": 27319,
"s": 26909,
"text": null
},
{
"code": null,
"e": 27327,
"s": 27319,
"text": "Output:"
},
{
"code": null,
"e": 27571,
"s": 27331,
"text": "Full Outer Join: A full outer join returns all the rows from the left dataframe, all the rows from the right dataframe, and matches up rows where possible, with NaNs elsewhere. But if the dataframe is complete, then we get the same output."
},
{
"code": null,
"e": 27580,
"s": 27571,
"text": "Example:"
},
{
"code": null,
"e": 27588,
"s": 27580,
"text": "Python3"
},
{
"code": "# importing pandasimport pandas as pd # Creating dataframe aa = pd.DataFrame() # Creating Dictionaryd = {'id': [1, 2, 10, 12], 'val1': ['a', 'b', 'c', 'd']} a = pd.DataFrame(d) # Creating dataframe bb = pd.DataFrame() # Creating dictionaryd = {'id': [1, 2, 9, 8], 'val1': ['p', 'q', 'r', 's']}b = pd.DataFrame(d) # full outer joindf = pd.merge(a, b, on='id', how='outer') # display dataframedf",
"e": 27997,
"s": 27588,
"text": null
},
{
"code": null,
"e": 28005,
"s": 27997,
"text": "Output:"
},
{
"code": null,
"e": 28179,
"s": 28005,
"text": "Index Join: To merge the dataframe on indices pass the left_index and right_index arguments as True i.e. both the dataframes are merged on an index using default Inner Join."
},
{
"code": null,
"e": 28188,
"s": 28179,
"text": "Example:"
},
{
"code": null,
"e": 28196,
"s": 28188,
"text": "Python3"
},
{
"code": "# importing pandasimport pandas as pd # Creating dataframe aa = pd.DataFrame() # Creating Dictionaryd = {'id': [1, 2, 10, 12], 'val1': ['a', 'b', 'c', 'd']} a = pd.DataFrame(d) # Creating dataframe bb = pd.DataFrame() # Creating dictionaryd = {'id': [1, 2, 9, 8], 'val1': ['p', 'q', 'r', 's']}b = pd.DataFrame(d) # index joindf = pd.merge(a, b, left_index=True, right_index=True) # display dataframedf",
"e": 28613,
"s": 28196,
"text": null
},
{
"code": null,
"e": 28621,
"s": 28613,
"text": "Output:"
},
{
"code": null,
"e": 28628,
"s": 28621,
"text": "Picked"
},
{
"code": null,
"e": 28642,
"s": 28628,
"text": "Python-pandas"
},
{
"code": null,
"e": 28666,
"s": 28642,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 28673,
"s": 28666,
"text": "Python"
},
{
"code": null,
"e": 28692,
"s": 28673,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28790,
"s": 28692,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28799,
"s": 28790,
"text": "Comments"
},
{
"code": null,
"e": 28812,
"s": 28799,
"text": "Old Comments"
},
{
"code": null,
"e": 28844,
"s": 28812,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28899,
"s": 28844,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 28955,
"s": 28899,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28994,
"s": 28955,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29036,
"s": 28994,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29078,
"s": 29036,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29109,
"s": 29078,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29131,
"s": 29109,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29160,
"s": 29131,
"text": "Create a directory in Python"
}
] |
Python | Create a stopwatch Using Clock Object in kivy - GeeksforGeeks | 29 Sep, 2021
Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications.In this, we are going to see how can we create a stopwatch using a label. In the code, we will be creating just a counter using the label in which when you set the time in seconds it will start decreasing like a countdown and in the second we will do the same by using clock object.
Kivy Tutorial – Learn Kivy with Examples.
Clock Object:
Kivy provides Clock objects.Clock objects can be made to call a function when a specified time period has elapsed.A clock object in Kivy can be configured to call a function upon every elapse of time duration or only once.
Kivy provides Clock objects.
Clock objects can be made to call a function when a specified time period has elapsed.
A clock object in Kivy can be configured to call a function upon every elapse of time duration or only once.
It is good to use kivy inbuilt module while working with clock: from kivy.clock import Clock
Basic Approach:
1) import kivy
2) import kivyApp
3) import label
4) import Animation
5) Import clock
6) import kivy properties(only needed one)
7) Set minimum version(optional)
8) Create Label class
9) Create App class
10) return Layout/widget/Class(according to requirement)
11) Run an instance of the class
# Simple Approach:
Python3
'''Code of How to create countdown using label only''' # Program to Show how to create a switch# import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # The Label widget is for rendering text.from kivy.uix.label import Label # Animation is used to animate Widget propertiesfrom kivy.animation import Animation # The Properties classes are used when you create an EventDispatcher.from kivy.properties import StringProperty, NumericProperty # create a label classclass Clock(Label): # Set the numeric property # i.e set the counter number you can change it accordingly a = NumericProperty(100) # seconds # To start countdown def start(self): Animation.cancel_all(self) # stop any current animations self.anim = Animation(a = 0, duration = self.a) # TO finish count down def finish_callback(animation, clock): clock.text = "FINISHED" self.anim.bind(on_complete = finish_callback) self.anim.start(self) # If u remove this there will be nothing on screen def on_a(self, instance, value): self.text = str(round(value, 1)) # Create the App classclass TimeApp(App): def build(self): # Create the object of Clock class clock = Clock() # call the function from class Clock clock.start() return clock # Run the Appif __name__ == "__main__": TimeApp().run()
Output:
Note: Countdown starts from 100 and ends on 0
# Now By using Clock Object:
Python3
'''Code of How to create countdown using label only''' # Program to Show how to create a switch# import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # The Label widget is for rendering text.from kivy.uix.label import Label # The Clock object allows you to schedule# a function call in the future; once or# repeatedly at specified intervals.from kivy.clock import Clock # The kivy App that extends from the App classclass ClockDemo(App): count = 0 def build(self): self.myLabel = Label(text ='Waiting for updates...') # Start the clock Clock.schedule_interval(self.Callback_Clock, 1) return self.myLabel def Callback_Clock(self, dt): self.count = self.count + 1 self.myLabel.text = "Updated % d...times"% self.count # Run the appif __name__ == '__main__': ClockDemo().run()
Output:
Note: This starts from 0 and runs until you cut the window
abhigoya
simranarora5sos
Python-gui
Python-kivy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Selecting rows in pandas DataFrame based on conditions
Reading and Writing to text files in Python
sum() function in Python
*args and **kwargs in Python | [
{
"code": null,
"e": 24306,
"s": 24278,
"text": "\n29 Sep, 2021"
},
{
"code": null,
"e": 24825,
"s": 24306,
"text": "Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications.In this, we are going to see how can we create a stopwatch using a label. In the code, we will be creating just a counter using the label in which when you set the time in seconds it will start decreasing like a countdown and in the second we will do the same by using clock object. "
},
{
"code": null,
"e": 24868,
"s": 24825,
"text": " Kivy Tutorial – Learn Kivy with Examples."
},
{
"code": null,
"e": 24883,
"s": 24868,
"text": "Clock Object: "
},
{
"code": null,
"e": 25106,
"s": 24883,
"text": "Kivy provides Clock objects.Clock objects can be made to call a function when a specified time period has elapsed.A clock object in Kivy can be configured to call a function upon every elapse of time duration or only once."
},
{
"code": null,
"e": 25135,
"s": 25106,
"text": "Kivy provides Clock objects."
},
{
"code": null,
"e": 25222,
"s": 25135,
"text": "Clock objects can be made to call a function when a specified time period has elapsed."
},
{
"code": null,
"e": 25331,
"s": 25222,
"text": "A clock object in Kivy can be configured to call a function upon every elapse of time duration or only once."
},
{
"code": null,
"e": 25424,
"s": 25331,
"text": "It is good to use kivy inbuilt module while working with clock: from kivy.clock import Clock"
},
{
"code": null,
"e": 25733,
"s": 25424,
"text": "Basic Approach:\n1) import kivy\n2) import kivyApp\n3) import label\n4) import Animation\n5) Import clock\n6) import kivy properties(only needed one)\n7) Set minimum version(optional)\n8) Create Label class\n9) Create App class\n10) return Layout/widget/Class(according to requirement)\n11) Run an instance of the class"
},
{
"code": null,
"e": 25752,
"s": 25733,
"text": "# Simple Approach:"
},
{
"code": null,
"e": 25760,
"s": 25752,
"text": "Python3"
},
{
"code": "'''Code of How to create countdown using label only''' # Program to Show how to create a switch# import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # The Label widget is for rendering text.from kivy.uix.label import Label # Animation is used to animate Widget propertiesfrom kivy.animation import Animation # The Properties classes are used when you create an EventDispatcher.from kivy.properties import StringProperty, NumericProperty # create a label classclass Clock(Label): # Set the numeric property # i.e set the counter number you can change it accordingly a = NumericProperty(100) # seconds # To start countdown def start(self): Animation.cancel_all(self) # stop any current animations self.anim = Animation(a = 0, duration = self.a) # TO finish count down def finish_callback(animation, clock): clock.text = \"FINISHED\" self.anim.bind(on_complete = finish_callback) self.anim.start(self) # If u remove this there will be nothing on screen def on_a(self, instance, value): self.text = str(round(value, 1)) # Create the App classclass TimeApp(App): def build(self): # Create the object of Clock class clock = Clock() # call the function from class Clock clock.start() return clock # Run the Appif __name__ == \"__main__\": TimeApp().run()",
"e": 27398,
"s": 25760,
"text": null
},
{
"code": null,
"e": 27406,
"s": 27398,
"text": "Output:"
},
{
"code": null,
"e": 27452,
"s": 27406,
"text": "Note: Countdown starts from 100 and ends on 0"
},
{
"code": null,
"e": 27481,
"s": 27452,
"text": "# Now By using Clock Object:"
},
{
"code": null,
"e": 27489,
"s": 27481,
"text": "Python3"
},
{
"code": "'''Code of How to create countdown using label only''' # Program to Show how to create a switch# import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # The Label widget is for rendering text.from kivy.uix.label import Label # The Clock object allows you to schedule# a function call in the future; once or# repeatedly at specified intervals.from kivy.clock import Clock # The kivy App that extends from the App classclass ClockDemo(App): count = 0 def build(self): self.myLabel = Label(text ='Waiting for updates...') # Start the clock Clock.schedule_interval(self.Callback_Clock, 1) return self.myLabel def Callback_Clock(self, dt): self.count = self.count + 1 self.myLabel.text = \"Updated % d...times\"% self.count # Run the appif __name__ == '__main__': ClockDemo().run()",
"e": 28587,
"s": 27489,
"text": null
},
{
"code": null,
"e": 28595,
"s": 28587,
"text": "Output:"
},
{
"code": null,
"e": 28656,
"s": 28595,
"text": "Note: This starts from 0 and runs until you cut the window "
},
{
"code": null,
"e": 28665,
"s": 28656,
"text": "abhigoya"
},
{
"code": null,
"e": 28681,
"s": 28665,
"text": "simranarora5sos"
},
{
"code": null,
"e": 28692,
"s": 28681,
"text": "Python-gui"
},
{
"code": null,
"e": 28704,
"s": 28692,
"text": "Python-kivy"
},
{
"code": null,
"e": 28711,
"s": 28704,
"text": "Python"
},
{
"code": null,
"e": 28809,
"s": 28711,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28818,
"s": 28809,
"text": "Comments"
},
{
"code": null,
"e": 28831,
"s": 28818,
"text": "Old Comments"
},
{
"code": null,
"e": 28849,
"s": 28831,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28871,
"s": 28849,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28903,
"s": 28871,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28945,
"s": 28903,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28971,
"s": 28945,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29008,
"s": 28971,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 29063,
"s": 29008,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 29107,
"s": 29063,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 29132,
"s": 29107,
"text": "sum() function in Python"
}
] |
Alternating Vowels and Consonants in C/C++ | Given an input string with vowels and consonants. Rearrange the string such a way that vowels and consonants occupies alternate position in final string. As we are arranging vowels and consonants at alternate position the input string must satisfy either of the following conditions −
Number of vowels and consonants must be same e.g. string "individual" has 5 vowels and 5 consonants.
Number of vowels and consonants must be same e.g. string "individual" has 5 vowels and 5 consonants.
If number of vowels are more, then difference between number of vowels and number of consonants must be 1 e.g. string "noe" has 2 vowels and 1 consonant.
If number of vowels are more, then difference between number of vowels and number of consonants must be 1 e.g. string "noe" has 2 vowels and 1 consonant.
If number of consonants are more, then difference between number of consonants and number of vowels must be 1 e.g. string "objective" has 4 vowels and 5 consonants.
If number of consonants are more, then difference between number of consonants and number of vowels must be 1 e.g. string "objective" has 4 vowels and 5 consonants.
1. count number of vowels
2. Count number of consonants
3. if difference between number of vowels and consonants or viceversa is greater than 1 then return error
4. Split input string into two parts:
a) First string contains only vowels
b) Second string contains only consonants
5. If number of consonants and vowels are equal, then create final string by picking a character from each string alternatively.
6. If number of vowels are greater than consonants, then:
a) Include additional vowel in final string to make both strings of equal length
b) Create final string by appending a character from each string alternatively
7. If number of consonants are greater than vowels, then
a) Include additional consonant in final string to make both strings of equal length
b) Create final string by appending a character from each string alternatively
Live Demo
#include <iostream>
#include <string>
using namespace std;
bool is_vowel(char ch) {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch =='u') {
return true;
}
return false;
}
string create_final_string(string &s1, string &s2, int start, int end) {
string final_string;
for (int i = 0, j = start; j < end; ++i, ++j) {
final_string = (final_string + s1.at(i)) + s2.at(j);
}
return final_string;
}
string create_alternate_string(string &s) {
int vowel_cnt, consonant_cnt;
string vowel_str, consonant_str;
vowel_cnt = consonant_cnt = 0;
for (char c : s) {
if (is_vowel(c)) {
++vowel_cnt;
vowel_str += c;
} else {
++consonant_cnt;
consonant_str += c;
}
}
if (abs(consonant_cnt - vowel_cnt) >= 2) {
cerr << "String cannot be formed with alternating vowels and cosonants\n";
exit(1);
}
if ((consonant_cnt - vowel_cnt) == 0) {
return create_final_string(vowel_str, consonant_str, 0, vowel_cnt);
} else if (vowel_cnt > consonant_cnt) {
return vowel_str.at(0) + create_final_string(consonant_str,vowel_str, 1, vowel_cnt);
}
return consonant_str.at(0) + create_final_string(vowel_str,consonant_str, 1, consonant_cnt);
}
int main() {
string s1 = "individual";
string s2 = "noe";
string s3 = "objective";
cout << "Input : " << s1 << "\n";
cout << "Output: " << create_alternate_string(s1) << "\n\n";
cout << "Input : " << s2 << "\n";
cout << "Output: " << create_alternate_string(s2) << "\n\n";
cout << "Input : " << s3 << "\n";
cout << "Output: " << create_alternate_string(s3) << "\n\n";
}
When you compile and execute above code it will generate following output −
Input : individual
Output: inidivudal
Input : noe
Output: one
Input : objective
Output: bojecitev | [
{
"code": null,
"e": 1347,
"s": 1062,
"text": "Given an input string with vowels and consonants. Rearrange the string such a way that vowels and consonants occupies alternate position in final string. As we are arranging vowels and consonants at alternate position the input string must satisfy either of the following conditions −"
},
{
"code": null,
"e": 1448,
"s": 1347,
"text": "Number of vowels and consonants must be same e.g. string \"individual\" has 5 vowels and 5 consonants."
},
{
"code": null,
"e": 1549,
"s": 1448,
"text": "Number of vowels and consonants must be same e.g. string \"individual\" has 5 vowels and 5 consonants."
},
{
"code": null,
"e": 1703,
"s": 1549,
"text": "If number of vowels are more, then difference between number of vowels and number of consonants must be 1 e.g. string \"noe\" has 2 vowels and 1 consonant."
},
{
"code": null,
"e": 1857,
"s": 1703,
"text": "If number of vowels are more, then difference between number of vowels and number of consonants must be 1 e.g. string \"noe\" has 2 vowels and 1 consonant."
},
{
"code": null,
"e": 2022,
"s": 1857,
"text": "If number of consonants are more, then difference between number of consonants and number of vowels must be 1 e.g. string \"objective\" has 4 vowels and 5 consonants."
},
{
"code": null,
"e": 2187,
"s": 2022,
"text": "If number of consonants are more, then difference between number of consonants and number of vowels must be 1 e.g. string \"objective\" has 4 vowels and 5 consonants."
},
{
"code": null,
"e": 3052,
"s": 2187,
"text": "1. count number of vowels\n2. Count number of consonants\n3. if difference between number of vowels and consonants or viceversa is greater than 1 then return error\n4. Split input string into two parts:\n a) First string contains only vowels\n b) Second string contains only consonants\n5. If number of consonants and vowels are equal, then create final string by picking a character from each string alternatively.\n6. If number of vowels are greater than consonants, then:\n a) Include additional vowel in final string to make both strings of equal length\n b) Create final string by appending a character from each string alternatively\n7. If number of consonants are greater than vowels, then\n a) Include additional consonant in final string to make both strings of equal length\n b) Create final string by appending a character from each string alternatively"
},
{
"code": null,
"e": 3063,
"s": 3052,
"text": " Live Demo"
},
{
"code": null,
"e": 4721,
"s": 3063,
"text": "#include <iostream>\n#include <string>\nusing namespace std;\nbool is_vowel(char ch) {\n if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch =='u') {\n return true;\n }\n return false;\n}\nstring create_final_string(string &s1, string &s2, int start, int end) {\n string final_string;\n for (int i = 0, j = start; j < end; ++i, ++j) {\n final_string = (final_string + s1.at(i)) + s2.at(j);\n }\n return final_string;\n}\nstring create_alternate_string(string &s) {\n int vowel_cnt, consonant_cnt;\n string vowel_str, consonant_str;\n vowel_cnt = consonant_cnt = 0;\n for (char c : s) {\n if (is_vowel(c)) {\n ++vowel_cnt;\n vowel_str += c;\n } else {\n ++consonant_cnt;\n consonant_str += c;\n }\n }\n if (abs(consonant_cnt - vowel_cnt) >= 2) {\n cerr << \"String cannot be formed with alternating vowels and cosonants\\n\";\n exit(1);\n }\n if ((consonant_cnt - vowel_cnt) == 0) {\n return create_final_string(vowel_str, consonant_str, 0, vowel_cnt);\n } else if (vowel_cnt > consonant_cnt) {\n return vowel_str.at(0) + create_final_string(consonant_str,vowel_str, 1, vowel_cnt);\n }\n return consonant_str.at(0) + create_final_string(vowel_str,consonant_str, 1, consonant_cnt);\n}\nint main() {\n string s1 = \"individual\";\n string s2 = \"noe\";\n string s3 = \"objective\";\n cout << \"Input : \" << s1 << \"\\n\";\n cout << \"Output: \" << create_alternate_string(s1) << \"\\n\\n\";\n cout << \"Input : \" << s2 << \"\\n\";\n cout << \"Output: \" << create_alternate_string(s2) << \"\\n\\n\";\n cout << \"Input : \" << s3 << \"\\n\";\n cout << \"Output: \" << create_alternate_string(s3) << \"\\n\\n\";\n}"
},
{
"code": null,
"e": 4797,
"s": 4721,
"text": "When you compile and execute above code it will generate following output −"
},
{
"code": null,
"e": 4895,
"s": 4797,
"text": "Input : individual\nOutput: inidivudal\nInput : noe\nOutput: one\nInput : objective\nOutput: bojecitev"
}
] |
T-SQL - INSERT Statement | The SQL Server INSERT INTO statement is used to add new rows of data to a table in the database.
Following are the two basic syntaxes of INSERT INTO statement.
INSERT INTO TABLE_NAME [(column1, column2, column3,...columnN)]
VALUES (value1, value2, value3,...valueN);
Where column1, column2,...columnN are the names of the columns in the table into which you want to insert data.
You need not specify the column(s) name in the SQL query if you are adding values for all the columns of the table. But make sure the order of the values is in the same order as the columns in the table. Following is the SQL INSERT INTO syntax −
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);
Following statements will create six records in CUSTOMERS table −
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (3, 'kaushik', 23, 'Kota', 2000.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (6, 'Komal', 22, 'MP', 4500.00 );
You can create a record in CUSTOMERS table using second syntax as follows −
INSERT INTO CUSTOMERS VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );
All the above statements will produce the following records in CUSTOMERS table −
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
You can populate data into a table through SELECT statement over another table provided another table has a set of fields, which are required to populate first table. Following is the syntax −
INSERT INTO first_table_name
SELECT column1, column2, ...columnN
FROM second_table_name
[WHERE condition];
12 Lectures
2 hours
Nishant Malik
10 Lectures
1.5 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
20 Lectures
2 hours
Asif Hussain
10 Lectures
1.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2157,
"s": 2060,
"text": "The SQL Server INSERT INTO statement is used to add new rows of data to a table in the database."
},
{
"code": null,
"e": 2220,
"s": 2157,
"text": "Following are the two basic syntaxes of INSERT INTO statement."
},
{
"code": null,
"e": 2332,
"s": 2220,
"text": "INSERT INTO TABLE_NAME [(column1, column2, column3,...columnN)] \nVALUES (value1, value2, value3,...valueN); \n"
},
{
"code": null,
"e": 2444,
"s": 2332,
"text": "Where column1, column2,...columnN are the names of the columns in the table into which you want to insert data."
},
{
"code": null,
"e": 2690,
"s": 2444,
"text": "You need not specify the column(s) name in the SQL query if you are adding values for all the columns of the table. But make sure the order of the values is in the same order as the columns in the table. Following is the SQL INSERT INTO syntax −"
},
{
"code": null,
"e": 2754,
"s": 2690,
"text": "INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);"
},
{
"code": null,
"e": 2820,
"s": 2754,
"text": "Following statements will create six records in CUSTOMERS table −"
},
{
"code": null,
"e": 3421,
"s": 2820,
"text": "INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) \nVALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );\n \nINSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) \nVALUES (2, 'Khilan', 25, 'Delhi', 1500.00 ); \n\nINSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) \nVALUES (3, 'kaushik', 23, 'Kota', 2000.00 ); \n\nINSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) \nVALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 ); \n \nINSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) \nVALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 ); \n\nINSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) \nVALUES (6, 'Komal', 22, 'MP', 4500.00 );"
},
{
"code": null,
"e": 3497,
"s": 3421,
"text": "You can create a record in CUSTOMERS table using second syntax as follows −"
},
{
"code": null,
"e": 3566,
"s": 3497,
"text": "INSERT INTO CUSTOMERS VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );\n"
},
{
"code": null,
"e": 3647,
"s": 3566,
"text": "All the above statements will produce the following records in CUSTOMERS table −"
},
{
"code": null,
"e": 4104,
"s": 3647,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00 \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00 \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n"
},
{
"code": null,
"e": 4297,
"s": 4104,
"text": "You can populate data into a table through SELECT statement over another table provided another table has a set of fields, which are required to populate first table. Following is the syntax −"
},
{
"code": null,
"e": 4425,
"s": 4297,
"text": "INSERT INTO first_table_name \n SELECT column1, column2, ...columnN \n FROM second_table_name \n [WHERE condition];\n"
},
{
"code": null,
"e": 4458,
"s": 4425,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4473,
"s": 4458,
"text": " Nishant Malik"
},
{
"code": null,
"e": 4508,
"s": 4473,
"text": "\n 10 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4523,
"s": 4508,
"text": " Nishant Malik"
},
{
"code": null,
"e": 4558,
"s": 4523,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4573,
"s": 4558,
"text": " Nishant Malik"
},
{
"code": null,
"e": 4606,
"s": 4573,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4620,
"s": 4606,
"text": " Asif Hussain"
},
{
"code": null,
"e": 4655,
"s": 4620,
"text": "\n 10 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4670,
"s": 4655,
"text": " Nishant Malik"
},
{
"code": null,
"e": 4705,
"s": 4670,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 4719,
"s": 4705,
"text": " Asif Hussain"
},
{
"code": null,
"e": 4726,
"s": 4719,
"text": " Print"
},
{
"code": null,
"e": 4737,
"s": 4726,
"text": " Add Notes"
}
] |
Ruby | Hash flatten() function - GeeksforGeeks | 07 Jan, 2020
Hash#flatten() is a Hash class method which returns the one-dimensional flattening hash array.
Syntax: Hash.flatten()
Parameter: Hash values
Return: one-dimensional flattening hash array
Example #1 :
# Ruby code for Hash.flatten() method # declaring Hash valuea = {a:100, b:200} # declaring Hash valueb = {a:100, c:[300, 45], b:200} # declaring Hash valuec = {a:100} # flatten Valueputs "Hash a flatten form : #{a.flatten()}\n\n" puts "Hash b flatten form : #{b.flatten()}\n\n" puts "Hash c flatten form : #{c.flatten()}\n\n"
Output :
Hash a flatten form : [:a, 100, :b, 200]
Hash b flatten form : [:a, 100, :c, [300, 45], :b, 200]
Hash c flatten form : [:a, 100]
Example #2 :
# Ruby code for Hash.flatten() method # declaring Hash valuea = { "a" => 100, "b" => 200 } # declaring Hash valueb = {"a" => 100} # declaring Hash valuec = {"a" => 100, "c" => [300, 200, 500], "b" => 200} # flatten Valueputs "Hash a flatten form : #{a.flatten()}\n\n" puts "Hash b flatten form : #{b.flatten()}\n\n" puts "Hash c flatten form : #{c.flatten()}\n\n"
Output :
Hash a flatten form : ["a", 100, "b", 200]
Hash b flatten form : ["a", 100]
Hash c flatten form : ["a", 100, "c", [300, 200, 500], "b", 200]
Ruby Hash-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Ruby | Array count() operation
Include v/s Extend in Ruby
Ruby | Enumerator each_with_index function
Ruby | Array select() function
Global Variable in Ruby
Ruby | Hash delete() function
Ruby | String gsub! Method
Ruby | String capitalize() Method
How to Make a Custom Array of Hashes in Ruby?
Ruby | Case Statement | [
{
"code": null,
"e": 23381,
"s": 23353,
"text": "\n07 Jan, 2020"
},
{
"code": null,
"e": 23476,
"s": 23381,
"text": "Hash#flatten() is a Hash class method which returns the one-dimensional flattening hash array."
},
{
"code": null,
"e": 23499,
"s": 23476,
"text": "Syntax: Hash.flatten()"
},
{
"code": null,
"e": 23522,
"s": 23499,
"text": "Parameter: Hash values"
},
{
"code": null,
"e": 23568,
"s": 23522,
"text": "Return: one-dimensional flattening hash array"
},
{
"code": null,
"e": 23581,
"s": 23568,
"text": "Example #1 :"
},
{
"code": "# Ruby code for Hash.flatten() method # declaring Hash valuea = {a:100, b:200} # declaring Hash valueb = {a:100, c:[300, 45], b:200} # declaring Hash valuec = {a:100} # flatten Valueputs \"Hash a flatten form : #{a.flatten()}\\n\\n\" puts \"Hash b flatten form : #{b.flatten()}\\n\\n\" puts \"Hash c flatten form : #{c.flatten()}\\n\\n\"",
"e": 23915,
"s": 23581,
"text": null
},
{
"code": null,
"e": 23924,
"s": 23915,
"text": "Output :"
},
{
"code": null,
"e": 24057,
"s": 23924,
"text": "Hash a flatten form : [:a, 100, :b, 200]\n\nHash b flatten form : [:a, 100, :c, [300, 45], :b, 200]\n\nHash c flatten form : [:a, 100]\n\n"
},
{
"code": null,
"e": 24070,
"s": 24057,
"text": "Example #2 :"
},
{
"code": "# Ruby code for Hash.flatten() method # declaring Hash valuea = { \"a\" => 100, \"b\" => 200 } # declaring Hash valueb = {\"a\" => 100} # declaring Hash valuec = {\"a\" => 100, \"c\" => [300, 200, 500], \"b\" => 200} # flatten Valueputs \"Hash a flatten form : #{a.flatten()}\\n\\n\" puts \"Hash b flatten form : #{b.flatten()}\\n\\n\" puts \"Hash c flatten form : #{c.flatten()}\\n\\n\"",
"e": 24442,
"s": 24070,
"text": null
},
{
"code": null,
"e": 24451,
"s": 24442,
"text": "Output :"
},
{
"code": null,
"e": 24596,
"s": 24451,
"text": "Hash a flatten form : [\"a\", 100, \"b\", 200]\n\nHash b flatten form : [\"a\", 100]\n\nHash c flatten form : [\"a\", 100, \"c\", [300, 200, 500], \"b\", 200]\n\n"
},
{
"code": null,
"e": 24612,
"s": 24596,
"text": "Ruby Hash-class"
},
{
"code": null,
"e": 24625,
"s": 24612,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 24630,
"s": 24625,
"text": "Ruby"
},
{
"code": null,
"e": 24728,
"s": 24630,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24737,
"s": 24728,
"text": "Comments"
},
{
"code": null,
"e": 24750,
"s": 24737,
"text": "Old Comments"
},
{
"code": null,
"e": 24781,
"s": 24750,
"text": "Ruby | Array count() operation"
},
{
"code": null,
"e": 24808,
"s": 24781,
"text": "Include v/s Extend in Ruby"
},
{
"code": null,
"e": 24851,
"s": 24808,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 24882,
"s": 24851,
"text": "Ruby | Array select() function"
},
{
"code": null,
"e": 24906,
"s": 24882,
"text": "Global Variable in Ruby"
},
{
"code": null,
"e": 24936,
"s": 24906,
"text": "Ruby | Hash delete() function"
},
{
"code": null,
"e": 24963,
"s": 24936,
"text": "Ruby | String gsub! Method"
},
{
"code": null,
"e": 24997,
"s": 24963,
"text": "Ruby | String capitalize() Method"
},
{
"code": null,
"e": 25043,
"s": 24997,
"text": "How to Make a Custom Array of Hashes in Ruby?"
}
] |
HTML | DOM onmouseover event - GeeksforGeeks | 04 Aug, 2021
The DOM onmouseover event in HTML occurs when the mouse pointer is moved onto an element or its children.Supported Tags: It supports All HTML elements, EXCEPT:
<base>
<bdo>
<br>
<head>
<html>
<iframe>
<meta>
<param>
<script>
<style>
<title>
Syntax:
In HTML:
<element onmouseover="myScript">
In JavaScript:
object.onmouseover = function(){myScript};
In JavaScript, using the addEventListener() method:
object.addEventListener("mouseover", myScript);
Example:
html
<!DOCTYPE html><html> <head> <title> DOM onmouseover event </title></head> <body> <center> <h1 id="hID"> GeeksforGeeks </h1> <h2> HTML DOM onmouseover event </h2> <script> document.getElementById( "hID").addEventListener( "mouseover", over); document.getElementById( "hID").addEventListener( "mouseout", out); function over() { document.getElementById( "hID").style.color = "green"; } function out() { document.getElementById( "hID").style.color = "black"; } </script> </center></body> </html>
Output:
Supported Browsers: The browsers supported by HTML DOM onmouseover event are listed below:
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
ManasChhabra2
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
Design a web page using HTML and CSS
How to create an HTML button that acts like a link?
How to position a div at the bottom of its container using CSS?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Angular Libraries For Web Developers
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 24996,
"s": 24968,
"text": "\n04 Aug, 2021"
},
{
"code": null,
"e": 25157,
"s": 24996,
"text": "The DOM onmouseover event in HTML occurs when the mouse pointer is moved onto an element or its children.Supported Tags: It supports All HTML elements, EXCEPT: "
},
{
"code": null,
"e": 25164,
"s": 25157,
"text": "<base>"
},
{
"code": null,
"e": 25170,
"s": 25164,
"text": "<bdo>"
},
{
"code": null,
"e": 25175,
"s": 25170,
"text": "<br>"
},
{
"code": null,
"e": 25182,
"s": 25175,
"text": "<head>"
},
{
"code": null,
"e": 25189,
"s": 25182,
"text": "<html>"
},
{
"code": null,
"e": 25198,
"s": 25189,
"text": "<iframe>"
},
{
"code": null,
"e": 25206,
"s": 25198,
"text": " <meta>"
},
{
"code": null,
"e": 25214,
"s": 25206,
"text": "<param>"
},
{
"code": null,
"e": 25223,
"s": 25214,
"text": "<script>"
},
{
"code": null,
"e": 25231,
"s": 25223,
"text": "<style>"
},
{
"code": null,
"e": 25239,
"s": 25231,
"text": "<title>"
},
{
"code": null,
"e": 25249,
"s": 25239,
"text": "Syntax: "
},
{
"code": null,
"e": 25260,
"s": 25249,
"text": "In HTML: "
},
{
"code": null,
"e": 25293,
"s": 25260,
"text": "<element onmouseover=\"myScript\">"
},
{
"code": null,
"e": 25310,
"s": 25293,
"text": "In JavaScript: "
},
{
"code": null,
"e": 25353,
"s": 25310,
"text": "object.onmouseover = function(){myScript};"
},
{
"code": null,
"e": 25407,
"s": 25353,
"text": "In JavaScript, using the addEventListener() method: "
},
{
"code": null,
"e": 25455,
"s": 25407,
"text": "object.addEventListener(\"mouseover\", myScript);"
},
{
"code": null,
"e": 25466,
"s": 25455,
"text": "Example: "
},
{
"code": null,
"e": 25471,
"s": 25466,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> DOM onmouseover event </title></head> <body> <center> <h1 id=\"hID\"> GeeksforGeeks </h1> <h2> HTML DOM onmouseover event </h2> <script> document.getElementById( \"hID\").addEventListener( \"mouseover\", over); document.getElementById( \"hID\").addEventListener( \"mouseout\", out); function over() { document.getElementById( \"hID\").style.color = \"green\"; } function out() { document.getElementById( \"hID\").style.color = \"black\"; } </script> </center></body> </html>",
"e": 26233,
"s": 25471,
"text": null
},
{
"code": null,
"e": 26243,
"s": 26233,
"text": "Output: "
},
{
"code": null,
"e": 26336,
"s": 26243,
"text": "Supported Browsers: The browsers supported by HTML DOM onmouseover event are listed below: "
},
{
"code": null,
"e": 26350,
"s": 26336,
"text": "Google Chrome"
},
{
"code": null,
"e": 26368,
"s": 26350,
"text": "Internet Explorer"
},
{
"code": null,
"e": 26376,
"s": 26368,
"text": "Firefox"
},
{
"code": null,
"e": 26389,
"s": 26376,
"text": "Apple Safari"
},
{
"code": null,
"e": 26395,
"s": 26389,
"text": "Opera"
},
{
"code": null,
"e": 26534,
"s": 26397,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 26548,
"s": 26534,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 26557,
"s": 26548,
"text": "HTML-DOM"
},
{
"code": null,
"e": 26562,
"s": 26557,
"text": "HTML"
},
{
"code": null,
"e": 26579,
"s": 26562,
"text": "Web Technologies"
},
{
"code": null,
"e": 26584,
"s": 26579,
"text": "HTML"
},
{
"code": null,
"e": 26682,
"s": 26584,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26691,
"s": 26682,
"text": "Comments"
},
{
"code": null,
"e": 26704,
"s": 26691,
"text": "Old Comments"
},
{
"code": null,
"e": 26754,
"s": 26704,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 26778,
"s": 26754,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 26815,
"s": 26778,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 26867,
"s": 26815,
"text": "How to create an HTML button that acts like a link?"
},
{
"code": null,
"e": 26931,
"s": 26867,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 26973,
"s": 26931,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27006,
"s": 26973,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27049,
"s": 27006,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27093,
"s": 27049,
"text": "Top 10 Angular Libraries For Web Developers"
}
] |
Ionic - Cordova Camera | The Cordova camera plugin uses the native camera for taking pictures or getting images from the image gallery.
Open your project root folder in command prompt, then download and install the Cordova camera plugin with the following command.
C:\Users\Username\Desktop\MyApp> cordova plugin add org.apache.cordova.camera
Now, we will create a service for using a camera plugin. We will use the AngularJS factory and promise object $q that needs to be injected to the factory.
.factory('Camera', function($q) {
return {
getPicture: function(options) {
var q = $q.defer();
navigator.camera.getPicture(function(result) {
q.resolve(result);
}, function(err) {
q.reject(err);
}, options);
return q.promise;
}
}
});
To use this service in the app, we need to inject it to a controller as a dependency. Cordova camera API provides the getPicture method, which is used for taking photos using a native camera.
The native camera settings can be additionally customized by passing the options parameter to the takePicture function. Copy the above-mentioned code sample to your controller to trigger this behavior. It will open the camera application and return a success callback function with the image data or error callback function with an error message. We will also need two buttons that will call the functions we are about to create and we need to show the image on the screen.
<button class = "button" ng-click = "takePicture()">Take Picture</button>
<button class = "button" ng-click = "getPicture()">Open Gallery</button>
<img ng-src = "{{user.picture}}">
.controller('MyCtrl', function($scope, Camera) {
$scope.takePicture = function (options) {
var options = {
quality : 75,
targetWidth: 200,
targetHeight: 200,
sourceType: 1
};
Camera.getPicture(options).then(function(imageData) {
$scope.picture = imageData;;
}, function(err) {
console.log(err);
});
};
})
The output will look as shown in the following screenshot.
If you want to use images from your gallery, the only thing you need to change is the sourceType method from your options parameter. This change will open a dialog popup instead of camera and allow you to choose the image you want from the device.
You can see the following code, where the sourceType option is changed to 0. Now, when you tap the second button, it will open the file menu from the device.
.controller('MyCtrl', function($scope, Camera) {
$scope.getPicture = function (options) {
var options = {
quality : 75,
targetWidth: 200,
targetHeight: 200,
sourceType: 0
};
Camera.getPicture(options).then(function(imageData) {
$scope.picture = imageData;;
}, function(err) {
console.log(err);
});
};
})
The output will look as shown in the following screenshot.
When you save the image you took, it will appear on the screen. You can style it the way you want.
Several other options can be used as well, some of which are given in the following table.
16 Lectures
2.5 hours
Frahaan Hussain
185 Lectures
46.5 hours
Nikhil Agarwal
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2574,
"s": 2463,
"text": "The Cordova camera plugin uses the native camera for taking pictures or getting images from the image gallery."
},
{
"code": null,
"e": 2703,
"s": 2574,
"text": "Open your project root folder in command prompt, then download and install the Cordova camera plugin with the following command."
},
{
"code": null,
"e": 2782,
"s": 2703,
"text": "C:\\Users\\Username\\Desktop\\MyApp> cordova plugin add org.apache.cordova.camera\n"
},
{
"code": null,
"e": 2937,
"s": 2782,
"text": "Now, we will create a service for using a camera plugin. We will use the AngularJS factory and promise object $q that needs to be injected to the factory."
},
{
"code": null,
"e": 3260,
"s": 2937,
"text": ".factory('Camera', function($q) {\n return {\n getPicture: function(options) {\n var q = $q.defer();\n\n navigator.camera.getPicture(function(result) {\n q.resolve(result);\n }, function(err) {\n q.reject(err);\n }, options);\n\n return q.promise;\n }\n }\n});"
},
{
"code": null,
"e": 3452,
"s": 3260,
"text": "To use this service in the app, we need to inject it to a controller as a dependency. Cordova camera API provides the getPicture method, which is used for taking photos using a native camera."
},
{
"code": null,
"e": 3926,
"s": 3452,
"text": "The native camera settings can be additionally customized by passing the options parameter to the takePicture function. Copy the above-mentioned code sample to your controller to trigger this behavior. It will open the camera application and return a success callback function with the image data or error callback function with an error message. We will also need two buttons that will call the functions we are about to create and we need to show the image on the screen."
},
{
"code": null,
"e": 4107,
"s": 3926,
"text": "<button class = \"button\" ng-click = \"takePicture()\">Take Picture</button>\n<button class = \"button\" ng-click = \"getPicture()\">Open Gallery</button>\n<img ng-src = \"{{user.picture}}\">"
},
{
"code": null,
"e": 4503,
"s": 4107,
"text": ".controller('MyCtrl', function($scope, Camera) {\n $scope.takePicture = function (options) {\n var options = {\n quality : 75,\n targetWidth: 200,\n targetHeight: 200,\n sourceType: 1\n };\n\n Camera.getPicture(options).then(function(imageData) {\n $scope.picture = imageData;;\n }, function(err) {\n console.log(err);\n });\n };\n})"
},
{
"code": null,
"e": 4562,
"s": 4503,
"text": "The output will look as shown in the following screenshot."
},
{
"code": null,
"e": 4810,
"s": 4562,
"text": "If you want to use images from your gallery, the only thing you need to change is the sourceType method from your options parameter. This change will open a dialog popup instead of camera and allow you to choose the image you want from the device."
},
{
"code": null,
"e": 4968,
"s": 4810,
"text": "You can see the following code, where the sourceType option is changed to 0. Now, when you tap the second button, it will open the file menu from the device."
},
{
"code": null,
"e": 5363,
"s": 4968,
"text": ".controller('MyCtrl', function($scope, Camera) {\n $scope.getPicture = function (options) {\n\t var options = {\n quality : 75,\n targetWidth: 200,\n targetHeight: 200,\n sourceType: 0\n };\n\n Camera.getPicture(options).then(function(imageData) {\n $scope.picture = imageData;;\n }, function(err) {\n console.log(err);\n });\n }; \n})"
},
{
"code": null,
"e": 5422,
"s": 5363,
"text": "The output will look as shown in the following screenshot."
},
{
"code": null,
"e": 5521,
"s": 5422,
"text": "When you save the image you took, it will appear on the screen. You can style it the way you want."
},
{
"code": null,
"e": 5612,
"s": 5521,
"text": "Several other options can be used as well, some of which are given in the following table."
},
{
"code": null,
"e": 5647,
"s": 5612,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5664,
"s": 5647,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5701,
"s": 5664,
"text": "\n 185 Lectures \n 46.5 hours \n"
},
{
"code": null,
"e": 5717,
"s": 5701,
"text": " Nikhil Agarwal"
},
{
"code": null,
"e": 5724,
"s": 5717,
"text": " Print"
},
{
"code": null,
"e": 5735,
"s": 5724,
"text": " Add Notes"
}
] |
Interactive Network Visualization | by Himanshu Sharma | Towards Data Science | Pyviz is a python module that is used to create networks that can be customized on per node or per edge basis. It contains different customizations like the size of the node, edges, user-defined labels. The graphs created using pyviz are highly interactive which allows dragging, hovering, and selecting different nodes and edges.
Each graph created using Pyviz can have a custom layout that can be tweaked for user-defined requirements.
Pyviz is a wrapper built around the amazing VisJS library. In this article, we will be exploring Pyviz for creating network graphs using python.
Let’s get started...
Like any other python library, we will install the Pyviz library using pip. The command for which is given below.
pip install pyvis
In order to create a graph network, we will be using the network class instance of Pyviz which can be imported using the code given below.
from pyvis.network import Network
Now that we have imported the network class instance we will start building our graph network by adding nodes. We can add nodes one by one or we can also create a list of nodes.
net = Network()#Adding node one by onenet.add_node(1, label="Node 1")net.add_node(2) #Adding node as a listnodes = ["a", "b", "c", "d"]net.add_nodes(nodes) net.add_nodes("hello")
Next, we will create edges that will connect these nodes with specified weights given to each edge. The code for which is given below.
net.add_edge(0, 1, weight=.87)
The final step is to visualize the graph we have created as a static HTML file as we know this file will be highly interactive.
net.toggle_physics(True)net.show('mygraph.html')
We can dynamically alter the settings of our network using the configuration UI. It will add buttons to the UI. So that we can tweak our graphs to find out the most optimal physics parameters and the layouts.
net.show_buttons(filter_=['physics'])
So this is how you can create your own graph network visualization. Go ahead try this and let me know if you face any issues in the response section.
This article is in collaboration with Piyush Ingale.
Thanks for reading! If you want to get in touch with me, feel free to reach me on [email protected] or my LinkedIn Profile. You can view my Github profile for different data science projects and packages tutorials. Also, feel free to explore my profile and read different articles I have written related to Data Science. | [
{
"code": null,
"e": 503,
"s": 172,
"text": "Pyviz is a python module that is used to create networks that can be customized on per node or per edge basis. It contains different customizations like the size of the node, edges, user-defined labels. The graphs created using pyviz are highly interactive which allows dragging, hovering, and selecting different nodes and edges."
},
{
"code": null,
"e": 610,
"s": 503,
"text": "Each graph created using Pyviz can have a custom layout that can be tweaked for user-defined requirements."
},
{
"code": null,
"e": 755,
"s": 610,
"text": "Pyviz is a wrapper built around the amazing VisJS library. In this article, we will be exploring Pyviz for creating network graphs using python."
},
{
"code": null,
"e": 776,
"s": 755,
"text": "Let’s get started..."
},
{
"code": null,
"e": 890,
"s": 776,
"text": "Like any other python library, we will install the Pyviz library using pip. The command for which is given below."
},
{
"code": null,
"e": 908,
"s": 890,
"text": "pip install pyvis"
},
{
"code": null,
"e": 1047,
"s": 908,
"text": "In order to create a graph network, we will be using the network class instance of Pyviz which can be imported using the code given below."
},
{
"code": null,
"e": 1081,
"s": 1047,
"text": "from pyvis.network import Network"
},
{
"code": null,
"e": 1259,
"s": 1081,
"text": "Now that we have imported the network class instance we will start building our graph network by adding nodes. We can add nodes one by one or we can also create a list of nodes."
},
{
"code": null,
"e": 1438,
"s": 1259,
"text": "net = Network()#Adding node one by onenet.add_node(1, label=\"Node 1\")net.add_node(2) #Adding node as a listnodes = [\"a\", \"b\", \"c\", \"d\"]net.add_nodes(nodes) net.add_nodes(\"hello\")"
},
{
"code": null,
"e": 1573,
"s": 1438,
"text": "Next, we will create edges that will connect these nodes with specified weights given to each edge. The code for which is given below."
},
{
"code": null,
"e": 1604,
"s": 1573,
"text": "net.add_edge(0, 1, weight=.87)"
},
{
"code": null,
"e": 1732,
"s": 1604,
"text": "The final step is to visualize the graph we have created as a static HTML file as we know this file will be highly interactive."
},
{
"code": null,
"e": 1781,
"s": 1732,
"text": "net.toggle_physics(True)net.show('mygraph.html')"
},
{
"code": null,
"e": 1990,
"s": 1781,
"text": "We can dynamically alter the settings of our network using the configuration UI. It will add buttons to the UI. So that we can tweak our graphs to find out the most optimal physics parameters and the layouts."
},
{
"code": null,
"e": 2028,
"s": 1990,
"text": "net.show_buttons(filter_=['physics'])"
},
{
"code": null,
"e": 2178,
"s": 2028,
"text": "So this is how you can create your own graph network visualization. Go ahead try this and let me know if you face any issues in the response section."
},
{
"code": null,
"e": 2231,
"s": 2178,
"text": "This article is in collaboration with Piyush Ingale."
}
] |
Semaphore in Java | A semaphore is used to control access to a shared resource when a process is being executed. This is done with the help of a counter. When this counter value is greater than 0, access to share resource is provided. On the other hand, if the value of counter is zero, then access to shared resources is denied. The counter basically keeps a count of the number of permissions it has given to the shared resource. This means, a semaphore provides access to a shared resource for a thread.
Semaphores are present in the java.util.concurrent package. The concept of semaphore is implemented implicitly.
If the count of semaphore is greater than 0, the thread gets access to shared resource. The count of the semaphore will be decrement simultaneously. Otherwise, if the count of semaphore is not0, the thread would be blocked from accessing the shared resource until the semaphore releases the other thread’s access. When the thread doesn’t need the shared resource, it gives away its permission. At this point in time, the semaphore’s count would be increment. If a different thread also requires access to shared resource, it can compete to access the shared resource.
Following is an example −
public class Demo {
private boolean my_signal = false;
public synchronized void accept() {
this.my_signal = true;
this.notify();
}
public synchronized void give_it() throws InterruptedException {
while(!this.my_signal) wait();
this.my_signal = false;
}
}
The ‘accept’ method is used to send a signal that is stored inside a semaphore. The ‘give_it’ function waits for a signal. When this function receives a signal, its flag is cleared, and the control exits from this function. Using a semaphore in this manner, none of the signals would be missed. | [
{
"code": null,
"e": 1549,
"s": 1062,
"text": "A semaphore is used to control access to a shared resource when a process is being executed. This is done with the help of a counter. When this counter value is greater than 0, access to share resource is provided. On the other hand, if the value of counter is zero, then access to shared resources is denied. The counter basically keeps a count of the number of permissions it has given to the shared resource. This means, a semaphore provides access to a shared resource for a thread."
},
{
"code": null,
"e": 1661,
"s": 1549,
"text": "Semaphores are present in the java.util.concurrent package. The concept of semaphore is implemented implicitly."
},
{
"code": null,
"e": 2229,
"s": 1661,
"text": "If the count of semaphore is greater than 0, the thread gets access to shared resource. The count of the semaphore will be decrement simultaneously. Otherwise, if the count of semaphore is not0, the thread would be blocked from accessing the shared resource until the semaphore releases the other thread’s access. When the thread doesn’t need the shared resource, it gives away its permission. At this point in time, the semaphore’s count would be increment. If a different thread also requires access to shared resource, it can compete to access the shared resource."
},
{
"code": null,
"e": 2255,
"s": 2229,
"text": "Following is an example −"
},
{
"code": null,
"e": 2549,
"s": 2255,
"text": "public class Demo {\n private boolean my_signal = false;\n public synchronized void accept() {\n this.my_signal = true;\n this.notify();\n }\n public synchronized void give_it() throws InterruptedException {\n while(!this.my_signal) wait();\n this.my_signal = false;\n }\n}"
},
{
"code": null,
"e": 2844,
"s": 2549,
"text": "The ‘accept’ method is used to send a signal that is stored inside a semaphore. The ‘give_it’ function waits for a signal. When this function receives a signal, its flag is cleared, and the control exits from this function. Using a semaphore in this manner, none of the signals would be missed."
}
] |
Creating a Dataset from Scratch. Using web scraping, API calls, and... | by Jesse Neumann | Towards Data Science | This blog walks through the entire process of creating a dataset for use in a larger data science project.
The data science project involves modeling the success of video games, discovering the importance of individual features, and then creating an interactive web app.
The web app will allow a game developer to input and modify a game design in order to maximize the predicted success given the resources available to the developer.
One of the most important aspects of any project, and one of the most overlooked is project planning.
Having a plan will ensure you consistently move forward toward your goal, and your resulting project will be much better organized and will be completed much sooner (if you’re like me you are easily distracted by new feature ideas).
The best way I have found so far is to use the planning section of your github’s project repository. I use this section to set up a automated Kanban style project board that will complete steps automatically after you merge a pull request for the specific issue.
Setting up the board is simple:
Go to your project repo and click on ‘Projects’ tab.Fill out the form and click ‘Create Project’
Go to your project repo and click on ‘Projects’ tab.
Fill out the form and click ‘Create Project’
Now that we have our project board set up, go ahead and delete the default informative cards that appear as part of the template.
After that, begin adding cards for each of the main steps necessary for successfully completing the project:
Identify features that will be strong predictors for a games success, and find a source where they can be obtainedCreate a data dictionary with the feature name, a short description, the type, and the sourceDecide on which database to use and set it upImplement a class for interacting with the databaseImplement a class for scraping the data from SteamImplement a program for obtaining the data from RAWG APICombine the two programs to create a script that will populate the databaseUpload the completed dataset to Kaggle
Identify features that will be strong predictors for a games success, and find a source where they can be obtained
Create a data dictionary with the feature name, a short description, the type, and the source
Decide on which database to use and set it up
Implement a class for interacting with the database
Implement a class for scraping the data from Steam
Implement a program for obtaining the data from RAWG API
Combine the two programs to create a script that will populate the database
Upload the completed dataset to Kaggle
Here is our project board now, with the cards moved around a little to illustrate how you can track your workflow:
Now as you begin working on the project you can select the card you are working on currently, and click on the ‘...’ and convert it to an issue. This will enable you to submit a pull request that will automatically close the issue and move it into the ‘Done’ column.
Here is what the almost completed project board looks like:
Now that we have an outline and a project board set up, we can ensure that anytime we are working on a card we are moving toward the end goal. No more getting sidetracked by adding cool (unnecessary?) features we think up on the fly.
Now that we have the planning out of the way, it’s time to start implementing each of our cards. Not all of the cards require coding or a pull request, especially in the early phase when we are developing the architecture.
The first place to start will be the Steam store, which is the largest online marketplace for PC games, and one of the most active gaming communities online.
Googling steam store will give us this link: https://store.steampowered.com/
Clicking on the link will take us to the homepage:
Clicking on a random game will show us what data is available and we can decide whether or not that piece of data will be a valuable predictor or not.
Heres a random game page:
Right away we can see some data points that will be useful for our dataset.
Let’s keep these data points in mind as we start looking for complementary data from an API source.
After googling “game developer apis” and clicking on the first result that is not an ad, we arrive at https://rapidapi.com/blog/top-video-game-apis/.
Several of the API’s are dedicated to specific games such as Minecraft and League of Legends, and will not be useful for our dataset.
The very first API on the list, however, is the RAWG Video Games Database API, which sounds promising even though I don’t know what ‘RAWG’ stands for.
We can check out the different response schema’s and identify any features that sound relevant for our dataset:
Once again we can see several features that could be useful for our dataset. Let’s keep these two resources handy and come up with a complete list of features we want our dataset to contain.
Not only is it best-practice to create a high-quality data dictionary which explains each variable, it is also extremely useful for several of the tasks we will complete for our project.
Creating a table using markdown is quick and easy, and provides us with a clean looking overview of all the features:
We now have a nice looking data-dictionary which will be our source of truth for the dataset.
Any changes to the dataset should first be recorded in the data-dictionary before being implemented by the individual classes.
One of the worst feelings ever is when your scraping program throws an error after 8 hours and all the data gathered up to that point is erased.
In order to avoid such bad feelings, we will use a simple database to persist the data while we are running the scraping program.
All we need our database to do is hold our data and let us know if a game has already been saved or not, so we can avoid redundancy.
There are several database options that would work for this simple project, but we will be using sqlite3. This will give us a super simple database on our local system that we can interact with using SQL.
To organize our code better and to keep the SQL all in one place we will create a class to manage and interact with our database. One important method we do need to add however is the ability to save our database as a ‘csv’ file.
In order to keep this post from taking 200 hours to read I will not be diving into much detail for the classes.
I plan on creating a few shorter blogs about how to create each individual class, but for now you can check out the full code repository here:
https://github.com/Jesse989/game-oracle
Also, if you have any comments, questions, or recommendations, please reach out to me. I really appreciate the chance to discuss these things.
This is basically a utility class for managing our database and handling the SQL so we don’t have to re-write the queries multiple times.
In addition, I have given it a ‘.to_csv()’ method that will create a csv file with the entire contents of our ‘games’ table.
Now that we have a way to persist the data, let’s focus on finding the data we want to save. Since we are dealing with two sources for our data, it makes sense to create two separate classes, one for each source.
First will be to come up with a way to obtain the data from the Steam store. To do this we will write a class that will use some basic python scraping libraries; Requests, BeautifulSoup, and the python library re (regular expressions).
This object will be responsible for requesting the individual game url, and then parsing the desired information using a combination of BeautifulSoup searches and regex.
As you can see, the class consists mostly of two public methods: ‘get_game_html’ and ‘strip_features’.
The first method fetches the page from the specified url, and then the second method is called on the resulting html.
The ‘strip_features’ method is where the entire results object is built, and consists mainly of composing the resulting game dict by using the private helper methods.
Now that we have completed the first half of obtaining the data, let’s move on and create the class that will interact with the RAWG API.
Dealing with API’s is definitely the easier of the two tasks, and as you can see this class is almost half as many lines of code.
The goal for this class is to have an interface we can use to call the API and parse the response into the correct format for our database.
This class exposes one public method, ‘get_game’ which expects a string representing a game title.
It then makes an API request to search for games that have the same title as the string we passed in. We assume the first game in the response list is the correct one, definitely not the best strategy, though it works in our case.
We then finish up by sending one more request with the newly acquired RAWG ID, which sends us back the full game information we are looking for.
The rest of the private helper methods parse and shape the response data into the correct format for our database.
Now that we have the tools for obtaining the data and saving it in our database, we just need to create a class that will orchestrate the procedures.
The main purpose of this class is to obtain the urls for the games we want in our dataset, and then to iterate through that list and use our previously defined classes to obtain and save the resulting data of each game.
This class introduces another useful tool, Selenium. Selenium was created to automate web browsing for testing, though it has become a standard in the data scientists web scraping toolkit.
We use Selenium over Requests here because the results page loads incrementally as we scroll down. Using Selenium we will automate the scrolling action and save the entire page-source once we have reached the bottom.
We can then load the html into BeautifulSoup and strip out all the individual game urls.
One of the reasons I chose create the url list this way, is that the results are sorted by popularity. That means our database index will inherently represent the popularity of a game, which we can use in our analysis and modeling.
To run the crawler:
# instantiate our crawlersc = SteamCrawl()# start the processsc.crawl()
The crawler will then extract all the individual urls from the saved html, and will begin to iterate through each individual game url. First the crawler will check and make sure the game has not been saved already. If it has been then we move onto the next url, if it has not then we fetch the info using our Game Parser and RAWG API, and insert the new info into the database.
Disclaimer: The program did throw an error on the last game in the list. Thankfully the games were already persisted in the database so I could just call ‘.to_csv’ on the database client.
# Using the crawlers database client 'to_csv' method we createdsc.dbc.to_csv('games.csv')
Now that we have a csv file for our database, we can inspect it and see how well our program did at obtaining as much of the data as possible.
games_df = pd.read_csv('games.csv')games_df.info()
From the info above, we can see that there are some issues (‘Publisher’ was not collected for any game, definitely an oversight in the code), but overall the dataset appears to be fairly close to what we were expecting.
After cleaning and imputing we should have a pretty solid dataset we can use to answer our original questions.
games_df.head()
Not bad for writing a few scripts and then crossing our fingers for 11 hours.
Now that we have done this much work it only makes sense that we share it with the data science community. The best way to do this is to upload it to Kaggle.com, where it will be available to any data scientist who could benefit from it.
We navigate to https://www.kaggle.com/datasets, and click the ‘New Dataset’ button. This will open up a popup that will ask us to drag or upload our desired file. As usual, Kaggle makes it very easy for us to create our dataset.
After it uploads, we will be redirected to the landing page for our dataset. To make our dataset more available and give it a higher usability score, we make sure to go through and fill in as much information as possible.
Here is the link for the newly created dataset:
https://www.kaggle.com/jesneuman/pc-games
In this article, we walked through the process of creating a dataset from scratch using web scraping and API calls. These are two of the most common methods for gathering data, and having these skills will greatly increase your ability to gather insights and create recommendations.
Thanks so much for taking the time to read my article. I hope it was informative and concise. If not please let me know how I could improve it!
Please leave comments, questions, suggestions, or any feedback, as I really appreciate the opportunity to engage with others and to grow as a data scientist.
Disclaimer: Although I do attempt to write high-quality best-practices conforming code, I am in no way an expert and this code may not represent the ‘best’ way to implement this.
If you have any recommendations concerning any of the code, procedures, writing, etc. I would love to hear those as well. | [
{
"code": null,
"e": 279,
"s": 172,
"text": "This blog walks through the entire process of creating a dataset for use in a larger data science project."
},
{
"code": null,
"e": 443,
"s": 279,
"text": "The data science project involves modeling the success of video games, discovering the importance of individual features, and then creating an interactive web app."
},
{
"code": null,
"e": 608,
"s": 443,
"text": "The web app will allow a game developer to input and modify a game design in order to maximize the predicted success given the resources available to the developer."
},
{
"code": null,
"e": 710,
"s": 608,
"text": "One of the most important aspects of any project, and one of the most overlooked is project planning."
},
{
"code": null,
"e": 943,
"s": 710,
"text": "Having a plan will ensure you consistently move forward toward your goal, and your resulting project will be much better organized and will be completed much sooner (if you’re like me you are easily distracted by new feature ideas)."
},
{
"code": null,
"e": 1206,
"s": 943,
"text": "The best way I have found so far is to use the planning section of your github’s project repository. I use this section to set up a automated Kanban style project board that will complete steps automatically after you merge a pull request for the specific issue."
},
{
"code": null,
"e": 1238,
"s": 1206,
"text": "Setting up the board is simple:"
},
{
"code": null,
"e": 1335,
"s": 1238,
"text": "Go to your project repo and click on ‘Projects’ tab.Fill out the form and click ‘Create Project’"
},
{
"code": null,
"e": 1388,
"s": 1335,
"text": "Go to your project repo and click on ‘Projects’ tab."
},
{
"code": null,
"e": 1433,
"s": 1388,
"text": "Fill out the form and click ‘Create Project’"
},
{
"code": null,
"e": 1563,
"s": 1433,
"text": "Now that we have our project board set up, go ahead and delete the default informative cards that appear as part of the template."
},
{
"code": null,
"e": 1672,
"s": 1563,
"text": "After that, begin adding cards for each of the main steps necessary for successfully completing the project:"
},
{
"code": null,
"e": 2195,
"s": 1672,
"text": "Identify features that will be strong predictors for a games success, and find a source where they can be obtainedCreate a data dictionary with the feature name, a short description, the type, and the sourceDecide on which database to use and set it upImplement a class for interacting with the databaseImplement a class for scraping the data from SteamImplement a program for obtaining the data from RAWG APICombine the two programs to create a script that will populate the databaseUpload the completed dataset to Kaggle"
},
{
"code": null,
"e": 2310,
"s": 2195,
"text": "Identify features that will be strong predictors for a games success, and find a source where they can be obtained"
},
{
"code": null,
"e": 2404,
"s": 2310,
"text": "Create a data dictionary with the feature name, a short description, the type, and the source"
},
{
"code": null,
"e": 2450,
"s": 2404,
"text": "Decide on which database to use and set it up"
},
{
"code": null,
"e": 2502,
"s": 2450,
"text": "Implement a class for interacting with the database"
},
{
"code": null,
"e": 2553,
"s": 2502,
"text": "Implement a class for scraping the data from Steam"
},
{
"code": null,
"e": 2610,
"s": 2553,
"text": "Implement a program for obtaining the data from RAWG API"
},
{
"code": null,
"e": 2686,
"s": 2610,
"text": "Combine the two programs to create a script that will populate the database"
},
{
"code": null,
"e": 2725,
"s": 2686,
"text": "Upload the completed dataset to Kaggle"
},
{
"code": null,
"e": 2840,
"s": 2725,
"text": "Here is our project board now, with the cards moved around a little to illustrate how you can track your workflow:"
},
{
"code": null,
"e": 3107,
"s": 2840,
"text": "Now as you begin working on the project you can select the card you are working on currently, and click on the ‘...’ and convert it to an issue. This will enable you to submit a pull request that will automatically close the issue and move it into the ‘Done’ column."
},
{
"code": null,
"e": 3167,
"s": 3107,
"text": "Here is what the almost completed project board looks like:"
},
{
"code": null,
"e": 3401,
"s": 3167,
"text": "Now that we have an outline and a project board set up, we can ensure that anytime we are working on a card we are moving toward the end goal. No more getting sidetracked by adding cool (unnecessary?) features we think up on the fly."
},
{
"code": null,
"e": 3624,
"s": 3401,
"text": "Now that we have the planning out of the way, it’s time to start implementing each of our cards. Not all of the cards require coding or a pull request, especially in the early phase when we are developing the architecture."
},
{
"code": null,
"e": 3782,
"s": 3624,
"text": "The first place to start will be the Steam store, which is the largest online marketplace for PC games, and one of the most active gaming communities online."
},
{
"code": null,
"e": 3859,
"s": 3782,
"text": "Googling steam store will give us this link: https://store.steampowered.com/"
},
{
"code": null,
"e": 3910,
"s": 3859,
"text": "Clicking on the link will take us to the homepage:"
},
{
"code": null,
"e": 4061,
"s": 3910,
"text": "Clicking on a random game will show us what data is available and we can decide whether or not that piece of data will be a valuable predictor or not."
},
{
"code": null,
"e": 4087,
"s": 4061,
"text": "Heres a random game page:"
},
{
"code": null,
"e": 4163,
"s": 4087,
"text": "Right away we can see some data points that will be useful for our dataset."
},
{
"code": null,
"e": 4263,
"s": 4163,
"text": "Let’s keep these data points in mind as we start looking for complementary data from an API source."
},
{
"code": null,
"e": 4413,
"s": 4263,
"text": "After googling “game developer apis” and clicking on the first result that is not an ad, we arrive at https://rapidapi.com/blog/top-video-game-apis/."
},
{
"code": null,
"e": 4547,
"s": 4413,
"text": "Several of the API’s are dedicated to specific games such as Minecraft and League of Legends, and will not be useful for our dataset."
},
{
"code": null,
"e": 4698,
"s": 4547,
"text": "The very first API on the list, however, is the RAWG Video Games Database API, which sounds promising even though I don’t know what ‘RAWG’ stands for."
},
{
"code": null,
"e": 4810,
"s": 4698,
"text": "We can check out the different response schema’s and identify any features that sound relevant for our dataset:"
},
{
"code": null,
"e": 5001,
"s": 4810,
"text": "Once again we can see several features that could be useful for our dataset. Let’s keep these two resources handy and come up with a complete list of features we want our dataset to contain."
},
{
"code": null,
"e": 5188,
"s": 5001,
"text": "Not only is it best-practice to create a high-quality data dictionary which explains each variable, it is also extremely useful for several of the tasks we will complete for our project."
},
{
"code": null,
"e": 5306,
"s": 5188,
"text": "Creating a table using markdown is quick and easy, and provides us with a clean looking overview of all the features:"
},
{
"code": null,
"e": 5400,
"s": 5306,
"text": "We now have a nice looking data-dictionary which will be our source of truth for the dataset."
},
{
"code": null,
"e": 5527,
"s": 5400,
"text": "Any changes to the dataset should first be recorded in the data-dictionary before being implemented by the individual classes."
},
{
"code": null,
"e": 5672,
"s": 5527,
"text": "One of the worst feelings ever is when your scraping program throws an error after 8 hours and all the data gathered up to that point is erased."
},
{
"code": null,
"e": 5802,
"s": 5672,
"text": "In order to avoid such bad feelings, we will use a simple database to persist the data while we are running the scraping program."
},
{
"code": null,
"e": 5935,
"s": 5802,
"text": "All we need our database to do is hold our data and let us know if a game has already been saved or not, so we can avoid redundancy."
},
{
"code": null,
"e": 6140,
"s": 5935,
"text": "There are several database options that would work for this simple project, but we will be using sqlite3. This will give us a super simple database on our local system that we can interact with using SQL."
},
{
"code": null,
"e": 6370,
"s": 6140,
"text": "To organize our code better and to keep the SQL all in one place we will create a class to manage and interact with our database. One important method we do need to add however is the ability to save our database as a ‘csv’ file."
},
{
"code": null,
"e": 6482,
"s": 6370,
"text": "In order to keep this post from taking 200 hours to read I will not be diving into much detail for the classes."
},
{
"code": null,
"e": 6625,
"s": 6482,
"text": "I plan on creating a few shorter blogs about how to create each individual class, but for now you can check out the full code repository here:"
},
{
"code": null,
"e": 6665,
"s": 6625,
"text": "https://github.com/Jesse989/game-oracle"
},
{
"code": null,
"e": 6808,
"s": 6665,
"text": "Also, if you have any comments, questions, or recommendations, please reach out to me. I really appreciate the chance to discuss these things."
},
{
"code": null,
"e": 6946,
"s": 6808,
"text": "This is basically a utility class for managing our database and handling the SQL so we don’t have to re-write the queries multiple times."
},
{
"code": null,
"e": 7071,
"s": 6946,
"text": "In addition, I have given it a ‘.to_csv()’ method that will create a csv file with the entire contents of our ‘games’ table."
},
{
"code": null,
"e": 7284,
"s": 7071,
"text": "Now that we have a way to persist the data, let’s focus on finding the data we want to save. Since we are dealing with two sources for our data, it makes sense to create two separate classes, one for each source."
},
{
"code": null,
"e": 7520,
"s": 7284,
"text": "First will be to come up with a way to obtain the data from the Steam store. To do this we will write a class that will use some basic python scraping libraries; Requests, BeautifulSoup, and the python library re (regular expressions)."
},
{
"code": null,
"e": 7690,
"s": 7520,
"text": "This object will be responsible for requesting the individual game url, and then parsing the desired information using a combination of BeautifulSoup searches and regex."
},
{
"code": null,
"e": 7793,
"s": 7690,
"text": "As you can see, the class consists mostly of two public methods: ‘get_game_html’ and ‘strip_features’."
},
{
"code": null,
"e": 7911,
"s": 7793,
"text": "The first method fetches the page from the specified url, and then the second method is called on the resulting html."
},
{
"code": null,
"e": 8078,
"s": 7911,
"text": "The ‘strip_features’ method is where the entire results object is built, and consists mainly of composing the resulting game dict by using the private helper methods."
},
{
"code": null,
"e": 8216,
"s": 8078,
"text": "Now that we have completed the first half of obtaining the data, let’s move on and create the class that will interact with the RAWG API."
},
{
"code": null,
"e": 8346,
"s": 8216,
"text": "Dealing with API’s is definitely the easier of the two tasks, and as you can see this class is almost half as many lines of code."
},
{
"code": null,
"e": 8486,
"s": 8346,
"text": "The goal for this class is to have an interface we can use to call the API and parse the response into the correct format for our database."
},
{
"code": null,
"e": 8585,
"s": 8486,
"text": "This class exposes one public method, ‘get_game’ which expects a string representing a game title."
},
{
"code": null,
"e": 8816,
"s": 8585,
"text": "It then makes an API request to search for games that have the same title as the string we passed in. We assume the first game in the response list is the correct one, definitely not the best strategy, though it works in our case."
},
{
"code": null,
"e": 8961,
"s": 8816,
"text": "We then finish up by sending one more request with the newly acquired RAWG ID, which sends us back the full game information we are looking for."
},
{
"code": null,
"e": 9076,
"s": 8961,
"text": "The rest of the private helper methods parse and shape the response data into the correct format for our database."
},
{
"code": null,
"e": 9226,
"s": 9076,
"text": "Now that we have the tools for obtaining the data and saving it in our database, we just need to create a class that will orchestrate the procedures."
},
{
"code": null,
"e": 9446,
"s": 9226,
"text": "The main purpose of this class is to obtain the urls for the games we want in our dataset, and then to iterate through that list and use our previously defined classes to obtain and save the resulting data of each game."
},
{
"code": null,
"e": 9635,
"s": 9446,
"text": "This class introduces another useful tool, Selenium. Selenium was created to automate web browsing for testing, though it has become a standard in the data scientists web scraping toolkit."
},
{
"code": null,
"e": 9852,
"s": 9635,
"text": "We use Selenium over Requests here because the results page loads incrementally as we scroll down. Using Selenium we will automate the scrolling action and save the entire page-source once we have reached the bottom."
},
{
"code": null,
"e": 9941,
"s": 9852,
"text": "We can then load the html into BeautifulSoup and strip out all the individual game urls."
},
{
"code": null,
"e": 10173,
"s": 9941,
"text": "One of the reasons I chose create the url list this way, is that the results are sorted by popularity. That means our database index will inherently represent the popularity of a game, which we can use in our analysis and modeling."
},
{
"code": null,
"e": 10193,
"s": 10173,
"text": "To run the crawler:"
},
{
"code": null,
"e": 10265,
"s": 10193,
"text": "# instantiate our crawlersc = SteamCrawl()# start the processsc.crawl()"
},
{
"code": null,
"e": 10643,
"s": 10265,
"text": "The crawler will then extract all the individual urls from the saved html, and will begin to iterate through each individual game url. First the crawler will check and make sure the game has not been saved already. If it has been then we move onto the next url, if it has not then we fetch the info using our Game Parser and RAWG API, and insert the new info into the database."
},
{
"code": null,
"e": 10831,
"s": 10643,
"text": "Disclaimer: The program did throw an error on the last game in the list. Thankfully the games were already persisted in the database so I could just call ‘.to_csv’ on the database client."
},
{
"code": null,
"e": 10921,
"s": 10831,
"text": "# Using the crawlers database client 'to_csv' method we createdsc.dbc.to_csv('games.csv')"
},
{
"code": null,
"e": 11064,
"s": 10921,
"text": "Now that we have a csv file for our database, we can inspect it and see how well our program did at obtaining as much of the data as possible."
},
{
"code": null,
"e": 11115,
"s": 11064,
"text": "games_df = pd.read_csv('games.csv')games_df.info()"
},
{
"code": null,
"e": 11335,
"s": 11115,
"text": "From the info above, we can see that there are some issues (‘Publisher’ was not collected for any game, definitely an oversight in the code), but overall the dataset appears to be fairly close to what we were expecting."
},
{
"code": null,
"e": 11446,
"s": 11335,
"text": "After cleaning and imputing we should have a pretty solid dataset we can use to answer our original questions."
},
{
"code": null,
"e": 11462,
"s": 11446,
"text": "games_df.head()"
},
{
"code": null,
"e": 11540,
"s": 11462,
"text": "Not bad for writing a few scripts and then crossing our fingers for 11 hours."
},
{
"code": null,
"e": 11778,
"s": 11540,
"text": "Now that we have done this much work it only makes sense that we share it with the data science community. The best way to do this is to upload it to Kaggle.com, where it will be available to any data scientist who could benefit from it."
},
{
"code": null,
"e": 12007,
"s": 11778,
"text": "We navigate to https://www.kaggle.com/datasets, and click the ‘New Dataset’ button. This will open up a popup that will ask us to drag or upload our desired file. As usual, Kaggle makes it very easy for us to create our dataset."
},
{
"code": null,
"e": 12229,
"s": 12007,
"text": "After it uploads, we will be redirected to the landing page for our dataset. To make our dataset more available and give it a higher usability score, we make sure to go through and fill in as much information as possible."
},
{
"code": null,
"e": 12277,
"s": 12229,
"text": "Here is the link for the newly created dataset:"
},
{
"code": null,
"e": 12319,
"s": 12277,
"text": "https://www.kaggle.com/jesneuman/pc-games"
},
{
"code": null,
"e": 12602,
"s": 12319,
"text": "In this article, we walked through the process of creating a dataset from scratch using web scraping and API calls. These are two of the most common methods for gathering data, and having these skills will greatly increase your ability to gather insights and create recommendations."
},
{
"code": null,
"e": 12746,
"s": 12602,
"text": "Thanks so much for taking the time to read my article. I hope it was informative and concise. If not please let me know how I could improve it!"
},
{
"code": null,
"e": 12904,
"s": 12746,
"text": "Please leave comments, questions, suggestions, or any feedback, as I really appreciate the opportunity to engage with others and to grow as a data scientist."
},
{
"code": null,
"e": 13083,
"s": 12904,
"text": "Disclaimer: Although I do attempt to write high-quality best-practices conforming code, I am in no way an expert and this code may not represent the ‘best’ way to implement this."
}
] |
PostgreSQL - Exit - GeeksforGeeks | 08 Feb, 2021
In PostgreSQL, The EXIT statement is used to terminate all types of loops like unconditional loops, a while loop, or a for loop or terminate a block of code specified by the begin..end keywords.
We can use the exit to terminate looping statements using the following syntax:
exit [label] [when condition]
If we analyze the above syntax:
Label: The label is used to signify the loop which we want to exit. It is often used in the case of nested looping. If a label is not present, the current loop is terminated.
Condition: The condition is a simple boolean expression that determines when we want to terminate the loop. When the value of the boolean expression becomes true, the loop is terminated.
Both of the above are optional. We can use exit with a condition like:
exit when cnt < 5;
Without using the condition in exit, we can rewrite the same code using the IF statement as:
if cnt < 5 then
exit;
end if;
Suppose we a have loop that is used to print all numbers from 1 to 10. We can use the EXIT statement in the following manner to limit printing the numbers up to 7 only.
do $$
declare
n integer:= 8;
cnt integer := 1 ;
begin
loop
exit when cnt = n ;
raise notice '%', cnt;
cnt := cnt + 1 ;
end loop;
end; $$;
Output:
In the above example, we terminate our loop as soon as the value of our cnt variable reaches n(here 8) and thus, only values up to 7 are printed.
We can then the exit statement to terminate a block of code specified by the begin..end keywords. In this case, the exit directly passes the flow of the program to after the end keyword, thus ending the current block.
<<block_label>>
BEGIN
Statements
EXIT [block_label] [WHEN condition];
Statements
END block_label;
Using this syntax, we can terminate the block of code prematurely, thus preventing the statements after the exit to be run.
The following example shows how we can use EXIT to exit a block.
do
$$
begin
raise notice '%', 'Before block';
<<normalblock>>
begin
raise notice '%', 'Before exit ; inside block';
exit normalblock;
raise notice '%', 'After exit ; inside block';
end;
raise notice '%', 'End of block';
end;
$$;
Output:
In the above example, the statement after exit was not printed as the block was terminated using EXIT before the statement. Thus inside the block, only statements before EXIT were executed and after that, the flow simply passes after the block ended.
Picked
Technical Scripter 2020
PostgreSQL
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
PostgreSQL - Change Column Type
PostgreSQL - Psql commands
PostgreSQL - For Loops
PostgreSQL - Function Returning A Table
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - ROW_NUMBER Function
PostgreSQL - Copy Table
How to use PostgreSQL Database in Django? | [
{
"code": null,
"e": 27609,
"s": 27581,
"text": "\n08 Feb, 2021"
},
{
"code": null,
"e": 27804,
"s": 27609,
"text": "In PostgreSQL, The EXIT statement is used to terminate all types of loops like unconditional loops, a while loop, or a for loop or terminate a block of code specified by the begin..end keywords."
},
{
"code": null,
"e": 27884,
"s": 27804,
"text": "We can use the exit to terminate looping statements using the following syntax:"
},
{
"code": null,
"e": 27914,
"s": 27884,
"text": "exit [label] [when condition]"
},
{
"code": null,
"e": 27946,
"s": 27914,
"text": "If we analyze the above syntax:"
},
{
"code": null,
"e": 28122,
"s": 27946,
"text": "Label: The label is used to signify the loop which we want to exit. It is often used in the case of nested looping. If a label is not present, the current loop is terminated. "
},
{
"code": null,
"e": 28309,
"s": 28122,
"text": "Condition: The condition is a simple boolean expression that determines when we want to terminate the loop. When the value of the boolean expression becomes true, the loop is terminated."
},
{
"code": null,
"e": 28380,
"s": 28309,
"text": "Both of the above are optional. We can use exit with a condition like:"
},
{
"code": null,
"e": 28399,
"s": 28380,
"text": "exit when cnt < 5;"
},
{
"code": null,
"e": 28492,
"s": 28399,
"text": "Without using the condition in exit, we can rewrite the same code using the IF statement as:"
},
{
"code": null,
"e": 28524,
"s": 28492,
"text": "if cnt < 5 then\n exit;\nend if;"
},
{
"code": null,
"e": 28693,
"s": 28524,
"text": "Suppose we a have loop that is used to print all numbers from 1 to 10. We can use the EXIT statement in the following manner to limit printing the numbers up to 7 only."
},
{
"code": null,
"e": 28843,
"s": 28693,
"text": "do $$\ndeclare\n n integer:= 8;\n cnt integer := 1 ; \nbegin\nloop \nexit when cnt = n ;\nraise notice '%', cnt; \ncnt := cnt + 1 ; \nend loop; \nend; $$;"
},
{
"code": null,
"e": 28851,
"s": 28843,
"text": "Output:"
},
{
"code": null,
"e": 28997,
"s": 28851,
"text": "In the above example, we terminate our loop as soon as the value of our cnt variable reaches n(here 8) and thus, only values up to 7 are printed."
},
{
"code": null,
"e": 29215,
"s": 28997,
"text": "We can then the exit statement to terminate a block of code specified by the begin..end keywords. In this case, the exit directly passes the flow of the program to after the end keyword, thus ending the current block."
},
{
"code": null,
"e": 29322,
"s": 29215,
"text": "<<block_label>>\nBEGIN\n Statements\n EXIT [block_label] [WHEN condition];\n Statements\nEND block_label;"
},
{
"code": null,
"e": 29446,
"s": 29322,
"text": "Using this syntax, we can terminate the block of code prematurely, thus preventing the statements after the exit to be run."
},
{
"code": null,
"e": 29511,
"s": 29446,
"text": "The following example shows how we can use EXIT to exit a block."
},
{
"code": null,
"e": 29758,
"s": 29511,
"text": "do\n$$\nbegin\n raise notice '%', 'Before block';\n <<normalblock>> \n begin\n raise notice '%', 'Before exit ; inside block';\n exit normalblock;\n raise notice '%', 'After exit ; inside block';\n end;\n raise notice '%', 'End of block';\nend;\n$$;"
},
{
"code": null,
"e": 29766,
"s": 29758,
"text": "Output:"
},
{
"code": null,
"e": 30017,
"s": 29766,
"text": "In the above example, the statement after exit was not printed as the block was terminated using EXIT before the statement. Thus inside the block, only statements before EXIT were executed and after that, the flow simply passes after the block ended."
},
{
"code": null,
"e": 30024,
"s": 30017,
"text": "Picked"
},
{
"code": null,
"e": 30048,
"s": 30024,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 30059,
"s": 30048,
"text": "PostgreSQL"
},
{
"code": null,
"e": 30078,
"s": 30059,
"text": "Technical Scripter"
},
{
"code": null,
"e": 30176,
"s": 30078,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30185,
"s": 30176,
"text": "Comments"
},
{
"code": null,
"e": 30198,
"s": 30185,
"text": "Old Comments"
},
{
"code": null,
"e": 30230,
"s": 30198,
"text": "PostgreSQL - Change Column Type"
},
{
"code": null,
"e": 30257,
"s": 30230,
"text": "PostgreSQL - Psql commands"
},
{
"code": null,
"e": 30280,
"s": 30257,
"text": "PostgreSQL - For Loops"
},
{
"code": null,
"e": 30320,
"s": 30280,
"text": "PostgreSQL - Function Returning A Table"
},
{
"code": null,
"e": 30375,
"s": 30320,
"text": "PostgreSQL - Create Auto-increment Column using SERIAL"
},
{
"code": null,
"e": 30409,
"s": 30375,
"text": "PostgreSQL - ARRAY_AGG() Function"
},
{
"code": null,
"e": 30433,
"s": 30409,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 30466,
"s": 30433,
"text": "PostgreSQL - ROW_NUMBER Function"
},
{
"code": null,
"e": 30490,
"s": 30466,
"text": "PostgreSQL - Copy Table"
}
] |
Most efficient method to groupby on an array of objects in Javascript | The most efficient method to group by a key on an array of objects in js is to use the reduce function.
The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.
const people = [
{ name: 'Lee', age: 21 },
{ name: 'Ajay', age: 20 },
{ name: 'Jane', age: 20 }
];
function groupBy(objectArray, property) {
return objectArray.reduce((acc, obj) => {
const key = obj[property];
if (!acc[key]) {
acc[key] = [];
}
// Add object to list for given key's value
acc[key].push(obj);
return acc;
}, {});
}
const groupedPeople = groupBy(people, 'age');
console.log(groupedPeople);
This will give the output −
{ 20: [ { name: 'Ajay', age: 20 }, { name: 'Jane', age: 20 } ],
21: [ { name: 'Lee', age: 21 } ] } | [
{
"code": null,
"e": 1166,
"s": 1062,
"text": "The most efficient method to group by a key on an array of objects in js is to use the reduce function."
},
{
"code": null,
"e": 1299,
"s": 1166,
"text": "The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value."
},
{
"code": null,
"e": 1763,
"s": 1299,
"text": "const people = [\n { name: 'Lee', age: 21 },\n { name: 'Ajay', age: 20 },\n { name: 'Jane', age: 20 }\n];\nfunction groupBy(objectArray, property) {\n return objectArray.reduce((acc, obj) => {\n const key = obj[property];\n if (!acc[key]) {\n acc[key] = [];\n }\n // Add object to list for given key's value\n acc[key].push(obj);\n return acc;\n }, {});\n}\nconst groupedPeople = groupBy(people, 'age');\nconsole.log(groupedPeople);"
},
{
"code": null,
"e": 1791,
"s": 1763,
"text": "This will give the output −"
},
{
"code": null,
"e": 1890,
"s": 1791,
"text": "{ 20: [ { name: 'Ajay', age: 20 }, { name: 'Jane', age: 20 } ],\n21: [ { name: 'Lee', age: 21 } ] }"
}
] |
How to call a method that returns some other method in Java - GeeksforGeeks | 10 Jun, 2020
A method is a collection of statements that perform some specific task and return the result to the caller. A method can also perform some specific task without returning anything. In this article, we will understand how to call a method that returns some other method in Java.
In Java, there are two types of methods. They are:
Static Method: Static methods are the methods in Java that can be called without creating an object of the class. They are referenced by the class name itself or reference to the object of that class.Instance Method: Instance method are methods which require an object of its class to be created before it can be called. To invoke an instance method, we have to create an object of the class in within which it defined.
Static Method: Static methods are the methods in Java that can be called without creating an object of the class. They are referenced by the class name itself or reference to the object of that class.
Instance Method: Instance method are methods which require an object of its class to be created before it can be called. To invoke an instance method, we have to create an object of the class in within which it defined.
Calling a static method that returns some other static method: Since static method(s) are associated to the class in which they reside (i.e.) they can be called even without creating an instance of the class, we can directly define a method which calls the method by calling the definition of the method. Let’s understand how to do this with the following examples:
Example 1: In this example, lets visualize a car. A car has to start before it is driven. Therefore, a car has a start function which starts the car. In order for a car to start, its engine has to start first and the remaining other entities start thereby finally making the car ready to run. Therefore, this carStart() function need to have a signature engineStart() which starts the engine. That is:// Java program to visualize the Car // A class Carpublic class CarFunc { // A method engineStart() which // simply starts the engine public static void engineStart() { System.out.println("Engine Started!"); } // A method carStart() which starts // the engine and other entities // required public static void carStart() { // Calling the function // engineStart() inside the // definition of function // carStart() engineStart(); // Definitions of starting // various other entities // can be defined here // Finally, the car is // started System.out.println("Car Started!"); } public static void main(String[] args) { carStart(); // When the car is started, // we are ready to drive System.out.println("Let's Drive!"); }}Output:Engine Started!
Car Started!
Let's Drive!
// Java program to visualize the Car // A class Carpublic class CarFunc { // A method engineStart() which // simply starts the engine public static void engineStart() { System.out.println("Engine Started!"); } // A method carStart() which starts // the engine and other entities // required public static void carStart() { // Calling the function // engineStart() inside the // definition of function // carStart() engineStart(); // Definitions of starting // various other entities // can be defined here // Finally, the car is // started System.out.println("Car Started!"); } public static void main(String[] args) { carStart(); // When the car is started, // we are ready to drive System.out.println("Let's Drive!"); }}
Engine Started!
Car Started!
Let's Drive!
Example 2: In this example, lets consider a similar example where the entities are accelerator and increase speed. In order to increase the speed of the vehicle, the accelerator is pressed. Once the accelerator is pressed, the speed is increased until it doesn’t reach the speed limit. This is implemented as follows:// A carSpeed class which manages// the speed of the classpublic class CarSpeedFunc { // Speed is a global variable. If // the speed is changed at any // part of the car, then the overall // speed of the car automatically // changes static int speed = 0; // Function to increase the speed public static void increaseSpeed() { speed = speed + 50; System.out.println( "Speed increased by 50 km/hr"); // main() called inside this function main(new String[0]); } // Method which performs the increase // speed function when the accelerator // is pressed public static void pressAccelerator() { System.out.println( "Accelerator pressed " + "to increase speed"); increaseSpeed(); } // Driver code public static void main(String[] args) { System.out.println( "Driving with speed = " + speed + "km/hr"); if (speed < 200) { pressAccelerator(); } else { System.out.println( "Speed Limit Reached! " + "Drive Slow. Stay safe."); } }}Output:Driving with speed = 0km/hr
Accelerator pressed to increase speed
Speed increased by 50 km/hr
Driving with speed = 50km/hr
Accelerator pressed to increase speed
Speed increased by 50 km/hr
Driving with speed = 100km/hr
Accelerator pressed to increase speed
Speed increased by 50 km/hr
Driving with speed = 150km/hr
Accelerator pressed to increase speed
Speed increased by 50 km/hr
Driving with speed = 200km/hr
Speed Limit Reached! Drive Slow. Stay safe.
// A carSpeed class which manages// the speed of the classpublic class CarSpeedFunc { // Speed is a global variable. If // the speed is changed at any // part of the car, then the overall // speed of the car automatically // changes static int speed = 0; // Function to increase the speed public static void increaseSpeed() { speed = speed + 50; System.out.println( "Speed increased by 50 km/hr"); // main() called inside this function main(new String[0]); } // Method which performs the increase // speed function when the accelerator // is pressed public static void pressAccelerator() { System.out.println( "Accelerator pressed " + "to increase speed"); increaseSpeed(); } // Driver code public static void main(String[] args) { System.out.println( "Driving with speed = " + speed + "km/hr"); if (speed < 200) { pressAccelerator(); } else { System.out.println( "Speed Limit Reached! " + "Drive Slow. Stay safe."); } }}
Driving with speed = 0km/hr
Accelerator pressed to increase speed
Speed increased by 50 km/hr
Driving with speed = 50km/hr
Accelerator pressed to increase speed
Speed increased by 50 km/hr
Driving with speed = 100km/hr
Accelerator pressed to increase speed
Speed increased by 50 km/hr
Driving with speed = 150km/hr
Accelerator pressed to increase speed
Speed increased by 50 km/hr
Driving with speed = 200km/hr
Speed Limit Reached! Drive Slow. Stay safe.
Calling a static method that returns some other static method: Instance method(s) belong to the Object of the class, not to the class (i.e.) they can be called after creating the Object of the class. An instance method can also be called from another method. But, we need to know the address of the method which we are calling. The address of the current object is stored in the keywords like this and super. Let’s understand this with an example. In this example, the super keyword is used to call the object of the parent class from the child class. That is:
class GFG { // A nested parent class // which has the method // detail public static class BriefDescription { void detail() { System.out.println( "Ferrari 812 is " + "an awesome car."); } } // A child class extending the // parent class public static class DetailedDescription extends BriefDescription { // Overriding the parent // method @Override void detail() { // Using super keyword to call // 'detail()' method from the // parent class // 'BriefDescription' super.detail(); System.out.println( "It has a seating " + "capacity of 2, " + "fuel economy of 7 kmpl " + "and comes with a horsepower " + "of 588 kW."); } } // Driver code public static void main(String[] args) { BriefDescription briefDesc = new BriefDescription(); BriefDescription detailDesc = new DetailedDescription(); System.out.println( "Brief detail of Ferrari:"); // Method from the parent class // is invoked briefDesc.detail(); System.out.println( "Complete detail of Ferrari:"); // Method from both parent class // and subclass is invoked. detailDesc.detail(); }}
Brief detail of Ferrari:
Ferrari 812 is an awesome car.
Complete detail of Ferrari:
Ferrari 812 is an awesome car.
It has a seating capacity of 2, fuel economy of 7 kmpl and comes with a horsepower of 588 kW.
java-basics
Java-Functions
Static Keyword
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
Difference between Abstract Class and Interface in Java
How to remove an element from ArrayList in Java? | [
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n10 Jun, 2020"
},
{
"code": null,
"e": 23835,
"s": 23557,
"text": "A method is a collection of statements that perform some specific task and return the result to the caller. A method can also perform some specific task without returning anything. In this article, we will understand how to call a method that returns some other method in Java."
},
{
"code": null,
"e": 23886,
"s": 23835,
"text": "In Java, there are two types of methods. They are:"
},
{
"code": null,
"e": 24306,
"s": 23886,
"text": "Static Method: Static methods are the methods in Java that can be called without creating an object of the class. They are referenced by the class name itself or reference to the object of that class.Instance Method: Instance method are methods which require an object of its class to be created before it can be called. To invoke an instance method, we have to create an object of the class in within which it defined."
},
{
"code": null,
"e": 24507,
"s": 24306,
"text": "Static Method: Static methods are the methods in Java that can be called without creating an object of the class. They are referenced by the class name itself or reference to the object of that class."
},
{
"code": null,
"e": 24727,
"s": 24507,
"text": "Instance Method: Instance method are methods which require an object of its class to be created before it can be called. To invoke an instance method, we have to create an object of the class in within which it defined."
},
{
"code": null,
"e": 25093,
"s": 24727,
"text": "Calling a static method that returns some other static method: Since static method(s) are associated to the class in which they reside (i.e.) they can be called even without creating an instance of the class, we can directly define a method which calls the method by calling the definition of the method. Let’s understand how to do this with the following examples:"
},
{
"code": null,
"e": 26435,
"s": 25093,
"text": "Example 1: In this example, lets visualize a car. A car has to start before it is driven. Therefore, a car has a start function which starts the car. In order for a car to start, its engine has to start first and the remaining other entities start thereby finally making the car ready to run. Therefore, this carStart() function need to have a signature engineStart() which starts the engine. That is:// Java program to visualize the Car // A class Carpublic class CarFunc { // A method engineStart() which // simply starts the engine public static void engineStart() { System.out.println(\"Engine Started!\"); } // A method carStart() which starts // the engine and other entities // required public static void carStart() { // Calling the function // engineStart() inside the // definition of function // carStart() engineStart(); // Definitions of starting // various other entities // can be defined here // Finally, the car is // started System.out.println(\"Car Started!\"); } public static void main(String[] args) { carStart(); // When the car is started, // we are ready to drive System.out.println(\"Let's Drive!\"); }}Output:Engine Started!\nCar Started!\nLet's Drive!\n"
},
{
"code": "// Java program to visualize the Car // A class Carpublic class CarFunc { // A method engineStart() which // simply starts the engine public static void engineStart() { System.out.println(\"Engine Started!\"); } // A method carStart() which starts // the engine and other entities // required public static void carStart() { // Calling the function // engineStart() inside the // definition of function // carStart() engineStart(); // Definitions of starting // various other entities // can be defined here // Finally, the car is // started System.out.println(\"Car Started!\"); } public static void main(String[] args) { carStart(); // When the car is started, // we are ready to drive System.out.println(\"Let's Drive!\"); }}",
"e": 27327,
"s": 26435,
"text": null
},
{
"code": null,
"e": 27370,
"s": 27327,
"text": "Engine Started!\nCar Started!\nLet's Drive!\n"
},
{
"code": null,
"e": 29338,
"s": 27370,
"text": "Example 2: In this example, lets consider a similar example where the entities are accelerator and increase speed. In order to increase the speed of the vehicle, the accelerator is pressed. Once the accelerator is pressed, the speed is increased until it doesn’t reach the speed limit. This is implemented as follows:// A carSpeed class which manages// the speed of the classpublic class CarSpeedFunc { // Speed is a global variable. If // the speed is changed at any // part of the car, then the overall // speed of the car automatically // changes static int speed = 0; // Function to increase the speed public static void increaseSpeed() { speed = speed + 50; System.out.println( \"Speed increased by 50 km/hr\"); // main() called inside this function main(new String[0]); } // Method which performs the increase // speed function when the accelerator // is pressed public static void pressAccelerator() { System.out.println( \"Accelerator pressed \" + \"to increase speed\"); increaseSpeed(); } // Driver code public static void main(String[] args) { System.out.println( \"Driving with speed = \" + speed + \"km/hr\"); if (speed < 200) { pressAccelerator(); } else { System.out.println( \"Speed Limit Reached! \" + \"Drive Slow. Stay safe.\"); } }}Output:Driving with speed = 0km/hr\nAccelerator pressed to increase speed\nSpeed increased by 50 km/hr\nDriving with speed = 50km/hr\nAccelerator pressed to increase speed\nSpeed increased by 50 km/hr\nDriving with speed = 100km/hr\nAccelerator pressed to increase speed\nSpeed increased by 50 km/hr\nDriving with speed = 150km/hr\nAccelerator pressed to increase speed\nSpeed increased by 50 km/hr\nDriving with speed = 200km/hr\nSpeed Limit Reached! Drive Slow. Stay safe.\n"
},
{
"code": "// A carSpeed class which manages// the speed of the classpublic class CarSpeedFunc { // Speed is a global variable. If // the speed is changed at any // part of the car, then the overall // speed of the car automatically // changes static int speed = 0; // Function to increase the speed public static void increaseSpeed() { speed = speed + 50; System.out.println( \"Speed increased by 50 km/hr\"); // main() called inside this function main(new String[0]); } // Method which performs the increase // speed function when the accelerator // is pressed public static void pressAccelerator() { System.out.println( \"Accelerator pressed \" + \"to increase speed\"); increaseSpeed(); } // Driver code public static void main(String[] args) { System.out.println( \"Driving with speed = \" + speed + \"km/hr\"); if (speed < 200) { pressAccelerator(); } else { System.out.println( \"Speed Limit Reached! \" + \"Drive Slow. Stay safe.\"); } }}",
"e": 30527,
"s": 29338,
"text": null
},
{
"code": null,
"e": 30983,
"s": 30527,
"text": "Driving with speed = 0km/hr\nAccelerator pressed to increase speed\nSpeed increased by 50 km/hr\nDriving with speed = 50km/hr\nAccelerator pressed to increase speed\nSpeed increased by 50 km/hr\nDriving with speed = 100km/hr\nAccelerator pressed to increase speed\nSpeed increased by 50 km/hr\nDriving with speed = 150km/hr\nAccelerator pressed to increase speed\nSpeed increased by 50 km/hr\nDriving with speed = 200km/hr\nSpeed Limit Reached! Drive Slow. Stay safe.\n"
},
{
"code": null,
"e": 31544,
"s": 30983,
"text": "Calling a static method that returns some other static method: Instance method(s) belong to the Object of the class, not to the class (i.e.) they can be called after creating the Object of the class. An instance method can also be called from another method. But, we need to know the address of the method which we are calling. The address of the current object is stored in the keywords like this and super. Let’s understand this with an example. In this example, the super keyword is used to call the object of the parent class from the child class. That is:"
},
{
"code": "class GFG { // A nested parent class // which has the method // detail public static class BriefDescription { void detail() { System.out.println( \"Ferrari 812 is \" + \"an awesome car.\"); } } // A child class extending the // parent class public static class DetailedDescription extends BriefDescription { // Overriding the parent // method @Override void detail() { // Using super keyword to call // 'detail()' method from the // parent class // 'BriefDescription' super.detail(); System.out.println( \"It has a seating \" + \"capacity of 2, \" + \"fuel economy of 7 kmpl \" + \"and comes with a horsepower \" + \"of 588 kW.\"); } } // Driver code public static void main(String[] args) { BriefDescription briefDesc = new BriefDescription(); BriefDescription detailDesc = new DetailedDescription(); System.out.println( \"Brief detail of Ferrari:\"); // Method from the parent class // is invoked briefDesc.detail(); System.out.println( \"Complete detail of Ferrari:\"); // Method from both parent class // and subclass is invoked. detailDesc.detail(); }}",
"e": 33007,
"s": 31544,
"text": null
},
{
"code": null,
"e": 33217,
"s": 33007,
"text": "Brief detail of Ferrari:\nFerrari 812 is an awesome car.\nComplete detail of Ferrari:\nFerrari 812 is an awesome car.\nIt has a seating capacity of 2, fuel economy of 7 kmpl and comes with a horsepower of 588 kW.\n"
},
{
"code": null,
"e": 33229,
"s": 33217,
"text": "java-basics"
},
{
"code": null,
"e": 33244,
"s": 33229,
"text": "Java-Functions"
},
{
"code": null,
"e": 33259,
"s": 33244,
"text": "Static Keyword"
},
{
"code": null,
"e": 33264,
"s": 33259,
"text": "Java"
},
{
"code": null,
"e": 33269,
"s": 33264,
"text": "Java"
},
{
"code": null,
"e": 33367,
"s": 33269,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33376,
"s": 33367,
"text": "Comments"
},
{
"code": null,
"e": 33389,
"s": 33376,
"text": "Old Comments"
},
{
"code": null,
"e": 33419,
"s": 33389,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 33434,
"s": 33419,
"text": "Stream In Java"
},
{
"code": null,
"e": 33455,
"s": 33434,
"text": "Constructors in Java"
},
{
"code": null,
"e": 33501,
"s": 33455,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 33520,
"s": 33501,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 33537,
"s": 33520,
"text": "Generics in Java"
},
{
"code": null,
"e": 33580,
"s": 33537,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 33596,
"s": 33580,
"text": "Strings in Java"
},
{
"code": null,
"e": 33652,
"s": 33596,
"text": "Difference between Abstract Class and Interface in Java"
}
] |
How to Read Data From Text File in Excel VBA? - GeeksforGeeks | 29 Oct, 2021
VBA Program to read a Text file line by line (Sales Data) and places on a worksheet.
Sales Data in Text File: 5 Fields [ Product, Qtr 1, Qtr 2, Qtr 3 and Qtr 4 ] and 25 Records (Incl. header)
Sales data
VBA code will read a text file and places on worksheet cells as below
Declaring variables:
'Variable declarations
Dim line As String, Filename As String, i As Integer, valuesArr() As String
Initialize “Filename” variable with full path and filename
'Text file fullPath
Filename = "D:\Excel\ReadTextFile\sales.txt" 'update your full file path
i = 1
Open input file to read text
'Open file
Open Filename For Input As #2
Read input file line by line
'Read line by line - text file
While Not EOF(2)
Line Input #2, line
Split by comma and store it in valueArr(). In our example, each line has 5 values concatenated with comma.
'split the line by comma separated, assigned in an array
valuesArr() = Split(line, ",")
Add text to respective cells from valuesArr(). Read each item in an array by it’s index value
Cells(i, "A").Value = valuesArr(0)
Cells(i, "B").Value = valuesArr(1)
Cells(i, "C").Value = valuesArr(2)
Cells(i, "D").Value = valuesArr(3)
Cells(i, "E").Value = valuesArr(4)
Increment counter i, to move next line.
i = i + 1
Close while loop
Wend
Close file
'Close file
Close #2
Approach:
Step 1: Open Excel.
Step 2: Add a shape (Read Text File) to your worksheet .
Step 3: Right-click on “Read Text file” and “Assign Macro..”
Step 4: Select ReadTextFileLineByLine Macro
Step 5: Save your excel file as “Excel Macro-Enabled Workbook” *.xlsm
Step 6: Click “Read Text file”
Step 7: Adjust column width in your excel file.
Excel-VBA
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Pivot Tables in Excel
How to Extract Text Only from Alphanumeric String in Excel?
How to Easily Calculate the Dot Product in Excel?
VLOOKUP Function in Excel With Examples
How to Create a Macro in Excel?
How to Calculate Relative Standard Deviation in Excel?
How to Check if the Number is Prime Number in Excel?
How to Delete a Module in Excel VBA?
How to Calculate Frequency Distribution in Excel?
Scenario Manager in Excel | [
{
"code": null,
"e": 24725,
"s": 24694,
"text": " \n29 Oct, 2021\n"
},
{
"code": null,
"e": 24811,
"s": 24725,
"text": "VBA Program to read a Text file line by line (Sales Data) and places on a worksheet. "
},
{
"code": null,
"e": 24918,
"s": 24811,
"text": "Sales Data in Text File: 5 Fields [ Product, Qtr 1, Qtr 2, Qtr 3 and Qtr 4 ] and 25 Records (Incl. header)"
},
{
"code": null,
"e": 24929,
"s": 24918,
"text": "Sales data"
},
{
"code": null,
"e": 24999,
"s": 24929,
"text": "VBA code will read a text file and places on worksheet cells as below"
},
{
"code": null,
"e": 25020,
"s": 24999,
"text": "Declaring variables:"
},
{
"code": null,
"e": 25127,
"s": 25020,
"text": " 'Variable declarations\n Dim line As String, Filename As String, i As Integer, valuesArr() As String"
},
{
"code": null,
"e": 25186,
"s": 25127,
"text": "Initialize “Filename” variable with full path and filename"
},
{
"code": null,
"e": 25297,
"s": 25186,
"text": " 'Text file fullPath\n Filename = \"D:\\Excel\\ReadTextFile\\sales.txt\" 'update your full file path\n i = 1"
},
{
"code": null,
"e": 25327,
"s": 25297,
"text": "Open input file to read text "
},
{
"code": null,
"e": 25376,
"s": 25327,
"text": " 'Open file\n Open Filename For Input As #2"
},
{
"code": null,
"e": 25405,
"s": 25376,
"text": "Read input file line by line"
},
{
"code": null,
"e": 25489,
"s": 25405,
"text": " 'Read line by line - text file\n While Not EOF(2)\n Line Input #2, line"
},
{
"code": null,
"e": 25597,
"s": 25489,
"text": "Split by comma and store it in valueArr(). In our example, each line has 5 values concatenated with comma."
},
{
"code": null,
"e": 25701,
"s": 25597,
"text": " 'split the line by comma separated, assigned in an array\n valuesArr() = Split(line, \",\")"
},
{
"code": null,
"e": 25796,
"s": 25701,
"text": "Add text to respective cells from valuesArr(). Read each item in an array by it’s index value"
},
{
"code": null,
"e": 26011,
"s": 25796,
"text": " Cells(i, \"A\").Value = valuesArr(0)\n Cells(i, \"B\").Value = valuesArr(1)\n Cells(i, \"C\").Value = valuesArr(2)\n Cells(i, \"D\").Value = valuesArr(3)\n Cells(i, \"E\").Value = valuesArr(4)"
},
{
"code": null,
"e": 26051,
"s": 26011,
"text": "Increment counter i, to move next line."
},
{
"code": null,
"e": 26069,
"s": 26051,
"text": " i = i + 1"
},
{
"code": null,
"e": 26086,
"s": 26069,
"text": "Close while loop"
},
{
"code": null,
"e": 26095,
"s": 26086,
"text": " Wend"
},
{
"code": null,
"e": 26106,
"s": 26095,
"text": "Close file"
},
{
"code": null,
"e": 26127,
"s": 26106,
"text": "'Close file\nClose #2"
},
{
"code": null,
"e": 26137,
"s": 26127,
"text": "Approach:"
},
{
"code": null,
"e": 26157,
"s": 26137,
"text": "Step 1: Open Excel."
},
{
"code": null,
"e": 26215,
"s": 26157,
"text": "Step 2: Add a shape (Read Text File) to your worksheet ."
},
{
"code": null,
"e": 26276,
"s": 26215,
"text": "Step 3: Right-click on “Read Text file” and “Assign Macro..”"
},
{
"code": null,
"e": 26320,
"s": 26276,
"text": "Step 4: Select ReadTextFileLineByLine Macro"
},
{
"code": null,
"e": 26391,
"s": 26320,
"text": "Step 5: Save your excel file as “Excel Macro-Enabled Workbook” *.xlsm"
},
{
"code": null,
"e": 26423,
"s": 26391,
"text": "Step 6: Click “Read Text file” "
},
{
"code": null,
"e": 26471,
"s": 26423,
"text": "Step 7: Adjust column width in your excel file."
},
{
"code": null,
"e": 26483,
"s": 26471,
"text": "\nExcel-VBA\n"
},
{
"code": null,
"e": 26492,
"s": 26483,
"text": "\nPicked\n"
},
{
"code": null,
"e": 26500,
"s": 26492,
"text": "\nExcel\n"
},
{
"code": null,
"e": 26705,
"s": 26500,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 26727,
"s": 26705,
"text": "Pivot Tables in Excel"
},
{
"code": null,
"e": 26787,
"s": 26727,
"text": "How to Extract Text Only from Alphanumeric String in Excel?"
},
{
"code": null,
"e": 26837,
"s": 26787,
"text": "How to Easily Calculate the Dot Product in Excel?"
},
{
"code": null,
"e": 26877,
"s": 26837,
"text": "VLOOKUP Function in Excel With Examples"
},
{
"code": null,
"e": 26909,
"s": 26877,
"text": "How to Create a Macro in Excel?"
},
{
"code": null,
"e": 26964,
"s": 26909,
"text": "How to Calculate Relative Standard Deviation in Excel?"
},
{
"code": null,
"e": 27017,
"s": 26964,
"text": "How to Check if the Number is Prime Number in Excel?"
},
{
"code": null,
"e": 27054,
"s": 27017,
"text": "How to Delete a Module in Excel VBA?"
},
{
"code": null,
"e": 27104,
"s": 27054,
"text": "How to Calculate Frequency Distribution in Excel?"
}
] |
Building a ChatBot in Python — The Beginner’s Guide | by Behic Guven | Towards Data Science | Welcome to Beginner’s Guide to Building a Chatbot in Python
In this article, I will show you how to build a simple chatbot using the python programming language. We will not use any external chatbot packages. The whole project will be written in plain Python. This is a great way to understand how chatbots actually work. Learning behind the scenes will also give us an insight into the chatbot packages. I will share some Chatbot building platforms in the introduction section of this article. Feel free to check them later if you are interested to learn more about Chatbots. I can’t wait to walk you through this project; let’s get started!
Introduction
Step 1 — User Templates
Step 2 — ChatBot Responses
Step 3 — Response Function
Step 4 — Relation Function
Step 5 — Send Message Function
Final Step — Testing the ChatBot
Video Demonstration
In 1994, when Michael Mauldin produced his first chatbot and called it“Julia” and that’s the time when the word “chatterbot” entered first time in our dictionary. A chatbot is described as a computer program designed to simulate conversation with human users, particularly over the internet. It is software designed to mimic how people interact with each other. It can be seen as a virtual assistant that interacts with users through text messages or voice messages and this allows companies to get more close to their customers.
There are many ChatBot platforms that help companies to create personalized chatbots. The database and APIs play a big role in these chatbot platforms. Some of those platforms are Amazon Lex, Microsoft Azure Bot, ChatterBot. You can check their websites to learn more.
Hopefully, in a future article, I would like to show how to create an advanced level chatbot using one of those platforms, but for today we will keep things simple and basic. If you are ready, let’s start programming!
First thing first, we will tell the chatbot to ask the user’s name. This will make our chatbot more realistic and practical. Let’s run this line in our Jupyter Notebook:
print("BOT: What do you want me to call you?")user_name = input()
Now, let’s create the templates. In this chatbot project, we will have only two people: the user, and the chatbot. When printing out the conversation timeline, these templates will help us to know who is saying what. The values that will go between the curly brackets will be responsive, and you will understand what I mean in the next step.
bot_template = "BOT : {0}"user_template = user_name + " : {0}"
This step is a little long because it handles most of the conversation. We are defining the chatbot in this step. We have to put in the questions that our chat is expected to hear and the answers that the chatbot has. To make things more interesting, I’ve created three responses for each question. This way, the bot will have a different answer to the same question. More details will be under the code. Let me show the code first:
name = "Funny Bot 101" weather = "rainy" mood = "Happy"responses = { "what's your name?": [ "They call me {0}".format(name), "I usually go by {0}".format(name), "My name is the {0}".format(name) ],"what's today's weather?": [ "The weather is {0}".format(weather), "It's {0} today".format(weather), "Let me check, it looks {0} today".format(weather) ],"Are you a robot?": [ "What do you think?", "Maybe yes, maybe no!", "Yes, I am a robot with human feelings.", ],"how are you?": [ "I am feeling {0}".format(mood), "{0}! How about you?".format(mood), "I am {0}! How about yourself?".format(mood), ],"": [ "Hey! Are you there?", "What do you mean by saying nothing?", "Sometimes saying nothing tells a lot :)", ],"default": ["this is a default message"] }
At the beginning of this code, we are defining some variables that we want to use in the conversation. The great thing about this is that it can be reusable in the code. And when we want to change the value, we don’t have to go through all the lines. Changing the variable’s value will be updated automatically within the whole code.
As you can see, we are using “format()” in the responses. This function helps us to pass the values inside the strings very easily. The format is much clear this way. Also, you can pass more than one variable using the format function. So there is no limit if you want to add more layered conversations.
The responses are created as dictionaries. So the answers are found after knowing the question. To make things cool, I’ve even added some responses even when the user replies without writing anything.
Nothing complicated here. We are defining the function that will pick a response by passing in the user’s message. For this function, we will need to import a library called random. Since we don’t want our bot to repeat the same response each time for the same quick; we will pick a random response each time the user asks the same question.
def respond(message):if message in responses: bot_message = random.choice(responses[message])else: bot_message = random.choice(responses["default"])return bot_message
This is an extra function that I’ve added after testing the chatbot with my crazy questions. So, if you want to understand the difference, try the chatbot with and without this function. You will see why I decided to write this function. And one good part about writing the whole chatbot from scratch is that we can add our personal touches to it.
In the Chatbot responses step, we defined answers lists to specific questions. And since we are using dictionaries, if the question is not exactly the same (literally), the chatbot will not return the response for that question we tried to ask. Sometimes, we might forget the question mark, or a letter in the sentence or something else.
In this finding relation function, we are checking the question and trying to find the key terms that might help us to understand the question. You will understand what I mean when you see the function:
def related(x_text): if "name" in x_text: y_text = "what's your name?"elif "weather" in x_text: y_text = "what's today's weather?"elif "robot" in x_text: y_text = "are you a robot?"elif "how are" in x_text: y_text = "how are you?"else: y_text = ""return y_text
I used if and else statements, but it could be done using switch cases too. Feel free to convert it to a switch case. Also, this is just to give some idea. There are many other techniques to increase the understanding, for example, by using NLP (Natural Language Processing) techniques.
Here is a simple example of how the function returns the question that probably asked by the user:
Almost done, this is the last step of us writing a function. In this function, we are writing the conversation in timeline order and also calling the response function that was created earlier. After getting the answer from the response function, we are passing it into the conversation print outs. This is a short function, and here it is:
def send_message(message): print(user_template.format(message)) response = respond(message) print(bot_template.format(response))
Great, you made it to the final step! Everything is ready. All we need is to get the program started. We will write a while loop and pass the functions inside it. I preferred using infinite while loop so that it repeats asking the user for an input.
while 1: my_input = input() my_input = my_input.lower() related_text = related(my_input) send_message(related_text)if my_input == "exit" or my_input == "stop": break
Firstly, we are asking for an input from the user. We can think of it as our bot is listening to the user here.
Secondly, we are lowercasing all the letters in the input. This way we don’t have to worry if the user used capital or lower case letters. It makes strings easier to understand.
Thirdly, we are running the related function. This way, we predict the question asked by checking the keywords.
Fourthly, we are sending the returned question to the bot using the send_message function that we created in the fifth step. The response function going to be called under the send_message function.
Lastly, I’ve added an if statement to check if the user wants to quit the conversation. Entering “exit” or “stop” into the input box will trigger the program to stop. Since we are in a while loop, this also helps to break the loop.
After running the while loop block, this is how the conversation begins:
Congrats!! You have a created a Chatbot from scratch without using any chatbot modules (packages). My goal in this project was to give some understanding how chatbots work and they can be improved. Working on hands-on programming projects like this one is the best way to sharpen your coding skills. That’s all for this article. Hope to see you in the next one.
Thank you,
Here is my blog and YouTube channel to stay inspired. | [
{
"code": null,
"e": 107,
"s": 47,
"text": "Welcome to Beginner’s Guide to Building a Chatbot in Python"
},
{
"code": null,
"e": 690,
"s": 107,
"text": "In this article, I will show you how to build a simple chatbot using the python programming language. We will not use any external chatbot packages. The whole project will be written in plain Python. This is a great way to understand how chatbots actually work. Learning behind the scenes will also give us an insight into the chatbot packages. I will share some Chatbot building platforms in the introduction section of this article. Feel free to check them later if you are interested to learn more about Chatbots. I can’t wait to walk you through this project; let’s get started!"
},
{
"code": null,
"e": 703,
"s": 690,
"text": "Introduction"
},
{
"code": null,
"e": 727,
"s": 703,
"text": "Step 1 — User Templates"
},
{
"code": null,
"e": 754,
"s": 727,
"text": "Step 2 — ChatBot Responses"
},
{
"code": null,
"e": 781,
"s": 754,
"text": "Step 3 — Response Function"
},
{
"code": null,
"e": 808,
"s": 781,
"text": "Step 4 — Relation Function"
},
{
"code": null,
"e": 839,
"s": 808,
"text": "Step 5 — Send Message Function"
},
{
"code": null,
"e": 872,
"s": 839,
"text": "Final Step — Testing the ChatBot"
},
{
"code": null,
"e": 892,
"s": 872,
"text": "Video Demonstration"
},
{
"code": null,
"e": 1422,
"s": 892,
"text": "In 1994, when Michael Mauldin produced his first chatbot and called it“Julia” and that’s the time when the word “chatterbot” entered first time in our dictionary. A chatbot is described as a computer program designed to simulate conversation with human users, particularly over the internet. It is software designed to mimic how people interact with each other. It can be seen as a virtual assistant that interacts with users through text messages or voice messages and this allows companies to get more close to their customers."
},
{
"code": null,
"e": 1691,
"s": 1422,
"text": "There are many ChatBot platforms that help companies to create personalized chatbots. The database and APIs play a big role in these chatbot platforms. Some of those platforms are Amazon Lex, Microsoft Azure Bot, ChatterBot. You can check their websites to learn more."
},
{
"code": null,
"e": 1909,
"s": 1691,
"text": "Hopefully, in a future article, I would like to show how to create an advanced level chatbot using one of those platforms, but for today we will keep things simple and basic. If you are ready, let’s start programming!"
},
{
"code": null,
"e": 2079,
"s": 1909,
"text": "First thing first, we will tell the chatbot to ask the user’s name. This will make our chatbot more realistic and practical. Let’s run this line in our Jupyter Notebook:"
},
{
"code": null,
"e": 2145,
"s": 2079,
"text": "print(\"BOT: What do you want me to call you?\")user_name = input()"
},
{
"code": null,
"e": 2487,
"s": 2145,
"text": "Now, let’s create the templates. In this chatbot project, we will have only two people: the user, and the chatbot. When printing out the conversation timeline, these templates will help us to know who is saying what. The values that will go between the curly brackets will be responsive, and you will understand what I mean in the next step."
},
{
"code": null,
"e": 2550,
"s": 2487,
"text": "bot_template = \"BOT : {0}\"user_template = user_name + \" : {0}\""
},
{
"code": null,
"e": 2983,
"s": 2550,
"text": "This step is a little long because it handles most of the conversation. We are defining the chatbot in this step. We have to put in the questions that our chat is expected to hear and the answers that the chatbot has. To make things more interesting, I’ve created three responses for each question. This way, the bot will have a different answer to the same question. More details will be under the code. Let me show the code first:"
},
{
"code": null,
"e": 3737,
"s": 2983,
"text": "name = \"Funny Bot 101\" weather = \"rainy\" mood = \"Happy\"responses = { \"what's your name?\": [ \"They call me {0}\".format(name), \"I usually go by {0}\".format(name), \"My name is the {0}\".format(name) ],\"what's today's weather?\": [ \"The weather is {0}\".format(weather), \"It's {0} today\".format(weather), \"Let me check, it looks {0} today\".format(weather) ],\"Are you a robot?\": [ \"What do you think?\", \"Maybe yes, maybe no!\", \"Yes, I am a robot with human feelings.\", ],\"how are you?\": [ \"I am feeling {0}\".format(mood), \"{0}! How about you?\".format(mood), \"I am {0}! How about yourself?\".format(mood), ],\"\": [ \"Hey! Are you there?\", \"What do you mean by saying nothing?\", \"Sometimes saying nothing tells a lot :)\", ],\"default\": [\"this is a default message\"] }"
},
{
"code": null,
"e": 4071,
"s": 3737,
"text": "At the beginning of this code, we are defining some variables that we want to use in the conversation. The great thing about this is that it can be reusable in the code. And when we want to change the value, we don’t have to go through all the lines. Changing the variable’s value will be updated automatically within the whole code."
},
{
"code": null,
"e": 4375,
"s": 4071,
"text": "As you can see, we are using “format()” in the responses. This function helps us to pass the values inside the strings very easily. The format is much clear this way. Also, you can pass more than one variable using the format function. So there is no limit if you want to add more layered conversations."
},
{
"code": null,
"e": 4576,
"s": 4375,
"text": "The responses are created as dictionaries. So the answers are found after knowing the question. To make things cool, I’ve even added some responses even when the user replies without writing anything."
},
{
"code": null,
"e": 4918,
"s": 4576,
"text": "Nothing complicated here. We are defining the function that will pick a response by passing in the user’s message. For this function, we will need to import a library called random. Since we don’t want our bot to repeat the same response each time for the same quick; we will pick a random response each time the user asks the same question."
},
{
"code": null,
"e": 5093,
"s": 4918,
"text": "def respond(message):if message in responses: bot_message = random.choice(responses[message])else: bot_message = random.choice(responses[\"default\"])return bot_message"
},
{
"code": null,
"e": 5441,
"s": 5093,
"text": "This is an extra function that I’ve added after testing the chatbot with my crazy questions. So, if you want to understand the difference, try the chatbot with and without this function. You will see why I decided to write this function. And one good part about writing the whole chatbot from scratch is that we can add our personal touches to it."
},
{
"code": null,
"e": 5779,
"s": 5441,
"text": "In the Chatbot responses step, we defined answers lists to specific questions. And since we are using dictionaries, if the question is not exactly the same (literally), the chatbot will not return the response for that question we tried to ask. Sometimes, we might forget the question mark, or a letter in the sentence or something else."
},
{
"code": null,
"e": 5982,
"s": 5779,
"text": "In this finding relation function, we are checking the question and trying to find the key terms that might help us to understand the question. You will understand what I mean when you see the function:"
},
{
"code": null,
"e": 6265,
"s": 5982,
"text": "def related(x_text): if \"name\" in x_text: y_text = \"what's your name?\"elif \"weather\" in x_text: y_text = \"what's today's weather?\"elif \"robot\" in x_text: y_text = \"are you a robot?\"elif \"how are\" in x_text: y_text = \"how are you?\"else: y_text = \"\"return y_text"
},
{
"code": null,
"e": 6552,
"s": 6265,
"text": "I used if and else statements, but it could be done using switch cases too. Feel free to convert it to a switch case. Also, this is just to give some idea. There are many other techniques to increase the understanding, for example, by using NLP (Natural Language Processing) techniques."
},
{
"code": null,
"e": 6651,
"s": 6552,
"text": "Here is a simple example of how the function returns the question that probably asked by the user:"
},
{
"code": null,
"e": 6992,
"s": 6651,
"text": "Almost done, this is the last step of us writing a function. In this function, we are writing the conversation in timeline order and also calling the response function that was created earlier. After getting the answer from the response function, we are passing it into the conversation print outs. This is a short function, and here it is:"
},
{
"code": null,
"e": 7127,
"s": 6992,
"text": "def send_message(message): print(user_template.format(message)) response = respond(message) print(bot_template.format(response))"
},
{
"code": null,
"e": 7377,
"s": 7127,
"text": "Great, you made it to the final step! Everything is ready. All we need is to get the program started. We will write a while loop and pass the functions inside it. I preferred using infinite while loop so that it repeats asking the user for an input."
},
{
"code": null,
"e": 7555,
"s": 7377,
"text": "while 1: my_input = input() my_input = my_input.lower() related_text = related(my_input) send_message(related_text)if my_input == \"exit\" or my_input == \"stop\": break"
},
{
"code": null,
"e": 7667,
"s": 7555,
"text": "Firstly, we are asking for an input from the user. We can think of it as our bot is listening to the user here."
},
{
"code": null,
"e": 7845,
"s": 7667,
"text": "Secondly, we are lowercasing all the letters in the input. This way we don’t have to worry if the user used capital or lower case letters. It makes strings easier to understand."
},
{
"code": null,
"e": 7957,
"s": 7845,
"text": "Thirdly, we are running the related function. This way, we predict the question asked by checking the keywords."
},
{
"code": null,
"e": 8156,
"s": 7957,
"text": "Fourthly, we are sending the returned question to the bot using the send_message function that we created in the fifth step. The response function going to be called under the send_message function."
},
{
"code": null,
"e": 8388,
"s": 8156,
"text": "Lastly, I’ve added an if statement to check if the user wants to quit the conversation. Entering “exit” or “stop” into the input box will trigger the program to stop. Since we are in a while loop, this also helps to break the loop."
},
{
"code": null,
"e": 8461,
"s": 8388,
"text": "After running the while loop block, this is how the conversation begins:"
},
{
"code": null,
"e": 8823,
"s": 8461,
"text": "Congrats!! You have a created a Chatbot from scratch without using any chatbot modules (packages). My goal in this project was to give some understanding how chatbots work and they can be improved. Working on hands-on programming projects like this one is the best way to sharpen your coding skills. That’s all for this article. Hope to see you in the next one."
},
{
"code": null,
"e": 8834,
"s": 8823,
"text": "Thank you,"
}
] |
aSYNcrone - SYN Flood DDoS Tool - GeeksforGeeks | 28 Nov, 2021
aSYNcrone is a free and Open source tool available on GitHub. It uses perfectly legitimate HTTP traffic. It makes a full TCP connection and then requires only a few hundred requests at long-term and regular intervals. As a result, the tool doesn’t need to send a lot of traffic to exhaust the available connections on a server. we can perform denial of service attacks using this tool. its a framework written in python .this tool allows a single machine to take down another machine’s web server
It is an open-source tool so you can download it from GitHub for free of cost.
It uses perfectly legitimate HTTP traffic.
Denial of service attacks can be executed with the help of aSYNcrone by generating heavy traffic of botnets.
aSYNcrone sends multiple requests to the target as a result generates heavy traffic botnets.
aSYNcrone can be used to perform a DDoS attack on any webserver.
Denial of service attacks can be executed with the help of aSYNcrone by generating heavy traffic of botnets.
Step 1: Open your Kali Linux and then Open your Terminal.
git clone https://github.com/fatih4842/aSYNcrone.git
Step 2: Now use the following command to move into the directory of the tool.
cd aSYNcrone
Step 3: Now use the following command to install the tool.
gcc aSYNcrone.c -o aSYNcrone -lpthread
The tool has been downloaded successfully. Now we will see examples to use the tool.
Example 1: Use the aSYNcrone tool to perform a DDOS attack on an IP address.
DDoS
Attack has been started. This is how you can also perform a DDOS attack on a target.
Example 1: Use the aSYNcrone tool to perform a DDOS attack on an IP address.
./aSYNcrone <source port> <target IP> <target port> <thread number>
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
nohup Command in Linux with Examples
scp command in Linux with Examples
Thread functions in C/C++
mv command in Linux with examples
chown command in Linux with Examples
SED command in Linux | Set 2
Docker - COPY Instruction
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
nslookup command in Linux with Examples | [
{
"code": null,
"e": 24406,
"s": 24378,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 24905,
"s": 24406,
"text": "aSYNcrone is a free and Open source tool available on GitHub. It uses perfectly legitimate HTTP traffic. It makes a full TCP connection and then requires only a few hundred requests at long-term and regular intervals. As a result, the tool doesn’t need to send a lot of traffic to exhaust the available connections on a server. we can perform denial of service attacks using this tool. its a framework written in python .this tool allows a single machine to take down another machine’s web server"
},
{
"code": null,
"e": 24984,
"s": 24905,
"text": "It is an open-source tool so you can download it from GitHub for free of cost."
},
{
"code": null,
"e": 25027,
"s": 24984,
"text": "It uses perfectly legitimate HTTP traffic."
},
{
"code": null,
"e": 25136,
"s": 25027,
"text": "Denial of service attacks can be executed with the help of aSYNcrone by generating heavy traffic of botnets."
},
{
"code": null,
"e": 25229,
"s": 25136,
"text": "aSYNcrone sends multiple requests to the target as a result generates heavy traffic botnets."
},
{
"code": null,
"e": 25294,
"s": 25229,
"text": "aSYNcrone can be used to perform a DDoS attack on any webserver."
},
{
"code": null,
"e": 25403,
"s": 25294,
"text": "Denial of service attacks can be executed with the help of aSYNcrone by generating heavy traffic of botnets."
},
{
"code": null,
"e": 25461,
"s": 25403,
"text": "Step 1: Open your Kali Linux and then Open your Terminal."
},
{
"code": null,
"e": 25514,
"s": 25461,
"text": "git clone https://github.com/fatih4842/aSYNcrone.git"
},
{
"code": null,
"e": 25592,
"s": 25514,
"text": "Step 2: Now use the following command to move into the directory of the tool."
},
{
"code": null,
"e": 25605,
"s": 25592,
"text": "cd aSYNcrone"
},
{
"code": null,
"e": 25664,
"s": 25605,
"text": "Step 3: Now use the following command to install the tool."
},
{
"code": null,
"e": 25703,
"s": 25664,
"text": "gcc aSYNcrone.c -o aSYNcrone -lpthread"
},
{
"code": null,
"e": 25788,
"s": 25703,
"text": "The tool has been downloaded successfully. Now we will see examples to use the tool."
},
{
"code": null,
"e": 25865,
"s": 25788,
"text": "Example 1: Use the aSYNcrone tool to perform a DDOS attack on an IP address."
},
{
"code": null,
"e": 25870,
"s": 25865,
"text": "DDoS"
},
{
"code": null,
"e": 25955,
"s": 25870,
"text": "Attack has been started. This is how you can also perform a DDOS attack on a target."
},
{
"code": null,
"e": 26032,
"s": 25955,
"text": "Example 1: Use the aSYNcrone tool to perform a DDOS attack on an IP address."
},
{
"code": null,
"e": 26100,
"s": 26032,
"text": "./aSYNcrone <source port> <target IP> <target port> <thread number>"
},
{
"code": null,
"e": 26111,
"s": 26100,
"text": "Kali-Linux"
},
{
"code": null,
"e": 26123,
"s": 26111,
"text": "Linux-Tools"
},
{
"code": null,
"e": 26134,
"s": 26123,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26232,
"s": 26134,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26269,
"s": 26232,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 26304,
"s": 26269,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 26330,
"s": 26304,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 26364,
"s": 26330,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 26401,
"s": 26364,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 26430,
"s": 26401,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 26456,
"s": 26430,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 26496,
"s": 26456,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 26531,
"s": 26496,
"text": "Basic Operators in Shell Scripting"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.