title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
How to use sub-package in Java?
|
Subpackages are similar to sub-directories. Consider an example. The company had a com.apple.computers package that contained a Dell.java source file, it would be contained in a series of subdirectories like this β
....\com\apple\computers\Dell.java
At the time of compilation, the compiler creates a different output file for each class, interface, and enumeration defined in it. The base name of the output file is the name of the type, and its extension is .class.
For example β
// File Name:Dell.java
package com.apple.computers;
public class Dell {
}
class Ups {
}
Now, compile this file as follows using -d option β
$javac -d.Dell.java
The files will be compiled as follows β
.\com\apple\computers\Dell.class
.\com\apple\computers\Ups.class
You can import all the classes or interfaces defined in \com\apple\computers\ as follows β
import com.apple.computers.*;
|
[
{
"code": null,
"e": 1402,
"s": 1187,
"text": "Subpackages are similar to sub-directories. Consider an example. The company had a com.apple.computers package that contained a Dell.java source file, it would be contained in a series of subdirectories like this β"
},
{
"code": null,
"e": 1437,
"s": 1402,
"text": "....\\com\\apple\\computers\\Dell.java"
},
{
"code": null,
"e": 1655,
"s": 1437,
"text": "At the time of compilation, the compiler creates a different output file for each class, interface, and enumeration defined in it. The base name of the output file is the name of the type, and its extension is .class."
},
{
"code": null,
"e": 1669,
"s": 1655,
"text": "For example β"
},
{
"code": null,
"e": 1757,
"s": 1669,
"text": "// File Name:Dell.java\npackage com.apple.computers;\npublic class Dell {\n}\nclass Ups {\n}"
},
{
"code": null,
"e": 1809,
"s": 1757,
"text": "Now, compile this file as follows using -d option β"
},
{
"code": null,
"e": 1829,
"s": 1809,
"text": "$javac -d.Dell.java"
},
{
"code": null,
"e": 1869,
"s": 1829,
"text": "The files will be compiled as follows β"
},
{
"code": null,
"e": 1934,
"s": 1869,
"text": ".\\com\\apple\\computers\\Dell.class\n.\\com\\apple\\computers\\Ups.class"
},
{
"code": null,
"e": 2025,
"s": 1934,
"text": "You can import all the classes or interfaces defined in \\com\\apple\\computers\\ as follows β"
},
{
"code": null,
"e": 2055,
"s": 2025,
"text": "import com.apple.computers.*;"
}
] |
Go - Maps
|
Go provides another important data type named map which maps unique keys to values. A key is an object that you use to retrieve a value at a later date. Given a key and a value, you can store the value in a Map object. After the value is stored, you can retrieve it by using its key.
You must use make function to create a map.
/* declare a variable, by default map will be nil*/
var map_variable map[key_data_type]value_data_type
/* define the map as nil map can not be assigned any value*/
map_variable = make(map[key_data_type]value_data_type)
The following example illustrates how to create and use a map β
package main
import "fmt"
func main() {
var countryCapitalMap map[string]string
/* create a map*/
countryCapitalMap = make(map[string]string)
/* insert key-value pairs in the map*/
countryCapitalMap["France"] = "Paris"
countryCapitalMap["Italy"] = "Rome"
countryCapitalMap["Japan"] = "Tokyo"
countryCapitalMap["India"] = "New Delhi"
/* print map using keys*/
for country := range countryCapitalMap {
fmt.Println("Capital of",country,"is",countryCapitalMap[country])
}
/* test if entry is present in the map or not*/
capital, ok := countryCapitalMap["United States"]
/* if ok is true, entry is present otherwise entry is absent*/
if(ok){
fmt.Println("Capital of United States is", capital)
} else {
fmt.Println("Capital of United States is not present")
}
}
When the above code is compiled and executed, it produces the following result β
Capital of India is New Delhi
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of United States is not present
delete() function is used to delete an entry from a map. It requires the map and the corresponding key which is to be deleted. For example β
package main
import "fmt"
func main() {
/* create a map*/
countryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo","India":"New Delhi"}
fmt.Println("Original map")
/* print map */
for country := range countryCapitalMap {
fmt.Println("Capital of",country,"is",countryCapitalMap[country])
}
/* delete an entry */
delete(countryCapitalMap,"France");
fmt.Println("Entry for France is deleted")
fmt.Println("Updated map")
/* print map */
for country := range countryCapitalMap {
fmt.Println("Capital of",country,"is",countryCapitalMap[country])
}
}
When the above code is compiled and executed, it produces the following result β
Original Map
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of India is New Delhi
Entry for France is deleted
Updated Map
Capital of India is New Delhi
Capital of Italy is Rome
Capital of Japan is Tokyo
|
[
{
"code": null,
"e": 2355,
"s": 2071,
"text": "Go provides another important data type named map which maps unique keys to values. A key is an object that you use to retrieve a value at a later date. Given a key and a value, you can store the value in a Map object. After the value is stored, you can retrieve it by using its key."
},
{
"code": null,
"e": 2399,
"s": 2355,
"text": "You must use make function to create a map."
},
{
"code": null,
"e": 2620,
"s": 2399,
"text": "/* declare a variable, by default map will be nil*/\nvar map_variable map[key_data_type]value_data_type\n\n/* define the map as nil map can not be assigned any value*/\nmap_variable = make(map[key_data_type]value_data_type)\n"
},
{
"code": null,
"e": 2684,
"s": 2620,
"text": "The following example illustrates how to create and use a map β"
},
{
"code": null,
"e": 3531,
"s": 2684,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var countryCapitalMap map[string]string\n /* create a map*/\n countryCapitalMap = make(map[string]string)\n \n /* insert key-value pairs in the map*/\n countryCapitalMap[\"France\"] = \"Paris\"\n countryCapitalMap[\"Italy\"] = \"Rome\"\n countryCapitalMap[\"Japan\"] = \"Tokyo\"\n countryCapitalMap[\"India\"] = \"New Delhi\"\n \n /* print map using keys*/\n for country := range countryCapitalMap {\n fmt.Println(\"Capital of\",country,\"is\",countryCapitalMap[country])\n }\n \n /* test if entry is present in the map or not*/\n capital, ok := countryCapitalMap[\"United States\"]\n \n /* if ok is true, entry is present otherwise entry is absent*/\n if(ok){\n fmt.Println(\"Capital of United States is\", capital) \n } else {\n fmt.Println(\"Capital of United States is not present\") \n }\n}"
},
{
"code": null,
"e": 3612,
"s": 3531,
"text": "When the above code is compiled and executed, it produces the following result β"
},
{
"code": null,
"e": 3761,
"s": 3612,
"text": "Capital of India is New Delhi\nCapital of France is Paris\nCapital of Italy is Rome\nCapital of Japan is Tokyo\nCapital of United States is not present\n"
},
{
"code": null,
"e": 3902,
"s": 3761,
"text": "delete() function is used to delete an entry from a map. It requires the map and the corresponding key which is to be deleted. For example β"
},
{
"code": null,
"e": 4562,
"s": 3902,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() { \n /* create a map*/\n countryCapitalMap := map[string] string {\"France\":\"Paris\",\"Italy\":\"Rome\",\"Japan\":\"Tokyo\",\"India\":\"New Delhi\"}\n \n fmt.Println(\"Original map\") \n \n /* print map */\n for country := range countryCapitalMap {\n fmt.Println(\"Capital of\",country,\"is\",countryCapitalMap[country])\n }\n \n /* delete an entry */\n delete(countryCapitalMap,\"France\");\n fmt.Println(\"Entry for France is deleted\") \n \n fmt.Println(\"Updated map\") \n \n /* print map */\n for country := range countryCapitalMap {\n fmt.Println(\"Capital of\",country,\"is\",countryCapitalMap[country])\n }\n}"
},
{
"code": null,
"e": 4643,
"s": 4562,
"text": "When the above code is compiled and executed, it produces the following result β"
}
] |
Number of turns to reach from one node to other in binary tree
|
05 Aug, 2021
Given a binary tree and two nodes. The task is to count the number of turns needed to reach from one node to another node of the Binary tree.Examples:
Input: Below Binary Tree and two nodes
5 & 6
1
/ \
2 3
/ \ / \
4 5 6 7
/ / \
8 9 10
Output: Number of Turns needed to reach
from 5 to 6: 3
Input: For above tree if two nodes are 1 & 4
Output: Straight line : 0 turn
Idea based on the Lowest Common Ancestor in a Binary Tree We have to follow the step. 1...Find the LCA of given two nodes2...Given node present either on the left side or right side or equal to LCA. .... According to the above condition, our program falls under one of the two cases:
Case 1:
If none of the nodes is equal to
LCA, we get these nodes either on
the left side or right side.
We call two functions for each node.
....a) if (CountTurn(LCA->right, first,
false, &Count)
|| CountTurn(LCA->left, first,
true, &Count)) ;
....b) Same for second node.
....Here Count is used to store number of
turns needed to reach the target node.
Case 2:
If one of the nodes is equal to LCA_Node,
then we count only the number of turns needed
to reached the second node.
If LCA == (Either first or second)
....a) if (countTurn(LCA->right, second/first,
false, &Count)
|| countTurn(LCA->left, second/first,
true, &Count)) ;
3... Working of CountTurn Function // we pass turn true if we move // left subtree and false if we // move right subTree
CountTurn(LCA, Target_node, count, Turn)
// if found the key value in tree
if (root->key == key)
return true;
case 1:
If Turn is true that means we are
in left_subtree
If we going left_subtree then there
is no need to increment count
else
Increment count and set turn as false
case 2:
if Turn is false that means we are in
right_subtree
if we going right_subtree then there is
no need to increment count else
increment count and set turn as true.
// if key is not found.
return false;
Below is the implementation of the above idea.
C++
Java
Python3
C#
Javascript
// C++ Program to count number of turns// in a Binary Tree.#include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node { struct Node* left, *right; int key;}; // Utility function to create a new// tree NodeNode* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return temp;} // Utility function to find the LCA of// two given values n1 and n2.struct Node* findLCA(struct Node* root, int n1, int n2){ // Base case if (root == NULL) return NULL; // If either n1 or n2 matches with // root's key, report the presence by // returning root (Note that if a key // is ancestor of other, then the // ancestor key becomes LCA if (root->key == n1 || root->key == n2) return root; // Look for keys in left and right subtrees Node* left_lca = findLCA(root->left, n1, n2); Node* right_lca = findLCA(root->right, n1, n2); // If both of the above calls return // Non-NULL, then one key is present // in once subtree and other is present // in other, So this node is the LCA if (left_lca && right_lca) return root; // Otherwise check if left subtree or right // subtree is LCA return (left_lca != NULL) ? left_lca : right_lca;} // function count number of turn need to reach// given node from it's LCA we have two way tobool CountTurn(Node* root, int key, bool turn, int* count){ if (root == NULL) return false; // if found the key value in tree if (root->key == key) return true; // Case 1: if (turn == true) { if (CountTurn(root->left, key, turn, count)) return true; if (CountTurn(root->right, key, !turn, count)) { *count += 1; return true; } } else // Case 2: { if (CountTurn(root->right, key, turn, count)) return true; if (CountTurn(root->left, key, !turn, count)) { *count += 1; return true; } } return false;} // Function to find nodes common to given two nodesint NumberOFTurn(struct Node* root, int first, int second){ struct Node* LCA = findLCA(root, first, second); // there is no path between these two node if (LCA == NULL) return -1; int Count = 0; // case 1: if (LCA->key != first && LCA->key != second) { // count number of turns needs to reached // the second node from LCA if (CountTurn(LCA->right, second, false, &Count) || CountTurn(LCA->left, second, true, &Count)) ; // count number of turns needs to reached // the first node from LCA if (CountTurn(LCA->left, first, true, &Count) || CountTurn(LCA->right, first, false, &Count)) ; return Count + 1; } // case 2: if (LCA->key == first) { // count number of turns needs to reached // the second node from LCA CountTurn(LCA->right, second, false, &Count); CountTurn(LCA->left, second, true, &Count); return Count; } else { // count number of turns needs to reached // the first node from LCA1 CountTurn(LCA->right, first, false, &Count); CountTurn(LCA->left, first, true, &Count); return Count; }} // Driver program to test above functionsint main(){ // Let us create binary tree given in the above // example Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->left->left = newNode(8); root->right->left->left = newNode(9); root->right->left->right = newNode(10); int turn = 0; if ((turn = NumberOFTurn(root, 5, 10))) cout << turn << endl; else cout << "Not Possible" << endl; return 0;}
//A Java Program to count number of turns//in a Binary Tree.public class Turns_to_reach_another_node { // making Count global such that it can get // modified by different methods static int Count; // A Binary Tree Node static class Node { Node left, right; int key; // Constructor Node(int key) { this.key = key; left = null; right = null; } } // Utility function to find the LCA of // two given values n1 and n2. static Node findLCA(Node root, int n1, int n2) { // Base case if (root == null) return null; // If either n1 or n2 matches with // root's key, report the presence by // returning root (Note that if a key // is ancestor of other, then the // ancestor key becomes LCA if (root.key == n1 || root.key == n2) return root; // Look for keys in left and right subtrees Node left_lca = findLCA(root.left, n1, n2); Node right_lca = findLCA(root.right, n1, n2); // If both of the above calls return // Non-NULL, then one key is present // in once subtree and other is present // in other, So this node is the LCA if (left_lca != null && right_lca != null) return root; // Otherwise check if left subtree or right // subtree is LCA return (left_lca != null) ? left_lca : right_lca; } // function count number of turn need to reach // given node from it's LCA we have two way to static boolean CountTurn(Node root, int key, boolean turn) { if (root == null) return false; // if found the key value in tree if (root.key == key) return true; // Case 1: if (turn == true) { if (CountTurn(root.left, key, turn)) return true; if (CountTurn(root.right, key, !turn)) { Count += 1; return true; } } else // Case 2: { if (CountTurn(root.right, key, turn)) return true; if (CountTurn(root.left, key, !turn)) { Count += 1; return true; } } return false; } // Function to find nodes common to given two nodes static int NumberOfTurn(Node root, int first, int second) { Node LCA = findLCA(root, first, second); // there is no path between these two node if (LCA == null) return -1; Count = 0; // case 1: if (LCA.key != first && LCA.key != second) { // count number of turns needs to reached // the second node from LCA if (CountTurn(LCA.right, second, false) || CountTurn(LCA.left, second, true)) ; // count number of turns needs to reached // the first node from LCA if (CountTurn(LCA.left, first, true) || CountTurn(LCA.right, first, false)) ; return Count + 1; } // case 2: if (LCA.key == first) { // count number of turns needs to reached // the second node from LCA CountTurn(LCA.right, second, false); CountTurn(LCA.left, second, true); return Count; } else { // count number of turns needs to reached // the first node from LCA1 CountTurn(LCA.right, first, false); CountTurn(LCA.left, first, true); return Count; } } // Driver program to test above functions public static void main(String[] args) { // Let us create binary tree given in the above // example Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); root.left.left.left = new Node(8); root.right.left.left = new Node(9); root.right.left.right = new Node(10); int turn = 0; if ((turn = NumberOfTurn(root, 5, 10)) != 0) System.out.println(turn); else System.out.println("Not Possible"); } }// This code is contributed by Sumit Ghosh
# Python Program to count number of turns# in a Binary Tree. # A Binary Tree Nodeclass Node: def __init__(self): self.key = 0 self.left = None self.right = None # Utility function to create a new# tree Nodedef newNode(key: int) -> Node: temp = Node() temp.key = key temp.left = None temp.right = None return temp # Utility function to find the LCA of# two given values n1 and n2.def findLCA(root: Node, n1: int, n2: int) -> Node: # Base case if root is None: return None # If either n1 or n2 matches with # root's key, report the presence by # returning root (Note that if a key # is ancestor of other, then the # ancestor key becomes LCA if root.key == n1 or root.key == n2: return root # Look for keys in left and right subtrees left_lca = findLCA(root.left, n1, n2) right_lca = findLCA(root.right, n1, n2) # If both of the above calls return # Non-NULL, then one key is present # in once subtree and other is present # in other, So this node is the LCA if left_lca and right_lca: return root # Otherwise check if left subtree or right # subtree is LCA return (left_lca if left_lca is not None else right_lca) # function count number of turn need to reach# given node from it's LCA we have two way todef countTurn(root: Node, key: int, turn: bool) -> bool: global count if root is None: return False # if found the key value in tree if root.key == key: return True # Case 1: if turn is True: if countTurn(root.left, key, turn): return True if countTurn(root.right, key, not turn): count += 1 return True # Case 2: else: if countTurn(root.right, key, turn): return True if countTurn(root.left, key, not turn): count += 1 return True return False # Function to find nodes common to given two nodesdef numberOfTurn(root: Node, first: int, second: int) -> int: global count LCA = findLCA(root, first, second) # there is no path between these two node if LCA is None: return -1 count = 0 # case 1: if LCA.key != first and LCA.key != second: # count number of turns needs to reached # the second node from LCA if countTurn(LCA.right, second, False) or countTurn( LCA.left, second, True): pass # count number of turns needs to reached # the first node from LCA if countTurn(LCA.left, first, True) or countTurn( LCA.right, first, False): pass return count + 1 # case 2: if LCA.key == first: # count number of turns needs to reached # the second node from LCA countTurn(LCA.right, second, False) countTurn(LCA.left, second, True) return count else: # count number of turns needs to reached # the first node from LCA1 countTurn(LCA.right, first, False) countTurn(LCA.left, first, True) return count # Driver Codeif __name__ == "__main__": count = 0 # Let us create binary tree given in the above # example root = Node() root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.left = newNode(6) root.right.right = newNode(7) root.left.left.left = newNode(8) root.right.left.left = newNode(9) root.right.left.right = newNode(10) turn = numberOfTurn(root, 5, 10) if turn: print(turn) else: print("Not possible") # This code is contributed by# sanjeev2552
using System; //A C# Program to count number of turns//in a Binary Tree.public class Turns_to_reach_another_node{ // making Count global such that it can get // modified by different methods public static int Count; // A Binary Tree Node public class Node { public Node left, right; public int key; // Constructor public Node(int key) { this.key = key; left = null; right = null; } } // Utility function to find the LCA of // two given values n1 and n2. public static Node findLCA(Node root, int n1, int n2) { // Base case if (root == null) { return null; } // If either n1 or n2 matches with // root's key, report the presence by // returning root (Note that if a key // is ancestor of other, then the // ancestor key becomes LCA if (root.key == n1 || root.key == n2) { return root; } // Look for keys in left and right subtrees Node left_lca = findLCA(root.left, n1, n2); Node right_lca = findLCA(root.right, n1, n2); // If both of the above calls return // Non-NULL, then one key is present // in once subtree and other is present // in other, So this node is the LCA if (left_lca != null && right_lca != null) { return root; } // Otherwise check if left subtree or right // subtree is LCA return (left_lca != null) ? left_lca : right_lca; } // function count number of turn need to reach // given node from it's LCA we have two way to public static bool CountTurn(Node root, int key, bool turn) { if (root == null) { return false; } // if found the key value in tree if (root.key == key) { return true; } // Case 1: if (turn == true) { if (CountTurn(root.left, key, turn)) { return true; } if (CountTurn(root.right, key, !turn)) { Count += 1; return true; } } else // Case 2: { if (CountTurn(root.right, key, turn)) { return true; } if (CountTurn(root.left, key, !turn)) { Count += 1; return true; } } return false; } // Function to find nodes common to given two nodes public static int NumberOfTurn(Node root, int first, int second) { Node LCA = findLCA(root, first, second); // there is no path between these two node if (LCA == null) { return -1; } Count = 0; // case 1: if (LCA.key != first && LCA.key != second) { // count number of turns needs to reached // the second node from LCA if (CountTurn(LCA.right, second, false) || CountTurn(LCA.left, second, true)) { ; } // count number of turns needs to reached // the first node from LCA if (CountTurn(LCA.left, first, true) || CountTurn(LCA.right, first, false)) { ; } return Count + 1; } // case 2: if (LCA.key == first) { // count number of turns needs to reached // the second node from LCA CountTurn(LCA.right, second, false); CountTurn(LCA.left, second, true); return Count; } else { // count number of turns needs to reached // the first node from LCA1 CountTurn(LCA.right, first, false); CountTurn(LCA.left, first, true); return Count; } } // Driver program to test above functions public static void Main(string[] args) { // Let us create binary tree given in the above // example Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); root.left.left.left = new Node(8); root.right.left.left = new Node(9); root.right.left.right = new Node(10); int turn = 0; if ((turn = NumberOfTurn(root, 5, 10)) != 0) { Console.WriteLine(turn); } else { Console.WriteLine("Not Possible"); } } } // This code is contributed by Shrikant13
<script> //A Javascript Program to count number of turns //in a Binary Tree. // making Count global such that it can get // modified by different methods let Count; class Node { constructor(key) { this.left = null; this.right = null; this.key = key; } } // Utility function to find the LCA of // two given values n1 and n2. function findLCA(root, n1, n2) { // Base case if (root == null) return null; // If either n1 or n2 matches with // root's key, report the presence by // returning root (Note that if a key // is ancestor of other, then the // ancestor key becomes LCA if (root.key == n1 || root.key == n2) return root; // Look for keys in left and right subtrees let left_lca = findLCA(root.left, n1, n2); let right_lca = findLCA(root.right, n1, n2); // If both of the above calls return // Non-NULL, then one key is present // in once subtree and other is present // in other, So this node is the LCA if (left_lca != null && right_lca != null) return root; // Otherwise check if left subtree or right // subtree is LCA return (left_lca != null) ? left_lca : right_lca; } // function count number of turn need to reach // given node from it's LCA we have two way to function CountTurn(root, key, turn) { if (root == null) return false; // if found the key value in tree if (root.key == key) return true; // Case 1: if (turn == true) { if (CountTurn(root.left, key, turn)) return true; if (CountTurn(root.right, key, !turn)) { Count += 1; return true; } } else // Case 2: { if (CountTurn(root.right, key, turn)) return true; if (CountTurn(root.left, key, !turn)) { Count += 1; return true; } } return false; } // Function to find nodes common to given two nodes function NumberOfTurn(root, first, second) { let LCA = findLCA(root, first, second); // there is no path between these two node if (LCA == null) return -1; Count = 0; // case 1: if (LCA.key != first && LCA.key != second) { // count number of turns needs to reached // the second node from LCA if (CountTurn(LCA.right, second, false) || CountTurn(LCA.left, second, true)) ; // count number of turns needs to reached // the first node from LCA if (CountTurn(LCA.left, first, true) || CountTurn(LCA.right, first, false)) ; return Count + 1; } // case 2: if (LCA.key == first) { // count number of turns needs to reached // the second node from LCA CountTurn(LCA.right, second, false); CountTurn(LCA.left, second, true); return Count; } else { // count number of turns needs to reached // the first node from LCA1 CountTurn(LCA.right, first, false); CountTurn(LCA.left, first, true); return Count; } } // Let us create binary tree given in the above // example let root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); root.left.left.left = new Node(8); root.right.left.left = new Node(9); root.right.left.right = new Node(10); let turn = 0; if ((turn = NumberOfTurn(root, 5, 10)) != 0) document.write(turn); else document.write("Not Possible"); // This code is contributed by suresh07.</script>
4
Time Complexity: O(n)
Alternate Solution:
We have to follow the step.
Find the LCA of the given two nodesStore the path of two-node from LCA in strings S1 and S2 that will store βlβ if we have to take a left turn in the path starting from LCA to that node and βrβ if we take a right turn in the path starting from LCA.Reverse one of the strings and concatenate both strings.Count the number of time characters in our resultant string not equal to its adjacent character.
Find the LCA of the given two nodes
Store the path of two-node from LCA in strings S1 and S2 that will store βlβ if we have to take a left turn in the path starting from LCA to that node and βrβ if we take a right turn in the path starting from LCA.
Reverse one of the strings and concatenate both strings.
Count the number of time characters in our resultant string not equal to its adjacent character.
C++
// C++ Program to count number of turns// in a Binary Tree.#include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node { struct Node* left, *right; int key;}; // Utility function to create a new// tree NodeNode* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return temp;} //Preorder traversal to store l or r in the string traversing//from LCA to the given node keyvoid findPath(struct Node* root, int d,string str,string &s){ if(root==NULL){ return; } if(root->key==d){ s=str; return; } findPath(root->left,d,str+"l",s); findPath(root->right,d,str+"r",s);} // Utility function to find the LCA of// two given values n1 and n2.struct Node* findLCAUtil(struct Node* root, int n1, int n2,bool&v1,bool&v2){ // Base case if (root == NULL) return NULL; if (root->key == n1){ v1=true; return root; } if(root->key == n2){ v2=true; return root; } // Look for keys in left and right subtrees Node* left_lca = findLCAUtil(root->left, n1, n2,v1,v2); Node* right_lca = findLCAUtil(root->right, n1, n2,v1,v2); if (left_lca && right_lca){ return root; } return (left_lca != NULL) ? left_lca : right_lca;} bool find(Node* root, int x){ if(root==NULL){ return false; } if((root->key==x) || find(root->left,x) || find(root->right,x)){ return true; } return false;} //Function should return LCA of two nodes if both nodes are//present otherwise should return NULLNode* findLCA(struct Node* root, int first, int second){ bool v1=false; bool v2=false; Node* lca = findLCAUtil(root,first,second,v1,v2); if((v1&&v2) || (v1&&find(lca,second)) || (v2&&find(lca,first))){ return lca; } return NULL;} // function should return the number of turns required to go from//first node to second nodeint NumberOFTurns(struct Node* root, int first, int second){ // base cases if root is not present or both node values are same if(root==NULL || (first==second)){ return 0; } string s1 =""; string s2 = ""; Node* lca = findLCA(root,first,second); findPath(lca,first,"",s1); findPath(lca,second,"",s2); if(s1.length()==0 && s2.length()==0){ return -1; } reverse(s1.begin(),s1.end()); s1+=s2; int cnt=0; bool flag=false; for(int i=0; i<(s1.length()-1); i++){ if(s1[i]!=s1[i+1]){ flag=true; cnt+=1; } } if(!flag){ return -1; } return cnt;} // Driver program to test above functionsint main(){ // Let us create binary tree given in the above // example Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->left->left = newNode(8); root->right->left->left = newNode(9); root->right->left->right = newNode(10); int turn = 0; if ((turn = NumberOFTurns(root, 5, 10))!=-1) cout << turn << endl; else cout << "Not Possible" << endl; return 0;}
4
Time Complexity: O(n)
This article is contributed by Nishant 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 review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
shrikanth13
sanjeev2552
sufiaaleena12
suresh07
ashishbtechcs19
Samsung
Tree
Samsung
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Aug, 2021"
},
{
"code": null,
"e": 205,
"s": 52,
"text": "Given a binary tree and two nodes. The task is to count the number of turns needed to reach from one node to another node of the Binary tree.Examples: "
},
{
"code": null,
"e": 585,
"s": 205,
"text": "Input: Below Binary Tree and two nodes\n 5 & 6 \n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n / / \\\n 8 9 10\nOutput: Number of Turns needed to reach \nfrom 5 to 6: 3\n \nInput: For above tree if two nodes are 1 & 4\nOutput: Straight line : 0 turn "
},
{
"code": null,
"e": 872,
"s": 587,
"text": "Idea based on the Lowest Common Ancestor in a Binary Tree We have to follow the step. 1...Find the LCA of given two nodes2...Given node present either on the left side or right side or equal to LCA. .... According to the above condition, our program falls under one of the two cases: "
},
{
"code": null,
"e": 1655,
"s": 872,
"text": "Case 1: \nIf none of the nodes is equal to\nLCA, we get these nodes either on\nthe left side or right side. \nWe call two functions for each node.\n....a) if (CountTurn(LCA->right, first, \n false, &Count)\n || CountTurn(LCA->left, first, \n true, &Count)) ; \n....b) Same for second node.\n....Here Count is used to store number of \nturns needed to reach the target node. \n\nCase 2: \nIf one of the nodes is equal to LCA_Node,\nthen we count only the number of turns needed\nto reached the second node.\nIf LCA == (Either first or second)\n....a) if (countTurn(LCA->right, second/first, \n false, &Count) \n || countTurn(LCA->left, second/first, \n true, &Count)) ; "
},
{
"code": null,
"e": 1778,
"s": 1655,
"text": "3... Working of CountTurn Function // we pass turn true if we move // left subtree and false if we // move right subTree "
},
{
"code": null,
"e": 2332,
"s": 1778,
"text": "CountTurn(LCA, Target_node, count, Turn)\n\n// if found the key value in tree \nif (root->key == key)\n return true;\ncase 1: \n If Turn is true that means we are \n in left_subtree \n If we going left_subtree then there \n is no need to increment count \n else\n Increment count and set turn as false \ncase 2:\n if Turn is false that means we are in\n right_subtree \n if we going right_subtree then there is\n no need to increment count else\n increment count and set turn as true.\n\n// if key is not found.\nreturn false;\n "
},
{
"code": null,
"e": 2381,
"s": 2332,
"text": "Below is the implementation of the above idea. "
},
{
"code": null,
"e": 2385,
"s": 2381,
"text": "C++"
},
{
"code": null,
"e": 2390,
"s": 2385,
"text": "Java"
},
{
"code": null,
"e": 2398,
"s": 2390,
"text": "Python3"
},
{
"code": null,
"e": 2401,
"s": 2398,
"text": "C#"
},
{
"code": null,
"e": 2412,
"s": 2401,
"text": "Javascript"
},
{
"code": "// C++ Program to count number of turns// in a Binary Tree.#include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node { struct Node* left, *right; int key;}; // Utility function to create a new// tree NodeNode* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return temp;} // Utility function to find the LCA of// two given values n1 and n2.struct Node* findLCA(struct Node* root, int n1, int n2){ // Base case if (root == NULL) return NULL; // If either n1 or n2 matches with // root's key, report the presence by // returning root (Note that if a key // is ancestor of other, then the // ancestor key becomes LCA if (root->key == n1 || root->key == n2) return root; // Look for keys in left and right subtrees Node* left_lca = findLCA(root->left, n1, n2); Node* right_lca = findLCA(root->right, n1, n2); // If both of the above calls return // Non-NULL, then one key is present // in once subtree and other is present // in other, So this node is the LCA if (left_lca && right_lca) return root; // Otherwise check if left subtree or right // subtree is LCA return (left_lca != NULL) ? left_lca : right_lca;} // function count number of turn need to reach// given node from it's LCA we have two way tobool CountTurn(Node* root, int key, bool turn, int* count){ if (root == NULL) return false; // if found the key value in tree if (root->key == key) return true; // Case 1: if (turn == true) { if (CountTurn(root->left, key, turn, count)) return true; if (CountTurn(root->right, key, !turn, count)) { *count += 1; return true; } } else // Case 2: { if (CountTurn(root->right, key, turn, count)) return true; if (CountTurn(root->left, key, !turn, count)) { *count += 1; return true; } } return false;} // Function to find nodes common to given two nodesint NumberOFTurn(struct Node* root, int first, int second){ struct Node* LCA = findLCA(root, first, second); // there is no path between these two node if (LCA == NULL) return -1; int Count = 0; // case 1: if (LCA->key != first && LCA->key != second) { // count number of turns needs to reached // the second node from LCA if (CountTurn(LCA->right, second, false, &Count) || CountTurn(LCA->left, second, true, &Count)) ; // count number of turns needs to reached // the first node from LCA if (CountTurn(LCA->left, first, true, &Count) || CountTurn(LCA->right, first, false, &Count)) ; return Count + 1; } // case 2: if (LCA->key == first) { // count number of turns needs to reached // the second node from LCA CountTurn(LCA->right, second, false, &Count); CountTurn(LCA->left, second, true, &Count); return Count; } else { // count number of turns needs to reached // the first node from LCA1 CountTurn(LCA->right, first, false, &Count); CountTurn(LCA->left, first, true, &Count); return Count; }} // Driver program to test above functionsint main(){ // Let us create binary tree given in the above // example Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->left->left = newNode(8); root->right->left->left = newNode(9); root->right->left->right = newNode(10); int turn = 0; if ((turn = NumberOFTurn(root, 5, 10))) cout << turn << endl; else cout << \"Not Possible\" << endl; return 0;}",
"e": 6607,
"s": 2412,
"text": null
},
{
"code": "//A Java Program to count number of turns//in a Binary Tree.public class Turns_to_reach_another_node { // making Count global such that it can get // modified by different methods static int Count; // A Binary Tree Node static class Node { Node left, right; int key; // Constructor Node(int key) { this.key = key; left = null; right = null; } } // Utility function to find the LCA of // two given values n1 and n2. static Node findLCA(Node root, int n1, int n2) { // Base case if (root == null) return null; // If either n1 or n2 matches with // root's key, report the presence by // returning root (Note that if a key // is ancestor of other, then the // ancestor key becomes LCA if (root.key == n1 || root.key == n2) return root; // Look for keys in left and right subtrees Node left_lca = findLCA(root.left, n1, n2); Node right_lca = findLCA(root.right, n1, n2); // If both of the above calls return // Non-NULL, then one key is present // in once subtree and other is present // in other, So this node is the LCA if (left_lca != null && right_lca != null) return root; // Otherwise check if left subtree or right // subtree is LCA return (left_lca != null) ? left_lca : right_lca; } // function count number of turn need to reach // given node from it's LCA we have two way to static boolean CountTurn(Node root, int key, boolean turn) { if (root == null) return false; // if found the key value in tree if (root.key == key) return true; // Case 1: if (turn == true) { if (CountTurn(root.left, key, turn)) return true; if (CountTurn(root.right, key, !turn)) { Count += 1; return true; } } else // Case 2: { if (CountTurn(root.right, key, turn)) return true; if (CountTurn(root.left, key, !turn)) { Count += 1; return true; } } return false; } // Function to find nodes common to given two nodes static int NumberOfTurn(Node root, int first, int second) { Node LCA = findLCA(root, first, second); // there is no path between these two node if (LCA == null) return -1; Count = 0; // case 1: if (LCA.key != first && LCA.key != second) { // count number of turns needs to reached // the second node from LCA if (CountTurn(LCA.right, second, false) || CountTurn(LCA.left, second, true)) ; // count number of turns needs to reached // the first node from LCA if (CountTurn(LCA.left, first, true) || CountTurn(LCA.right, first, false)) ; return Count + 1; } // case 2: if (LCA.key == first) { // count number of turns needs to reached // the second node from LCA CountTurn(LCA.right, second, false); CountTurn(LCA.left, second, true); return Count; } else { // count number of turns needs to reached // the first node from LCA1 CountTurn(LCA.right, first, false); CountTurn(LCA.left, first, true); return Count; } } // Driver program to test above functions public static void main(String[] args) { // Let us create binary tree given in the above // example Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); root.left.left.left = new Node(8); root.right.left.left = new Node(9); root.right.left.right = new Node(10); int turn = 0; if ((turn = NumberOfTurn(root, 5, 10)) != 0) System.out.println(turn); else System.out.println(\"Not Possible\"); } }// This code is contributed by Sumit Ghosh",
"e": 10969,
"s": 6607,
"text": null
},
{
"code": "# Python Program to count number of turns# in a Binary Tree. # A Binary Tree Nodeclass Node: def __init__(self): self.key = 0 self.left = None self.right = None # Utility function to create a new# tree Nodedef newNode(key: int) -> Node: temp = Node() temp.key = key temp.left = None temp.right = None return temp # Utility function to find the LCA of# two given values n1 and n2.def findLCA(root: Node, n1: int, n2: int) -> Node: # Base case if root is None: return None # If either n1 or n2 matches with # root's key, report the presence by # returning root (Note that if a key # is ancestor of other, then the # ancestor key becomes LCA if root.key == n1 or root.key == n2: return root # Look for keys in left and right subtrees left_lca = findLCA(root.left, n1, n2) right_lca = findLCA(root.right, n1, n2) # If both of the above calls return # Non-NULL, then one key is present # in once subtree and other is present # in other, So this node is the LCA if left_lca and right_lca: return root # Otherwise check if left subtree or right # subtree is LCA return (left_lca if left_lca is not None else right_lca) # function count number of turn need to reach# given node from it's LCA we have two way todef countTurn(root: Node, key: int, turn: bool) -> bool: global count if root is None: return False # if found the key value in tree if root.key == key: return True # Case 1: if turn is True: if countTurn(root.left, key, turn): return True if countTurn(root.right, key, not turn): count += 1 return True # Case 2: else: if countTurn(root.right, key, turn): return True if countTurn(root.left, key, not turn): count += 1 return True return False # Function to find nodes common to given two nodesdef numberOfTurn(root: Node, first: int, second: int) -> int: global count LCA = findLCA(root, first, second) # there is no path between these two node if LCA is None: return -1 count = 0 # case 1: if LCA.key != first and LCA.key != second: # count number of turns needs to reached # the second node from LCA if countTurn(LCA.right, second, False) or countTurn( LCA.left, second, True): pass # count number of turns needs to reached # the first node from LCA if countTurn(LCA.left, first, True) or countTurn( LCA.right, first, False): pass return count + 1 # case 2: if LCA.key == first: # count number of turns needs to reached # the second node from LCA countTurn(LCA.right, second, False) countTurn(LCA.left, second, True) return count else: # count number of turns needs to reached # the first node from LCA1 countTurn(LCA.right, first, False) countTurn(LCA.left, first, True) return count # Driver Codeif __name__ == \"__main__\": count = 0 # Let us create binary tree given in the above # example root = Node() root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.left = newNode(6) root.right.right = newNode(7) root.left.left.left = newNode(8) root.right.left.left = newNode(9) root.right.left.right = newNode(10) turn = numberOfTurn(root, 5, 10) if turn: print(turn) else: print(\"Not possible\") # This code is contributed by# sanjeev2552",
"e": 14633,
"s": 10969,
"text": null
},
{
"code": "using System; //A C# Program to count number of turns//in a Binary Tree.public class Turns_to_reach_another_node{ // making Count global such that it can get // modified by different methods public static int Count; // A Binary Tree Node public class Node { public Node left, right; public int key; // Constructor public Node(int key) { this.key = key; left = null; right = null; } } // Utility function to find the LCA of // two given values n1 and n2. public static Node findLCA(Node root, int n1, int n2) { // Base case if (root == null) { return null; } // If either n1 or n2 matches with // root's key, report the presence by // returning root (Note that if a key // is ancestor of other, then the // ancestor key becomes LCA if (root.key == n1 || root.key == n2) { return root; } // Look for keys in left and right subtrees Node left_lca = findLCA(root.left, n1, n2); Node right_lca = findLCA(root.right, n1, n2); // If both of the above calls return // Non-NULL, then one key is present // in once subtree and other is present // in other, So this node is the LCA if (left_lca != null && right_lca != null) { return root; } // Otherwise check if left subtree or right // subtree is LCA return (left_lca != null) ? left_lca : right_lca; } // function count number of turn need to reach // given node from it's LCA we have two way to public static bool CountTurn(Node root, int key, bool turn) { if (root == null) { return false; } // if found the key value in tree if (root.key == key) { return true; } // Case 1: if (turn == true) { if (CountTurn(root.left, key, turn)) { return true; } if (CountTurn(root.right, key, !turn)) { Count += 1; return true; } } else // Case 2: { if (CountTurn(root.right, key, turn)) { return true; } if (CountTurn(root.left, key, !turn)) { Count += 1; return true; } } return false; } // Function to find nodes common to given two nodes public static int NumberOfTurn(Node root, int first, int second) { Node LCA = findLCA(root, first, second); // there is no path between these two node if (LCA == null) { return -1; } Count = 0; // case 1: if (LCA.key != first && LCA.key != second) { // count number of turns needs to reached // the second node from LCA if (CountTurn(LCA.right, second, false) || CountTurn(LCA.left, second, true)) { ; } // count number of turns needs to reached // the first node from LCA if (CountTurn(LCA.left, first, true) || CountTurn(LCA.right, first, false)) { ; } return Count + 1; } // case 2: if (LCA.key == first) { // count number of turns needs to reached // the second node from LCA CountTurn(LCA.right, second, false); CountTurn(LCA.left, second, true); return Count; } else { // count number of turns needs to reached // the first node from LCA1 CountTurn(LCA.right, first, false); CountTurn(LCA.left, first, true); return Count; } } // Driver program to test above functions public static void Main(string[] args) { // Let us create binary tree given in the above // example Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); root.left.left.left = new Node(8); root.right.left.left = new Node(9); root.right.left.right = new Node(10); int turn = 0; if ((turn = NumberOfTurn(root, 5, 10)) != 0) { Console.WriteLine(turn); } else { Console.WriteLine(\"Not Possible\"); } } } // This code is contributed by Shrikant13",
"e": 19373,
"s": 14633,
"text": null
},
{
"code": "<script> //A Javascript Program to count number of turns //in a Binary Tree. // making Count global such that it can get // modified by different methods let Count; class Node { constructor(key) { this.left = null; this.right = null; this.key = key; } } // Utility function to find the LCA of // two given values n1 and n2. function findLCA(root, n1, n2) { // Base case if (root == null) return null; // If either n1 or n2 matches with // root's key, report the presence by // returning root (Note that if a key // is ancestor of other, then the // ancestor key becomes LCA if (root.key == n1 || root.key == n2) return root; // Look for keys in left and right subtrees let left_lca = findLCA(root.left, n1, n2); let right_lca = findLCA(root.right, n1, n2); // If both of the above calls return // Non-NULL, then one key is present // in once subtree and other is present // in other, So this node is the LCA if (left_lca != null && right_lca != null) return root; // Otherwise check if left subtree or right // subtree is LCA return (left_lca != null) ? left_lca : right_lca; } // function count number of turn need to reach // given node from it's LCA we have two way to function CountTurn(root, key, turn) { if (root == null) return false; // if found the key value in tree if (root.key == key) return true; // Case 1: if (turn == true) { if (CountTurn(root.left, key, turn)) return true; if (CountTurn(root.right, key, !turn)) { Count += 1; return true; } } else // Case 2: { if (CountTurn(root.right, key, turn)) return true; if (CountTurn(root.left, key, !turn)) { Count += 1; return true; } } return false; } // Function to find nodes common to given two nodes function NumberOfTurn(root, first, second) { let LCA = findLCA(root, first, second); // there is no path between these two node if (LCA == null) return -1; Count = 0; // case 1: if (LCA.key != first && LCA.key != second) { // count number of turns needs to reached // the second node from LCA if (CountTurn(LCA.right, second, false) || CountTurn(LCA.left, second, true)) ; // count number of turns needs to reached // the first node from LCA if (CountTurn(LCA.left, first, true) || CountTurn(LCA.right, first, false)) ; return Count + 1; } // case 2: if (LCA.key == first) { // count number of turns needs to reached // the second node from LCA CountTurn(LCA.right, second, false); CountTurn(LCA.left, second, true); return Count; } else { // count number of turns needs to reached // the first node from LCA1 CountTurn(LCA.right, first, false); CountTurn(LCA.left, first, true); return Count; } } // Let us create binary tree given in the above // example let root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); root.left.left.left = new Node(8); root.right.left.left = new Node(9); root.right.left.right = new Node(10); let turn = 0; if ((turn = NumberOfTurn(root, 5, 10)) != 0) document.write(turn); else document.write(\"Not Possible\"); // This code is contributed by suresh07.</script>",
"e": 23432,
"s": 19373,
"text": null
},
{
"code": null,
"e": 23434,
"s": 23432,
"text": "4"
},
{
"code": null,
"e": 23456,
"s": 23434,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 23476,
"s": 23456,
"text": "Alternate Solution:"
},
{
"code": null,
"e": 23506,
"s": 23476,
"text": "We have to follow the step. "
},
{
"code": null,
"e": 23908,
"s": 23506,
"text": "Find the LCA of the given two nodesStore the path of two-node from LCA in strings S1 and S2 that will store βlβ if we have to take a left turn in the path starting from LCA to that node and βrβ if we take a right turn in the path starting from LCA.Reverse one of the strings and concatenate both strings.Count the number of time characters in our resultant string not equal to its adjacent character."
},
{
"code": null,
"e": 23944,
"s": 23908,
"text": "Find the LCA of the given two nodes"
},
{
"code": null,
"e": 24159,
"s": 23944,
"text": "Store the path of two-node from LCA in strings S1 and S2 that will store βlβ if we have to take a left turn in the path starting from LCA to that node and βrβ if we take a right turn in the path starting from LCA."
},
{
"code": null,
"e": 24216,
"s": 24159,
"text": "Reverse one of the strings and concatenate both strings."
},
{
"code": null,
"e": 24313,
"s": 24216,
"text": "Count the number of time characters in our resultant string not equal to its adjacent character."
},
{
"code": null,
"e": 24317,
"s": 24313,
"text": "C++"
},
{
"code": "// C++ Program to count number of turns// in a Binary Tree.#include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node { struct Node* left, *right; int key;}; // Utility function to create a new// tree NodeNode* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return temp;} //Preorder traversal to store l or r in the string traversing//from LCA to the given node keyvoid findPath(struct Node* root, int d,string str,string &s){ if(root==NULL){ return; } if(root->key==d){ s=str; return; } findPath(root->left,d,str+\"l\",s); findPath(root->right,d,str+\"r\",s);} // Utility function to find the LCA of// two given values n1 and n2.struct Node* findLCAUtil(struct Node* root, int n1, int n2,bool&v1,bool&v2){ // Base case if (root == NULL) return NULL; if (root->key == n1){ v1=true; return root; } if(root->key == n2){ v2=true; return root; } // Look for keys in left and right subtrees Node* left_lca = findLCAUtil(root->left, n1, n2,v1,v2); Node* right_lca = findLCAUtil(root->right, n1, n2,v1,v2); if (left_lca && right_lca){ return root; } return (left_lca != NULL) ? left_lca : right_lca;} bool find(Node* root, int x){ if(root==NULL){ return false; } if((root->key==x) || find(root->left,x) || find(root->right,x)){ return true; } return false;} //Function should return LCA of two nodes if both nodes are//present otherwise should return NULLNode* findLCA(struct Node* root, int first, int second){ bool v1=false; bool v2=false; Node* lca = findLCAUtil(root,first,second,v1,v2); if((v1&&v2) || (v1&&find(lca,second)) || (v2&&find(lca,first))){ return lca; } return NULL;} // function should return the number of turns required to go from//first node to second nodeint NumberOFTurns(struct Node* root, int first, int second){ // base cases if root is not present or both node values are same if(root==NULL || (first==second)){ return 0; } string s1 =\"\"; string s2 = \"\"; Node* lca = findLCA(root,first,second); findPath(lca,first,\"\",s1); findPath(lca,second,\"\",s2); if(s1.length()==0 && s2.length()==0){ return -1; } reverse(s1.begin(),s1.end()); s1+=s2; int cnt=0; bool flag=false; for(int i=0; i<(s1.length()-1); i++){ if(s1[i]!=s1[i+1]){ flag=true; cnt+=1; } } if(!flag){ return -1; } return cnt;} // Driver program to test above functionsint main(){ // Let us create binary tree given in the above // example Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->left->left = newNode(8); root->right->left->left = newNode(9); root->right->left->right = newNode(10); int turn = 0; if ((turn = NumberOFTurns(root, 5, 10))!=-1) cout << turn << endl; else cout << \"Not Possible\" << endl; return 0;}",
"e": 27518,
"s": 24317,
"text": null
},
{
"code": null,
"e": 27520,
"s": 27518,
"text": "4"
},
{
"code": null,
"e": 27543,
"s": 27520,
"text": "Time Complexity: O(n) "
},
{
"code": null,
"e": 27965,
"s": 27543,
"text": "This article is contributed by Nishant 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 review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 27977,
"s": 27965,
"text": "shrikanth13"
},
{
"code": null,
"e": 27989,
"s": 27977,
"text": "sanjeev2552"
},
{
"code": null,
"e": 28003,
"s": 27989,
"text": "sufiaaleena12"
},
{
"code": null,
"e": 28012,
"s": 28003,
"text": "suresh07"
},
{
"code": null,
"e": 28028,
"s": 28012,
"text": "ashishbtechcs19"
},
{
"code": null,
"e": 28036,
"s": 28028,
"text": "Samsung"
},
{
"code": null,
"e": 28041,
"s": 28036,
"text": "Tree"
},
{
"code": null,
"e": 28049,
"s": 28041,
"text": "Samsung"
},
{
"code": null,
"e": 28054,
"s": 28049,
"text": "Tree"
}
] |
Select a Random Node from a tree with equal probability
|
08 Jul, 2021
Given a Binary Tree with children Nodes, Return a random Node with equal Probability of selecting any Node in tree.Consider the given tree with root as 1.
10
/ \
20 30
/ \ / \
40 50 60 70
Examples:
Input : getRandom(root);
Output : A Random Node From Tree : 3
Input : getRandom(root);
Output : A Random Node From Tree : 2
A simple solution is to store Inorder traversal of tree in an array. Let the count of nodes be n. To get a random node, we generate a random number from 0 to n-1, use this number as index in array and return the value at index.An alternate solution is to modify tree structure. We store count of children in every node. Consider the above tree. We use inorder traversal here also. We generate a number smaller than or equal count of nodes. We traverse tree and go to the node at that index. We use counts to quickly reach the desired node. With counts, we reach in O(h) time where h is height of tree.
10,6
/ \
20,2 30,2
/ \ / \
40,0 50,0 60,0 70,0
The first value is node and second
value is count of children.
We start traversing the tree, on each node we either go to left subtree or right subtree considering whether the count of children is less than random count or not.If the random count is less than the count of children then we go left else we go right.Below is the implementation of above Algorithm. getElements will return count of children for root, InsertChildrenCount inserts children data to each node, RandomNode return the random node with the help of Utility Function RandomNodeUtil.
C++
Java
Python3
C#
Javascript
// CPP program to Select a Random Node from a tree#include <bits/stdc++.h>using namespace std; struct Node { int data; int children; Node *left, *right;}; Node* newNode(int data){ Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; temp->children = 0; return temp;} // This is used to fill children counts.int getElements(Node* root){ if (!root) return 0; return getElements(root->left) + getElements(root->right) + 1;} // Inserts Children count for each nodevoid insertChildrenCount(Node*& root){ if (!root) return; root->children = getElements(root) - 1; insertChildrenCount(root->left); insertChildrenCount(root->right);} // returns number of children for rootint children(Node* root){ if (!root) return 0; return root->children + 1;} // Helper Function to return a random nodeint randomNodeUtil(Node* root, int count){ if (!root) return 0; if (count == children(root->left)) return root->data; if (count < children(root->left)) return randomNodeUtil(root->left, count); return randomNodeUtil(root->right, count - children(root->left) - 1);} // Returns Random nodeint randomNode(Node* root){ srand(time(0)); int count = rand() % (root->children + 1); return randomNodeUtil(root, count);} int main(){ // Creating Above Tree Node* root = newNode(10); root->left = newNode(20); root->right = newNode(30); root->left->right = newNode(40); root->left->right = newNode(50); root->right->left = newNode(60); root->right->right = newNode(70); insertChildrenCount(root); cout << "A Random Node From Tree : " << randomNode(root) << endl; return 0;}
// Java program to Select a Random Node from a treeimport java.util.*;import java.lang.*;import java.io.*; class GFG{static class Node{ int data; int children; Node left, right;} static Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; temp.children = 0; return temp;} // This is used to fill children counts.static int getElements(Node root){ if (root == null) return 0; return getElements(root.left) + getElements(root.right) + 1;} // Inserts Children count for each nodestatic Node insertChildrenCount(Node root){ if (root == null) return null; root.children = getElements(root) - 1; root.left = insertChildrenCount(root.left); root.right = insertChildrenCount(root.right); return root;} // returns number of children for rootstatic int children(Node root){ if (root == null) return 0; return root.children + 1;} // Helper Function to return a random nodestatic int randomNodeUtil(Node root, int count){ if (root == null) return 0; if (count == children(root.left)) return root.data; if (count < children(root.left)) return randomNodeUtil(root.left, count); return randomNodeUtil(root.right, count - children(root.left) - 1);} // Returns Random nodestatic int randomNode(Node root){ int count = (int) Math.random() * (root.children + 1); return randomNodeUtil(root, count);} // Driver Codepublic static void main(String args[]){ // Creating Above Tree Node root = newNode(10); root.left = newNode(20); root.right = newNode(30); root.left.right = newNode(40); root.left.right = newNode(50); root.right.left = newNode(60); root.right.right = newNode(70); insertChildrenCount(root); System.out.println( "A Random Node From Tree : " + randomNode(root));}} // This code is contributed by Arnab Kundu
# Python3 program to Select a# Random Node from a treefrom random import randint class Node: def __init__(self, data): self.data = data self.children = 0 self.left = None self.right = None # This is used to fill children counts.def getElements(root): if root == None: return 0 return (getElements(root.left) + getElements(root.right) + 1) # Inserts Children count for each nodedef insertChildrenCount(root): if root == None: return root.children = getElements(root) - 1 insertChildrenCount(root.left) insertChildrenCount(root.right) # Returns number of children for rootdef children(root): if root == None: return 0 return root.children + 1 # Helper Function to return a random nodedef randomNodeUtil(root, count): if root == None: return 0 if count == children(root.left): return root.data if count < children(root.left): return randomNodeUtil(root.left, count) return randomNodeUtil(root.right, count - children(root.left) - 1) # Returns Random nodedef randomNode(root): count = randint(0, root.children) return randomNodeUtil(root, count) # Driver Codeif __name__ == "__main__": # Creating Above Tree root = Node(10) root.left = Node(20) root.right = Node(30) root.left.right = Node(40) root.left.right = Node(50) root.right.left = Node(60) root.right.right = Node(70) insertChildrenCount(root) print("A Random Node From Tree :", randomNode(root)) # This code is contributed by Rituraj Jain
// C# program to Select a Random Node from a treeusing System; class GFG{ class Node{ public int data; public int children; public Node left, right;} static Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; temp.children = 0; return temp;} // This is used to fill children counts.static int getElements(Node root){ if (root == null) return 0; return getElements(root.left) + getElements(root.right) + 1;} // Inserts Children count for each nodestatic Node insertChildrenCount(Node root){ if (root == null) return null; root.children = getElements(root) - 1; root.left = insertChildrenCount(root.left); root.right = insertChildrenCount(root.right); return root;} // returns number of children for rootstatic int children(Node root){ if (root == null) return 0; return root.children + 1;} // Helper Function to return a random nodestatic int randomNodeUtil(Node root, int count){ if (root == null) return 0; if (count == children(root.left)) return root.data; if (count < children(root.left)) return randomNodeUtil(root.left, count); return randomNodeUtil(root.right, count - children(root.left) - 1);} // Returns Random nodestatic int randomNode(Node root){ int count = (int) new Random().Next(0, root.children + 1); return randomNodeUtil(root, count);} // Driver Codepublic static void Main(String []args){ // Creating Above Tree Node root = newNode(10); root.left = newNode(20); root.right = newNode(30); root.left.right = newNode(40); root.left.right = newNode(50); root.right.left = newNode(60); root.right.right = newNode(70); insertChildrenCount(root); Console.Write( "A Random Node From Tree : " + randomNode(root));}} // This code is contributed by Arnab Kundu
<script> // JavaScript program to Select a Random Node from a tree class Node{ constructor(data) { this.data=data; this.left=this.right=null; this.children = 0; }} // This is used to fill children counts.function getElements(root){ if (root == null) return 0; return getElements(root.left) + getElements(root.right) + 1;} // Inserts Children count for each nodefunction insertChildrenCount(root){ if (root == null) return null; root.children = getElements(root) - 1; root.left = insertChildrenCount(root.left); root.right = insertChildrenCount(root.right); return root;} // returns number of children for rootfunction children(root){ if (root == null) return 0; return root.children + 1;} // Helper Function to return a random nodefunction randomNodeUtil(root,count){ if (root == null) return 0; if (count == children(root.left)) return root.data; if (count < children(root.left)) return randomNodeUtil(root.left, count); return randomNodeUtil(root.right, count - children(root.left) - 1);} // Returns Random nodefunction randomNode(root){ let count = Math.floor(Math.random() * (root.children + 1)); return randomNodeUtil(root, count);} // Driver Code// Creating Above Treelet root = new Node(10);root.left = new Node(20);root.right = new Node(30);root.left.right = new Node(40);root.left.right = new Node(50);root.right.left = new Node(60);root.right.right = new Node(70); insertChildrenCount(root); document.write( "A Random Node From Tree : " + randomNode(root)+"<br>"); // This code is contributed by avanitrachhadiya2155 </script>
Time Complexity of randomNode is O(h) where h is height of tree. Note that we are either moving to right or to left at a time.
rituraj_jain
andrew1234
avanitrachhadiya2155
Probability
Randomized
Tree
Tree
Probability
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Randomized Algorithms | Set 0 (Mathematical Background)
Binomial Random Variables
Implement random-0-6-Generator using the given random-0-1-Generator
Estimating the value of Pi using Monte Carlo | Parallel Computing Method
Randomized Algorithms | Set 3 (1/2 Approximate Median)
Tree Traversals (Inorder, Preorder and Postorder)
Level Order Binary Tree Traversal
Binary Tree | Set 1 (Introduction)
AVL Tree | Set 1 (Insertion)
Print Right View of a Binary Tree
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 Jul, 2021"
},
{
"code": null,
"e": 211,
"s": 54,
"text": "Given a Binary Tree with children Nodes, Return a random Node with equal Probability of selecting any Node in tree.Consider the given tree with root as 1. "
},
{
"code": null,
"e": 277,
"s": 211,
"text": " 10\n / \\\n 20 30\n / \\ / \\\n40 50 60 70"
},
{
"code": null,
"e": 289,
"s": 277,
"text": "Examples: "
},
{
"code": null,
"e": 414,
"s": 289,
"text": "Input : getRandom(root);\nOutput : A Random Node From Tree : 3\n\nInput : getRandom(root);\nOutput : A Random Node From Tree : 2"
},
{
"code": null,
"e": 1020,
"s": 416,
"text": "A simple solution is to store Inorder traversal of tree in an array. Let the count of nodes be n. To get a random node, we generate a random number from 0 to n-1, use this number as index in array and return the value at index.An alternate solution is to modify tree structure. We store count of children in every node. Consider the above tree. We use inorder traversal here also. We generate a number smaller than or equal count of nodes. We traverse tree and go to the node at that index. We use counts to quickly reach the desired node. With counts, we reach in O(h) time where h is height of tree. "
},
{
"code": null,
"e": 1166,
"s": 1020,
"text": " 10,6\n / \\\n 20,2 30,2\n / \\ / \\\n40,0 50,0 60,0 70,0\nThe first value is node and second\nvalue is count of children."
},
{
"code": null,
"e": 1659,
"s": 1166,
"text": "We start traversing the tree, on each node we either go to left subtree or right subtree considering whether the count of children is less than random count or not.If the random count is less than the count of children then we go left else we go right.Below is the implementation of above Algorithm. getElements will return count of children for root, InsertChildrenCount inserts children data to each node, RandomNode return the random node with the help of Utility Function RandomNodeUtil. "
},
{
"code": null,
"e": 1663,
"s": 1659,
"text": "C++"
},
{
"code": null,
"e": 1668,
"s": 1663,
"text": "Java"
},
{
"code": null,
"e": 1676,
"s": 1668,
"text": "Python3"
},
{
"code": null,
"e": 1679,
"s": 1676,
"text": "C#"
},
{
"code": null,
"e": 1690,
"s": 1679,
"text": "Javascript"
},
{
"code": "// CPP program to Select a Random Node from a tree#include <bits/stdc++.h>using namespace std; struct Node { int data; int children; Node *left, *right;}; Node* newNode(int data){ Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; temp->children = 0; return temp;} // This is used to fill children counts.int getElements(Node* root){ if (!root) return 0; return getElements(root->left) + getElements(root->right) + 1;} // Inserts Children count for each nodevoid insertChildrenCount(Node*& root){ if (!root) return; root->children = getElements(root) - 1; insertChildrenCount(root->left); insertChildrenCount(root->right);} // returns number of children for rootint children(Node* root){ if (!root) return 0; return root->children + 1;} // Helper Function to return a random nodeint randomNodeUtil(Node* root, int count){ if (!root) return 0; if (count == children(root->left)) return root->data; if (count < children(root->left)) return randomNodeUtil(root->left, count); return randomNodeUtil(root->right, count - children(root->left) - 1);} // Returns Random nodeint randomNode(Node* root){ srand(time(0)); int count = rand() % (root->children + 1); return randomNodeUtil(root, count);} int main(){ // Creating Above Tree Node* root = newNode(10); root->left = newNode(20); root->right = newNode(30); root->left->right = newNode(40); root->left->right = newNode(50); root->right->left = newNode(60); root->right->right = newNode(70); insertChildrenCount(root); cout << \"A Random Node From Tree : \" << randomNode(root) << endl; return 0;}",
"e": 3437,
"s": 1690,
"text": null
},
{
"code": "// Java program to Select a Random Node from a treeimport java.util.*;import java.lang.*;import java.io.*; class GFG{static class Node{ int data; int children; Node left, right;} static Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; temp.children = 0; return temp;} // This is used to fill children counts.static int getElements(Node root){ if (root == null) return 0; return getElements(root.left) + getElements(root.right) + 1;} // Inserts Children count for each nodestatic Node insertChildrenCount(Node root){ if (root == null) return null; root.children = getElements(root) - 1; root.left = insertChildrenCount(root.left); root.right = insertChildrenCount(root.right); return root;} // returns number of children for rootstatic int children(Node root){ if (root == null) return 0; return root.children + 1;} // Helper Function to return a random nodestatic int randomNodeUtil(Node root, int count){ if (root == null) return 0; if (count == children(root.left)) return root.data; if (count < children(root.left)) return randomNodeUtil(root.left, count); return randomNodeUtil(root.right, count - children(root.left) - 1);} // Returns Random nodestatic int randomNode(Node root){ int count = (int) Math.random() * (root.children + 1); return randomNodeUtil(root, count);} // Driver Codepublic static void main(String args[]){ // Creating Above Tree Node root = newNode(10); root.left = newNode(20); root.right = newNode(30); root.left.right = newNode(40); root.left.right = newNode(50); root.right.left = newNode(60); root.right.right = newNode(70); insertChildrenCount(root); System.out.println( \"A Random Node From Tree : \" + randomNode(root));}} // This code is contributed by Arnab Kundu",
"e": 5405,
"s": 3437,
"text": null
},
{
"code": "# Python3 program to Select a# Random Node from a treefrom random import randint class Node: def __init__(self, data): self.data = data self.children = 0 self.left = None self.right = None # This is used to fill children counts.def getElements(root): if root == None: return 0 return (getElements(root.left) + getElements(root.right) + 1) # Inserts Children count for each nodedef insertChildrenCount(root): if root == None: return root.children = getElements(root) - 1 insertChildrenCount(root.left) insertChildrenCount(root.right) # Returns number of children for rootdef children(root): if root == None: return 0 return root.children + 1 # Helper Function to return a random nodedef randomNodeUtil(root, count): if root == None: return 0 if count == children(root.left): return root.data if count < children(root.left): return randomNodeUtil(root.left, count) return randomNodeUtil(root.right, count - children(root.left) - 1) # Returns Random nodedef randomNode(root): count = randint(0, root.children) return randomNodeUtil(root, count) # Driver Codeif __name__ == \"__main__\": # Creating Above Tree root = Node(10) root.left = Node(20) root.right = Node(30) root.left.right = Node(40) root.left.right = Node(50) root.right.left = Node(60) root.right.right = Node(70) insertChildrenCount(root) print(\"A Random Node From Tree :\", randomNode(root)) # This code is contributed by Rituraj Jain",
"e": 7002,
"s": 5405,
"text": null
},
{
"code": "// C# program to Select a Random Node from a treeusing System; class GFG{ class Node{ public int data; public int children; public Node left, right;} static Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; temp.children = 0; return temp;} // This is used to fill children counts.static int getElements(Node root){ if (root == null) return 0; return getElements(root.left) + getElements(root.right) + 1;} // Inserts Children count for each nodestatic Node insertChildrenCount(Node root){ if (root == null) return null; root.children = getElements(root) - 1; root.left = insertChildrenCount(root.left); root.right = insertChildrenCount(root.right); return root;} // returns number of children for rootstatic int children(Node root){ if (root == null) return 0; return root.children + 1;} // Helper Function to return a random nodestatic int randomNodeUtil(Node root, int count){ if (root == null) return 0; if (count == children(root.left)) return root.data; if (count < children(root.left)) return randomNodeUtil(root.left, count); return randomNodeUtil(root.right, count - children(root.left) - 1);} // Returns Random nodestatic int randomNode(Node root){ int count = (int) new Random().Next(0, root.children + 1); return randomNodeUtil(root, count);} // Driver Codepublic static void Main(String []args){ // Creating Above Tree Node root = newNode(10); root.left = newNode(20); root.right = newNode(30); root.left.right = newNode(40); root.left.right = newNode(50); root.right.left = newNode(60); root.right.right = newNode(70); insertChildrenCount(root); Console.Write( \"A Random Node From Tree : \" + randomNode(root));}} // This code is contributed by Arnab Kundu",
"e": 8923,
"s": 7002,
"text": null
},
{
"code": "<script> // JavaScript program to Select a Random Node from a tree class Node{ constructor(data) { this.data=data; this.left=this.right=null; this.children = 0; }} // This is used to fill children counts.function getElements(root){ if (root == null) return 0; return getElements(root.left) + getElements(root.right) + 1;} // Inserts Children count for each nodefunction insertChildrenCount(root){ if (root == null) return null; root.children = getElements(root) - 1; root.left = insertChildrenCount(root.left); root.right = insertChildrenCount(root.right); return root;} // returns number of children for rootfunction children(root){ if (root == null) return 0; return root.children + 1;} // Helper Function to return a random nodefunction randomNodeUtil(root,count){ if (root == null) return 0; if (count == children(root.left)) return root.data; if (count < children(root.left)) return randomNodeUtil(root.left, count); return randomNodeUtil(root.right, count - children(root.left) - 1);} // Returns Random nodefunction randomNode(root){ let count = Math.floor(Math.random() * (root.children + 1)); return randomNodeUtil(root, count);} // Driver Code// Creating Above Treelet root = new Node(10);root.left = new Node(20);root.right = new Node(30);root.left.right = new Node(40);root.left.right = new Node(50);root.right.left = new Node(60);root.right.right = new Node(70); insertChildrenCount(root); document.write( \"A Random Node From Tree : \" + randomNode(root)+\"<br>\"); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 10644,
"s": 8923,
"text": null
},
{
"code": null,
"e": 10772,
"s": 10644,
"text": "Time Complexity of randomNode is O(h) where h is height of tree. Note that we are either moving to right or to left at a time. "
},
{
"code": null,
"e": 10785,
"s": 10772,
"text": "rituraj_jain"
},
{
"code": null,
"e": 10796,
"s": 10785,
"text": "andrew1234"
},
{
"code": null,
"e": 10817,
"s": 10796,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 10829,
"s": 10817,
"text": "Probability"
},
{
"code": null,
"e": 10840,
"s": 10829,
"text": "Randomized"
},
{
"code": null,
"e": 10845,
"s": 10840,
"text": "Tree"
},
{
"code": null,
"e": 10850,
"s": 10845,
"text": "Tree"
},
{
"code": null,
"e": 10862,
"s": 10850,
"text": "Probability"
},
{
"code": null,
"e": 10960,
"s": 10862,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11016,
"s": 10960,
"text": "Randomized Algorithms | Set 0 (Mathematical Background)"
},
{
"code": null,
"e": 11042,
"s": 11016,
"text": "Binomial Random Variables"
},
{
"code": null,
"e": 11110,
"s": 11042,
"text": "Implement random-0-6-Generator using the given random-0-1-Generator"
},
{
"code": null,
"e": 11183,
"s": 11110,
"text": "Estimating the value of Pi using Monte Carlo | Parallel Computing Method"
},
{
"code": null,
"e": 11238,
"s": 11183,
"text": "Randomized Algorithms | Set 3 (1/2 Approximate Median)"
},
{
"code": null,
"e": 11288,
"s": 11238,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 11322,
"s": 11288,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 11357,
"s": 11322,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 11386,
"s": 11357,
"text": "AVL Tree | Set 1 (Insertion)"
}
] |
Why βusing namespace stdβ is considered bad practice
|
Difficulty Level :
Medium
The statement using namespace std is generally considered bad practice. The alternative to this statement is to specify the namespace to which the identifier belongs using the scope operator(::) each time we declare a type. Although the statement saves us from typing std:: whenever we wish to access a class or type defined in the std namespace, it imports the entirety of the std namespace into the current namespace of the program. Let us take a few examples to understand why this might not be such a good thingLet us say we wish to use the cout from the std namespace. So we write
Example 1:
CPP
#include <iostream>using namespace std; cout << " Something to Display";
Now at a later stage of development, we wish to use another version of cout that is custom implemented in some library called βfooβ (for example)
CPP
#include <foo.h>#include <iostream>using namespace std; cout << " Something to display";
Notice now there is an ambiguity, to which library does cout point to? The compiler may detect this and not compile the program. In the worst case, the program may still compile but call the wrong function, since we never specified to which namespace the identifier belonged.Namespaces were introduced into C++ to resolve identifier name conflicts. This ensured that two objects can have the same name and yet be treated differently if they belonged to different namespaces. Notice how the exact opposite has occurred in this example. Instead of resolving a name conflict, we actually create a naming conflict.
When we import a namespace we are essentially pulling all type definitions into the current scope. The std namespace is huge. It has hundreds of predefined identifiers, so it is possible that a developer may overlook the fact there is another definition of their intended object in the std library. Unaware of this they may proceed to specify their own implementation and expect it to be used in later parts of the program. Thus there would exist two definitions for the same type in the current namespace. This is not allowed in C++, and even if the program compiles there is no way of knowing which definition is being used where.
The solution to the problem is to explicitly specify to which namespace our identifier belongs to using the scope operator (::). Thus one possible solution to the above example can be
CPP
#include <foo>#include <iostream> // Use cout of std librarystd::cout << "Something to display"; // Use cout of foo libraryfoo::cout < "Something to display";
But having to type std:: every time we define a type is tedious. It also makes our code look hairier with lots of type definitions and makes it difficult to read the code. Consider for example the code for getting the current time in the programExample 2:
CPP
#include <chrono>#include <iostream> auto start = std::chrono::high_performance_clock::now() // Do Something auto stop = std::chrono::high_peformance_clock::now();auto duration = std::duration_cast<std::chrono::milliseconds>(stop - start);
The source code that is littered with complicated and long type definitions is not very easy to read. This is something developers seek to avoid since code maintainability is chiefly important to them.There are a few ways to resolve this dilemma i.e specify exact namespace without littering code with std keywords.
Consider using typedefs typedefs save us from writing long type definitions. In our example 1, we could solve the problem using two typedefs one for std library and another for foo
CPP
#include <foo>#include <iostream> typedef std::cout cout_std;typedef foo::cout cout_foo; cout_std << "Something to write";cout_foo << "Something to write";
Instead of importing entire namespaces, import a truncated namespace In example 2 we could have imported only the chrono namespace under std.
CPP
#include <chrono>#include <iostream> // Import only the chrono namespace under stdusing std::chrono; auto start = high_performance_clock::now(); // Do Somethingauto stop = high_performance_clock::now();auto duration duration_cast<milliseconds>(stop - start);
We can also use the statement for importing a single identifier. To import only std::cout we could use
using std::cout;
If you still import entire namespaces, try to do so inside functions or limited scope and not in global scope.Use the βusing namespace stdβ statement inside function definitions or class, struct definitions. In doing so the namespace definitions get imported into a local scope, and we at least know where possible errors may originate if they do arise.
CPP
#include <iostream> // Avoid thisusing namespace std; void foo(){ // Inside function // Use the import statement inside limited scope using namespace std; // Proceed with function}
Conclusion. We have discussed alternative methods for accessing an identifier from a namespace. In all cases avoid importing entire namespaces into the source code.While good coding practices may take some time to learn and develop, they generally pay out in the long run. Writing clean, unambiguous and robust error-free code should be the intent of any programming developer.
akjlucky4all
HannahLim
saipranavkatta
varunmishrak1234
tejaskumar0020
cpp-namespaces
cpp-puzzle
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Templates in C++ with Examples
Operator Overloading in C++
Inheritance in C++
Queue in C++ Standard Template Library (STL)
Virtual Function in C++
unordered_map in C++ STL
Polymorphism in C++
Socket Programming in C/C++
C++ Classes and Objects
|
[
{
"code": null,
"e": 26,
"s": 0,
"text": "Difficulty Level :\nMedium"
},
{
"code": null,
"e": 612,
"s": 26,
"text": "The statement using namespace std is generally considered bad practice. The alternative to this statement is to specify the namespace to which the identifier belongs using the scope operator(::) each time we declare a type. Although the statement saves us from typing std:: whenever we wish to access a class or type defined in the std namespace, it imports the entirety of the std namespace into the current namespace of the program. Let us take a few examples to understand why this might not be such a good thingLet us say we wish to use the cout from the std namespace. So we write"
},
{
"code": null,
"e": 624,
"s": 612,
"text": "Example 1: "
},
{
"code": null,
"e": 628,
"s": 624,
"text": "CPP"
},
{
"code": "#include <iostream>using namespace std; cout << \" Something to Display\";",
"e": 701,
"s": 628,
"text": null
},
{
"code": null,
"e": 848,
"s": 701,
"text": "Now at a later stage of development, we wish to use another version of cout that is custom implemented in some library called βfooβ (for example) "
},
{
"code": null,
"e": 852,
"s": 848,
"text": "CPP"
},
{
"code": "#include <foo.h>#include <iostream>using namespace std; cout << \" Something to display\";",
"e": 941,
"s": 852,
"text": null
},
{
"code": null,
"e": 1552,
"s": 941,
"text": "Notice now there is an ambiguity, to which library does cout point to? The compiler may detect this and not compile the program. In the worst case, the program may still compile but call the wrong function, since we never specified to which namespace the identifier belonged.Namespaces were introduced into C++ to resolve identifier name conflicts. This ensured that two objects can have the same name and yet be treated differently if they belonged to different namespaces. Notice how the exact opposite has occurred in this example. Instead of resolving a name conflict, we actually create a naming conflict."
},
{
"code": null,
"e": 2185,
"s": 1552,
"text": "When we import a namespace we are essentially pulling all type definitions into the current scope. The std namespace is huge. It has hundreds of predefined identifiers, so it is possible that a developer may overlook the fact there is another definition of their intended object in the std library. Unaware of this they may proceed to specify their own implementation and expect it to be used in later parts of the program. Thus there would exist two definitions for the same type in the current namespace. This is not allowed in C++, and even if the program compiles there is no way of knowing which definition is being used where."
},
{
"code": null,
"e": 2370,
"s": 2185,
"text": "The solution to the problem is to explicitly specify to which namespace our identifier belongs to using the scope operator (::). Thus one possible solution to the above example can be "
},
{
"code": null,
"e": 2374,
"s": 2370,
"text": "CPP"
},
{
"code": "#include <foo>#include <iostream> // Use cout of std librarystd::cout << \"Something to display\"; // Use cout of foo libraryfoo::cout < \"Something to display\";",
"e": 2533,
"s": 2374,
"text": null
},
{
"code": null,
"e": 2790,
"s": 2533,
"text": "But having to type std:: every time we define a type is tedious. It also makes our code look hairier with lots of type definitions and makes it difficult to read the code. Consider for example the code for getting the current time in the programExample 2: "
},
{
"code": null,
"e": 2794,
"s": 2790,
"text": "CPP"
},
{
"code": "#include <chrono>#include <iostream> auto start = std::chrono::high_performance_clock::now() // Do Something auto stop = std::chrono::high_peformance_clock::now();auto duration = std::duration_cast<std::chrono::milliseconds>(stop - start);",
"e": 3040,
"s": 2794,
"text": null
},
{
"code": null,
"e": 3356,
"s": 3040,
"text": "The source code that is littered with complicated and long type definitions is not very easy to read. This is something developers seek to avoid since code maintainability is chiefly important to them.There are a few ways to resolve this dilemma i.e specify exact namespace without littering code with std keywords."
},
{
"code": null,
"e": 3537,
"s": 3356,
"text": "Consider using typedefs typedefs save us from writing long type definitions. In our example 1, we could solve the problem using two typedefs one for std library and another for foo"
},
{
"code": null,
"e": 3541,
"s": 3537,
"text": "CPP"
},
{
"code": "#include <foo>#include <iostream> typedef std::cout cout_std;typedef foo::cout cout_foo; cout_std << \"Something to write\";cout_foo << \"Something to write\";",
"e": 3697,
"s": 3541,
"text": null
},
{
"code": null,
"e": 3840,
"s": 3697,
"text": "Instead of importing entire namespaces, import a truncated namespace In example 2 we could have imported only the chrono namespace under std. "
},
{
"code": null,
"e": 3844,
"s": 3840,
"text": "CPP"
},
{
"code": "#include <chrono>#include <iostream> // Import only the chrono namespace under stdusing std::chrono; auto start = high_performance_clock::now(); // Do Somethingauto stop = high_performance_clock::now();auto duration duration_cast<milliseconds>(stop - start);",
"e": 4103,
"s": 3844,
"text": null
},
{
"code": null,
"e": 4207,
"s": 4103,
"text": "We can also use the statement for importing a single identifier. To import only std::cout we could use "
},
{
"code": null,
"e": 4224,
"s": 4207,
"text": "using std::cout;"
},
{
"code": null,
"e": 4578,
"s": 4224,
"text": "If you still import entire namespaces, try to do so inside functions or limited scope and not in global scope.Use the βusing namespace stdβ statement inside function definitions or class, struct definitions. In doing so the namespace definitions get imported into a local scope, and we at least know where possible errors may originate if they do arise."
},
{
"code": null,
"e": 4582,
"s": 4578,
"text": "CPP"
},
{
"code": "#include <iostream> // Avoid thisusing namespace std; void foo(){ // Inside function // Use the import statement inside limited scope using namespace std; // Proceed with function}",
"e": 4776,
"s": 4582,
"text": null
},
{
"code": null,
"e": 5155,
"s": 4776,
"text": "Conclusion. We have discussed alternative methods for accessing an identifier from a namespace. In all cases avoid importing entire namespaces into the source code.While good coding practices may take some time to learn and develop, they generally pay out in the long run. Writing clean, unambiguous and robust error-free code should be the intent of any programming developer. "
},
{
"code": null,
"e": 5168,
"s": 5155,
"text": "akjlucky4all"
},
{
"code": null,
"e": 5178,
"s": 5168,
"text": "HannahLim"
},
{
"code": null,
"e": 5193,
"s": 5178,
"text": "saipranavkatta"
},
{
"code": null,
"e": 5210,
"s": 5193,
"text": "varunmishrak1234"
},
{
"code": null,
"e": 5225,
"s": 5210,
"text": "tejaskumar0020"
},
{
"code": null,
"e": 5240,
"s": 5225,
"text": "cpp-namespaces"
},
{
"code": null,
"e": 5251,
"s": 5240,
"text": "cpp-puzzle"
},
{
"code": null,
"e": 5255,
"s": 5251,
"text": "C++"
},
{
"code": null,
"e": 5259,
"s": 5255,
"text": "CPP"
},
{
"code": null,
"e": 5357,
"s": 5259,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5384,
"s": 5357,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 5415,
"s": 5384,
"text": "Templates in C++ with Examples"
},
{
"code": null,
"e": 5443,
"s": 5415,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 5462,
"s": 5443,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 5507,
"s": 5462,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 5531,
"s": 5507,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 5556,
"s": 5531,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 5576,
"s": 5556,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 5604,
"s": 5576,
"text": "Socket Programming in C/C++"
}
] |
Tailwind CSS Box Sizing - GeeksforGeeks
|
23 Mar, 2022
This class accepts more than one value in tailwind CSS all the properties are covered as in class form. It is the alternative to the CSS box-sizing property. This class is used to defines how the user should calculate the total width and height of an element i.e. padding and borders, are to be included or not.
Box Sizing:
box-border
box-content
box-border: In this mode, the width and height properties include content, padding, and borders i.e. if we set an elementβs width to 200 pixels, that 200 pixels will include any border or padding we added, and the content box will shrink to absorb that extra width. This typically makes it much easier to size elements.
Syntax:
<element class="box-border">..</element>
Example:
HTML
<!DOCTYPE html> <head> <title>Tailwind box-border Class</title> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS box-border Class</b> <div class="box-border h-28 w-32 p-4 border-4 bg-green-500 m4"> A Computer Science Portal </div> </center></body> </html>
Output:
box-content: This is the default value of the box-sizing class. In this mode, the width and height class include only the content. Border and padding are not included in it i.e if we set an elementβs width to 200 pixels, then the elementβs content box will be 200 pixels wide, and the width of any border or padding will be added to the final rendered width.
Syntax:
<element class="box-content">..</element>
Example:
HTML
<!DOCTYPE html> <head> <title>Tailwind box-content Class</title> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS box-content Class</b> <div class="box-content h-28 w-32 p-4 border-4 bg-green-500 m4"> A Computer Science Portal </div> </center></body> </html>
Output:
Tailwind CSS
Tailwind-Layout
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 37411,
"s": 37383,
"text": "\n23 Mar, 2022"
},
{
"code": null,
"e": 37723,
"s": 37411,
"text": "This class accepts more than one value in tailwind CSS all the properties are covered as in class form. It is the alternative to the CSS box-sizing property. This class is used to defines how the user should calculate the total width and height of an element i.e. padding and borders, are to be included or not."
},
{
"code": null,
"e": 37735,
"s": 37723,
"text": "Box Sizing:"
},
{
"code": null,
"e": 37747,
"s": 37735,
"text": "box-border "
},
{
"code": null,
"e": 37760,
"s": 37747,
"text": "box-content "
},
{
"code": null,
"e": 38080,
"s": 37760,
"text": "box-border: In this mode, the width and height properties include content, padding, and borders i.e. if we set an elementβs width to 200 pixels, that 200 pixels will include any border or padding we added, and the content box will shrink to absorb that extra width. This typically makes it much easier to size elements."
},
{
"code": null,
"e": 38088,
"s": 38080,
"text": "Syntax:"
},
{
"code": null,
"e": 38129,
"s": 38088,
"text": "<element class=\"box-border\">..</element>"
},
{
"code": null,
"e": 38138,
"s": 38129,
"text": "Example:"
},
{
"code": null,
"e": 38143,
"s": 38138,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <head> <title>Tailwind box-border Class</title> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS box-border Class</b> <div class=\"box-border h-28 w-32 p-4 border-4 bg-green-500 m4\"> A Computer Science Portal </div> </center></body> </html>",
"e": 38634,
"s": 38143,
"text": null
},
{
"code": null,
"e": 38642,
"s": 38634,
"text": "Output:"
},
{
"code": null,
"e": 39001,
"s": 38642,
"text": "box-content: This is the default value of the box-sizing class. In this mode, the width and height class include only the content. Border and padding are not included in it i.e if we set an elementβs width to 200 pixels, then the elementβs content box will be 200 pixels wide, and the width of any border or padding will be added to the final rendered width."
},
{
"code": null,
"e": 39009,
"s": 39001,
"text": "Syntax:"
},
{
"code": null,
"e": 39051,
"s": 39009,
"text": "<element class=\"box-content\">..</element>"
},
{
"code": null,
"e": 39061,
"s": 39051,
"text": "Example: "
},
{
"code": null,
"e": 39066,
"s": 39061,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <head> <title>Tailwind box-content Class</title> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS box-content Class</b> <div class=\"box-content h-28 w-32 p-4 border-4 bg-green-500 m4\"> A Computer Science Portal </div> </center></body> </html>",
"e": 39560,
"s": 39066,
"text": null
},
{
"code": null,
"e": 39568,
"s": 39560,
"text": "Output:"
},
{
"code": null,
"e": 39581,
"s": 39568,
"text": "Tailwind CSS"
},
{
"code": null,
"e": 39597,
"s": 39581,
"text": "Tailwind-Layout"
},
{
"code": null,
"e": 39601,
"s": 39597,
"text": "CSS"
},
{
"code": null,
"e": 39618,
"s": 39601,
"text": "Web Technologies"
},
{
"code": null,
"e": 39716,
"s": 39618,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39778,
"s": 39716,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 39828,
"s": 39778,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 39876,
"s": 39828,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 39934,
"s": 39876,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 39989,
"s": 39934,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 40029,
"s": 39989,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 40062,
"s": 40029,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 40107,
"s": 40062,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 40150,
"s": 40107,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to Build a Bounce Ball with HTML and JavaScript ? - GeeksforGeeks
|
05 Jul, 2021
Bouncing ball can be created by using HTML, CSS, and JavaScript and perform some bouncing operations on that ball. You can see related article how to make smooth bounce animation using CSS.. This article will be divided into two portions, 1st portion we will decide the area where the bouncing ball will perform bouncing, basically, we will create a canvas where bouncing will be performed. 2nd portion will design the bouncing ball and add some bouncing functionality on it.HTML & CSS code: HTML and CSS code is used to create a canvas area where the ball will bounce. We will use a canvas tag and by using JavaScript we will struct the circle for the ball inside of that canvas. And the canvas area and background color of the canvas area is defined by the CSS.
html
<!DOCTYPE HTML><html> <head> <title> Bouncing Ball!! </title> <style> h1 { color: green; } canvas { background-color: #F08080; width: 600px; height: 400px; position: absolute; top: 20%; left: 20%; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Bouncing ball using JavaScript</h3> <canvas> </canvas> </center></body> </html>
JavaScript code: It is the core part of this article where we will struct the ball and perform the bouncing task. We will assign 4 variables, 2 for the created circle(ball) coordinates and others two for the respective speed of the bouncing ball. The radius variable is used for the ballβs radius. We also need to clear the canvas area to do so we will use the clearReact() function. All the bouncing and coordinate will decided by the math.random() function.
javascript
<script> var canvas = document.querySelector("canvas"); canvas.width = window.innerWidth; canvas.height = window.innerHeight; var l = canvas.getContext('2d'); // x and y are the coordinates of the circle // vx and vy are the respective speeds var x = Math.floor(Math.random() * innerWidth); var y = Math.floor(Math.random() * innerHeight); var vx = Math.floor(Math.random() * 2); var vy = Math.floor(Math.random() * 4); var radius = 20; move(); // This function will do the animation function move() { requestAnimationFrame(move); // It clears the specified pixels within // the given rectangle l.clearRect(0, 0, innerWidth, innerHeight); // Creating a circle l.beginPath(); l.strokeStyle = "black"; l.arc(x, y, radius, 0, Math.PI * 2, false); l.stroke(); // Conditions so that the ball bounces // from the edges if (radius + x > innerWidth) vx = 0 - vx; if (x - radius < 0) vx = 0 - vx; if (y + radius > innerHeight) vy = 0 - vy; if (y - radius < 0) vy = 0 - vy; x = x + vx; y = y + vy; }</script>
Complete code: It is the combination of above two sections i.e. combining HTML, CSS and JavaScript code. This code will create an output where a design vall will bounce in random pattern.
html
<!DOCTYPE HTML><html> <head> <title> Bouncing Ball!! </title> <style> h1 { color: green; } canvas { background-color: #F08080; width: 600px; height: 400px; position: absolute; top: 20%; left: 20%; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Bouncing ball using JavaScript</h3> <canvas> </canvas> <script> var canvas = document.querySelector("canvas"); canvas.width = window.innerWidth; canvas.height = window.innerHeight; var l = canvas.getContext('2d'); // x and y are the co-ordinates of the circle // vx and vy are the respective speeds var x = Math.floor(Math.random() * innerWidth); var y = Math.floor(Math.random() * innerHeight); var vx = Math.floor(Math.random() * 2); var vy = Math.floor(Math.random() * 4); var radius = 20; move(); // This function will do the animation function move() { requestAnimationFrame(move); // It clears the specified pixels within // the given rectangle l.clearRect(0, 0, innerWidth, innerHeight); // Creating a circle l.beginPath(); l.strokeStyle = "black"; l.arc(x, y, radius, 0, Math.PI * 2, false); l.stroke(); // Conditions sso that the ball bounces // from the edges if (radius + x > innerWidth) vx = 0 - vx; if (x - radius < 0) vx = 0 - vx; if (y + radius > innerHeight) vy = 0 - vy; if (y - radius < 0) vy = 0 - vy; x = x + vx; y = y + vy; } </script> </center></body> </html>
Output:
as5853535
CSS-Misc
HTML-Canvas
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to apply style to parent if it has child with CSS?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
How to set space between the flexbox ?
Design a web page using HTML and CSS
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
|
[
{
"code": null,
"e": 26441,
"s": 26413,
"text": "\n05 Jul, 2021"
},
{
"code": null,
"e": 27206,
"s": 26441,
"text": "Bouncing ball can be created by using HTML, CSS, and JavaScript and perform some bouncing operations on that ball. You can see related article how to make smooth bounce animation using CSS.. This article will be divided into two portions, 1st portion we will decide the area where the bouncing ball will perform bouncing, basically, we will create a canvas where bouncing will be performed. 2nd portion will design the bouncing ball and add some bouncing functionality on it.HTML & CSS code: HTML and CSS code is used to create a canvas area where the ball will bounce. We will use a canvas tag and by using JavaScript we will struct the circle for the ball inside of that canvas. And the canvas area and background color of the canvas area is defined by the CSS. "
},
{
"code": null,
"e": 27211,
"s": 27206,
"text": "html"
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Bouncing Ball!! </title> <style> h1 { color: green; } canvas { background-color: #F08080; width: 600px; height: 400px; position: absolute; top: 20%; left: 20%; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Bouncing ball using JavaScript</h3> <canvas> </canvas> </center></body> </html>",
"e": 27716,
"s": 27211,
"text": null
},
{
"code": null,
"e": 28177,
"s": 27716,
"text": "JavaScript code: It is the core part of this article where we will struct the ball and perform the bouncing task. We will assign 4 variables, 2 for the created circle(ball) coordinates and others two for the respective speed of the bouncing ball. The radius variable is used for the ballβs radius. We also need to clear the canvas area to do so we will use the clearReact() function. All the bouncing and coordinate will decided by the math.random() function. "
},
{
"code": null,
"e": 28188,
"s": 28177,
"text": "javascript"
},
{
"code": "<script> var canvas = document.querySelector(\"canvas\"); canvas.width = window.innerWidth; canvas.height = window.innerHeight; var l = canvas.getContext('2d'); // x and y are the coordinates of the circle // vx and vy are the respective speeds var x = Math.floor(Math.random() * innerWidth); var y = Math.floor(Math.random() * innerHeight); var vx = Math.floor(Math.random() * 2); var vy = Math.floor(Math.random() * 4); var radius = 20; move(); // This function will do the animation function move() { requestAnimationFrame(move); // It clears the specified pixels within // the given rectangle l.clearRect(0, 0, innerWidth, innerHeight); // Creating a circle l.beginPath(); l.strokeStyle = \"black\"; l.arc(x, y, radius, 0, Math.PI * 2, false); l.stroke(); // Conditions so that the ball bounces // from the edges if (radius + x > innerWidth) vx = 0 - vx; if (x - radius < 0) vx = 0 - vx; if (y + radius > innerHeight) vy = 0 - vy; if (y - radius < 0) vy = 0 - vy; x = x + vx; y = y + vy; }</script>",
"e": 29410,
"s": 28188,
"text": null
},
{
"code": null,
"e": 29599,
"s": 29410,
"text": "Complete code: It is the combination of above two sections i.e. combining HTML, CSS and JavaScript code. This code will create an output where a design vall will bounce in random pattern. "
},
{
"code": null,
"e": 29604,
"s": 29599,
"text": "html"
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Bouncing Ball!! </title> <style> h1 { color: green; } canvas { background-color: #F08080; width: 600px; height: 400px; position: absolute; top: 20%; left: 20%; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Bouncing ball using JavaScript</h3> <canvas> </canvas> <script> var canvas = document.querySelector(\"canvas\"); canvas.width = window.innerWidth; canvas.height = window.innerHeight; var l = canvas.getContext('2d'); // x and y are the co-ordinates of the circle // vx and vy are the respective speeds var x = Math.floor(Math.random() * innerWidth); var y = Math.floor(Math.random() * innerHeight); var vx = Math.floor(Math.random() * 2); var vy = Math.floor(Math.random() * 4); var radius = 20; move(); // This function will do the animation function move() { requestAnimationFrame(move); // It clears the specified pixels within // the given rectangle l.clearRect(0, 0, innerWidth, innerHeight); // Creating a circle l.beginPath(); l.strokeStyle = \"black\"; l.arc(x, y, radius, 0, Math.PI * 2, false); l.stroke(); // Conditions sso that the ball bounces // from the edges if (radius + x > innerWidth) vx = 0 - vx; if (x - radius < 0) vx = 0 - vx; if (y + radius > innerHeight) vy = 0 - vy; if (y - radius < 0) vy = 0 - vy; x = x + vx; y = y + vy; } </script> </center></body> </html>",
"e": 31647,
"s": 29604,
"text": null
},
{
"code": null,
"e": 31657,
"s": 31647,
"text": "Output: "
},
{
"code": null,
"e": 31669,
"s": 31659,
"text": "as5853535"
},
{
"code": null,
"e": 31678,
"s": 31669,
"text": "CSS-Misc"
},
{
"code": null,
"e": 31690,
"s": 31678,
"text": "HTML-Canvas"
},
{
"code": null,
"e": 31700,
"s": 31690,
"text": "HTML-Misc"
},
{
"code": null,
"e": 31716,
"s": 31700,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 31720,
"s": 31716,
"text": "CSS"
},
{
"code": null,
"e": 31725,
"s": 31720,
"text": "HTML"
},
{
"code": null,
"e": 31736,
"s": 31725,
"text": "JavaScript"
},
{
"code": null,
"e": 31753,
"s": 31736,
"text": "Web Technologies"
},
{
"code": null,
"e": 31780,
"s": 31753,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 31785,
"s": 31780,
"text": "HTML"
},
{
"code": null,
"e": 31883,
"s": 31785,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31938,
"s": 31883,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 31975,
"s": 31938,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 32039,
"s": 31975,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 32078,
"s": 32039,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 32115,
"s": 32078,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 32175,
"s": 32115,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 32228,
"s": 32175,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 32289,
"s": 32228,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 32313,
"s": 32289,
"text": "REST API (Introduction)"
}
] |
Python - Blood Cell Identification using Image Processing - GeeksforGeeks
|
28 Oct, 2021
Detection of White Blood Cell and Red Blood Cell is very useful for various medical applications, like counting of WBC, disease diagnosis, etc. Circle detection is the most suitable approach. This article is the implementation of suitable image segmentation and feature extraction techniques for blood cell identification, on the obtained enhanced images. For explaining the working and use of Image Enhancement and Edge Detection, this article is using the image: Input :
Original Blood Smear Microscopic Image
Code: Python Code for Image Enhancement
Python3
import numpy as npimport cv2import matplotlib.pyplot as plt # read original imageimage = cv2.imread("c1.png") # convert to gray scale imagegray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)cv2.imwrite('gray.png', gray) # apply median filter for smoothningblurM = cv2.medianBlur(gray, 5)cv2.imwrite('blurM.png', blurM) # apply gaussian filter for smoothningblurG = cv2.GaussianBlur(gray, (9, 9), 0)cv2.imwrite('blurG.png', blurG) # histogram equalizationhistoNorm = cv2.equalizeHist(gray)cv2.imwrite('histoNorm.png', histoNorm) # create a CLAHE object for# Contrast Limited Adaptive Histogram Equalization (CLAHE)clahe = cv2.createCLAHE(clipLimit = 2.0, tileGridSize=(8, 8))claheNorm = clahe.apply(gray)cv2.imwrite('claheNorm.png', claheNorm) # contrast stretching# Function to map each intensity level to output intensity level.def pixelVal(pix, r1, s1, r2, s2): if (0 <= pix and pix <= r1): return (s1 / r1) * pix elif (r1 < pix and pix <= r2): return ((s2 - s1) / (r2 - r1)) * (pix - r1) + s1 else: return ((255 - s2) / (255 - r2)) * (pix - r2) + s2 # Define parameters. r1 = 70s1 = 0r2 = 200s2 = 255 # Vectorize the function to apply it to each value in the Numpy array.pixelVal_vec = np.vectorize(pixelVal) # Apply contrast stretching.contrast_stretched = pixelVal_vec(gray, r1, s1, r2, s2)contrast_stretched_blurM = pixelVal_vec(blurM, r1, s1, r2, s2) cv2.imwrite('contrast_stretch.png', contrast_stretched)cv2.imwrite('contrast_stretch_blurM.png', contrast_stretched_blurM) # edge detection using canny edge detectoredge = cv2.Canny(gray, 100, 200)cv2.imwrite('edge.png', edge) edgeG = cv2.Canny(blurG, 100, 200)cv2.imwrite('edgeG.png', edgeG) edgeM = cv2.Canny(blurM, 100, 200)cv2.imwrite('edgeM.png', edgeM)
Output Enhanced Images:
Gray Scale Image
Median Filtered Image
Gaussian Filtered Image
Histogram Equalized Image
CLAHE Normalized Image
Contrast Stretched Image
Contrast Stretching on Median Filtered Image
Canny Edge Detection on Gaussian Filtered Image
Canny Edge Detection on Median Filtered Image
Image Segmentation and Feature Extraction
Python3
# read enhanced imageimg = cv2.imread('cell.png', 0) # morphological operationskernel = np.ones((5, 5), np.uint8)dilation = cv2.dilate(img, kernel, iterations = 1)closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel) # Adaptive thresholding on mean and gaussian filterth2 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, \ cv2.THRESH_BINARY, 11, 2)th3 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, \ cv2.THRESH_BINARY, 11, 2)# Otsu's thresholdingret4, th4 = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # Initialize the listCell_count, x_count, y_count = [], [], [] # read original image, to display the circle and center detection display = cv2.imread("D:/Projects / ImageProcessing / DA1 / sample1 / cellOrig.png") # hough transform with modified circular parameterscircles = cv2.HoughCircles(image, cv2.HOUGH_GRADIENT, 1.2, 20, param1 = 50, param2 = 28, minRadius = 1, maxRadius = 20) # circle detection and labeling using hough transformationif circles is not None: # convert the (x, y) coordinates and radius of the circles to integers circles = np.round(circles[0, :]).astype("int") # loop over the (x, y) coordinates and radius of the circles for (x, y, r) in circles: cv2.circle(display, (x, y), r, (0, 255, 0), 2) cv2.rectangle(display, (x - 2, y - 2), (x + 2, y + 2), (0, 128, 255), -1) Cell_count.append(r) x_count.append(x) y_count.append(y) # show the output image cv2.imshow("gray", display) cv2.waitKey(0) # display the count of white blood cellsprint(len(Cell_count))# Total number of radiusprint(Cell_count)# X co-ordinate of circleprint(x_count) # Y co-ordinate of circleprint(y_count)
Output Images:
Blood Cell Detectionq
Closing
Dilation
Adaptive Thresholding
Modified Haugh Transformation for circle detection
Summary of complete process
simmytarika5
sagar0719kumar
Image-Processing
OpenCV
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": 25561,
"s": 25533,
"text": "\n28 Oct, 2021"
},
{
"code": null,
"e": 26036,
"s": 25561,
"text": "Detection of White Blood Cell and Red Blood Cell is very useful for various medical applications, like counting of WBC, disease diagnosis, etc. Circle detection is the most suitable approach. This article is the implementation of suitable image segmentation and feature extraction techniques for blood cell identification, on the obtained enhanced images. For explaining the working and use of Image Enhancement and Edge Detection, this article is using the image: Input : "
},
{
"code": null,
"e": 26075,
"s": 26036,
"text": "Original Blood Smear Microscopic Image"
},
{
"code": null,
"e": 26117,
"s": 26075,
"text": "Code: Python Code for Image Enhancement "
},
{
"code": null,
"e": 26125,
"s": 26117,
"text": "Python3"
},
{
"code": "import numpy as npimport cv2import matplotlib.pyplot as plt # read original imageimage = cv2.imread(\"c1.png\") # convert to gray scale imagegray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)cv2.imwrite('gray.png', gray) # apply median filter for smoothningblurM = cv2.medianBlur(gray, 5)cv2.imwrite('blurM.png', blurM) # apply gaussian filter for smoothningblurG = cv2.GaussianBlur(gray, (9, 9), 0)cv2.imwrite('blurG.png', blurG) # histogram equalizationhistoNorm = cv2.equalizeHist(gray)cv2.imwrite('histoNorm.png', histoNorm) # create a CLAHE object for# Contrast Limited Adaptive Histogram Equalization (CLAHE)clahe = cv2.createCLAHE(clipLimit = 2.0, tileGridSize=(8, 8))claheNorm = clahe.apply(gray)cv2.imwrite('claheNorm.png', claheNorm) # contrast stretching# Function to map each intensity level to output intensity level.def pixelVal(pix, r1, s1, r2, s2): if (0 <= pix and pix <= r1): return (s1 / r1) * pix elif (r1 < pix and pix <= r2): return ((s2 - s1) / (r2 - r1)) * (pix - r1) + s1 else: return ((255 - s2) / (255 - r2)) * (pix - r2) + s2 # Define parameters. r1 = 70s1 = 0r2 = 200s2 = 255 # Vectorize the function to apply it to each value in the Numpy array.pixelVal_vec = np.vectorize(pixelVal) # Apply contrast stretching.contrast_stretched = pixelVal_vec(gray, r1, s1, r2, s2)contrast_stretched_blurM = pixelVal_vec(blurM, r1, s1, r2, s2) cv2.imwrite('contrast_stretch.png', contrast_stretched)cv2.imwrite('contrast_stretch_blurM.png', contrast_stretched_blurM) # edge detection using canny edge detectoredge = cv2.Canny(gray, 100, 200)cv2.imwrite('edge.png', edge) edgeG = cv2.Canny(blurG, 100, 200)cv2.imwrite('edgeG.png', edgeG) edgeM = cv2.Canny(blurM, 100, 200)cv2.imwrite('edgeM.png', edgeM)",
"e": 27884,
"s": 26125,
"text": null
},
{
"code": null,
"e": 27910,
"s": 27884,
"text": "Output Enhanced Images: "
},
{
"code": null,
"e": 27927,
"s": 27910,
"text": "Gray Scale Image"
},
{
"code": null,
"e": 27951,
"s": 27929,
"text": "Median Filtered Image"
},
{
"code": null,
"e": 27977,
"s": 27953,
"text": "Gaussian Filtered Image"
},
{
"code": null,
"e": 28005,
"s": 27979,
"text": "Histogram Equalized Image"
},
{
"code": null,
"e": 28030,
"s": 28007,
"text": "CLAHE Normalized Image"
},
{
"code": null,
"e": 28057,
"s": 28032,
"text": "Contrast Stretched Image"
},
{
"code": null,
"e": 28104,
"s": 28059,
"text": "Contrast Stretching on Median Filtered Image"
},
{
"code": null,
"e": 28154,
"s": 28106,
"text": "Canny Edge Detection on Gaussian Filtered Image"
},
{
"code": null,
"e": 28202,
"s": 28156,
"text": "Canny Edge Detection on Median Filtered Image"
},
{
"code": null,
"e": 28246,
"s": 28202,
"text": "Image Segmentation and Feature Extraction "
},
{
"code": null,
"e": 28254,
"s": 28246,
"text": "Python3"
},
{
"code": "# read enhanced imageimg = cv2.imread('cell.png', 0) # morphological operationskernel = np.ones((5, 5), np.uint8)dilation = cv2.dilate(img, kernel, iterations = 1)closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel) # Adaptive thresholding on mean and gaussian filterth2 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, \\ cv2.THRESH_BINARY, 11, 2)th3 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, \\ cv2.THRESH_BINARY, 11, 2)# Otsu's thresholdingret4, th4 = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # Initialize the listCell_count, x_count, y_count = [], [], [] # read original image, to display the circle and center detection display = cv2.imread(\"D:/Projects / ImageProcessing / DA1 / sample1 / cellOrig.png\") # hough transform with modified circular parameterscircles = cv2.HoughCircles(image, cv2.HOUGH_GRADIENT, 1.2, 20, param1 = 50, param2 = 28, minRadius = 1, maxRadius = 20) # circle detection and labeling using hough transformationif circles is not None: # convert the (x, y) coordinates and radius of the circles to integers circles = np.round(circles[0, :]).astype(\"int\") # loop over the (x, y) coordinates and radius of the circles for (x, y, r) in circles: cv2.circle(display, (x, y), r, (0, 255, 0), 2) cv2.rectangle(display, (x - 2, y - 2), (x + 2, y + 2), (0, 128, 255), -1) Cell_count.append(r) x_count.append(x) y_count.append(y) # show the output image cv2.imshow(\"gray\", display) cv2.waitKey(0) # display the count of white blood cellsprint(len(Cell_count))# Total number of radiusprint(Cell_count)# X co-ordinate of circleprint(x_count) # Y co-ordinate of circleprint(y_count) ",
"e": 30123,
"s": 28254,
"text": null
},
{
"code": null,
"e": 30139,
"s": 30123,
"text": "Output Images: "
},
{
"code": null,
"e": 30161,
"s": 30139,
"text": "Blood Cell Detectionq"
},
{
"code": null,
"e": 30171,
"s": 30163,
"text": "Closing"
},
{
"code": null,
"e": 30182,
"s": 30173,
"text": "Dilation"
},
{
"code": null,
"e": 30206,
"s": 30184,
"text": "Adaptive Thresholding"
},
{
"code": null,
"e": 30259,
"s": 30208,
"text": "Modified Haugh Transformation for circle detection"
},
{
"code": null,
"e": 30289,
"s": 30259,
"text": "Summary of complete process "
},
{
"code": null,
"e": 30304,
"s": 30291,
"text": "simmytarika5"
},
{
"code": null,
"e": 30319,
"s": 30304,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 30336,
"s": 30319,
"text": "Image-Processing"
},
{
"code": null,
"e": 30343,
"s": 30336,
"text": "OpenCV"
},
{
"code": null,
"e": 30350,
"s": 30343,
"text": "Python"
},
{
"code": null,
"e": 30448,
"s": 30350,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30480,
"s": 30448,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30522,
"s": 30480,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30564,
"s": 30522,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30591,
"s": 30564,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 30647,
"s": 30591,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30669,
"s": 30647,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 30708,
"s": 30669,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 30739,
"s": 30708,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30768,
"s": 30739,
"text": "Create a directory in Python"
}
] |
Matplotlib.pyplot.colorbar() function in Python - GeeksforGeeks
|
11 Dec, 2020
Colorbars are a visualization of the mapping from scalar values to colors. In Matplotlib they are drawn into a dedicated axis.
Note: Colorbars are typically created through Figure.colorbar or its pyplot wrapper pyplot.colorbar, which uses make_axes and Colorbar internally. As an end-user, you most likely wonβt have to call the methods or instantiate the classes in this module explicitly.
The colorbar() function in pyplot module of matplotlib adds a colorbar to a plot indicating the color scale.
Syntax:matplotlib.pyplot.colorbar(mappable=None, cax=None, ax=None, **kwarg)
Parameters:
ax: This parameter is an optional parameter and it contains Axes or list of Axes.
**kwarg(keyword arguments): This parameter is an optional parameter and are of two kinds:
colorbar properties:
extend:{βneitherβ, βbothβ, βminβ, βmaxβ} makes pointed end(s) for out-of-rangevalues.
label:The label on the colorbarβs long axis.
ticks:None or list of ticks or Locator.
Returns:colorbar which is an instance of the class βmatplotlib.colorbar.Colorbarβ.
Below examples illustrate the matplotlib.pyplot.colorbar() function in matplotlib.pyplot:
Example #1: To Add a horizontal colorbar to a scatterplot.
Python3
# Python Program illustrating# pyplot.colorbar() methodimport numpy as npimport matplotlib.pyplot as plt # Dataset# List of total number of items purchased # from each productspurchaseCount = [100, 200, 150, 23, 30, 50, 156, 32, 67, 89] # List of total likes of 10 productslikes = [50, 70, 100, 10, 10, 34, 56, 18, 35, 45] # List of Like/Dislike ratio of 10 productsratio = [1, 0.53, 2, 0.76, 0.5, 2.125, 0.56, 1.28, 1.09, 1.02] # scatterplotplt.scatter(x=purchaseCount, y=likes, c=ratio, cmap="summer") plt.colorbar(label="Like/Dislike Ratio", orientation="horizontal")plt.show()
Output:
Example #2: To Add a single colorbar to multiple subplots.
Python3
# Python Program illustrating# pyplot.colorbar() methodimport matplotlib.pyplot as plt # creates four Axesfig, axes = plt.subplots(nrows=2, ncols=2) for ax in axes.flat: im = ax.imshow(np.random.random((10, 10)), vmin=0, vmax=1) plt.colorbar(im, ax=axes.ravel().tolist()) plt.show()
Output:
Example #3: To Add colorbar to a non-mappable object.
Python3
# Python Program illustrating# pyplot.colorbar() methodimport numpy as npimport matplotlib as mplimport matplotlib.pyplot as plt x = np.linspace(0, 5, 100)N = 7 # colormapcmap = plt.get_cmap('jet', N) fig, ax1 = plt.subplots(1, 1, figsize=(8, 6)) for i, n in enumerate(np.linspace(0, 2, N)): y = x*i+n ax1.plot(x, y, c=cmap(i)) plt.xlabel('x-axis')plt.ylabel('y-axis') # Normalizernorm = mpl.colors.Normalize(vmin=0, vmax=2) # creating ScalarMappablesm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)sm.set_array([]) plt.colorbar(sm, ticks=np.linspace(0, 2, N)) plt.show()
Output:
Python-matplotlib
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 26231,
"s": 26203,
"text": "\n11 Dec, 2020"
},
{
"code": null,
"e": 26358,
"s": 26231,
"text": "Colorbars are a visualization of the mapping from scalar values to colors. In Matplotlib they are drawn into a dedicated axis."
},
{
"code": null,
"e": 26622,
"s": 26358,
"text": "Note: Colorbars are typically created through Figure.colorbar or its pyplot wrapper pyplot.colorbar, which uses make_axes and Colorbar internally. As an end-user, you most likely wonβt have to call the methods or instantiate the classes in this module explicitly."
},
{
"code": null,
"e": 26731,
"s": 26622,
"text": "The colorbar() function in pyplot module of matplotlib adds a colorbar to a plot indicating the color scale."
},
{
"code": null,
"e": 26808,
"s": 26731,
"text": "Syntax:matplotlib.pyplot.colorbar(mappable=None, cax=None, ax=None, **kwarg)"
},
{
"code": null,
"e": 26820,
"s": 26808,
"text": "Parameters:"
},
{
"code": null,
"e": 26902,
"s": 26820,
"text": "ax: This parameter is an optional parameter and it contains Axes or list of Axes."
},
{
"code": null,
"e": 26995,
"s": 26902,
"text": "**kwarg(keyword arguments): This parameter is an optional parameter and are of two kinds: "
},
{
"code": null,
"e": 27016,
"s": 26995,
"text": "colorbar properties:"
},
{
"code": null,
"e": 27105,
"s": 27016,
"text": "extend:{βneitherβ, βbothβ, βminβ, βmaxβ} makes pointed end(s) for out-of-rangevalues. "
},
{
"code": null,
"e": 27152,
"s": 27105,
"text": "label:The label on the colorbarβs long axis. "
},
{
"code": null,
"e": 27197,
"s": 27152,
"text": "ticks:None or list of ticks or Locator. "
},
{
"code": null,
"e": 27286,
"s": 27197,
"text": "Returns:colorbar which is an instance of the class βmatplotlib.colorbar.Colorbarβ. "
},
{
"code": null,
"e": 27376,
"s": 27286,
"text": "Below examples illustrate the matplotlib.pyplot.colorbar() function in matplotlib.pyplot:"
},
{
"code": null,
"e": 27435,
"s": 27376,
"text": "Example #1: To Add a horizontal colorbar to a scatterplot."
},
{
"code": null,
"e": 27443,
"s": 27435,
"text": "Python3"
},
{
"code": "# Python Program illustrating# pyplot.colorbar() methodimport numpy as npimport matplotlib.pyplot as plt # Dataset# List of total number of items purchased # from each productspurchaseCount = [100, 200, 150, 23, 30, 50, 156, 32, 67, 89] # List of total likes of 10 productslikes = [50, 70, 100, 10, 10, 34, 56, 18, 35, 45] # List of Like/Dislike ratio of 10 productsratio = [1, 0.53, 2, 0.76, 0.5, 2.125, 0.56, 1.28, 1.09, 1.02] # scatterplotplt.scatter(x=purchaseCount, y=likes, c=ratio, cmap=\"summer\") plt.colorbar(label=\"Like/Dislike Ratio\", orientation=\"horizontal\")plt.show()",
"e": 28054,
"s": 27443,
"text": null
},
{
"code": null,
"e": 28062,
"s": 28054,
"text": "Output:"
},
{
"code": null,
"e": 28121,
"s": 28062,
"text": "Example #2: To Add a single colorbar to multiple subplots."
},
{
"code": null,
"e": 28129,
"s": 28121,
"text": "Python3"
},
{
"code": "# Python Program illustrating# pyplot.colorbar() methodimport matplotlib.pyplot as plt # creates four Axesfig, axes = plt.subplots(nrows=2, ncols=2) for ax in axes.flat: im = ax.imshow(np.random.random((10, 10)), vmin=0, vmax=1) plt.colorbar(im, ax=axes.ravel().tolist()) plt.show()",
"e": 28419,
"s": 28129,
"text": null
},
{
"code": null,
"e": 28427,
"s": 28419,
"text": "Output:"
},
{
"code": null,
"e": 28481,
"s": 28427,
"text": "Example #3: To Add colorbar to a non-mappable object."
},
{
"code": null,
"e": 28489,
"s": 28481,
"text": "Python3"
},
{
"code": "# Python Program illustrating# pyplot.colorbar() methodimport numpy as npimport matplotlib as mplimport matplotlib.pyplot as plt x = np.linspace(0, 5, 100)N = 7 # colormapcmap = plt.get_cmap('jet', N) fig, ax1 = plt.subplots(1, 1, figsize=(8, 6)) for i, n in enumerate(np.linspace(0, 2, N)): y = x*i+n ax1.plot(x, y, c=cmap(i)) plt.xlabel('x-axis')plt.ylabel('y-axis') # Normalizernorm = mpl.colors.Normalize(vmin=0, vmax=2) # creating ScalarMappablesm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)sm.set_array([]) plt.colorbar(sm, ticks=np.linspace(0, 2, N)) plt.show()",
"e": 29077,
"s": 28489,
"text": null
},
{
"code": null,
"e": 29085,
"s": 29077,
"text": "Output:"
},
{
"code": null,
"e": 29103,
"s": 29085,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 29127,
"s": 29103,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 29134,
"s": 29127,
"text": "Python"
},
{
"code": null,
"e": 29153,
"s": 29134,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29251,
"s": 29153,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29269,
"s": 29251,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29304,
"s": 29269,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29336,
"s": 29304,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29358,
"s": 29336,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29400,
"s": 29358,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29430,
"s": 29400,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29456,
"s": 29430,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29485,
"s": 29456,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 29529,
"s": 29485,
"text": "Reading and Writing to text files in Python"
}
] |
Compute Cumulative Chi Square Density in R Programming - pchisq() Function - GeeksforGeeks
|
25 Jun, 2020
pchisq() function in R Language is used to compute cumulative chi square density for a vector of elements. It also creates a density plot for chi square cumulative distribution.
Syntax: pchisq(vec, df)
Parameters:vec: Vector of x-valuesdf: Degree of Freedom
Example 1:
# R program to compute # Cumulative Chi Square Density # Create a vector of x-valuesx <- seq(0, 10, by = 1) # Calling pchisq() Functiony <- pchisq(x, df = 5)y
Output:
[1] 0.00000000 0.03743423 0.15085496 0.30001416 0.45058405 0.58411981
[7] 0.69378108 0.77935969 0.84376437 0.89093584 0.92476475
Example 2:
# R program to compute # Cumulative Chi Square Density # Create a vector of x-valuesx <- seq(0, 10, by = 0.1) # Calling pchisq() Functiony <- pchisq(x, df = 5) # Plot a graph plot(y)
Output:
R-Statistics
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 filter R dataframe by multiple conditions?
Plot mean and standard deviation using ggplot2 in R
How to import an Excel File into R ?
|
[
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n25 Jun, 2020"
},
{
"code": null,
"e": 26665,
"s": 26487,
"text": "pchisq() function in R Language is used to compute cumulative chi square density for a vector of elements. It also creates a density plot for chi square cumulative distribution."
},
{
"code": null,
"e": 26689,
"s": 26665,
"text": "Syntax: pchisq(vec, df)"
},
{
"code": null,
"e": 26745,
"s": 26689,
"text": "Parameters:vec: Vector of x-valuesdf: Degree of Freedom"
},
{
"code": null,
"e": 26756,
"s": 26745,
"text": "Example 1:"
},
{
"code": "# R program to compute # Cumulative Chi Square Density # Create a vector of x-valuesx <- seq(0, 10, by = 1) # Calling pchisq() Functiony <- pchisq(x, df = 5)y",
"e": 26917,
"s": 26756,
"text": null
},
{
"code": null,
"e": 26925,
"s": 26917,
"text": "Output:"
},
{
"code": null,
"e": 27057,
"s": 26925,
"text": " [1] 0.00000000 0.03743423 0.15085496 0.30001416 0.45058405 0.58411981\n [7] 0.69378108 0.77935969 0.84376437 0.89093584 0.92476475\n"
},
{
"code": null,
"e": 27068,
"s": 27057,
"text": "Example 2:"
},
{
"code": "# R program to compute # Cumulative Chi Square Density # Create a vector of x-valuesx <- seq(0, 10, by = 0.1) # Calling pchisq() Functiony <- pchisq(x, df = 5) # Plot a graph plot(y)",
"e": 27254,
"s": 27068,
"text": null
},
{
"code": null,
"e": 27262,
"s": 27254,
"text": "Output:"
},
{
"code": null,
"e": 27275,
"s": 27262,
"text": "R-Statistics"
},
{
"code": null,
"e": 27286,
"s": 27275,
"text": "R Language"
},
{
"code": null,
"e": 27384,
"s": 27286,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27436,
"s": 27384,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27471,
"s": 27436,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27509,
"s": 27471,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 27567,
"s": 27509,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27610,
"s": 27567,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 27659,
"s": 27610,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 27676,
"s": 27659,
"text": "R - if statement"
},
{
"code": null,
"e": 27726,
"s": 27676,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 27778,
"s": 27726,
"text": "Plot mean and standard deviation using ggplot2 in R"
}
] |
Modify Numpy array to store an arbitrary length string - GeeksforGeeks
|
06 Mar, 2019
NumPy builds on (and is a successor to) the successful Numeric array object. Its goal is to create the corner-stone for a useful environment for scientific computing. NumPy provides two fundamental objects: an N-dimensional array object (ndarray) and a universal function object (ufunc).
The dtype of any numpy array containing string values is the maximum length of any string present in the array. Once set, it will only be able to store new string having length not more than the maximum length at the time of the creation. If we try to reassign some another string value having length greater than the maximum length of the existing elements, it simply discards all the values beyond the maximum length.
In this post we are going to discuss ways in which we can overcome this problem and create a numpy array of arbitrary length.
Letβs first visualize the problem with creating an arbitrary length numpy array of string type.
# importing numpy as npimport numpy as np # Create the numpy arraycountry = np.array(['USA', 'Japan', 'UK', '', 'India', 'China']) # Print the arrayprint(country)
Output :
As we can see in the output, the maximum length of any string length element in the given array is 5. Letβs try to assign a value having greater length at the place of missing value in the array.
# Assign 'New Zealand' at the place of missing valuecountry[country == ''] = 'New Zealand' # Print the modified arrayprint(country)
Output :
As we can see in the output, βNew Zβ has been assigned rather than βNew Zealandβ because of the limitation to the length. Now, letβs see the ways in which we can overcome this problem.
Problem #1 : Create a numpy array of arbitrary length.
Solution : While creating the array assign the βobjectβ dtype to it. This lets you have all the behaviors of the python string.
# importing the numpy library as npimport numpy as np # Create a numpy array# set the dtype to objectcountry = np.array(['USA', 'Japan', 'UK', '', 'India', 'China'], dtype = 'object') # Print the arrayprint(country)
Output :
Now we will use assign a value of arbitrary length at the place of missing value in the given array.
# Assign 'New Zealand' to the missing valuecountry[country == ''] = 'New Zealand' # Print the arrayprint(country)
Output :
As we can see in the output, we have successfully assigned an arbitrary length string to the given array object.
Problem #2 : Create a numpy array of arbitrary length.
Solution : We will use the numpy.astype() function to change the dtype of the given array object.
# importing the numpy library as npimport numpy as np # Create a numpy array# Notice we have not set the dtype of the object# this will lead to the length problem country = np.array(['USA', 'Japan', 'UK', '', 'India', 'China']) # Print the arrayprint(country)
Output :
Now we will change the dtype of the given array object using numpy.astype() function. Then we will assign an arbitrary length string to it.
# Change the dtype of the country# object to 'U256'country = country.astype('U256') # Assign 'New Zealand' to the missing valuecountry[country == ''] = 'New Zealand' # Print the arrayprint(country)
Output :
As we can see in the output, we have successfully assigned an arbitrary length string to the given array object.
Note : The maximum length of the string that we can assign in this case after changing the dtype is 256.
data-science
Python numpy-DataType
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
|
[
{
"code": null,
"e": 25707,
"s": 25679,
"text": "\n06 Mar, 2019"
},
{
"code": null,
"e": 25995,
"s": 25707,
"text": "NumPy builds on (and is a successor to) the successful Numeric array object. Its goal is to create the corner-stone for a useful environment for scientific computing. NumPy provides two fundamental objects: an N-dimensional array object (ndarray) and a universal function object (ufunc)."
},
{
"code": null,
"e": 26415,
"s": 25995,
"text": "The dtype of any numpy array containing string values is the maximum length of any string present in the array. Once set, it will only be able to store new string having length not more than the maximum length at the time of the creation. If we try to reassign some another string value having length greater than the maximum length of the existing elements, it simply discards all the values beyond the maximum length."
},
{
"code": null,
"e": 26541,
"s": 26415,
"text": "In this post we are going to discuss ways in which we can overcome this problem and create a numpy array of arbitrary length."
},
{
"code": null,
"e": 26637,
"s": 26541,
"text": "Letβs first visualize the problem with creating an arbitrary length numpy array of string type."
},
{
"code": "# importing numpy as npimport numpy as np # Create the numpy arraycountry = np.array(['USA', 'Japan', 'UK', '', 'India', 'China']) # Print the arrayprint(country)",
"e": 26802,
"s": 26637,
"text": null
},
{
"code": null,
"e": 26811,
"s": 26802,
"text": "Output :"
},
{
"code": null,
"e": 27007,
"s": 26811,
"text": "As we can see in the output, the maximum length of any string length element in the given array is 5. Letβs try to assign a value having greater length at the place of missing value in the array."
},
{
"code": "# Assign 'New Zealand' at the place of missing valuecountry[country == ''] = 'New Zealand' # Print the modified arrayprint(country)",
"e": 27140,
"s": 27007,
"text": null
},
{
"code": null,
"e": 27149,
"s": 27140,
"text": "Output :"
},
{
"code": null,
"e": 27334,
"s": 27149,
"text": "As we can see in the output, βNew Zβ has been assigned rather than βNew Zealandβ because of the limitation to the length. Now, letβs see the ways in which we can overcome this problem."
},
{
"code": null,
"e": 27389,
"s": 27334,
"text": "Problem #1 : Create a numpy array of arbitrary length."
},
{
"code": null,
"e": 27517,
"s": 27389,
"text": "Solution : While creating the array assign the βobjectβ dtype to it. This lets you have all the behaviors of the python string."
},
{
"code": "# importing the numpy library as npimport numpy as np # Create a numpy array# set the dtype to objectcountry = np.array(['USA', 'Japan', 'UK', '', 'India', 'China'], dtype = 'object') # Print the arrayprint(country)",
"e": 27735,
"s": 27517,
"text": null
},
{
"code": null,
"e": 27744,
"s": 27735,
"text": "Output :"
},
{
"code": null,
"e": 27845,
"s": 27744,
"text": "Now we will use assign a value of arbitrary length at the place of missing value in the given array."
},
{
"code": "# Assign 'New Zealand' to the missing valuecountry[country == ''] = 'New Zealand' # Print the arrayprint(country)",
"e": 27960,
"s": 27845,
"text": null
},
{
"code": null,
"e": 27969,
"s": 27960,
"text": "Output :"
},
{
"code": null,
"e": 28082,
"s": 27969,
"text": "As we can see in the output, we have successfully assigned an arbitrary length string to the given array object."
},
{
"code": null,
"e": 28137,
"s": 28082,
"text": "Problem #2 : Create a numpy array of arbitrary length."
},
{
"code": null,
"e": 28235,
"s": 28137,
"text": "Solution : We will use the numpy.astype() function to change the dtype of the given array object."
},
{
"code": "# importing the numpy library as npimport numpy as np # Create a numpy array# Notice we have not set the dtype of the object# this will lead to the length problem country = np.array(['USA', 'Japan', 'UK', '', 'India', 'China']) # Print the arrayprint(country)",
"e": 28497,
"s": 28235,
"text": null
},
{
"code": null,
"e": 28506,
"s": 28497,
"text": "Output :"
},
{
"code": null,
"e": 28646,
"s": 28506,
"text": "Now we will change the dtype of the given array object using numpy.astype() function. Then we will assign an arbitrary length string to it."
},
{
"code": "# Change the dtype of the country# object to 'U256'country = country.astype('U256') # Assign 'New Zealand' to the missing valuecountry[country == ''] = 'New Zealand' # Print the arrayprint(country)",
"e": 28846,
"s": 28646,
"text": null
},
{
"code": null,
"e": 28855,
"s": 28846,
"text": "Output :"
},
{
"code": null,
"e": 28968,
"s": 28855,
"text": "As we can see in the output, we have successfully assigned an arbitrary length string to the given array object."
},
{
"code": null,
"e": 29073,
"s": 28968,
"text": "Note : The maximum length of the string that we can assign in this case after changing the dtype is 256."
},
{
"code": null,
"e": 29086,
"s": 29073,
"text": "data-science"
},
{
"code": null,
"e": 29108,
"s": 29086,
"text": "Python numpy-DataType"
},
{
"code": null,
"e": 29121,
"s": 29108,
"text": "Python-numpy"
},
{
"code": null,
"e": 29128,
"s": 29121,
"text": "Python"
},
{
"code": null,
"e": 29226,
"s": 29128,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29244,
"s": 29226,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29276,
"s": 29244,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29298,
"s": 29276,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29340,
"s": 29298,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29366,
"s": 29340,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29395,
"s": 29366,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 29439,
"s": 29395,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 29476,
"s": 29439,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 29512,
"s": 29476,
"text": "Convert integer to string in Python"
}
] |
How to get the first and last elements of Deque in Python? - GeeksforGeeks
|
01 Oct, 2020
Deque is a Double Ended Queue which is implemented using the collections module in Python. Let us see how can we get the first and the last value in a Deque.
Method 1: Accessing the elements by their index.
The deque data structure from the collections module does not have a peek method, but similar results can be achieved by fetching the elements with square brackets. The first element can be accessed using [0] and the last element can be accessed using [-1].
Python3
# importing the modulefrom collections import deque # creating a deque dq = deque(['Geeks','for','Geeks', 'is', 'good']) # displaying the dequeprint(dq) # fetching the first elementprint(dq[0]) # fetching the last elementprint(dq[-1])
Output:
deque(['Geeks', 'for', 'Geeks', 'is', 'good'])
Geeks
good
Method 2: Using the popleft() and pop() method
popleft() method is used to pop the first element or the element from the left side of the queue and the pop() method to pop the last element or the element form the right side of the queue. It should be noted that these methods also delete the elements from the deque, so they should not be preferred when only fetching the first and the last element is the objective.
Python3
# importing the modulefrom collections import deque # creating a deque dq = deque(['Geeks','for','Geeks', 'is', 'good']) # displaying the dequeprint(dq) # fetching and deleting the first elementprint(dq.popleft()) # fetching and deleting the last elementprint(dq.pop()) # displaying the dequeprint(dq)
Output:
deque(['Geeks', 'for', 'Geeks', 'is', 'good'])
Geeks
good
deque(['for', 'Geeks', 'is'])
deque
Python collections-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 25695,
"s": 25537,
"text": "Deque is a Double Ended Queue which is implemented using the collections module in Python. Let us see how can we get the first and the last value in a Deque."
},
{
"code": null,
"e": 25745,
"s": 25695,
"text": "Method 1: Accessing the elements by their index. "
},
{
"code": null,
"e": 26003,
"s": 25745,
"text": "The deque data structure from the collections module does not have a peek method, but similar results can be achieved by fetching the elements with square brackets. The first element can be accessed using [0] and the last element can be accessed using [-1]."
},
{
"code": null,
"e": 26011,
"s": 26003,
"text": "Python3"
},
{
"code": "# importing the modulefrom collections import deque # creating a deque dq = deque(['Geeks','for','Geeks', 'is', 'good']) # displaying the dequeprint(dq) # fetching the first elementprint(dq[0]) # fetching the last elementprint(dq[-1])",
"e": 26262,
"s": 26011,
"text": null
},
{
"code": null,
"e": 26270,
"s": 26262,
"text": "Output:"
},
{
"code": null,
"e": 26329,
"s": 26270,
"text": "deque(['Geeks', 'for', 'Geeks', 'is', 'good'])\nGeeks\ngood\n"
},
{
"code": null,
"e": 26376,
"s": 26329,
"text": "Method 2: Using the popleft() and pop() method"
},
{
"code": null,
"e": 26746,
"s": 26376,
"text": "popleft() method is used to pop the first element or the element from the left side of the queue and the pop() method to pop the last element or the element form the right side of the queue. It should be noted that these methods also delete the elements from the deque, so they should not be preferred when only fetching the first and the last element is the objective."
},
{
"code": null,
"e": 26754,
"s": 26746,
"text": "Python3"
},
{
"code": "# importing the modulefrom collections import deque # creating a deque dq = deque(['Geeks','for','Geeks', 'is', 'good']) # displaying the dequeprint(dq) # fetching and deleting the first elementprint(dq.popleft()) # fetching and deleting the last elementprint(dq.pop()) # displaying the dequeprint(dq)",
"e": 27073,
"s": 26754,
"text": null
},
{
"code": null,
"e": 27081,
"s": 27073,
"text": "Output:"
},
{
"code": null,
"e": 27170,
"s": 27081,
"text": "deque(['Geeks', 'for', 'Geeks', 'is', 'good'])\nGeeks\ngood\ndeque(['for', 'Geeks', 'is'])\n"
},
{
"code": null,
"e": 27176,
"s": 27170,
"text": "deque"
},
{
"code": null,
"e": 27202,
"s": 27176,
"text": "Python collections-module"
},
{
"code": null,
"e": 27209,
"s": 27202,
"text": "Python"
},
{
"code": null,
"e": 27307,
"s": 27209,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27339,
"s": 27307,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27381,
"s": 27339,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27423,
"s": 27381,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27479,
"s": 27423,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27506,
"s": 27479,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27537,
"s": 27506,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27576,
"s": 27537,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27605,
"s": 27576,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 27627,
"s": 27605,
"text": "Defaultdict in Python"
}
] |
Astsu - Network Scanner Tool - GeeksforGeeks
|
04 Jan, 2022
Astsu is a free and open-source tool available on GitHub. Astsu is written in python language. You must have python language installed in your kali Linux operating system in order to use this tool. Astsu works as a scanner on the network. Astsu is used to scan a network using the IP address. Astsu can be used to scan common ports in which a TCP syn Packet to the destination port and the Nmap will check the services running on the port. Astsu can be used to discover open and closed ports on the network. Astsu can be used to scan the Operating system on the host. Astsu works as a scanner using an IP address.
Astsu sends the TCP Syn packet to the target port. During the TCP Syn if the port is open then perform Nmap scanning to check what service running on the port. Astsu shows all the open and closed ports during the scanning.
Astsu discovers all the hosts on the IP address of the domain. After discovering all possible IPβs astsu sends an ICMP packet to each IP. Astsu then waits for a response from each IP. After receiving all the responses from each IP the astsu prints all hosts.
Astsu sends an ICMP packet to the port destination and waits for a response from the domain. After receiving the response astsu extracts the TTL and finds the possible operating system of the host.
Astsu can perform simple network scanning.
Astsu can be used to scan all the target ports.
Astsu can be used to find which port is open and which is closed.
Astsu is used to discover hosts in a network.
Astsu can be used to perform reconnaissance in the early stages of penetration testing.
Step 1: Open your kali Linux operating system and use the following command to install the tool from GitHub.
git clone https://github.com/ReddyyZ/astsu.git
Step 2: Now use the following command to install the requirements of the tool.
python3 -m pip install -r requirements.txt
Step 3: The tool has been downloaded and installed in your kali linux operating system. Now Use the following command to run the tool.
python3 astsu.py -h
The tool is running successfully. Now we will see examples to use the tool.
Example 1: Use the astsu tool to find to scan common ports on the network.
python3 astsu.py -sC <ip address>
The astsu tool is filtering common ports.
Example 2: Use the astsu tool to find to scan common ports on the network.
python3 astsu.py -sA <ip address>
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux
|
[
{
"code": null,
"e": 25651,
"s": 25623,
"text": "\n04 Jan, 2022"
},
{
"code": null,
"e": 26265,
"s": 25651,
"text": "Astsu is a free and open-source tool available on GitHub. Astsu is written in python language. You must have python language installed in your kali Linux operating system in order to use this tool. Astsu works as a scanner on the network. Astsu is used to scan a network using the IP address. Astsu can be used to scan common ports in which a TCP syn Packet to the destination port and the Nmap will check the services running on the port. Astsu can be used to discover open and closed ports on the network. Astsu can be used to scan the Operating system on the host. Astsu works as a scanner using an IP address."
},
{
"code": null,
"e": 26488,
"s": 26265,
"text": "Astsu sends the TCP Syn packet to the target port. During the TCP Syn if the port is open then perform Nmap scanning to check what service running on the port. Astsu shows all the open and closed ports during the scanning."
},
{
"code": null,
"e": 26747,
"s": 26488,
"text": "Astsu discovers all the hosts on the IP address of the domain. After discovering all possible IPβs astsu sends an ICMP packet to each IP. Astsu then waits for a response from each IP. After receiving all the responses from each IP the astsu prints all hosts."
},
{
"code": null,
"e": 26945,
"s": 26747,
"text": "Astsu sends an ICMP packet to the port destination and waits for a response from the domain. After receiving the response astsu extracts the TTL and finds the possible operating system of the host."
},
{
"code": null,
"e": 26988,
"s": 26945,
"text": "Astsu can perform simple network scanning."
},
{
"code": null,
"e": 27036,
"s": 26988,
"text": "Astsu can be used to scan all the target ports."
},
{
"code": null,
"e": 27102,
"s": 27036,
"text": "Astsu can be used to find which port is open and which is closed."
},
{
"code": null,
"e": 27148,
"s": 27102,
"text": "Astsu is used to discover hosts in a network."
},
{
"code": null,
"e": 27236,
"s": 27148,
"text": "Astsu can be used to perform reconnaissance in the early stages of penetration testing."
},
{
"code": null,
"e": 27345,
"s": 27236,
"text": "Step 1: Open your kali Linux operating system and use the following command to install the tool from GitHub."
},
{
"code": null,
"e": 27392,
"s": 27345,
"text": "git clone https://github.com/ReddyyZ/astsu.git"
},
{
"code": null,
"e": 27471,
"s": 27392,
"text": "Step 2: Now use the following command to install the requirements of the tool."
},
{
"code": null,
"e": 27514,
"s": 27471,
"text": "python3 -m pip install -r requirements.txt"
},
{
"code": null,
"e": 27649,
"s": 27514,
"text": "Step 3: The tool has been downloaded and installed in your kali linux operating system. Now Use the following command to run the tool."
},
{
"code": null,
"e": 27669,
"s": 27649,
"text": "python3 astsu.py -h"
},
{
"code": null,
"e": 27745,
"s": 27669,
"text": "The tool is running successfully. Now we will see examples to use the tool."
},
{
"code": null,
"e": 27820,
"s": 27745,
"text": "Example 1: Use the astsu tool to find to scan common ports on the network."
},
{
"code": null,
"e": 27854,
"s": 27820,
"text": "python3 astsu.py -sC <ip address>"
},
{
"code": null,
"e": 27896,
"s": 27854,
"text": "The astsu tool is filtering common ports."
},
{
"code": null,
"e": 27971,
"s": 27896,
"text": "Example 2: Use the astsu tool to find to scan common ports on the network."
},
{
"code": null,
"e": 28005,
"s": 27971,
"text": "python3 astsu.py -sA <ip address>"
},
{
"code": null,
"e": 28016,
"s": 28005,
"text": "Kali-Linux"
},
{
"code": null,
"e": 28028,
"s": 28016,
"text": "Linux-Tools"
},
{
"code": null,
"e": 28039,
"s": 28028,
"text": "Linux-Unix"
},
{
"code": null,
"e": 28137,
"s": 28039,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28172,
"s": 28137,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 28206,
"s": 28172,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 28232,
"s": 28206,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 28261,
"s": 28232,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 28298,
"s": 28261,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 28335,
"s": 28298,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 28377,
"s": 28335,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 28403,
"s": 28377,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 28439,
"s": 28403,
"text": "uniq Command in LINUX with examples"
}
] |
Creating Frames using Swings in Java - GeeksforGeeks
|
17 Feb, 2022
Swing is a part of JFC (Java Foundation Classes). Building Graphical User Interface in Java requires the use of Swings. Swing Framework contains a large set of components that allow a high level of customization and provide rich functionalities and is used to create window-based applications. Java swing components are lightweight, platform-independent, provide powerful components like tables, scroll panels, buttons, lists, color chooser, etc. In this article, weβll see how to make frames using Swings in Java. Ways to create a frame:
Methods:
By creating the object of Frame class (association)By extending Frame class (inheritance)Create a frame using Swing inside main()
By creating the object of Frame class (association)
By extending Frame class (inheritance)
Create a frame using Swing inside main()
Way 1: By creating the object of Frame class (association)
In this, we will see how to create a JFrame window by instantiating the JFrame class.
Example:
Java
// Java program to create frames// using association import javax.swing.*;public class test1{ JFrame frame; test1() { // creating instance of JFrame with name "first way" frame=new JFrame("first way"); // creates instance of JButton JButton button = new JButton("let's see"); button.setBounds(200, 150, 90, 50); // setting close operation frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // adds button in JFrame frame.add(button); // sets 500 width and 600 height frame.setSize(500, 600); // uses no layout managers frame.setLayout(null); // makes the frame visible frame.setVisible(true); } public static void main(String[] args) { new test1(); }}
Way 2: By extending Frame class (inheritance)
In this example, we will be inheriting JFrame class to create JFrame window and hence it wonβt be required to create an instance of JFrame class explicitly.
Example:
Java
// Java program to create a// frame using inheritance(). import javax.swing.*; // inheriting JFramepublic class test2 extends JFrame{ JFrame frame; test2() { setTitle("this is also a title"); // create button JButton button = new JButton("click"); button.setBounds(165, 135, 115, 55); // adding button on frame add(button); // setting close operation setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 500); setLayout(null); setVisible(true); } public static void main(String[] args) { new test2(); }}
Output:
Note : You wonβt be able to run this code on an online compiler, so I have added an image to show you the output.
Way 3: Create a frame using Swing inside main()
Example 1:
Java
// Java program to create a frame// using Swings in main(). import javax.swing.*;public class Swing_example{ public static void main(String[] args) { // creates instance of JFrame JFrame frame1 = new JFrame(); // creates instance of JButton JButton button1 = new JButton("click"); JButton button2 = new JButton("again click"); // x axis, y axis, width, height button1.setBounds(160, 150 ,80, 80); button2.setBounds(190, 190, 100, 200); // adds button1 in Frame1 frame1.add(button1); // adds button2 in Frame1 frame1.add(button2); // 400 width and 500 height of frame1 frame1.setSize(400, 500) ; // uses no layout managers frame1.setLayout(null); // makes the frame visible frame1.setVisible(true); }}
Output:
Note: You wonβt be able to run this code on the online compiler, so I have added an image to show you the output.
Example 2:
Java
// Java program to create a frame// using Swings in main(). import javax.swing.*;public class Swing_example_2{ public static void main(String[] args) { // creates instance of JFrame JFrame frame1 = new JFrame(); // creates instance of JButton JButton button1 = new JButton("button1"); // "button2" appears on the button JButton button2 = new JButton("button2"); // x axis, y axis, width, height button1.setBounds(180, 50, 80, 80); button2.setBounds(180, 140, 80, 80); //adds button1 in Frame1 frame1.add(button1); //adds button2 in Frame1 frame1.add(button2); //400 width and 500 height of frame1 frame1.setSize(500, 300) ; //uses no layout managers frame1.setLayout(null); //makes the frame visible frame1.setVisible(true); }}
Output:
Note : You wonβt be able to run this code on an online compiler, so I have added an image to show you the output.
This article is contributed by Shitij Chawla. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
solankimayank
simranarora5sos
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
|
[
{
"code": null,
"e": 25785,
"s": 25757,
"text": "\n17 Feb, 2022"
},
{
"code": null,
"e": 26325,
"s": 25785,
"text": "Swing is a part of JFC (Java Foundation Classes). Building Graphical User Interface in Java requires the use of Swings. Swing Framework contains a large set of components that allow a high level of customization and provide rich functionalities and is used to create window-based applications. Java swing components are lightweight, platform-independent, provide powerful components like tables, scroll panels, buttons, lists, color chooser, etc. In this article, weβll see how to make frames using Swings in Java. Ways to create a frame: "
},
{
"code": null,
"e": 26334,
"s": 26325,
"text": "Methods:"
},
{
"code": null,
"e": 26464,
"s": 26334,
"text": "By creating the object of Frame class (association)By extending Frame class (inheritance)Create a frame using Swing inside main()"
},
{
"code": null,
"e": 26516,
"s": 26464,
"text": "By creating the object of Frame class (association)"
},
{
"code": null,
"e": 26555,
"s": 26516,
"text": "By extending Frame class (inheritance)"
},
{
"code": null,
"e": 26596,
"s": 26555,
"text": "Create a frame using Swing inside main()"
},
{
"code": null,
"e": 26655,
"s": 26596,
"text": "Way 1: By creating the object of Frame class (association)"
},
{
"code": null,
"e": 26742,
"s": 26655,
"text": "In this, we will see how to create a JFrame window by instantiating the JFrame class. "
},
{
"code": null,
"e": 26751,
"s": 26742,
"text": "Example:"
},
{
"code": null,
"e": 26756,
"s": 26751,
"text": "Java"
},
{
"code": "// Java program to create frames// using association import javax.swing.*;public class test1{ JFrame frame; test1() { // creating instance of JFrame with name \"first way\" frame=new JFrame(\"first way\"); // creates instance of JButton JButton button = new JButton(\"let's see\"); button.setBounds(200, 150, 90, 50); // setting close operation frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // adds button in JFrame frame.add(button); // sets 500 width and 600 height frame.setSize(500, 600); // uses no layout managers frame.setLayout(null); // makes the frame visible frame.setVisible(true); } public static void main(String[] args) { new test1(); }}",
"e": 27589,
"s": 26756,
"text": null
},
{
"code": null,
"e": 27635,
"s": 27589,
"text": "Way 2: By extending Frame class (inheritance)"
},
{
"code": null,
"e": 27793,
"s": 27635,
"text": "In this example, we will be inheriting JFrame class to create JFrame window and hence it wonβt be required to create an instance of JFrame class explicitly. "
},
{
"code": null,
"e": 27802,
"s": 27793,
"text": "Example:"
},
{
"code": null,
"e": 27807,
"s": 27802,
"text": "Java"
},
{
"code": "// Java program to create a// frame using inheritance(). import javax.swing.*; // inheriting JFramepublic class test2 extends JFrame{ JFrame frame; test2() { setTitle(\"this is also a title\"); // create button JButton button = new JButton(\"click\"); button.setBounds(165, 135, 115, 55); // adding button on frame add(button); // setting close operation setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 500); setLayout(null); setVisible(true); } public static void main(String[] args) { new test2(); }}",
"e": 28442,
"s": 27807,
"text": null
},
{
"code": null,
"e": 28450,
"s": 28442,
"text": "Output:"
},
{
"code": null,
"e": 28567,
"s": 28450,
"text": " Note : You wonβt be able to run this code on an online compiler, so I have added an image to show you the output. "
},
{
"code": null,
"e": 28615,
"s": 28567,
"text": "Way 3: Create a frame using Swing inside main()"
},
{
"code": null,
"e": 28626,
"s": 28615,
"text": "Example 1:"
},
{
"code": null,
"e": 28631,
"s": 28626,
"text": "Java"
},
{
"code": "// Java program to create a frame// using Swings in main(). import javax.swing.*;public class Swing_example{ public static void main(String[] args) { // creates instance of JFrame JFrame frame1 = new JFrame(); // creates instance of JButton JButton button1 = new JButton(\"click\"); JButton button2 = new JButton(\"again click\"); // x axis, y axis, width, height button1.setBounds(160, 150 ,80, 80); button2.setBounds(190, 190, 100, 200); // adds button1 in Frame1 frame1.add(button1); // adds button2 in Frame1 frame1.add(button2); // 400 width and 500 height of frame1 frame1.setSize(400, 500) ; // uses no layout managers frame1.setLayout(null); // makes the frame visible frame1.setVisible(true); }}",
"e": 29498,
"s": 28631,
"text": null
},
{
"code": null,
"e": 29507,
"s": 29498,
"text": "Output: "
},
{
"code": null,
"e": 29622,
"s": 29507,
"text": "Note: You wonβt be able to run this code on the online compiler, so I have added an image to show you the output. "
},
{
"code": null,
"e": 29633,
"s": 29622,
"text": "Example 2:"
},
{
"code": null,
"e": 29638,
"s": 29633,
"text": "Java"
},
{
"code": "// Java program to create a frame// using Swings in main(). import javax.swing.*;public class Swing_example_2{ public static void main(String[] args) { // creates instance of JFrame JFrame frame1 = new JFrame(); // creates instance of JButton JButton button1 = new JButton(\"button1\"); // \"button2\" appears on the button JButton button2 = new JButton(\"button2\"); // x axis, y axis, width, height button1.setBounds(180, 50, 80, 80); button2.setBounds(180, 140, 80, 80); //adds button1 in Frame1 frame1.add(button1); //adds button2 in Frame1 frame1.add(button2); //400 width and 500 height of frame1 frame1.setSize(500, 300) ; //uses no layout managers frame1.setLayout(null); //makes the frame visible frame1.setVisible(true); }}",
"e": 30548,
"s": 29638,
"text": null
},
{
"code": null,
"e": 30558,
"s": 30548,
"text": "Output: "
},
{
"code": null,
"e": 30673,
"s": 30558,
"text": "Note : You wonβt be able to run this code on an online compiler, so I have added an image to show you the output. "
},
{
"code": null,
"e": 31095,
"s": 30673,
"text": "This article is contributed by Shitij Chawla. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 31109,
"s": 31095,
"text": "solankimayank"
},
{
"code": null,
"e": 31125,
"s": 31109,
"text": "simranarora5sos"
},
{
"code": null,
"e": 31130,
"s": 31125,
"text": "Java"
},
{
"code": null,
"e": 31135,
"s": 31130,
"text": "Java"
},
{
"code": null,
"e": 31233,
"s": 31135,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31284,
"s": 31233,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 31314,
"s": 31284,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 31333,
"s": 31314,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 31348,
"s": 31333,
"text": "Stream In Java"
},
{
"code": null,
"e": 31379,
"s": 31348,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 31397,
"s": 31379,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 31429,
"s": 31397,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 31449,
"s": 31429,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 31481,
"s": 31449,
"text": "Multidimensional Arrays in Java"
}
] |
Check whether a number is circular prime or not - GeeksforGeeks
|
30 Sep, 2021
We are given a number n. Our task is to check whether the number is circular prime or not.Circular Prime : A prime number is said to be a circular prime if after any cyclic permutations of the digits, it remains a prime.Examples:
Input : n = 113
Output : Yes
All cyclic permutations of 113 (311
and 131) are prime.
Input : 1193
Output : Yes
The idea is simple, we generate all permutations of given number and check each permutation for prime. To generate permutations, we one by one move last digit to first position.
C++
Java
Python
C#
PHP
Javascript
// Program to check if a number is circular// prime or not.#include <iostream>#include <cmath>using namespace std; // Function to check if a number is prime or not.bool isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true;} // Function to check if the number is circular// prime or not.bool checkCircular(int N){ // Count digits. int count = 0, temp = N; while (temp) { count++; temp /= 10; } int num = N; while (isPrime(num)) { // Following three lines generate the next // circular permutation of a number. We move // last digit to first position. int rem = num % 10; int div = num / 10; num = (pow(10, count - 1)) * rem + div; // If all the permutations are checked and // we obtain original number exit from loop. if (num == N) return true; } return false;} // Driver Programint main(){ int N = 1193; if (checkCircular(N)) cout << "Yes" << endl; else cout << "No" << endl; return 0;}
// Java Program to check if a number// is circular prime or not.import java.lang.*; class GFG{ // Function to check if a number is prime or not. static boolean isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } // Function to check if the number is circular // prime or not. static boolean checkCircular(int N) { // Count digits. int count = 0, temp = N; while (temp>0) { count++; temp /= 10; } int num = N; while (isPrime(num)) { // Following three lines generate the next // circular permutation of a number. We // move last digit to first position. int rem = num % 10; int div = num / 10; num = (int)((Math.pow(10, count - 1)) * rem) + div; // If all the permutations are checked and // we obtain original number exit from loop. if (num == N) return true; } return false; } // Driver Program public static void main (String[] args) { int N = 1193; if (checkCircular(N)) System.out.println("Yes"); else System.out.println("No"); }}/* This code is contributed by Kriti Shukla */
# Python Program to check if a number# is circular prime or not. import math # Function to check if a number is prime# or not.def isPrime(n) : # Corner cases if (n <= 1) : return False if (n <= 3) : return True # This is checked so that we can skip # middle five numbers in below loop if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while i * i <= n : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True # Function to check if the number is# circular prime or not.def checkCircular(N) : #Count digits. count = 0 temp = N while (temp > 0) : count = count + 1 temp = temp / 10 num = N; while (isPrime(num)) : # Following three lines generate the # next circular permutation of a # number. We move last digit to # first position. rem = num % 10 div = num / 10 num = (int)((math.pow(10, count - 1)) * rem)+ div # If all the permutations are checked # and we obtain original number exit # from loop. if (num == N) : return True return False # Driver ProgramN = 1193;if (checkCircular(N)) : print "Yes"else : print "No" # This code is contributed by Nikita Tiwari
// C# Program to check if a number// is circular prime or not.using System; class GFG { // Function to check if a // number is prime or not. static bool isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we // can skip middle five numbers // in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } // Function to check if the number // is circular prime or not. static bool checkCircular(int N) { // Count digits. int count = 0, temp = N; while (temp > 0) { count++; temp /= 10; } int num = N; while (isPrime(num)) { // Following three lines generate // the next circular permutation // of a number. We move last digit // to first position. int rem = num % 10; int div = num / 10; num = (int)((Math.Pow(10, count - 1)) * rem) + div; // If all the permutations are // checked and we obtain original // number exit from loop. if (num == N) return true; } return false; } // Driver code public static void Main () { int N = 1193; if (checkCircular(N)) Console.Write("Yes"); else Console.Write("No"); }} // This code is contributed by Nitin Mittal.
<?php// Program to check if// a number is circular// prime or not. // Function to check if a// number is prime or not.function isPrime($n){ // Corner cases if ($n <= 1) return false; if ($n <= 3) return true; // This is checked so that // we can skip middle five // numbers in below loop if ($n % 2 == 0 || $n % 3 == 0) return false; for ($i = 5; $i * $i <= $n; $i = $i + 6) if ($n % $i == 0 || $n % ($i + 2) == 0) return -1; return true;} // Function to check if// the number is circular// prime or not.function checkCircular($N){ // Count digits. $count = 0; $temp = $N; while ($temp) { $count++; $temp =(int)$temp / 10; } $num = $N; while (isPrime($num)) { // Following three lines generate // the next circular permutation // of a number. We move last digit // to first position. $rem = $num % 10; $div = (int)$num / 10; $num = (pow(10, $count - 1)) * $rem + $div; // If all the permutations are // checked and we obtain original // number exit from loop. if ($num == $N) return true; } return -1;} // Driver Code$N = 1193;if (checkCircular($N)) echo "Yes" ,"\n";else echo "No" ,"\n"; // This code is contributed// by akt_mit?>
<script> // Javascript Program to check if a number // is circular prime or not. // Function to check if a // number is prime or not. function isPrime(n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we // can skip middle five numbers // in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (let i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } // Function to check if the number // is circular prime or not. function checkCircular(N) { // Count digits. let count = 0, temp = N; while (temp > 0) { count++; temp = parseInt(temp / 10, 10); } let num = N; while (isPrime(num)) { // Following three lines generate // the next circular permutation // of a number. We move last digit // to first position. let rem = num % 10; let div = parseInt(num / 10, 10); num = ((Math.pow(10, count - 1)) * rem) + div; // If all the permutations are // checked and we obtain original // number exit from loop. if (num == N) return true; } return false; } let N = 1193; if (checkCircular(N)) document.write("Yes"); else document.write("No"); </script>
Output:
Yes
Time Complexity: O(N*N1/2)
Auxiliary Space: O(1)Optimizations: Clearly numbers containing 0, 2, 4, 5, 6, or 8 can never be circular primes as numbers ending with these will always be divisible by 2 or 5. Hence one of their permutation will not be a prime. While counting digits in first step, we can also check if current digit is one of these.This article is contributed by Vineet Joshi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
jit_t
subhammahato348
divyeshrabadiya07
dhanya4
Prime Number
Mathematical
Mathematical
Prime Number
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
Program for factorial of a number
Print all possible combinations of r elements in a given array of size n
Program for Decimal to Binary Conversion
The Knight's tour problem | Backtracking-1
Operators in C / C++
Find minimum number of coins that make a given value
Program to find sum of elements in a given array
|
[
{
"code": null,
"e": 25909,
"s": 25881,
"text": "\n30 Sep, 2021"
},
{
"code": null,
"e": 26140,
"s": 25909,
"text": "We are given a number n. Our task is to check whether the number is circular prime or not.Circular Prime : A prime number is said to be a circular prime if after any cyclic permutations of the digits, it remains a prime.Examples: "
},
{
"code": null,
"e": 26255,
"s": 26140,
"text": "Input : n = 113 \nOutput : Yes\nAll cyclic permutations of 113 (311\nand 131) are prime. \n\nInput : 1193\nOutput : Yes"
},
{
"code": null,
"e": 26435,
"s": 26255,
"text": "The idea is simple, we generate all permutations of given number and check each permutation for prime. To generate permutations, we one by one move last digit to first position. "
},
{
"code": null,
"e": 26439,
"s": 26435,
"text": "C++"
},
{
"code": null,
"e": 26444,
"s": 26439,
"text": "Java"
},
{
"code": null,
"e": 26451,
"s": 26444,
"text": "Python"
},
{
"code": null,
"e": 26454,
"s": 26451,
"text": "C#"
},
{
"code": null,
"e": 26458,
"s": 26454,
"text": "PHP"
},
{
"code": null,
"e": 26469,
"s": 26458,
"text": "Javascript"
},
{
"code": "// Program to check if a number is circular// prime or not.#include <iostream>#include <cmath>using namespace std; // Function to check if a number is prime or not.bool isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true;} // Function to check if the number is circular// prime or not.bool checkCircular(int N){ // Count digits. int count = 0, temp = N; while (temp) { count++; temp /= 10; } int num = N; while (isPrime(num)) { // Following three lines generate the next // circular permutation of a number. We move // last digit to first position. int rem = num % 10; int div = num / 10; num = (pow(10, count - 1)) * rem + div; // If all the permutations are checked and // we obtain original number exit from loop. if (num == N) return true; } return false;} // Driver Programint main(){ int N = 1193; if (checkCircular(N)) cout << \"Yes\" << endl; else cout << \"No\" << endl; return 0;}",
"e": 27816,
"s": 26469,
"text": null
},
{
"code": "// Java Program to check if a number// is circular prime or not.import java.lang.*; class GFG{ // Function to check if a number is prime or not. static boolean isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } // Function to check if the number is circular // prime or not. static boolean checkCircular(int N) { // Count digits. int count = 0, temp = N; while (temp>0) { count++; temp /= 10; } int num = N; while (isPrime(num)) { // Following three lines generate the next // circular permutation of a number. We // move last digit to first position. int rem = num % 10; int div = num / 10; num = (int)((Math.pow(10, count - 1)) * rem) + div; // If all the permutations are checked and // we obtain original number exit from loop. if (num == N) return true; } return false; } // Driver Program public static void main (String[] args) { int N = 1193; if (checkCircular(N)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}/* This code is contributed by Kriti Shukla */",
"e": 29447,
"s": 27816,
"text": null
},
{
"code": "# Python Program to check if a number# is circular prime or not. import math # Function to check if a number is prime# or not.def isPrime(n) : # Corner cases if (n <= 1) : return False if (n <= 3) : return True # This is checked so that we can skip # middle five numbers in below loop if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while i * i <= n : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True # Function to check if the number is# circular prime or not.def checkCircular(N) : #Count digits. count = 0 temp = N while (temp > 0) : count = count + 1 temp = temp / 10 num = N; while (isPrime(num)) : # Following three lines generate the # next circular permutation of a # number. We move last digit to # first position. rem = num % 10 div = num / 10 num = (int)((math.pow(10, count - 1)) * rem)+ div # If all the permutations are checked # and we obtain original number exit # from loop. if (num == N) : return True return False # Driver ProgramN = 1193;if (checkCircular(N)) : print \"Yes\"else : print \"No\" # This code is contributed by Nikita Tiwari",
"e": 30819,
"s": 29447,
"text": null
},
{
"code": "// C# Program to check if a number// is circular prime or not.using System; class GFG { // Function to check if a // number is prime or not. static bool isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we // can skip middle five numbers // in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } // Function to check if the number // is circular prime or not. static bool checkCircular(int N) { // Count digits. int count = 0, temp = N; while (temp > 0) { count++; temp /= 10; } int num = N; while (isPrime(num)) { // Following three lines generate // the next circular permutation // of a number. We move last digit // to first position. int rem = num % 10; int div = num / 10; num = (int)((Math.Pow(10, count - 1)) * rem) + div; // If all the permutations are // checked and we obtain original // number exit from loop. if (num == N) return true; } return false; } // Driver code public static void Main () { int N = 1193; if (checkCircular(N)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }} // This code is contributed by Nitin Mittal.",
"e": 32517,
"s": 30819,
"text": null
},
{
"code": "<?php// Program to check if// a number is circular// prime or not. // Function to check if a// number is prime or not.function isPrime($n){ // Corner cases if ($n <= 1) return false; if ($n <= 3) return true; // This is checked so that // we can skip middle five // numbers in below loop if ($n % 2 == 0 || $n % 3 == 0) return false; for ($i = 5; $i * $i <= $n; $i = $i + 6) if ($n % $i == 0 || $n % ($i + 2) == 0) return -1; return true;} // Function to check if// the number is circular// prime or not.function checkCircular($N){ // Count digits. $count = 0; $temp = $N; while ($temp) { $count++; $temp =(int)$temp / 10; } $num = $N; while (isPrime($num)) { // Following three lines generate // the next circular permutation // of a number. We move last digit // to first position. $rem = $num % 10; $div = (int)$num / 10; $num = (pow(10, $count - 1)) * $rem + $div; // If all the permutations are // checked and we obtain original // number exit from loop. if ($num == $N) return true; } return -1;} // Driver Code$N = 1193;if (checkCircular($N)) echo \"Yes\" ,\"\\n\";else echo \"No\" ,\"\\n\"; // This code is contributed// by akt_mit?>",
"e": 33916,
"s": 32517,
"text": null
},
{
"code": "<script> // Javascript Program to check if a number // is circular prime or not. // Function to check if a // number is prime or not. function isPrime(n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we // can skip middle five numbers // in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (let i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } // Function to check if the number // is circular prime or not. function checkCircular(N) { // Count digits. let count = 0, temp = N; while (temp > 0) { count++; temp = parseInt(temp / 10, 10); } let num = N; while (isPrime(num)) { // Following three lines generate // the next circular permutation // of a number. We move last digit // to first position. let rem = num % 10; let div = parseInt(num / 10, 10); num = ((Math.pow(10, count - 1)) * rem) + div; // If all the permutations are // checked and we obtain original // number exit from loop. if (num == N) return true; } return false; } let N = 1193; if (checkCircular(N)) document.write(\"Yes\"); else document.write(\"No\"); </script>",
"e": 35515,
"s": 33916,
"text": null
},
{
"code": null,
"e": 35524,
"s": 35515,
"text": "Output: "
},
{
"code": null,
"e": 35528,
"s": 35524,
"text": "Yes"
},
{
"code": null,
"e": 35555,
"s": 35528,
"text": "Time Complexity: O(N*N1/2)"
},
{
"code": null,
"e": 36292,
"s": 35555,
"text": "Auxiliary Space: O(1)Optimizations: Clearly numbers containing 0, 2, 4, 5, 6, or 8 can never be circular primes as numbers ending with these will always be divisible by 2 or 5. Hence one of their permutation will not be a prime. While counting digits in first step, we can also check if current digit is one of these.This article is contributed by Vineet Joshi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 36305,
"s": 36292,
"text": "nitin mittal"
},
{
"code": null,
"e": 36311,
"s": 36305,
"text": "jit_t"
},
{
"code": null,
"e": 36327,
"s": 36311,
"text": "subhammahato348"
},
{
"code": null,
"e": 36345,
"s": 36327,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 36353,
"s": 36345,
"text": "dhanya4"
},
{
"code": null,
"e": 36366,
"s": 36353,
"text": "Prime Number"
},
{
"code": null,
"e": 36379,
"s": 36366,
"text": "Mathematical"
},
{
"code": null,
"e": 36392,
"s": 36379,
"text": "Mathematical"
},
{
"code": null,
"e": 36405,
"s": 36392,
"text": "Prime Number"
},
{
"code": null,
"e": 36503,
"s": 36405,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36527,
"s": 36503,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 36570,
"s": 36527,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 36584,
"s": 36570,
"text": "Prime Numbers"
},
{
"code": null,
"e": 36618,
"s": 36584,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 36691,
"s": 36618,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 36732,
"s": 36691,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 36775,
"s": 36732,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 36796,
"s": 36775,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 36849,
"s": 36796,
"text": "Find minimum number of coins that make a given value"
}
] |
Minimum Number of Manipulations required to make two Strings Anagram Without Deletion of Character - GeeksforGeeks
|
16 Nov, 2021
Given two strings s1 and s2, we need to find the minimum number of manipulations required to make two strings anagram without deleting any character.
Note:- The anagram strings have same set of characters, sequence of characters can be different. If deletion of character is allowed and cost is given, refer to Minimum Cost To Make Two Strings IdenticalQuestion Source: Yatra.com Interview Experience | Set 7
Examples:
Input :
s1 = "aba"
s2 = "baa"
Output : 0
Explanation: Both String contains identical characters
Input :
s1 = "ddcf"
s2 = "cedk"
Output : 2
Explanation : Here, we need to change two characters
in either of the strings to make them identical. We
can change 'd' and 'f' in s1 or 'e' and 'k' in s2.
Assumption: Length of both the Strings is considered similar
C++
Java
Python3
C#
PHP
Javascript
// C++ Program to find minimum number// of manipulations required to make// two strings identical#include <bits/stdc++.h>using namespace std; // Counts the no of manipulations // required int countManipulations(string s1, string s2) { int count = 0; // store the count of character int char_count[26]; for (int i = 0; i < 26; i++) { char_count[i] = 0; } // iterate though the first String // and update count for (int i = 0; i < s1.length(); i++) char_count[s1[i] - 'a']++; // iterate through the second string // update char_count. // if character is not found in // char_count then increase count for (int i = 0; i < s2.length(); i++) { char_count[s2[i] - 'a']--; } for(int i = 0; i < 26; ++i) { if(char_count[i] != 0) { count+=abs(char_count[i]); } } return count / 2; } // Driver code int main() { string s1 = "ddcf"; string s2 = "cedk"; cout<<countManipulations(s1, s2); } // This code is contributed by vt_m.
// Java Program to find minimum number of manipulations// required to make two strings identicalpublic class Similar_strings { // Counts the no of manipulations required static int countManipulations(String s1, String s2) { int count = 0; // store the count of character int char_count[] = new int[26]; // iterate though the first String and update // count for (int i = 0; i < s1.length(); i++) char_count[s1.charAt(i) - 'a']++; // iterate through the second string // update char_count. // if character is not found in char_count // then increase count for (int i = 0; i < s2.length(); i++) { char_count[s2.charAt(i) - 'a']--; } for(int i = 0; i < 26; ++i) { if(char_count[i] != 0) { count+= Math.abs(char_count[i]); } } return count / 2; } // Driver code public static void main(String[] args) { String s1 = "ddcf"; String s2 = "cedk"; System.out.println(countManipulations(s1, s2)); }}
# Python3 Program to find minimum number# of manipulations required to make# two strings identical # Counts the no of manipulations# requireddef countManipulations(s1, s2): count = 0 # store the count of character char_count = [0] * 26 for i in range(26): char_count[i] = 0 # iterate though the first String # and update count for i in range(len( s1)): char_count[ord(s1[i]) - ord('a')] += 1 # iterate through the second string # update char_count. # if character is not found in # char_count then increase count for i in range(len(s2)): char_count[ord(s2[i]) - ord('a')] -= 1 for i in range(26): if char_count[i] != 0: count += abs(char_count[i]) return count / 2 # Driver codeif __name__ == "__main__": s1 = "ddcf" s2 = "cedk" print(countManipulations(s1, s2)) # This code is contributed by ita_c
// C# Program to find minimum number// of manipulations required to make// two strings identicalusing System; public class GFG { // Counts the no of manipulations // required static int countManipulations(string s1, string s2) { int count = 0; // store the count of character int []char_count = new int[26]; // iterate though the first String // and update count for (int i = 0; i < s1.Length; i++) char_count[s1[i] - 'a']++; // iterate through the second string // update char_count. // if character is not found in // char_count then increase count for (int i = 0; i < s2.Length; i++) char_count[s2[i] - 'a']--; for(int i = 0; i < 26; ++i) { if(char_count[i] != 0) { count+= Math.Abs(char_count[i]); } } return count / 2; } // Driver code public static void Main() { string s1 = "ddcf"; string s2 = "cedk"; Console.WriteLine( countManipulations(s1, s2)); }} // This code is contributed by vt_m.
<?php// PHP Program to find minimum number// of manipulations required to make// two strings identical // Counts the no of manipulations// requiredfunction countManipulations($s1, $s2){ $count = 0; // store the count of character $char_count = array_fill(0, 26, 0); // iterate though the first String // and update count for ($i = 0; $i < strlen($s1); $i++) $char_count[ord($s1[$i]) - ord('a')] += 1; // iterate through the second string // update char_count. // if character is not found in // char_count then increase count for ($i = 0; $i < strlen($s2); $i++) { $char_count[ord($s2[$i]) - ord('a')] -= 1; } for ($i = 0; $i < 26; $i++) { if($char_count[i]!=0) { $count+=abs($char_count[i]); } } return ($count) / 2;} // Driver code$s1 = "ddcf";$s2 = "cedk"; echo countManipulations($s1, $s2); // This code is contributed by Ryuga?>
<script> // Javascript program to find minimum number// of manipulations required to make// two strings identical // Counts the no of manipulations// requiredfunction countManipulations(s1, s2){ let count = 0; // Store the count of character let char_count = new Array(26); for(let i = 0; i < char_count.length; i++) { char_count[i] = 0; } // Iterate though the first String and // update count for(let i = 0; i < s1.length; i++) char_count[s1[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; // Iterate through the second string // update char_count. // If character is not found in char_count // then increase count for(let i = 0; i < s2.length; i++) { char_count[s2[i].charCodeAt(0) - 'a'.charCodeAt(0)]--; } for(let i = 0; i < 26; ++i) { if (char_count[i] != 0) { count += Math.abs(char_count[i]); } } return count / 2;} // Driver codelet s1 = "ddcf";let s2 = "cedk"; document.write(countManipulations(s1, s2)); // This code is contributed by avanitrachhadiya2155 </script>
Output:
2
Time Complexity: O(n), where n is the length of the string.
This article is contributed by Sumit Ghosh and improved by Md Istakhar Ansari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
VikashTripathi
ukasp
ankthon
mdistakharansari
avanitrachhadiya2155
pragup
anagram
Yatra.com
Strings
Yatra.com
Strings
anagram
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Caesar Cipher in Cryptography
Check whether two strings are anagram of each other
Top 50 String Coding Problems for Interviews
Length of the longest substring without repeating characters
Reverse words in a given string
Remove duplicates from a given string
How to split a string in C/C++, Python and Java?
Print all the duplicates in the input string
|
[
{
"code": null,
"e": 26625,
"s": 26597,
"text": "\n16 Nov, 2021"
},
{
"code": null,
"e": 26776,
"s": 26625,
"text": "Given two strings s1 and s2, we need to find the minimum number of manipulations required to make two strings anagram without deleting any character. "
},
{
"code": null,
"e": 27036,
"s": 26776,
"text": "Note:- The anagram strings have same set of characters, sequence of characters can be different. If deletion of character is allowed and cost is given, refer to Minimum Cost To Make Two Strings IdenticalQuestion Source: Yatra.com Interview Experience | Set 7 "
},
{
"code": null,
"e": 27047,
"s": 27036,
"text": "Examples: "
},
{
"code": null,
"e": 27373,
"s": 27047,
"text": "Input : \n s1 = \"aba\"\n s2 = \"baa\"\nOutput : 0\nExplanation: Both String contains identical characters\n\nInput :\n s1 = \"ddcf\"\n s2 = \"cedk\"\nOutput : 2\nExplanation : Here, we need to change two characters\nin either of the strings to make them identical. We \ncan change 'd' and 'f' in s1 or 'e' and 'k' in s2."
},
{
"code": null,
"e": 27435,
"s": 27373,
"text": "Assumption: Length of both the Strings is considered similar "
},
{
"code": null,
"e": 27439,
"s": 27435,
"text": "C++"
},
{
"code": null,
"e": 27444,
"s": 27439,
"text": "Java"
},
{
"code": null,
"e": 27452,
"s": 27444,
"text": "Python3"
},
{
"code": null,
"e": 27455,
"s": 27452,
"text": "C#"
},
{
"code": null,
"e": 27459,
"s": 27455,
"text": "PHP"
},
{
"code": null,
"e": 27470,
"s": 27459,
"text": "Javascript"
},
{
"code": "// C++ Program to find minimum number// of manipulations required to make// two strings identical#include <bits/stdc++.h>using namespace std; // Counts the no of manipulations // required int countManipulations(string s1, string s2) { int count = 0; // store the count of character int char_count[26]; for (int i = 0; i < 26; i++) { char_count[i] = 0; } // iterate though the first String // and update count for (int i = 0; i < s1.length(); i++) char_count[s1[i] - 'a']++; // iterate through the second string // update char_count. // if character is not found in // char_count then increase count for (int i = 0; i < s2.length(); i++) { char_count[s2[i] - 'a']--; } for(int i = 0; i < 26; ++i) { if(char_count[i] != 0) { count+=abs(char_count[i]); } } return count / 2; } // Driver code int main() { string s1 = \"ddcf\"; string s2 = \"cedk\"; cout<<countManipulations(s1, s2); } // This code is contributed by vt_m.",
"e": 28691,
"s": 27470,
"text": null
},
{
"code": "// Java Program to find minimum number of manipulations// required to make two strings identicalpublic class Similar_strings { // Counts the no of manipulations required static int countManipulations(String s1, String s2) { int count = 0; // store the count of character int char_count[] = new int[26]; // iterate though the first String and update // count for (int i = 0; i < s1.length(); i++) char_count[s1.charAt(i) - 'a']++; // iterate through the second string // update char_count. // if character is not found in char_count // then increase count for (int i = 0; i < s2.length(); i++) { char_count[s2.charAt(i) - 'a']--; } for(int i = 0; i < 26; ++i) { if(char_count[i] != 0) { count+= Math.abs(char_count[i]); } } return count / 2; } // Driver code public static void main(String[] args) { String s1 = \"ddcf\"; String s2 = \"cedk\"; System.out.println(countManipulations(s1, s2)); }}",
"e": 29834,
"s": 28691,
"text": null
},
{
"code": "# Python3 Program to find minimum number# of manipulations required to make# two strings identical # Counts the no of manipulations# requireddef countManipulations(s1, s2): count = 0 # store the count of character char_count = [0] * 26 for i in range(26): char_count[i] = 0 # iterate though the first String # and update count for i in range(len( s1)): char_count[ord(s1[i]) - ord('a')] += 1 # iterate through the second string # update char_count. # if character is not found in # char_count then increase count for i in range(len(s2)): char_count[ord(s2[i]) - ord('a')] -= 1 for i in range(26): if char_count[i] != 0: count += abs(char_count[i]) return count / 2 # Driver codeif __name__ == \"__main__\": s1 = \"ddcf\" s2 = \"cedk\" print(countManipulations(s1, s2)) # This code is contributed by ita_c",
"e": 30779,
"s": 29834,
"text": null
},
{
"code": "// C# Program to find minimum number// of manipulations required to make// two strings identicalusing System; public class GFG { // Counts the no of manipulations // required static int countManipulations(string s1, string s2) { int count = 0; // store the count of character int []char_count = new int[26]; // iterate though the first String // and update count for (int i = 0; i < s1.Length; i++) char_count[s1[i] - 'a']++; // iterate through the second string // update char_count. // if character is not found in // char_count then increase count for (int i = 0; i < s2.Length; i++) char_count[s2[i] - 'a']--; for(int i = 0; i < 26; ++i) { if(char_count[i] != 0) { count+= Math.Abs(char_count[i]); } } return count / 2; } // Driver code public static void Main() { string s1 = \"ddcf\"; string s2 = \"cedk\"; Console.WriteLine( countManipulations(s1, s2)); }} // This code is contributed by vt_m.",
"e": 31972,
"s": 30779,
"text": null
},
{
"code": "<?php// PHP Program to find minimum number// of manipulations required to make// two strings identical // Counts the no of manipulations// requiredfunction countManipulations($s1, $s2){ $count = 0; // store the count of character $char_count = array_fill(0, 26, 0); // iterate though the first String // and update count for ($i = 0; $i < strlen($s1); $i++) $char_count[ord($s1[$i]) - ord('a')] += 1; // iterate through the second string // update char_count. // if character is not found in // char_count then increase count for ($i = 0; $i < strlen($s2); $i++) { $char_count[ord($s2[$i]) - ord('a')] -= 1; } for ($i = 0; $i < 26; $i++) { if($char_count[i]!=0) { $count+=abs($char_count[i]); } } return ($count) / 2;} // Driver code$s1 = \"ddcf\";$s2 = \"cedk\"; echo countManipulations($s1, $s2); // This code is contributed by Ryuga?>",
"e": 32946,
"s": 31972,
"text": null
},
{
"code": "<script> // Javascript program to find minimum number// of manipulations required to make// two strings identical // Counts the no of manipulations// requiredfunction countManipulations(s1, s2){ let count = 0; // Store the count of character let char_count = new Array(26); for(let i = 0; i < char_count.length; i++) { char_count[i] = 0; } // Iterate though the first String and // update count for(let i = 0; i < s1.length; i++) char_count[s1[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; // Iterate through the second string // update char_count. // If character is not found in char_count // then increase count for(let i = 0; i < s2.length; i++) { char_count[s2[i].charCodeAt(0) - 'a'.charCodeAt(0)]--; } for(let i = 0; i < 26; ++i) { if (char_count[i] != 0) { count += Math.abs(char_count[i]); } } return count / 2;} // Driver codelet s1 = \"ddcf\";let s2 = \"cedk\"; document.write(countManipulations(s1, s2)); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 34094,
"s": 32946,
"text": null
},
{
"code": null,
"e": 34103,
"s": 34094,
"text": "Output: "
},
{
"code": null,
"e": 34105,
"s": 34103,
"text": "2"
},
{
"code": null,
"e": 34166,
"s": 34105,
"text": "Time Complexity: O(n), where n is the length of the string. "
},
{
"code": null,
"e": 34620,
"s": 34166,
"text": "This article is contributed by Sumit Ghosh and improved by Md Istakhar Ansari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 34625,
"s": 34620,
"text": "vt_m"
},
{
"code": null,
"e": 34640,
"s": 34625,
"text": "VikashTripathi"
},
{
"code": null,
"e": 34646,
"s": 34640,
"text": "ukasp"
},
{
"code": null,
"e": 34654,
"s": 34646,
"text": "ankthon"
},
{
"code": null,
"e": 34671,
"s": 34654,
"text": "mdistakharansari"
},
{
"code": null,
"e": 34692,
"s": 34671,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 34699,
"s": 34692,
"text": "pragup"
},
{
"code": null,
"e": 34707,
"s": 34699,
"text": "anagram"
},
{
"code": null,
"e": 34717,
"s": 34707,
"text": "Yatra.com"
},
{
"code": null,
"e": 34725,
"s": 34717,
"text": "Strings"
},
{
"code": null,
"e": 34735,
"s": 34725,
"text": "Yatra.com"
},
{
"code": null,
"e": 34743,
"s": 34735,
"text": "Strings"
},
{
"code": null,
"e": 34751,
"s": 34743,
"text": "anagram"
},
{
"code": null,
"e": 34849,
"s": 34751,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34902,
"s": 34849,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 34938,
"s": 34902,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 34968,
"s": 34938,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 35020,
"s": 34968,
"text": "Check whether two strings are anagram of each other"
},
{
"code": null,
"e": 35065,
"s": 35020,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 35126,
"s": 35065,
"text": "Length of the longest substring without repeating characters"
},
{
"code": null,
"e": 35158,
"s": 35126,
"text": "Reverse words in a given string"
},
{
"code": null,
"e": 35196,
"s": 35158,
"text": "Remove duplicates from a given string"
},
{
"code": null,
"e": 35245,
"s": 35196,
"text": "How to split a string in C/C++, Python and Java?"
}
] |
Python | os.getloadavg() method - GeeksforGeeks
|
25 Jun, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Pythonβs standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.getloadavg() method in Python is used to get the load average over the last 1, 5, and 15 minutes. The load average is the average of the number of processes in the system run queue over a given period of time over 1, 5 and 15 minutes. This method raises OSError if the load average is unobtainable.
Note: This method is available on UNIX platforms only.
Syntax: os.getloadavg()
Parameter: No parameter is required.
Return Type: This method returns a tuple object consisting of float values which denotes the load average over the last 1, 5, and 15 minutes.
# Python program to explain os.getloadavg() method # importing os module import os # Get the load average over# the last 1, 5, and 15 minutes # using os.getloadavg() methodload1, load5, load15 = os.getloadavg() # Print the load average over# the last 1, 5, and 15 minutes print("Load average over the last 1 minute:", load1)print("Load average over the last 5 minute:", load5)print("Load average over the last 15 minute:", load15)
Load average over the last 1 minute: 0.34
Load average over the last 5 minute: 0.42
Load average over the last 15 minute: 0.46
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n25 Jun, 2019"
},
{
"code": null,
"e": 25756,
"s": 25537,
"text": "OS module in Python provides functions for interacting with the operating system. OS comes under Pythonβs standard utility modules. This module provides a portable way of using operating system dependent functionality."
},
{
"code": null,
"e": 26058,
"s": 25756,
"text": "os.getloadavg() method in Python is used to get the load average over the last 1, 5, and 15 minutes. The load average is the average of the number of processes in the system run queue over a given period of time over 1, 5 and 15 minutes. This method raises OSError if the load average is unobtainable."
},
{
"code": null,
"e": 26113,
"s": 26058,
"text": "Note: This method is available on UNIX platforms only."
},
{
"code": null,
"e": 26137,
"s": 26113,
"text": "Syntax: os.getloadavg()"
},
{
"code": null,
"e": 26174,
"s": 26137,
"text": "Parameter: No parameter is required."
},
{
"code": null,
"e": 26316,
"s": 26174,
"text": "Return Type: This method returns a tuple object consisting of float values which denotes the load average over the last 1, 5, and 15 minutes."
},
{
"code": "# Python program to explain os.getloadavg() method # importing os module import os # Get the load average over# the last 1, 5, and 15 minutes # using os.getloadavg() methodload1, load5, load15 = os.getloadavg() # Print the load average over# the last 1, 5, and 15 minutes print(\"Load average over the last 1 minute:\", load1)print(\"Load average over the last 5 minute:\", load5)print(\"Load average over the last 15 minute:\", load15)",
"e": 26752,
"s": 26316,
"text": null
},
{
"code": null,
"e": 26880,
"s": 26752,
"text": "Load average over the last 1 minute: 0.34\nLoad average over the last 5 minute: 0.42\nLoad average over the last 15 minute: 0.46\n"
},
{
"code": null,
"e": 26897,
"s": 26880,
"text": "python-os-module"
},
{
"code": null,
"e": 26904,
"s": 26897,
"text": "Python"
},
{
"code": null,
"e": 27002,
"s": 26904,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27034,
"s": 27002,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27076,
"s": 27034,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27118,
"s": 27076,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27174,
"s": 27118,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27201,
"s": 27174,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27232,
"s": 27201,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27271,
"s": 27232,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27300,
"s": 27271,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 27322,
"s": 27300,
"text": "Defaultdict in Python"
}
] |
Convert an Iterable to Stream in Java - GeeksforGeeks
|
11 Dec, 2018
Given an Iterable, the task is to convert it into Stream in Java.
Examples:
Input: Iterable = [1, 2, 3, 4, 5]
Output: {1, 2, 3, 4, 5}
Input: Iterable = ['G', 'e', 'e', 'k', 's']
Output: {'G', 'e', 'e', 'k', 's'}
Approach:
Get the Iterable.Convert the Iterable to Spliterator using Iterable.spliterator() method.Convert the formed Spliterator into Sequential Stream using StreamSupport.stream() method.Return the stream.
Get the Iterable.
Convert the Iterable to Spliterator using Iterable.spliterator() method.
Convert the formed Spliterator into Sequential Stream using StreamSupport.stream() method.
Return the stream.
Below is the implementation of the above approach:
// Java program to get a Stream// from a given Iterable import java.util.*;import java.util.stream.*; class GFG { // Function to get the Stream public static <T> Stream<T> getStreamFromIterable(Iterable<T> iterable) { // Convert the Iterable to Spliterator Spliterator<T> spliterator = iterable.spliterator(); // Get a Sequential Stream from spliterator return StreamSupport.stream(spliterator, false); } // Driver code public static void main(String[] args) { // Get the Iterator Iterable<Integer> iterable = Arrays.asList(1, 2, 3, 4, 5); // Get the Stream from the Iterable Stream<Integer> stream = getStreamFromIterable(iterable); // Print the elements of stream stream.forEach(s -> System.out.println(s)); }}
1
2
3
4
5
Java - util package
Java-Iterable
java-stream
Java-Stream-programs
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
|
[
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n11 Dec, 2018"
},
{
"code": null,
"e": 25291,
"s": 25225,
"text": "Given an Iterable, the task is to convert it into Stream in Java."
},
{
"code": null,
"e": 25301,
"s": 25291,
"text": "Examples:"
},
{
"code": null,
"e": 25439,
"s": 25301,
"text": "Input: Iterable = [1, 2, 3, 4, 5]\nOutput: {1, 2, 3, 4, 5}\n\nInput: Iterable = ['G', 'e', 'e', 'k', 's']\nOutput: {'G', 'e', 'e', 'k', 's'}\n"
},
{
"code": null,
"e": 25449,
"s": 25439,
"text": "Approach:"
},
{
"code": null,
"e": 25647,
"s": 25449,
"text": "Get the Iterable.Convert the Iterable to Spliterator using Iterable.spliterator() method.Convert the formed Spliterator into Sequential Stream using StreamSupport.stream() method.Return the stream."
},
{
"code": null,
"e": 25665,
"s": 25647,
"text": "Get the Iterable."
},
{
"code": null,
"e": 25738,
"s": 25665,
"text": "Convert the Iterable to Spliterator using Iterable.spliterator() method."
},
{
"code": null,
"e": 25829,
"s": 25738,
"text": "Convert the formed Spliterator into Sequential Stream using StreamSupport.stream() method."
},
{
"code": null,
"e": 25848,
"s": 25829,
"text": "Return the stream."
},
{
"code": null,
"e": 25899,
"s": 25848,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// Java program to get a Stream// from a given Iterable import java.util.*;import java.util.stream.*; class GFG { // Function to get the Stream public static <T> Stream<T> getStreamFromIterable(Iterable<T> iterable) { // Convert the Iterable to Spliterator Spliterator<T> spliterator = iterable.spliterator(); // Get a Sequential Stream from spliterator return StreamSupport.stream(spliterator, false); } // Driver code public static void main(String[] args) { // Get the Iterator Iterable<Integer> iterable = Arrays.asList(1, 2, 3, 4, 5); // Get the Stream from the Iterable Stream<Integer> stream = getStreamFromIterable(iterable); // Print the elements of stream stream.forEach(s -> System.out.println(s)); }}",
"e": 26758,
"s": 25899,
"text": null
},
{
"code": null,
"e": 26769,
"s": 26758,
"text": "1\n2\n3\n4\n5\n"
},
{
"code": null,
"e": 26789,
"s": 26769,
"text": "Java - util package"
},
{
"code": null,
"e": 26803,
"s": 26789,
"text": "Java-Iterable"
},
{
"code": null,
"e": 26815,
"s": 26803,
"text": "java-stream"
},
{
"code": null,
"e": 26836,
"s": 26815,
"text": "Java-Stream-programs"
},
{
"code": null,
"e": 26841,
"s": 26836,
"text": "Java"
},
{
"code": null,
"e": 26846,
"s": 26841,
"text": "Java"
},
{
"code": null,
"e": 26944,
"s": 26846,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26959,
"s": 26944,
"text": "Stream In Java"
},
{
"code": null,
"e": 26980,
"s": 26959,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26999,
"s": 26980,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27029,
"s": 26999,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27075,
"s": 27029,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27092,
"s": 27075,
"text": "Generics in Java"
},
{
"code": null,
"e": 27113,
"s": 27092,
"text": "Introduction to Java"
},
{
"code": null,
"e": 27156,
"s": 27113,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 27192,
"s": 27156,
"text": "Internal Working of HashMap in Java"
}
] |
Express.js res.cookie() Function - GeeksforGeeks
|
05 May, 2021
The res.cookie() function is used to set the cookie name to value. The value parameter may be a string or object converted to JSON.Syntax:
res.cookie(name, value [, options])
Parameters: The name parameter holds the name of the cookie and the value parameter is the value assigned to the cookie name. The options parameter contains various properties like encode, expires, domain, etc.Return Value: It returns an Object.Installation of express module:
You can visit the link to Install express module. You can install this package by using this command.
You can visit the link to Install express module. You can install this package by using this command.
npm install express
After installing the express module, you can check your express version in command prompt using the command.
After installing the express module, you can check your express version in command prompt using the command.
npm version express
After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.
After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.
node index.js
Example 1: Filename: index.js
javascript
var express = require('express');var app = express();var PORT = 3000; // Without middlewareapp.get('/', function(req, res){ // key-value res.cookie('name', 'geeksforgeeks'); res.send("Cookie Set");}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);});
Steps to run the program:
The project structure will look like this:
The project structure will look like this:
Make sure you have installed express module using the following command:
Make sure you have installed express module using the following command:
npm install express
Run index.js file using below command:
Run index.js file using below command:
node index.js
Output:
Output:
Server listening on PORT 3000
Open your browser and go to http://localhost:3000/, now you the following output on your screen:
Open your browser and go to http://localhost:3000/, now you the following output on your screen:
Cookie Set
Example 2: Filename: index.js
javascript
var express = require('express');var app = express();var PORT = 3000; // With middlewareapp.use('/', function(req, res, next){ res.cookie('title', 'GeeksforGeeks'); res.send("Cookie Set"); next();}) app.get('/', function(req, res){ console.log('Cookie SET');}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);});
Run index.js file using below command:
node index.js
Now open the browser and go to http://localhost:3000/, now check your console and you will see the following output:
Server listening on PORT 3000
Cookie SET
And you will see the following output on your browser:
Cookie Set
Reference: https://expressjs.com/en/5x/api.html#res.cookie
surinderdawra388
Express.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
Node.js fs.readFile() Method
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": 30835,
"s": 30807,
"text": "\n05 May, 2021"
},
{
"code": null,
"e": 30976,
"s": 30835,
"text": "The res.cookie() function is used to set the cookie name to value. The value parameter may be a string or object converted to JSON.Syntax: "
},
{
"code": null,
"e": 31012,
"s": 30976,
"text": "res.cookie(name, value [, options])"
},
{
"code": null,
"e": 31291,
"s": 31012,
"text": "Parameters: The name parameter holds the name of the cookie and the value parameter is the value assigned to the cookie name. The options parameter contains various properties like encode, expires, domain, etc.Return Value: It returns an Object.Installation of express module: "
},
{
"code": null,
"e": 31395,
"s": 31291,
"text": "You can visit the link to Install express module. You can install this package by using this command. "
},
{
"code": null,
"e": 31499,
"s": 31395,
"text": "You can visit the link to Install express module. You can install this package by using this command. "
},
{
"code": null,
"e": 31519,
"s": 31499,
"text": "npm install express"
},
{
"code": null,
"e": 31630,
"s": 31519,
"text": "After installing the express module, you can check your express version in command prompt using the command. "
},
{
"code": null,
"e": 31741,
"s": 31630,
"text": "After installing the express module, you can check your express version in command prompt using the command. "
},
{
"code": null,
"e": 31761,
"s": 31741,
"text": "npm version express"
},
{
"code": null,
"e": 31898,
"s": 31761,
"text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command. "
},
{
"code": null,
"e": 32035,
"s": 31898,
"text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command. "
},
{
"code": null,
"e": 32049,
"s": 32035,
"text": "node index.js"
},
{
"code": null,
"e": 32081,
"s": 32049,
"text": "Example 1: Filename: index.js "
},
{
"code": null,
"e": 32092,
"s": 32081,
"text": "javascript"
},
{
"code": "var express = require('express');var app = express();var PORT = 3000; // Without middlewareapp.get('/', function(req, res){ // key-value res.cookie('name', 'geeksforgeeks'); res.send(\"Cookie Set\");}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});",
"e": 32418,
"s": 32092,
"text": null
},
{
"code": null,
"e": 32446,
"s": 32418,
"text": "Steps to run the program: "
},
{
"code": null,
"e": 32491,
"s": 32446,
"text": "The project structure will look like this: "
},
{
"code": null,
"e": 32536,
"s": 32491,
"text": "The project structure will look like this: "
},
{
"code": null,
"e": 32611,
"s": 32536,
"text": "Make sure you have installed express module using the following command: "
},
{
"code": null,
"e": 32686,
"s": 32611,
"text": "Make sure you have installed express module using the following command: "
},
{
"code": null,
"e": 32706,
"s": 32686,
"text": "npm install express"
},
{
"code": null,
"e": 32747,
"s": 32706,
"text": "Run index.js file using below command: "
},
{
"code": null,
"e": 32788,
"s": 32747,
"text": "Run index.js file using below command: "
},
{
"code": null,
"e": 32802,
"s": 32788,
"text": "node index.js"
},
{
"code": null,
"e": 32812,
"s": 32802,
"text": "Output: "
},
{
"code": null,
"e": 32822,
"s": 32812,
"text": "Output: "
},
{
"code": null,
"e": 32852,
"s": 32822,
"text": "Server listening on PORT 3000"
},
{
"code": null,
"e": 32952,
"s": 32852,
"text": " Open your browser and go to http://localhost:3000/, now you the following output on your screen: "
},
{
"code": null,
"e": 33053,
"s": 32954,
"text": "Open your browser and go to http://localhost:3000/, now you the following output on your screen: "
},
{
"code": null,
"e": 33064,
"s": 33053,
"text": "Cookie Set"
},
{
"code": null,
"e": 33100,
"s": 33068,
"text": "Example 2: Filename: index.js "
},
{
"code": null,
"e": 33111,
"s": 33100,
"text": "javascript"
},
{
"code": "var express = require('express');var app = express();var PORT = 3000; // With middlewareapp.use('/', function(req, res, next){ res.cookie('title', 'GeeksforGeeks'); res.send(\"Cookie Set\"); next();}) app.get('/', function(req, res){ console.log('Cookie SET');}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});",
"e": 33500,
"s": 33111,
"text": null
},
{
"code": null,
"e": 33541,
"s": 33500,
"text": "Run index.js file using below command: "
},
{
"code": null,
"e": 33555,
"s": 33541,
"text": "node index.js"
},
{
"code": null,
"e": 33674,
"s": 33555,
"text": "Now open the browser and go to http://localhost:3000/, now check your console and you will see the following output: "
},
{
"code": null,
"e": 33715,
"s": 33674,
"text": "Server listening on PORT 3000\nCookie SET"
},
{
"code": null,
"e": 33772,
"s": 33715,
"text": "And you will see the following output on your browser: "
},
{
"code": null,
"e": 33783,
"s": 33772,
"text": "Cookie Set"
},
{
"code": null,
"e": 33843,
"s": 33783,
"text": "Reference: https://expressjs.com/en/5x/api.html#res.cookie "
},
{
"code": null,
"e": 33860,
"s": 33843,
"text": "surinderdawra388"
},
{
"code": null,
"e": 33871,
"s": 33860,
"text": "Express.js"
},
{
"code": null,
"e": 33879,
"s": 33871,
"text": "Node.js"
},
{
"code": null,
"e": 33896,
"s": 33879,
"text": "Web Technologies"
},
{
"code": null,
"e": 33994,
"s": 33896,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34027,
"s": 33994,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 34075,
"s": 34027,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 34108,
"s": 34075,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 34138,
"s": 34108,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 34167,
"s": 34138,
"text": "Node.js fs.readFile() Method"
},
{
"code": null,
"e": 34207,
"s": 34167,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 34240,
"s": 34207,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 34285,
"s": 34240,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 34328,
"s": 34285,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Peewee - Quick Guide
|
Peewee is a Python Object Relational Mapping (ORM) library which was developed by a U.S. based software engineer Charles Leifer in October 2010. Its latest version is 3.13.3. Peewee supports SQLite, MySQL, PostgreSQL and Cockroach databases.
Object Relational Mapping is a programming technique for converting data between incompatible type systems in object-oriented programming languages.
Class as defined in an Object Oriented (OO) programming language such as Python, is considered as non-scalar. It cannot be expressed as primitive types such as integers and strings.
On the other hand, databases like Oracle, MySQL, SQLite and others can only store and manipulate scalar values such as integers and strings organised within tables.
The programmer must either convert the object values into groups of scalar data types for storage in the database or convert them back upon retrieval, or only use simple scalar values within the program.
In an ORM system, each class maps to a table in the underlying database. Instead of writing tedious database interfacing code yourself, an ORM takes care of these issues, while you can focus on programming the logics of the system.
To install latest version of Peewee as hosted on PyPI (Python Package Index), use pip installer.
pip3 install peewee
There are no other dependencies for Peewee to work. It works with SQLite without installing any other package as sqlite3 module is bundled with standard library.
However, to work with MySQL and PostgreSQL, you may have to install DB-API compatible driver modules pymysql and pyscopg2 respectively. Cockroach database is handled through playhouse extension that is installed by default along with Peewee.
Peewee is an open source project hosted on https://github.com/coleifer/peewee repository. Hence, it can be installed from here by using git.
git clone https://github.com/coleifer/peewee.git
cd peewee
python setup.py install
An object of Database class from Peewee package represents connection to a database. Peewee provides out-of-box support for SQLite, PostgreSQL and MySQL databases through corresponding subclasses of Database class.
Database class instance has all the information required to open connection with database engine, and is used to execute queries, manage transactions and perform introspection of tables, columns, etc.
Database class has SqliteDatabase, PostgresqlDatabase and MySQLDatabase sub-classes. While DB-API driver for SQLite in the form of sqlite3 module is included in Pythonβs standard library, psycopg2 and pymysql modules will have to be installed first for using PostgreSql and MySQL databases with Peewee.
Python has built-in support for SQLite database in the form of sqlite3 module. Hence, it is very easy to connect. Object of SqliteDatabase class in Peewee represents connection object.
con=SqliteDatabase(name, pragmas, timeout)
Here, pragma is SQLite extension which is used to modify operation of SQLite library. This parameter is either a dictionary or a list of 2-tuples containing pragma key and value to set every time a connection is opened.
Timeout parameter is specified in seconds to set busy-timeout of SQLite driver. Both the parameters are optional.
Following statement creates a connection with a new SQLite database (if it doesnβt exist already).
>>> db = peewee.SqliteDatabase('mydatabase.db')
Pragma parameters are generally given for a new database connection. Typical attributes mentioned in pragmase dictionary are journal_mode, cache_size, locking_mode, foreign-keys, etc.
>>> db = peewee.SqliteDatabase(
'test.db', pragmas={'journal_mode': 'wal', 'cache_size': 10000,'foreign_keys': 1}
)
Following pragma settings are ideal to be specified β
Peewee also has Another Python SQLite Wrapper (apsw), an advanced sqlite driver. It provides advanced features such as virtual tables and file systems, and shared connections. APSW is faster than the standard library sqlite3 module.
An object of Model sub class in Peewee API corresponds to a table in the database with which connection has been established. It allows performing database table operations with the help of methods defined in the Model class.
A user defined Model has one or more class attributes, each of them is an object of Field class. Peewee has a number of subclasses for holding data of different types. Examples are TextField, DatetimeField, etc. They correspond to the fields or columns in the database table. Reference of associated database and table and model configuration is mentioned in Meta class. Following attributes are used to specify configuration β
The meta class attributes are explained below β
Database
Database for model.
db_table
Name of the table to store data. By default, it is name of model class.
Indexes
A list of fields to index.
primary_key
A composite key instance.
Constraints
A list of table constraints.
Schema
The database schema for the model.
Temporary
Indicate temporary table.
depends_on
Indicate this table depends on another for creation.
without_rowid
Indicate that table should not have rowid (SQLite only).
Following code defines Model class for User table in mydatabase.db β
from peewee import *
db = SqliteDatabase('mydatabase.db')
class User (Model):
name=TextField()
age=IntegerField()
class Meta:
database=db
db_table='User'
User.create_table()
The create_table() method is a classmethod of Model class that performs equivalent CREATE TABLE query. Another instance method save() adds a row corresponding to object.
from peewee import *
db = SqliteDatabase('mydatabase.db')
class User (Model):
name=TextField()
age=IntegerField()
class Meta:
database=db
db_table='User'
User.create_table()
rec1=User(name="Rajesh", age=21)
rec1.save()
Other methods in Model class are as follows β
Classmethod alias()
Create an alias to the model-class. It allows the same Model to any referred multiple times in a query.
Classmethod select()
Performs a SELECT query operation. If no fields are explicitly provided as argument, the query will by default SELECT * equivalent.
Classmethod update()
Performs an UPDATE query function.
classmethod insert()
Inserts a new row in the underlying table mapped to model.
classmethod delete()
Executes delete query and is usually associated with a filter by where clause.
classmethod get()
Retrieve a single row from mapped table matching the given filters.
get_id()
Instance method returns primary key of a row.
save()
Save the data of object as a new row. If primary-key value is already present, it will cause an UPDATE query to be executed.
classmethod bind()
Bind the model to the given database.
Model class contains one or more attributes that are objects of Field class in Peewee. Base Field class is not directly instantiated. Peewee defines different sub classes for equivalent SQL data types.
Constructor of Field class has following parametersβ
column_name (str)
Specify column name for field.
primary_key (bool)
Field is the primary key.
constraints (list)
List of constraints to apply to column
choices (list)
An iterable of 2-tuples mapping column values to display labels.
null (bool)
Field allows NULLs.
index (bool)
Create an index on field.
unique (bool)
Create an unique index on field.
Default
Default value.
collation (str)
Collation name for field.
help_text (str)
Help-text for field, metadata purposes.
verbose_name (str)
Verbose name for field, metadata purposes.
Subclasses of Field class are mapped to corresponding data types in various databases, i.e. SQLite, PostgreSQL, MySQL, etc.
The numeric field classes in Peewee are given below β
IntegerField
Field class for storing integers.
BigIntegerField
Field class for storing big integers (maps to integer, bigint, and bigint type in SQLite, PostegreSQL and MySQL respectively).
SmallIntegerField
Field class for storing small integers (if supported by database).
FloatField
Field class for storing floating-point numbers corresponds to real data types.
DoubleField
Field class for storing double-precision floating-point numbers maps to equivalent data types in corresponding SQL databases.
DecimalField
Field class for storing decimal numbers. The parameters are mentioned below β
max_digits (int) β Maximum digits to store.
max_digits (int) β Maximum digits to store.
decimal_places (int) β Maximum precision.
decimal_places (int) β Maximum precision.
auto_round (bool) β Automatically round values.
auto_round (bool) β Automatically round values.
The text fields which are available in Peewee are as follows β
CharField
Field class for storing strings. Max 255 characters. Equivalent SQL data type is varchar.
FixedCharField
Field class for storing fixed-length strings.
TextField
Field class for storing text. Maps to TEXT data type in SQLite and PostgreSQL, and longtext in MySQL.
The binary fields in Peewee are explained below β
BlobField
Field class for storing binary data.
BitField
Field class for storing options in a 64-bit integer column.
BigBitField
Field class for storing arbitrarily-large bitmaps in a Binary Large OBject (BLOB). The field will grow the underlying buffer as necessary.
UUIDField
Field class for storing universally unique identifier (UUID) objects. Maps to UUID type in Postgres. SQLite and MySQL do not have a UUID type, it is stored as a VARCHAR.
The date and time fields in Peewee are as follows β
DateTimeField
Field class for storing datetime.datetime objects. Accepts a special parameter string formats, with which the datetime can be encoded.
DateField
Field class for storing datetime.date objects. Accepts a special parameter string formats to encode date.
TimeField
Field class for storing datetime.time objectsAccepts a special parameter formats to show encoded time.
Since SQLite doesnβt have DateTime data types, this field is mapped as string.
This class is used to establish foreign key relationship in two models and hence, the respective tables in database. This class in instantiated with following parameters β
model (Model)
Model to reference. If set to βselfβ, it is a self-referential foreign key.
field (Field)
Field to reference on model (default is primary key).
backref (str)
Accessor name for back-reference. β+β disables the back-reference accessor.
on_delete (str)
ON DELETE action.
on_update (str)
ON UPDATE action.
lazy_load (bool)
Fetch the related object, when the foreign-key field attribute is accessed. If FALSE, accessing the foreign-key field will return the value stored in the foreign-key column.
Here is an example of ForeignKeyField.
from peewee import *
db = SqliteDatabase('mydatabase.db')
class Customer(Model):
id=IntegerField(primary_key=True)
name = TextField()
address = TextField()
phone = IntegerField()
class Meta:
database=db
db_table='Customers'
class Invoice(Model):
id=IntegerField(primary_key=True)
invno=IntegerField()
amount=IntegerField()
custid=ForeignKeyField(Customer, backref='Invoices')
class Meta:
database=db
db_table='Invoices'
db.create_tables([Customer, Invoice])
When above script is executed, following SQL queries are run β
CREATE TABLE Customers (
id INTEGER NOT NULL
PRIMARY KEY,
name TEXT NOT NULL,
address TEXT NOT NULL,
phone INTEGER NOT NULL
);
CREATE TABLE Invoices (
id INTEGER NOT NULL
PRIMARY KEY,
invno INTEGER NOT NULL,
amount INTEGER NOT NULL,
custid_id INTEGER NOT NULL,
FOREIGN KEY (
custid_id
)
REFERENCES Customers (id)
);
When verified in SQLiteStuidio GUI tool, the table structure appears as below β
The other field types in Peewee include β
IPField
Field class for storing IPv4 addresses efficiently (as integers).
BooleanField
Field class for storing boolean values.
AutoField
Field class for storing auto-incrementing primary keys.
IdentityField
Field class for storing auto-incrementing primary keys using the new Postgres 10 IDENTITYField class for storing auto-incrementing primary keys using the new Postgres 10 IDENTITY column type. column type.
In Peewee, there are more than one commands by which, it is possible to add a new record in the table. We have already used save() method of Model instance.
rec1=User(name="Rajesh", age=21)
rec1.save()
The Peewee.Model class also has a create() method that creates a new instance and add its data in the table.
User.create(name="Kiran", age=19)
In addition to this, Model also has insert() as class method that constructs SQL insert query object. The execute() method of Query object performs adding a row in underlying table.
q = User.insert(name='Lata', age=20)
q.execute()
The query object is an equivalent INSERT query.q.sql() returns the query string.
print (q.sql())
('INSERT INTO "User" ("name", "age") VALUES (?, ?)', ['Lata', 20])
Here is the complete code that demonstrates the use of above ways of inserting record.
from peewee import *
db = SqliteDatabase('mydatabase.db')
class User (Model):
name=TextField()
age=IntegerField()
class Meta:
database=db
db_table='User'
db.create_tables([User])
rec1=User(name="Rajesh", age=21)
rec1.save()
a=User(name="Amar", age=20)
a.save()
User.create(name="Kiran", age=19)
q = User.insert(name='Lata', age=20)
q.execute()
db.close()
We can verify the result in SQLiteStudio GUI.
In order to use multiple rows at once in the table, Peewee provides two methods: bulk_create and insert_many.
The insert_many() method generates equivalent INSERT query, using list of dictionary objects, each having field value pairs of one object.
rows=[{"name":"Rajesh", "age":21}, {"name":"Amar", "age":20}]
q=User.insert_many(rows)
q.execute()
Here too, q.sql() returns the INSERT query string is obtained as below β
print (q.sql())
('INSERT INTO "User" ("name", "age") VALUES (?, ?), (?, ?)', ['Rajesh', 21, 'Amar', 20])
This method takes a list argument that contains one or more unsaved instances of the model mapped to a table.
a=User(name="Kiran", age=19)
b=User(name='Lata', age=20)
User.bulk_create([a,b])
Following code uses both approaches to perform bulk insert operation.
from peewee import *
db = SqliteDatabase('mydatabase.db')
class User (Model):
name=TextField()
age=IntegerField()
class Meta:
database=db
db_table='User'
db.create_tables([User])
rows=[{"name":"Rajesh", "age":21}, {"name":"Amar", "age":20}]
q=User.insert_many(rows)
q.execute()
a=User(name="Kiran", age=19)
b=User(name='Lata', age=20)
User.bulk_create([a,b])
db.close()
Simplest and the most obvious way to retrieve data from tables is to call select() method of corresponding model. Inside select() method, we can specify one or more field attributes. However, if none is specified, all columns are selected.
Model.select() returns a list of model instances corresponding to rows. This is similar to the result set returned by SELECT query, which can be traversed by a for loop.
from peewee import *
db = SqliteDatabase('mydatabase.db')
class User (Model):
name=TextField()
age=IntegerField()
class Meta:
database=db
db_table='User'
rows=User.select()
print (rows.sql())
for row in rows:
print ("name: {} age: {}".format(row.name, row.age))
db.close()
The above script displays the following output β
('SELECT "t1"."id", "t1"."name", "t1"."age" FROM "User" AS "t1"', [])
name: Rajesh age: 21
name: Amar age : 20
name: Kiran age : 19
name: Lata age : 20
It is possible to retrieve data from SQLite table by using where clause. Peewee supports following list of logical operators.
Following code displays name with age>=20:
rows=User.select().where (User.age>=20)
for row in rows:
print ("name: {} age: {}".format(row.name, row.age))
Following code displays only those name present in the names list.
names=['Anil', 'Amar', 'Kiran', 'Bala']
rows=User.select().where (User.name << names)
for row in rows:
print ("name: {} age: {}".format(row.name, row.age))
The SELECT query thus generated by Peewee will be β
('SELECT "t1"."id", "t1"."name", "t1"."age" FROM "User" AS "t1" WHERE
("t1"."name" IN (?, ?, ?, ?))', ['Anil', 'Amar', 'Kiran', 'Bala'])
Resultant output will be as follows β
name: Amar age: 20
name: Kiran age: 19
In addition to the above logical operators as defined in core Python, Peewee provides following methods for filtering β
.in_(value)
.not_in(value)
NOT IN lookup.
.is_null(is_null)
IS NULL or IS NOT NULL. Accepts boolean param.
.contains(substr)
Wild-card search for substring.
.startswith(prefix)
Search for values beginning with prefix.
.endswith(suffix)
Search for values ending with suffix.
.between(low, high)
Search for values between low and high.
.regexp(exp)
Regular expression match (case-sensitive).
.iregexp(exp)
Regular expression match (case-insensitive).
.bin_and(value)
Binary AND.
.bin_or(value)
Binary OR.
.concat(other)
Concatenate two strings or objects using ||.
.distinct()
Mark column for DISTINCT selection.
.collate(collation)
Specify column with the given collation.
.cast(type)
Cast the value of the column to the given type.
As an example of above methods, look at the following code. It retrieves names starting with βRβ or ending with βrβ.
rows=User.select().where (User.name.startswith('R') | User.name.endswith('r'))
Equivalent SQL SELECT query is:
('SELECT "t1"."id", "t1"."name", "t1"."age" FROM "User" AS "t1" WHERE
(("t1"."name" LIKE ?) OR ("t1"."name" LIKE ?))', ['R%', '%r'])
Pythonβs built-in operators in, not in, and, or etc. will not work. Instead, use Peewee alternatives.
You can use β
.in_() and .not_in() methods instead of in and not in operators.
.in_() and .not_in() methods instead of in and not in operators.
& instead of and.
& instead of and.
| instead of or.
| instead of or.
~ instead of not.
~ instead of not.
.is_null() instead of is.
.is_null() instead of is.
None or == None.
None or == None.
It is recommended that the table in a relational database, should have one of the columns applied with primary key constraint. Accordingly, Peewee Model class can also specify field attribute with primary-key argument set to True. However, if model class doesnβt have any primary key, Peewee automatically creates one with the name βidβ. Note that the User model defined above doesnβt have any field explicitly defined as primary key. Hence, the mapped User table in our database has an id field.
To define an auto-incrementing integer primary key, use AutoField object as one attribute in the model.
class User (Model):
user_id=AutoField()
name=TextField()
age=IntegerField()
class Meta:
database=db
db_table='User'
This will translate into following CREATE TABLE query β
CREATE TABLE User (
user_id INTEGER NOT NULL
PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER NOT NULL
);
You can also assign any non-integer field as a primary key by setting primary_key parameter to True. Let us say we want to store certain alphanumeric value as user_id.
class User (Model):
user_id=TextField(primary_key=True)
name=TextField()
age=IntegerField()
class Meta:
database=db
db_table='User'
However, when model contains non-integer field as primary key, the save() method of model instance doesnβt cause database driver to generate new ID automatically, hence we need to pass force_insert=True parameter. However, note that the create() method implicitly specifies force_insert parameter.
User.create(user_id='A001',name="Rajesh", age=21)
b=User(user_id='A002',name="Amar", age=20)
b.save(force_insert=True)
The save() method also updates an existing row in the table, at which time, force_insert primary is not necessary, as ID with unique primary key is already existing.
Peewee allows feature of defining composite primary key. Object of CompositeKey class is defined as primary key in Meta class. In following example, a composite key consisting of name and city fields of User model has been assigned as composite key.
class User (Model):
name=TextField()
city=TextField()
age=IntegerField()
class Meta:
database=db
db_table='User'
primary_key=CompositeKey('name', 'city')
This model translates in the following CREATE TABLE query.
CREATE TABLE User (
name TEXT NOT NULL,
city TEXT NOT NULL,
age INTEGER NOT NULL,
PRIMARY KEY (
name,
city
)
);
If you wish, the table should not have a primary key, then specify primary_key=False in modelβs Meta class.
Existing data can be modified by calling save() method on model instance as well as with update() class method.
Following example fetches a row from User table with the help of get() method and updates it by changing the value of age field.
row=User.get(User.name=="Amar")
print ("name: {} age: {}".format(row.name, row.age))
row.age=25
row.save()
The update() method of Method class generates UPDATE query. The query objectβs execute() method is then invoked.
Following example uses update() method to change the age column of rows in which it is >20.
qry=User.update({User.age:25}).where(User.age>20)
print (qry.sql())
qry.execute()
The SQL query rendered by update() method is as follows β
('UPDATE "User" SET "age" = ? WHERE ("User"."age" > ?)', [25, 20])
Peewee also has a bulk_update() method to help update multiple model instance in a single query operation. The method requires model objects to be updated and list of fields to be updated.
Following example updates the age field of specified rows by new value.
rows=User.select()
rows[0].age=25
rows[2].age=23
User.bulk_update([rows[0], rows[2]], fields=[User.age])
Running delete_instance() method on a model instance delete corresponding row from the mapped table.
obj=User.get(User.name=="Amar")
obj.delete_instance()
On the other hand, delete() is a class method defined in model class, which generates DELETE query. Executing it effectively deletes rows from the table.
db.create_tables([User])
qry=User.delete().where (User.age==25)
qry.execute()
Concerned table in database shows effect of DELETE query as follows β
('DELETE FROM "User" WHERE ("User"."age" = ?)', [25])
By using Peewee ORM, it is possible to define a model which will create a table with index on single column as well as multiple columns.
As per the Field attribute definition, setting unique constraint to True will create an index on the mapped field. Similarly, passing index=True parameter to field constructor also create index on the specified field.
In following example, we have two fields in MyUser model, with username field having unique parameter set to True and email field has index=True.
class MyUser(Model):
username = CharField(unique=True)
email = CharField(index=True)
class Meta:
database=db
db_table='MyUser'
As a result, SQLiteStudio graphical user interface (GUI) shows indexes created as follows β
In order to define a multi-column index, we need to add indexes attribute in Meta class inside definition of our model class. It is a tuple of 2-item tuples, one tuple for one index definition. Inside each 2-element tuple, the first part of which is a tuple of the names of the fields, the second part is set to True to make it unique, and otherwise is False.
We define MyUser model with a two-column unique index as follows β
class MyUser (Model):
name=TextField()
city=TextField()
age=IntegerField()
class Meta:
database=db
db_table='MyUser'
indexes=(
(('name', 'city'), True),
)
Accordingly, SQLiteStudio shows index definition as in the following figure β
Index can be built outside model definition as well.
You can also create index by manually providing SQL helper statement as parameter to add_index() method.
MyUser.add_index(SQL('CREATE INDEX idx on MyUser(name);'))
Above method is particularly required when using SQLite. For MySQL and PostgreSQL, we can obtain Index object and use it with add_index() method.
ind=MyUser.index(MyUser.name)
MyUser.add_index(ind)
Constraints are restrictions imposed on the possible values that can be put in a field. One such constraint is primary key. When primary_key=True is specified in Field definition, each row can only store unique value β same value of the field cannot be repeated in another row.
If a field is not a primary key, still it can be constrained to store unique values in table. Field constructor also has constraints parameter.
Following example applies CHECK constraint on age field.
class MyUser (Model):
name=TextField()
city=TextField()
age=IntegerField(constraints=[Check('name<10')])
class Meta:
database=db
db_table='MyUser'
This will generate following Data Definition Language (DDL) expression β
CREATE TABLE MyUser (
id INTEGER NOT NULL
PRIMARY KEY,
name TEXT NOT NULL,
city TEXT NOT NULL,
age INTEGER NOT NULL
CHECK (name < 10)
);
As a result, if a new row with age<10 will result in error.
MyUser.create(name="Rajesh", city="Mumbai",age=9)
peewee.IntegrityError: CHECK constraint failed: MyUser
In the field definition, we can also use DEFAULT constraint as in following definition of city field.
city=TextField(constraints=[SQL("DEFAULT 'Mumbai'")])
So, the model object can be constructed with or without explicit value of city. If not used, city field will be filled by default value β Mumbai.
As mentioned earlier, Peewee supports MySQL database through MySQLDatabase class. However, unlike SQLite database, Peewee canβt create a MySql database. You need to create it manually or using functionality of DB-API compliant module such as pymysql.
First, you should have MySQL server installed in your machine. It can be a standalone MySQL server installed from https://dev.mysql.com/downloads/installer/.
You can also work on Apache bundled with MySQL (such as XAMPP downloaded and installed from https://www.apachefriends.org/download.html ).
Next, we install pymysql module, DB-API compatible Python driver.
pip install pymysql
The create a new database named mydatabase. We shall use phpmyadmin interface available in XAMPP.
If you choose to create database programmatically, use following Python script β
import pymysql
conn = pymysql.connect(host='localhost', user='root', password='')
conn.cursor().execute('CREATE DATABASE mydatabase')
conn.close()
Once a database is created on the server, we can now declare a model and thereby, create a mapped table in it.
The MySQLDatabase object requires server credentials such as host, port, user name and password.
from peewee import *
db = MySQLDatabase('mydatabase', host='localhost', port=3306, user='root', password='')
class MyUser (Model):
name=TextField()
city=TextField(constraints=[SQL("DEFAULT 'Mumbai'")])
age=IntegerField()
class Meta:
database=db
db_table='MyUser'
db.connect()
db.create_tables([MyUser])
The Phpmyadmin web interface now shows myuser table created.
Peewee supports PostgreSQL database as well. It has PostgresqlDatabase class for that purpose. In this chapter, we shall see how we can connect to Postgres database and create a table in it, with the help of Peewee model.
As in case of MySQL, it is not possible to create database on Postgres server with Peeweeβs functionality. The database has to be created manually using Postgres shell or PgAdmin tool.
First, we need to install Postgres server. For windows OS, we can download https://get.enterprisedb.com/postgresql/postgresql-13.1-1-windows-x64.exe and install.
Next, install Python driver for Postgres β Psycopg2 package using pip installer.
pip install psycopg2
Then start the server, either from PgAdmin tool or psql shell. We are now in a position to create a database. Run following Python script to create mydatabase on Postgres server.
import psycopg2
conn = psycopg2.connect(host='localhost', user='postgres', password='postgres')
conn.cursor().execute('CREATE DATABASE mydatabase')
conn.close()
Check that the database is created. In psql shell, it can be verified with \l command β
To declare MyUser model and create a table of same name in above database, run following Python code β
from peewee import *
db = PostgresqlDatabase('mydatabase', host='localhost', port=5432, user='postgres', password='postgres')
class MyUser (Model):
name=TextField()
city=TextField(constraints=[SQL("DEFAULT 'Mumbai'")])
age=IntegerField()
class Meta:
database=db
db_table='MyUser'
db.connect()
db.create_tables([MyUser])
We can verify that table is created. Inside the shell, connect to mydatabase and get list of tables in it.
To check structure of newly created MyUser database, run following query in the shell.
If your database is scheduled to vary at run-time, use DatabaseProxy helper to have better control over how you initialise it. The DatabaseProxy object is a placeholder with the help of which database can be selected in run-time.
In the following example, an appropriate database is selected depending on the applicationβs configuration setting.
from peewee import *
db_proxy = DatabaseProxy() # Create a proxy for our db.
class MyUser (Model):
name=TextField()
city=TextField(constraints=[SQL("DEFAULT 'Mumbai'")])
age=IntegerField()
class Meta:
database=db_proxy
db_table='MyUser'
# Based on configuration, use a different database.
if app.config['TESTING']:
db = SqliteDatabase(':memory:')
elif app.config['DEBUG']:
db = SqliteDatabase('mydatabase.db')
else:
db = PostgresqlDatabase(
'mydatabase', host='localhost', port=5432, user='postgres', password='postgres'
)
# Configure our proxy to use the db we specified in config.
db_proxy.initialize(db)
db.connect()
db.create_tables([MyUser])
You can also associate models to any database object during run-time using bind() method declared in both database class and model class.
Following example uses bind() method in database class.
from peewee import *
class MyUser (Model):
name=TextField()
city=TextField(constraints=[SQL("DEFAULT 'Mumbai'")])
age=IntegerField()
db = MySQLDatabase('mydatabase', host='localhost', port=3306, user='root', password='')
db.connect()
db.bind([MyUser])
db.create_tables([MyUser])
The same bind() method is also defined in Model class.
from peewee import *
class MyUser (Model):
name=TextField()
city=TextField(constraints=[SQL("DEFAULT 'Mumbai'")])
age=IntegerField()
db = MySQLDatabase('mydatabase', host='localhost', port=3306, user='root', password='')
db.connect()
MyUser.bind(db)
db.create_tables([MyUser])
Database object is created with autoconnect parameter set as True by default. Instead, to manage database connection programmatically, it is initially set to False.
db=SqliteDatabase("mydatabase", autoconnect=False)
The database class has connect() method that establishes connection with the database present on the server.
db.connect()
It is always recommended to close the connection at the end of operations performed.
db.close()
If you try to open an already open connection, Peewee raises OperationError.
>>> db.connect()
True
>>> db.connect()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\peewee\lib\site-packages\peewee.py", line 3031, in connect
raise OperationalError('Connection already opened.')
peewee.OperationalError: Connection already opened.
To avoid this error, use reuse_if_open=True as argument to connect() method.
>>> db.connect(reuse_if_open=True)
False
Calling close() on already closed connection wonβt result error. You can however, check if the connection is already closed with is_closed() method.
>>> if db.is_closed()==True:
db.connect()
True
>>>
Instead of explicitly calling db.close() in the end, it is also possible to use database object as context_manager.
from peewee import *
db = SqliteDatabase('mydatabase.db', autoconnect=False)
class User (Model):
user_id=TextField(primary_key=True)
name=TextField()
age=IntegerField()
class Meta:
database=db
db_table='User'
with db:
db.connect()
db.create_tables([User])
Peewee supports implementing different type of SQL JOIN queries. Its Model class has a join() method that returns a Join instance.
M1.joint(m2, join_type, on)
The joins table mapped with M1 model to that of m2 model and returns Join class instance. The on parameter is None by default and is expression to use as join predicate.
Peewee supports following Join types (Default is INNER).
JOIN.INNER
JOIN.INNER
JOIN.LEFT_OUTER
JOIN.LEFT_OUTER
JOIN.RIGHT_OUTER
JOIN.RIGHT_OUTER
JOIN.FULL
JOIN.FULL
JOIN.FULL_OUTER
JOIN.FULL_OUTER
JOIN.CROSS
JOIN.CROSS
To show use of join() method, we first declare following models β
db = SqliteDatabase('mydatabase.db')
class BaseModel(Model):
class Meta:
database = db
class Item(BaseModel):
itemname = TextField()
price = IntegerField()
class Brand(BaseModel):
brandname = TextField()
item = ForeignKeyField(Item, backref='brands')
class Bill(BaseModel):
item = ForeignKeyField(Item, backref='bills')
brand = ForeignKeyField(Brand, backref='bills')
qty = DecimalField()
db.create_tables([Item, Brand, Bill])
Next, we populate these tables with following test data β
The item table is given below β
Given below is the brand table β
The bill table is as follows β
To perform a simple join operation between Brand and Item tables, execute the following code β
qs=Brand.select().join(Item)
for q in qs:
print ("Brand ID:{} Item Name: {} Price: {}".format(q.id, q.brandname, q.item.price))
The resultant output will be as follows β
Brand ID:1 Item Name: Dell Price: 25000
Brand ID:2 Item Name: Epson Price: 12000
Brand ID:3 Item Name: HP Price: 25000
Brand ID:4 Item Name: iBall Price: 4000
Brand ID:5 Item Name: Sharp Price: 12000
We have a Bill model having two foreign key relationships with item and brand models. To fetch data from all three tables, use following code β
qs=Bill.select().join(Brand).join(Item)
for q in qs:
print ("BillNo:{} Brand:{} Item:{} price:{} Quantity:{}".format(q.id, \
q.brand.brandname, q.item.itemname, q.item.price, q.qty))
Following output will be displayed, based on our test data β
BillNo:1 Brand:HP Item:Laptop price:25000 Quantity:5
BillNo:2 Brand:Epson Item:Printer price:12000 Quantity:2
BillNo:3 Brand:iBall Item:Router price:4000 Quantity:5
In SQL, a subquery is an embedded query in WHERE clause of another query. We can implement subquery as a model.select() as a parameter inside where attribute of outer model.select() statement.
To demonstrate use of subquery in Peewee, let us use defined following models β
from peewee import *
db = SqliteDatabase('mydatabase.db')
class BaseModel(Model):
class Meta:
database = db
class Contacts(BaseModel):
RollNo = IntegerField()
Name = TextField()
City = TextField()
class Branches(BaseModel):
RollNo = IntegerField()
Faculty = TextField()
db.create_tables([Contacts, Branches])
After tables are created, they are populated with following sample data β
The contacts table is given below β
In order to display name and city from contact table only for RollNo registered for ETC faculty, following code generates a SELECT query with another SELECT query in its WHERE clause.
#this query is used as subquery
faculty=Branches.select(Branches.RollNo).where(Branches.Faculty=="ETC")
names=Contacts.select().where (Contacts.RollNo .in_(faculty))
print ("RollNo and City for Faculty='ETC'")
for name in names:
print ("RollNo:{} City:{}".format(name.RollNo, name.City))
db.close()
Above code will display the following result:
RollNo and City for Faculty='ETC'
RollNo:103 City:Indore
RollNo:104 City:Nasik
RollNo:108 City:Delhi
RollNo:110 City:Nasik
It is possible to select records from a table using order_by clause along with modelβs select() method. Additionally, by attaching desc() to the field attribute on which sorting is to be performed, records will be collected in descending order.
Following code display records from contact table in ascending order of City names.
rows=Contacts.select().order_by(Contacts.City)
print ("Contact list in order of city")
for row in rows:
print ("RollNo:{} Name: {} City:{}".format(row.RollNo,row.Name, row.City))
Here is the sorted list which is arranged according to ascending order of city name.
Contact list in order of city
RollNo:107 Name: Beena City:Chennai
RollNo:102 Name: Amar City:Delhi
RollNo:108 Name: John City:Delhi
RollNo:103 Name: Raam City:Indore
RollNo:101 Name: Anil City:Mumbai
RollNo:106 Name: Hema City:Nagpur
RollNo:104 Name: Leena City:Nasik
RollNo:109 Name: Jaya City:Nasik
RollNo:110 Name: Raja City:Nasik
RollNo:105 Name: Keshav City:Pune
Following code displays list in descending order of Name field.
rows=Contacts.select().order_by(Contacts.Name.desc())
print ("Contact list in descending order of Name")
for row in rows:
print ("RollNo:{} Name: {} City:{}".format(row.RollNo,row.Name, row.City))
The output is as follows β
Contact list in descending order of Name
RollNo:110 Name: Raja City:Nasik
RollNo:103 Name: Raam City:Indore
RollNo:104 Name: Leena City:Nasik
RollNo:105 Name: Keshav City:Pune
RollNo:108 Name: John City:Delhi
RollNo:109 Name: Jaya City:Nasik
RollNo:106 Name: Hema City:Nagpur
RollNo:107 Name: Beena City:Chennai
RollNo:101 Name: Anil City:Mumbai
RollNo:102 Name: Amar City:Delhi
We can find number of records reported in any SELECT query by attaching count() method. For example, following statement returns number of rows in Contacts table with City=βNasikβ.
qry=Contacts.select().where (Contacts.City=='Nasik').count()
print (qry)
SQL has GROUP BY clause in SELECT query. Peewee supports it in the form of group_by() method. Following code returns city wise count of names in Contacts table.
from peewee import *
db = SqliteDatabase('mydatabase.db')
class Contacts(BaseModel):
RollNo = IntegerField()
Name = TextField()
City = TextField()
class Meta:
database = db
db.create_tables([Contacts])
qry=Contacts.select(Contacts.City, fn.Count(Contacts.City).alias('count')).group_by(Contacts.City)
print (qry.sql())
for q in qry:
print (q.City, q.count)
The SELECT query emitted by Peewee will be as follows β
('SELECT "t1"."City", Count("t1"."City") AS "count" FROM "contacts" AS "t1" GROUP BY "t1"."City"', [])
As per sample data in Contacts table, following output is displayed β
Chennai 1
Delhi 2
Indore 1
Mumbai 1
Nagpur 1
Nasik 3
Pune 1
American National Standards Institute (ANSI) Structured Query Language (SQL) standard defines many SQL functions.
Aggregate functions like the following are useful in Peewee.
AVG() - Returns the average value.
AVG() - Returns the average value.
COUNT() - Returns the number of rows.
COUNT() - Returns the number of rows.
FIRST() - Returns the first value.
FIRST() - Returns the first value.
LAST() - Returns the last value.
LAST() - Returns the last value.
MAX() - Returns the largest value.
MAX() - Returns the largest value.
MIN() - Returns the smallest value.
MIN() - Returns the smallest value.
SUM() - Returns the sum.
SUM() - Returns the sum.
In order to implement these SQL functions, Peewee has a SQL helper function fn(). In above example, we used it to find count of records for each city.
Following example builds a SELECT query that employs SUM() function.
Using Bill and Item tables from models defined earlier, we shall display sum of quantity of each item as entered in Bill table.
The item table with the data is given below β
The bill table is as follows β
We create a join between Bill and Item table, select item name from Item table and sum of quantity from Bill table.
from peewee import *
db = SqliteDatabase('mydatabase.db')
class BaseModel(Model):
class Meta:
database = db
class Item(BaseModel):
itemname = TextField()
price = IntegerField()
class Brand(BaseModel):
brandname = TextField()
item = ForeignKeyField(Item, backref='brands')
class Bill(BaseModel):
item = ForeignKeyField(Item, backref='bills')
brand = ForeignKeyField(Brand, backref='bills')
qty = DecimalField()
db.create_tables([Item, Brand, Bill])
qs=Bill.select(Item.itemname, fn.SUM(Bill.qty).alias('Sum'))
.join(Item).group_by(Item.itemname)
print (qs)
for q in qs:
print ("Item: {} sum: {}".format(q.item.itemname, q.Sum))
db.close()
Above script executes the following SELECT query β
SELECT "t1"."itemname", SUM("t2"."qty") AS "Sum" FROM "bill" AS "t2"
INNER JOIN "item" AS "t1" ON ("t2"."item_id" = "t1"."id") GROUP BY "t1"."itemname"
Accordingly, the output is as follows β
Item: Laptop sum: 6
Item: Printer sum: 8
Item: Router sum: 8
It is possible to iterate over the resultset without creating model instances. This may be achieved by using the following β
tuples() method.
tuples() method.
dicts() method.
dicts() method.
To return data of fields in SELECT query as collection of tuples, use tuples() method.
qry=Contacts.select(Contacts.City, fn.Count(Contacts.City).alias('count'))
.group_by(Contacts.City).tuples()
lst=[]
for q in qry:
lst.append(q)
print (lst)
The output is given below β
[
('Chennai', 1),
('Delhi', 2),
('Indore', 1),
('Mumbai', 1),
('Nagpur', 1),
('Nasik', 3),
('Pune', 1)
]
To obtain collection of dictionary objects β
qs=Brand.select().join(Item).dicts()
lst=[]
for q in qs:
lst.append(q)
print (lst)
The output is stated below β
[
{'id': 1, 'brandname': 'Dell', 'item': 1},
{'id': 2, 'brandname': 'Epson', 'item': 2},
{'id': 3, 'brandname': 'HP', 'item': 1},
{'id': 4, 'brandname': 'iBall', 'item': 3},
{'id': 5, 'brandname': 'Sharp', 'item': 2}
]
Peewee has Expression class with the help of which we can add any customized operator in Peeweeβs list of operators. Constructor for Expression requires three arguments, left operand, operator and right operand.
op=Expression(left, operator, right)
Using Expression class, we define a mod() function that accepts arguments for left and right and β%β as operator.
from peewee import Expression # the building block for expressions
def mod(lhs, rhs):
return Expression(lhs, '%', rhs)
We can use it in a SELECT query to obtain list of records in Contacts table with even id.
from peewee import *
db = SqliteDatabase('mydatabase.db')
class BaseModel(Model):
class Meta:
database = db
class Contacts(BaseModel):
RollNo = IntegerField()
Name = TextField()
City = TextField()
db.create_tables([Contacts])
from peewee import Expression # the building block for expressions
def mod(lhs, rhs):
return Expression(lhs,'%', rhs)
qry=Contacts.select().where (mod(Contacts.id,2)==0)
print (qry.sql())
for q in qry:
print (q.id, q.Name, q.City)
This code will emit following SQL query represented by the string β
('SELECT "t1"."id", "t1"."RollNo", "t1"."Name", "t1"."City" FROM "contacts" AS "t1" WHERE (("t1"."id" % ?) = ?)', [2, 0])
Therefore, the output is as follows β
2 Amar Delhi
4 Leena Nasik
6 Hema Nagpur
8 John Delhi
10 Raja Nasik
Peeweeβs database class has atomic() method that creates a context manager. It starts a new transaction. Inside the context block, it is possible to commit or rollback the transaction depending upon whether it has been successfully done or it encountered exception.
with db.atomic() as transaction:
try:
User.create(name='Amar', age=20)
transaction.commit()
except DatabaseError:
transaction.rollback()
The atomic() can also be used as decorator.
@db.atomic()
def create_user(nm,n):
return User.create(name=nm, age=n)
create_user('Amar', 20)
More than one atomic transaction blocks can also be nested.
with db.atomic() as txn1:
User.create('name'='Amar', age=20)
with db.atomic() as txn2:
User.get(name='Amar')
Pythonβs DB-API standard (recommended by PEP 249) specifies the types of Exception classes to be defined by any DB-API compliant module (such as pymysql, pyscopg2, etc.).
Peewee API provides easy-to-use wrappers for these exceptions. PeeweeException is the base classes from which following Exception classes has been defined in Peewee API β
DatabaseError
DatabaseError
DataError
DataError
IntegrityError
IntegrityError
InterfaceError
InterfaceError
InternalError
InternalError
NotSupportedError
NotSupportedError
OperationalError
OperationalError
ProgrammingError
ProgrammingError
Instead of DB-API specific exceptions to be tried, we can implement above ones from Peewee.
Peewee also provides a non-ORM API to access the databases. Instead of defining models and fields, we can bind the database tables and columns to Table and Column objects defined in Peewee and execute queries with their help.
To begin with, declare a Table object corresponding to the one in our database. You have to specify table name and list of columns. Optionally, a primary key can also be provided.
Contacts=Table('Contacts', ('id', 'RollNo', 'Name', 'City'))
This table object is bound with the database with bind() method.
Contacts=Contacts.bind(db)
Now, we can set up a SELECT query on this table object with select() method and iterate over the resultset as follows β
names=Contacts.select()
for name in names:
print (name)
The rows are by default returned as dictionaries.
{'id': 1, 'RollNo': 101, 'Name': 'Anil', 'City': 'Mumbai'}
{'id': 2, 'RollNo': 102, 'Name': 'Amar', 'City': 'Delhi'}
{'id': 3, 'RollNo': 103, 'Name': 'Raam', 'City': 'Indore'}
{'id': 4, 'RollNo': 104, 'Name': 'Leena', 'City': 'Nasik'}
{'id': 5, 'RollNo': 105, 'Name': 'Keshav', 'City': 'Pune'}
{'id': 6, 'RollNo': 106, 'Name': 'Hema', 'City': 'Nagpur'}
{'id': 7, 'RollNo': 107, 'Name': 'Beena', 'City': 'Chennai'}
{'id': 8, 'RollNo': 108, 'Name': 'John', 'City': 'Delhi'}
{'id': 9, 'RollNo': 109, 'Name': 'Jaya', 'City': 'Nasik'}
{'id': 10, 'RollNo': 110, 'Name': 'Raja', 'City': 'Nasik'}
If needed, they can be obtained as tuples, namedtuples or objects.
The program is as follows β
names=Contacts.select().tuples()
for name in names:
print (name)
The output is given below β
(1, 101, 'Anil', 'Mumbai')
(2, 102, 'Amar', 'Delhi')
(3, 103, 'Raam', 'Indore')
(4, 104, 'Leena', 'Nasik')
(5, 105, 'Keshav', 'Pune')
(6, 106, 'Hema', 'Nagpur')
(7, 107, 'Beena', 'Chennai')
(8, 108, 'John', 'Delhi')
(9, 109, 'Jaya', 'Nasik')
(10, 110, 'Raja', 'Nasik')
The program is stated below β
names=Contacts.select().namedtuples()
for name in names:
print (name)
The output is given below β
Row(id=1, RollNo=101, Name='Anil', City='Mumbai')
Row(id=2, RollNo=102, Name='Amar', City='Delhi')
Row(id=3, RollNo=103, Name='Raam', City='Indore')
Row(id=4, RollNo=104, Name='Leena', City='Nasik')
Row(id=5, RollNo=105, Name='Keshav', City='Pune')
Row(id=6, RollNo=106, Name='Hema', City='Nagpur')
Row(id=7, RollNo=107, Name='Beena', City='Chennai')
Row(id=8, RollNo=108, Name='John', City='Delhi')
Row(id=9, RollNo=109, Name='Jaya', City='Nasik')
Row(id=10, RollNo=110, Name='Raja', City='Nasik')
To insert a new record, INSERT query is constructed as follows β
id = Contacts.insert(RollNo=111, Name='Abdul', City='Surat').execute()
If a list of records to be added is stored either as a list of dictionaries or as list of tuples, they can be added in bulk.
Records=[{βRollNoβ:112, βNameβ:βAjayβ, βCityβ:βMysoreβ},
{βRollNoβ:113, βNameβ:βMajidβ,βCityβ:βDelhiβ}}
Or
Records=[(112, βAjayβ,βMysoreβ), (113, βMajidβ, βDelhiβ)}
The INSERT query is written as follows β
Contacts.insert(Records).execute()
The Peewee Table object has update() method to implement SQL UPDATE query. To change City for all records from Nasik to Nagar, we use following query.
Contacts.update(City='Nagar').where((Contacts.City=='Nasik')).execute()
Finally, Table class in Peewee also has delete() method to implement DELETE query in SQL.
Contacts.delete().where(Contacts.Name=='Abdul').execute()
Peewee can work seamlessly with most of the Python web framework APIs. Whenever the Web Server Gateway Interface (WSGI) server receives a connection request from client, the connection with database is established, and then the connection is closed upon delivering a response.
While using in a Flask based web application, connection has an effect on @app.before_request decorator and is disconnected on @app.teardown_request.
from flask import Flask
from peewee import *
db = SqliteDatabase('mydatabase.db')
app = Flask(__name__)
@app.before_request
def _db_connect():
db.connect()
@app.teardown_request
def _db_close(exc):
if not db.is_closed():
db.close()
Peewee API can also be used in Django. To do so, add a middleware in Django app.
def PeeweeConnectionMiddleware(get_response):
def middleware(request):
db.connect()
try:
response = get_response(request)
finally:
if not db.is_closed():
db.close()
return response
return middleware
Middleware is added in Djangoβs settings module.
# settings.py
MIDDLEWARE_CLASSES = (
# Our custom middleware appears first in the list.
'my_blog.middleware.PeeweeConnectionMiddleware',
#followed by default middleware list.
..
)
Peewee can be comfortably used with other frameworks such as Bottle, Pyramid and Tornado, etc.
Peewee comes with a Playhouse namespace. It is a collection of various extension modules. One of them is a playhouse.sqlite_ext module. It mainly defines SqliteExtDatabase class which inherits SqliteDatabase class, supports following additional features β
The features of SQLite Extensions which are supported by Peewee are as follows β
Full-text search.
Full-text search.
JavaScript Object Notation (JSON) extension integration.
JavaScript Object Notation (JSON) extension integration.
Closure table extension support.
Closure table extension support.
LSM1 extension support.
LSM1 extension support.
User-defined table functions.
User-defined table functions.
Support for online backups using backup API: backup_to_file().
Support for online backups using backup API: backup_to_file().
BLOB API support, for efficient binary data storage.
BLOB API support, for efficient binary data storage.
JSON data can be stored, if a special JSONField is declared as one of the field attributes.
class MyModel(Model):
json_data = JSONField(json_dumps=my_json_dumps)
To activate full-text search, the model can have DocIdField to define primary key.
class NoteIndex(FTSModel):
docid = DocIDField()
content = SearchField()
class Meta:
database = db
FTSModel is a Subclass of VirtualModel which is available at http://docs.peewee-orm.com/en/latest/peewee/sqlite_ext.html#VirtualModel to be used with the FTS3 and FTS4 full-text search extensions. Sqlite will treat all column types as TEXT (although, you can store other data types, Sqlite will treat them as text).
SearchField is a Field-class to be used for columns on models representing full-text search virtual tables.
SqliteDatabase supports AutoField for increasing primary key. However, SqliteExtDatabase supports AutoIncrementField to ensure that primary always increases monotonically, irrespective of row deletions.
SqliteQ module in playhouse namespace (playhouse.sqliteq) defines subclass of SqliteExeDatabase to handle serialised concurrent writes to a SQlite database.
On the other hand, playhouse.apsw module carries support for apsw sqlite driver. Another Python SQLite Wrapper (APSW) is fast and can handle nested transactions, that are managed explicitly by you code.
from apsw_ext import *
db = APSWDatabase('testdb')
class BaseModel(Model):
class Meta:
database = db
class MyModel(BaseModel):
field1 = CharField()
field2 = DateTimeField()
Additional PostgreSQL functionality is enabled by helpers which are defined in playhouse.postgres_ext module. This module defines PostgresqlExtDatabase class and provides the following additional field types to be exclusively used for declaration of model to be mapped against PostgreSQL database table.
The features of PostgreSQL Extensions which are supported by Peewee are as follows β
ArrayField field type, for storing arrays.
ArrayField field type, for storing arrays.
HStoreField field type, for storing key/value pairs.
HStoreField field type, for storing key/value pairs.
IntervalField field type, for storing timedelta objects.
IntervalField field type, for storing timedelta objects.
JSONField field type, for storing JSON data.
JSONField field type, for storing JSON data.
BinaryJSONField field type for the jsonb JSON data type.
BinaryJSONField field type for the jsonb JSON data type.
TSVectorField field type, for storing full-text search data.
TSVectorField field type, for storing full-text search data.
DateTimeTZField field type, a timezone-aware datetime field.
DateTimeTZField field type, a timezone-aware datetime field.
Additional Postgres-specific features in this module are meant to provide.
hstore support.
hstore support.
server-side cursors.
server-side cursors.
full-text search.
full-text search.
Postgres hstore is a key:value store that can be embedded in a table as one of the fields of type HStoreField. To enable hstore support, create database instance with register_hstore=True parameter.
db = PostgresqlExtDatabase('mydatabase', register_hstore=True)
Define a model with one HStoreField.
class Vehicles(BaseExtModel):
type = CharField()
features = HStoreField()
Create a model instance as follows β
v=Vechicle.create(type='Car', specs:{'mfg':'Maruti', 'Fuel':'Petrol', 'model':'Alto'})
To access hstore values β
obj=Vehicle.get(Vehicle.id=v.id)
print (obj.features)
Alternate implementation of MysqlDatabase class is provided by MySQLConnectorDatabase defined in playhouse.mysql_ext module. It uses Pythonβs DB-API compatible official mysql/python connector.
from playhouse.mysql_ext import MySQLConnectorDatabase
db = MySQLConnectorDatabase('mydatabase', host='localhost', user='root', password='')
CockroachDB or Cockroach Database (CRDB) is developed by computer software company Cockroach Labs. It is a scalable, consistently-replicated, transactional datastore which is designed to store copies of data in multiple locations in order to deliver speedy access.
Peewee provides support to this database by way of CockroachDatabase class defined in playhouse.cockroachdb extension module. The module contains definition of CockroachDatabase as subclass of PostgresqlDatabase class from the core module.
Moreover, there is run_transaction() method which runs a function inside a transaction and provides automatic client-side retry logic.
The extension also has certain special field classes that are used as attribute in CRDB compatible model.
UUIDKeyField - A primary-key field that uses CRDBβs UUID type with a default randomly-generated UUID.
UUIDKeyField - A primary-key field that uses CRDBβs UUID type with a default randomly-generated UUID.
RowIDField - A primary-key field that uses CRDBβs INT type with a default unique_rowid().
RowIDField - A primary-key field that uses CRDBβs INT type with a default unique_rowid().
JSONField - Same as the Postgres BinaryJSONField.
JSONField - Same as the Postgres BinaryJSONField.
ArrayField - Same as the Postgres extension, but does not support multi-dimensional arrays.
ArrayField - Same as the Postgres extension, but does not support multi-dimensional arrays.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2626,
"s": 2384,
"text": "Peewee is a Python Object Relational Mapping (ORM) library which was developed by a U.S. based software engineer Charles Leifer in October 2010. Its latest version is 3.13.3. Peewee supports SQLite, MySQL, PostgreSQL and Cockroach databases."
},
{
"code": null,
"e": 2775,
"s": 2626,
"text": "Object Relational Mapping is a programming technique for converting data between incompatible type systems in object-oriented programming languages."
},
{
"code": null,
"e": 2957,
"s": 2775,
"text": "Class as defined in an Object Oriented (OO) programming language such as Python, is considered as non-scalar. It cannot be expressed as primitive types such as integers and strings."
},
{
"code": null,
"e": 3122,
"s": 2957,
"text": "On the other hand, databases like Oracle, MySQL, SQLite and others can only store and manipulate scalar values such as integers and strings organised within tables."
},
{
"code": null,
"e": 3326,
"s": 3122,
"text": "The programmer must either convert the object values into groups of scalar data types for storage in the database or convert them back upon retrieval, or only use simple scalar values within the program."
},
{
"code": null,
"e": 3558,
"s": 3326,
"text": "In an ORM system, each class maps to a table in the underlying database. Instead of writing tedious database interfacing code yourself, an ORM takes care of these issues, while you can focus on programming the logics of the system."
},
{
"code": null,
"e": 3655,
"s": 3558,
"text": "To install latest version of Peewee as hosted on PyPI (Python Package Index), use pip installer."
},
{
"code": null,
"e": 3676,
"s": 3655,
"text": "pip3 install peewee\n"
},
{
"code": null,
"e": 3838,
"s": 3676,
"text": "There are no other dependencies for Peewee to work. It works with SQLite without installing any other package as sqlite3 module is bundled with standard library."
},
{
"code": null,
"e": 4080,
"s": 3838,
"text": "However, to work with MySQL and PostgreSQL, you may have to install DB-API compatible driver modules pymysql and pyscopg2 respectively. Cockroach database is handled through playhouse extension that is installed by default along with Peewee."
},
{
"code": null,
"e": 4221,
"s": 4080,
"text": "Peewee is an open source project hosted on https://github.com/coleifer/peewee repository. Hence, it can be installed from here by using git."
},
{
"code": null,
"e": 4305,
"s": 4221,
"text": "git clone https://github.com/coleifer/peewee.git\ncd peewee\npython setup.py install\n"
},
{
"code": null,
"e": 4520,
"s": 4305,
"text": "An object of Database class from Peewee package represents connection to a database. Peewee provides out-of-box support for SQLite, PostgreSQL and MySQL databases through corresponding subclasses of Database class."
},
{
"code": null,
"e": 4721,
"s": 4520,
"text": "Database class instance has all the information required to open connection with database engine, and is used to execute queries, manage transactions and perform introspection of tables, columns, etc."
},
{
"code": null,
"e": 5024,
"s": 4721,
"text": "Database class has SqliteDatabase, PostgresqlDatabase and MySQLDatabase sub-classes. While DB-API driver for SQLite in the form of sqlite3 module is included in Pythonβs standard library, psycopg2 and pymysql modules will have to be installed first for using PostgreSql and MySQL databases with Peewee."
},
{
"code": null,
"e": 5209,
"s": 5024,
"text": "Python has built-in support for SQLite database in the form of sqlite3 module. Hence, it is very easy to connect. Object of SqliteDatabase class in Peewee represents connection object."
},
{
"code": null,
"e": 5253,
"s": 5209,
"text": "con=SqliteDatabase(name, pragmas, timeout)\n"
},
{
"code": null,
"e": 5473,
"s": 5253,
"text": "Here, pragma is SQLite extension which is used to modify operation of SQLite library. This parameter is either a dictionary or a list of 2-tuples containing pragma key and value to set every time a connection is opened."
},
{
"code": null,
"e": 5587,
"s": 5473,
"text": "Timeout parameter is specified in seconds to set busy-timeout of SQLite driver. Both the parameters are optional."
},
{
"code": null,
"e": 5686,
"s": 5587,
"text": "Following statement creates a connection with a new SQLite database (if it doesnβt exist already)."
},
{
"code": null,
"e": 5735,
"s": 5686,
"text": ">>> db = peewee.SqliteDatabase('mydatabase.db')\n"
},
{
"code": null,
"e": 5919,
"s": 5735,
"text": "Pragma parameters are generally given for a new database connection. Typical attributes mentioned in pragmase dictionary are journal_mode, cache_size, locking_mode, foreign-keys, etc."
},
{
"code": null,
"e": 6038,
"s": 5919,
"text": ">>> db = peewee.SqliteDatabase(\n 'test.db', pragmas={'journal_mode': 'wal', 'cache_size': 10000,'foreign_keys': 1}\n)"
},
{
"code": null,
"e": 6092,
"s": 6038,
"text": "Following pragma settings are ideal to be specified β"
},
{
"code": null,
"e": 6325,
"s": 6092,
"text": "Peewee also has Another Python SQLite Wrapper (apsw), an advanced sqlite driver. It provides advanced features such as virtual tables and file systems, and shared connections. APSW is faster than the standard library sqlite3 module."
},
{
"code": null,
"e": 6551,
"s": 6325,
"text": "An object of Model sub class in Peewee API corresponds to a table in the database with which connection has been established. It allows performing database table operations with the help of methods defined in the Model class."
},
{
"code": null,
"e": 6979,
"s": 6551,
"text": "A user defined Model has one or more class attributes, each of them is an object of Field class. Peewee has a number of subclasses for holding data of different types. Examples are TextField, DatetimeField, etc. They correspond to the fields or columns in the database table. Reference of associated database and table and model configuration is mentioned in Meta class. Following attributes are used to specify configuration β"
},
{
"code": null,
"e": 7027,
"s": 6979,
"text": "The meta class attributes are explained below β"
},
{
"code": null,
"e": 7036,
"s": 7027,
"text": "Database"
},
{
"code": null,
"e": 7056,
"s": 7036,
"text": "Database for model."
},
{
"code": null,
"e": 7065,
"s": 7056,
"text": "db_table"
},
{
"code": null,
"e": 7137,
"s": 7065,
"text": "Name of the table to store data. By default, it is name of model class."
},
{
"code": null,
"e": 7145,
"s": 7137,
"text": "Indexes"
},
{
"code": null,
"e": 7172,
"s": 7145,
"text": "A list of fields to index."
},
{
"code": null,
"e": 7184,
"s": 7172,
"text": "primary_key"
},
{
"code": null,
"e": 7210,
"s": 7184,
"text": "A composite key instance."
},
{
"code": null,
"e": 7222,
"s": 7210,
"text": "Constraints"
},
{
"code": null,
"e": 7251,
"s": 7222,
"text": "A list of table constraints."
},
{
"code": null,
"e": 7258,
"s": 7251,
"text": "Schema"
},
{
"code": null,
"e": 7293,
"s": 7258,
"text": "The database schema for the model."
},
{
"code": null,
"e": 7303,
"s": 7293,
"text": "Temporary"
},
{
"code": null,
"e": 7329,
"s": 7303,
"text": "Indicate temporary table."
},
{
"code": null,
"e": 7340,
"s": 7329,
"text": "depends_on"
},
{
"code": null,
"e": 7393,
"s": 7340,
"text": "Indicate this table depends on another for creation."
},
{
"code": null,
"e": 7407,
"s": 7393,
"text": "without_rowid"
},
{
"code": null,
"e": 7464,
"s": 7407,
"text": "Indicate that table should not have rowid (SQLite only)."
},
{
"code": null,
"e": 7533,
"s": 7464,
"text": "Following code defines Model class for User table in mydatabase.db β"
},
{
"code": null,
"e": 7728,
"s": 7533,
"text": "from peewee import *\ndb = SqliteDatabase('mydatabase.db')\nclass User (Model):\n name=TextField()\n age=IntegerField()\n class Meta:\n database=db\n db_table='User'\nUser.create_table()"
},
{
"code": null,
"e": 7898,
"s": 7728,
"text": "The create_table() method is a classmethod of Model class that performs equivalent CREATE TABLE query. Another instance method save() adds a row corresponding to object."
},
{
"code": null,
"e": 8139,
"s": 7898,
"text": "from peewee import *\ndb = SqliteDatabase('mydatabase.db')\nclass User (Model):\n name=TextField()\n age=IntegerField()\n class Meta:\n database=db\n db_table='User'\n\nUser.create_table()\nrec1=User(name=\"Rajesh\", age=21)\nrec1.save()"
},
{
"code": null,
"e": 8185,
"s": 8139,
"text": "Other methods in Model class are as follows β"
},
{
"code": null,
"e": 8205,
"s": 8185,
"text": "Classmethod alias()"
},
{
"code": null,
"e": 8309,
"s": 8205,
"text": "Create an alias to the model-class. It allows the same Model to any referred multiple times in a query."
},
{
"code": null,
"e": 8330,
"s": 8309,
"text": "Classmethod select()"
},
{
"code": null,
"e": 8462,
"s": 8330,
"text": "Performs a SELECT query operation. If no fields are explicitly provided as argument, the query will by default SELECT * equivalent."
},
{
"code": null,
"e": 8483,
"s": 8462,
"text": "Classmethod update()"
},
{
"code": null,
"e": 8518,
"s": 8483,
"text": "Performs an UPDATE query function."
},
{
"code": null,
"e": 8539,
"s": 8518,
"text": "classmethod insert()"
},
{
"code": null,
"e": 8598,
"s": 8539,
"text": "Inserts a new row in the underlying table mapped to model."
},
{
"code": null,
"e": 8619,
"s": 8598,
"text": "classmethod delete()"
},
{
"code": null,
"e": 8698,
"s": 8619,
"text": "Executes delete query and is usually associated with a filter by where clause."
},
{
"code": null,
"e": 8716,
"s": 8698,
"text": "classmethod get()"
},
{
"code": null,
"e": 8784,
"s": 8716,
"text": "Retrieve a single row from mapped table matching the given filters."
},
{
"code": null,
"e": 8793,
"s": 8784,
"text": "get_id()"
},
{
"code": null,
"e": 8839,
"s": 8793,
"text": "Instance method returns primary key of a row."
},
{
"code": null,
"e": 8846,
"s": 8839,
"text": "save()"
},
{
"code": null,
"e": 8971,
"s": 8846,
"text": "Save the data of object as a new row. If primary-key value is already present, it will cause an UPDATE query to be executed."
},
{
"code": null,
"e": 8990,
"s": 8971,
"text": "classmethod bind()"
},
{
"code": null,
"e": 9028,
"s": 8990,
"text": "Bind the model to the given database."
},
{
"code": null,
"e": 9230,
"s": 9028,
"text": "Model class contains one or more attributes that are objects of Field class in Peewee. Base Field class is not directly instantiated. Peewee defines different sub classes for equivalent SQL data types."
},
{
"code": null,
"e": 9283,
"s": 9230,
"text": "Constructor of Field class has following parametersβ"
},
{
"code": null,
"e": 9301,
"s": 9283,
"text": "column_name (str)"
},
{
"code": null,
"e": 9332,
"s": 9301,
"text": "Specify column name for field."
},
{
"code": null,
"e": 9351,
"s": 9332,
"text": "primary_key (bool)"
},
{
"code": null,
"e": 9377,
"s": 9351,
"text": "Field is the primary key."
},
{
"code": null,
"e": 9396,
"s": 9377,
"text": "constraints (list)"
},
{
"code": null,
"e": 9435,
"s": 9396,
"text": "List of constraints to apply to column"
},
{
"code": null,
"e": 9450,
"s": 9435,
"text": "choices (list)"
},
{
"code": null,
"e": 9515,
"s": 9450,
"text": "An iterable of 2-tuples mapping column values to display labels."
},
{
"code": null,
"e": 9527,
"s": 9515,
"text": "null (bool)"
},
{
"code": null,
"e": 9547,
"s": 9527,
"text": "Field allows NULLs."
},
{
"code": null,
"e": 9560,
"s": 9547,
"text": "index (bool)"
},
{
"code": null,
"e": 9586,
"s": 9560,
"text": "Create an index on field."
},
{
"code": null,
"e": 9600,
"s": 9586,
"text": "unique (bool)"
},
{
"code": null,
"e": 9633,
"s": 9600,
"text": "Create an unique index on field."
},
{
"code": null,
"e": 9641,
"s": 9633,
"text": "Default"
},
{
"code": null,
"e": 9656,
"s": 9641,
"text": "Default value."
},
{
"code": null,
"e": 9672,
"s": 9656,
"text": "collation (str)"
},
{
"code": null,
"e": 9698,
"s": 9672,
"text": "Collation name for field."
},
{
"code": null,
"e": 9714,
"s": 9698,
"text": "help_text (str)"
},
{
"code": null,
"e": 9754,
"s": 9714,
"text": "Help-text for field, metadata purposes."
},
{
"code": null,
"e": 9773,
"s": 9754,
"text": "verbose_name (str)"
},
{
"code": null,
"e": 9816,
"s": 9773,
"text": "Verbose name for field, metadata purposes."
},
{
"code": null,
"e": 9940,
"s": 9816,
"text": "Subclasses of Field class are mapped to corresponding data types in various databases, i.e. SQLite, PostgreSQL, MySQL, etc."
},
{
"code": null,
"e": 9994,
"s": 9940,
"text": "The numeric field classes in Peewee are given below β"
},
{
"code": null,
"e": 10007,
"s": 9994,
"text": "IntegerField"
},
{
"code": null,
"e": 10041,
"s": 10007,
"text": "Field class for storing integers."
},
{
"code": null,
"e": 10057,
"s": 10041,
"text": "BigIntegerField"
},
{
"code": null,
"e": 10184,
"s": 10057,
"text": "Field class for storing big integers (maps to integer, bigint, and bigint type in SQLite, PostegreSQL and MySQL respectively)."
},
{
"code": null,
"e": 10202,
"s": 10184,
"text": "SmallIntegerField"
},
{
"code": null,
"e": 10269,
"s": 10202,
"text": "Field class for storing small integers (if supported by database)."
},
{
"code": null,
"e": 10280,
"s": 10269,
"text": "FloatField"
},
{
"code": null,
"e": 10359,
"s": 10280,
"text": "Field class for storing floating-point numbers corresponds to real data types."
},
{
"code": null,
"e": 10371,
"s": 10359,
"text": "DoubleField"
},
{
"code": null,
"e": 10497,
"s": 10371,
"text": "Field class for storing double-precision floating-point numbers maps to equivalent data types in corresponding SQL databases."
},
{
"code": null,
"e": 10510,
"s": 10497,
"text": "DecimalField"
},
{
"code": null,
"e": 10588,
"s": 10510,
"text": "Field class for storing decimal numbers. The parameters are mentioned below β"
},
{
"code": null,
"e": 10632,
"s": 10588,
"text": "max_digits (int) β Maximum digits to store."
},
{
"code": null,
"e": 10676,
"s": 10632,
"text": "max_digits (int) β Maximum digits to store."
},
{
"code": null,
"e": 10718,
"s": 10676,
"text": "decimal_places (int) β Maximum precision."
},
{
"code": null,
"e": 10760,
"s": 10718,
"text": "decimal_places (int) β Maximum precision."
},
{
"code": null,
"e": 10808,
"s": 10760,
"text": "auto_round (bool) β Automatically round values."
},
{
"code": null,
"e": 10856,
"s": 10808,
"text": "auto_round (bool) β Automatically round values."
},
{
"code": null,
"e": 10919,
"s": 10856,
"text": "The text fields which are available in Peewee are as follows β"
},
{
"code": null,
"e": 10929,
"s": 10919,
"text": "CharField"
},
{
"code": null,
"e": 11019,
"s": 10929,
"text": "Field class for storing strings. Max 255 characters. Equivalent SQL data type is varchar."
},
{
"code": null,
"e": 11034,
"s": 11019,
"text": "FixedCharField"
},
{
"code": null,
"e": 11080,
"s": 11034,
"text": "Field class for storing fixed-length strings."
},
{
"code": null,
"e": 11090,
"s": 11080,
"text": "TextField"
},
{
"code": null,
"e": 11192,
"s": 11090,
"text": "Field class for storing text. Maps to TEXT data type in SQLite and PostgreSQL, and longtext in MySQL."
},
{
"code": null,
"e": 11242,
"s": 11192,
"text": "The binary fields in Peewee are explained below β"
},
{
"code": null,
"e": 11252,
"s": 11242,
"text": "BlobField"
},
{
"code": null,
"e": 11289,
"s": 11252,
"text": "Field class for storing binary data."
},
{
"code": null,
"e": 11298,
"s": 11289,
"text": "BitField"
},
{
"code": null,
"e": 11358,
"s": 11298,
"text": "Field class for storing options in a 64-bit integer column."
},
{
"code": null,
"e": 11370,
"s": 11358,
"text": "BigBitField"
},
{
"code": null,
"e": 11509,
"s": 11370,
"text": "Field class for storing arbitrarily-large bitmaps in a Binary Large OBject (BLOB). The field will grow the underlying buffer as necessary."
},
{
"code": null,
"e": 11519,
"s": 11509,
"text": "UUIDField"
},
{
"code": null,
"e": 11689,
"s": 11519,
"text": "Field class for storing universally unique identifier (UUID) objects. Maps to UUID type in Postgres. SQLite and MySQL do not have a UUID type, it is stored as a VARCHAR."
},
{
"code": null,
"e": 11741,
"s": 11689,
"text": "The date and time fields in Peewee are as follows β"
},
{
"code": null,
"e": 11755,
"s": 11741,
"text": "DateTimeField"
},
{
"code": null,
"e": 11890,
"s": 11755,
"text": "Field class for storing datetime.datetime objects. Accepts a special parameter string formats, with which the datetime can be encoded."
},
{
"code": null,
"e": 11900,
"s": 11890,
"text": "DateField"
},
{
"code": null,
"e": 12006,
"s": 11900,
"text": "Field class for storing datetime.date objects. Accepts a special parameter string formats to encode date."
},
{
"code": null,
"e": 12016,
"s": 12006,
"text": "TimeField"
},
{
"code": null,
"e": 12119,
"s": 12016,
"text": "Field class for storing datetime.time objectsAccepts a special parameter formats to show encoded time."
},
{
"code": null,
"e": 12198,
"s": 12119,
"text": "Since SQLite doesnβt have DateTime data types, this field is mapped as string."
},
{
"code": null,
"e": 12370,
"s": 12198,
"text": "This class is used to establish foreign key relationship in two models and hence, the respective tables in database. This class in instantiated with following parameters β"
},
{
"code": null,
"e": 12384,
"s": 12370,
"text": "model (Model)"
},
{
"code": null,
"e": 12460,
"s": 12384,
"text": "Model to reference. If set to βselfβ, it is a self-referential foreign key."
},
{
"code": null,
"e": 12474,
"s": 12460,
"text": "field (Field)"
},
{
"code": null,
"e": 12528,
"s": 12474,
"text": "Field to reference on model (default is primary key)."
},
{
"code": null,
"e": 12542,
"s": 12528,
"text": "backref (str)"
},
{
"code": null,
"e": 12618,
"s": 12542,
"text": "Accessor name for back-reference. β+β disables the back-reference accessor."
},
{
"code": null,
"e": 12634,
"s": 12618,
"text": "on_delete (str)"
},
{
"code": null,
"e": 12652,
"s": 12634,
"text": "ON DELETE action."
},
{
"code": null,
"e": 12668,
"s": 12652,
"text": "on_update (str)"
},
{
"code": null,
"e": 12686,
"s": 12668,
"text": "ON UPDATE action."
},
{
"code": null,
"e": 12703,
"s": 12686,
"text": "lazy_load (bool)"
},
{
"code": null,
"e": 12877,
"s": 12703,
"text": "Fetch the related object, when the foreign-key field attribute is accessed. If FALSE, accessing the foreign-key field will return the value stored in the foreign-key column."
},
{
"code": null,
"e": 12916,
"s": 12877,
"text": "Here is an example of ForeignKeyField."
},
{
"code": null,
"e": 13431,
"s": 12916,
"text": "from peewee import *\n\ndb = SqliteDatabase('mydatabase.db')\nclass Customer(Model):\n id=IntegerField(primary_key=True)\n name = TextField()\n address = TextField()\n phone = IntegerField()\n class Meta:\n database=db\n db_table='Customers'\n\nclass Invoice(Model):\n id=IntegerField(primary_key=True)\n invno=IntegerField()\n amount=IntegerField()\n custid=ForeignKeyField(Customer, backref='Invoices')\n class Meta:\n database=db\n db_table='Invoices'\n\ndb.create_tables([Customer, Invoice])"
},
{
"code": null,
"e": 13494,
"s": 13431,
"text": "When above script is executed, following SQL queries are run β"
},
{
"code": null,
"e": 13855,
"s": 13494,
"text": "CREATE TABLE Customers (\n id INTEGER NOT NULL\n PRIMARY KEY,\n name TEXT NOT NULL,\n address TEXT NOT NULL,\n phone INTEGER NOT NULL\n);\nCREATE TABLE Invoices (\n id INTEGER NOT NULL\n PRIMARY KEY,\n invno INTEGER NOT NULL,\n amount INTEGER NOT NULL,\n custid_id INTEGER NOT NULL,\n FOREIGN KEY (\n custid_id\n )\n REFERENCES Customers (id)\n);"
},
{
"code": null,
"e": 13935,
"s": 13855,
"text": "When verified in SQLiteStuidio GUI tool, the table structure appears as below β"
},
{
"code": null,
"e": 13977,
"s": 13935,
"text": "The other field types in Peewee include β"
},
{
"code": null,
"e": 13985,
"s": 13977,
"text": "IPField"
},
{
"code": null,
"e": 14051,
"s": 13985,
"text": "Field class for storing IPv4 addresses efficiently (as integers)."
},
{
"code": null,
"e": 14064,
"s": 14051,
"text": "BooleanField"
},
{
"code": null,
"e": 14104,
"s": 14064,
"text": "Field class for storing boolean values."
},
{
"code": null,
"e": 14114,
"s": 14104,
"text": "AutoField"
},
{
"code": null,
"e": 14170,
"s": 14114,
"text": "Field class for storing auto-incrementing primary keys."
},
{
"code": null,
"e": 14184,
"s": 14170,
"text": "IdentityField"
},
{
"code": null,
"e": 14389,
"s": 14184,
"text": "Field class for storing auto-incrementing primary keys using the new Postgres 10 IDENTITYField class for storing auto-incrementing primary keys using the new Postgres 10 IDENTITY column type. column type."
},
{
"code": null,
"e": 14546,
"s": 14389,
"text": "In Peewee, there are more than one commands by which, it is possible to add a new record in the table. We have already used save() method of Model instance."
},
{
"code": null,
"e": 14591,
"s": 14546,
"text": "rec1=User(name=\"Rajesh\", age=21)\nrec1.save()"
},
{
"code": null,
"e": 14700,
"s": 14591,
"text": "The Peewee.Model class also has a create() method that creates a new instance and add its data in the table."
},
{
"code": null,
"e": 14735,
"s": 14700,
"text": "User.create(name=\"Kiran\", age=19)\n"
},
{
"code": null,
"e": 14917,
"s": 14735,
"text": "In addition to this, Model also has insert() as class method that constructs SQL insert query object. The execute() method of Query object performs adding a row in underlying table."
},
{
"code": null,
"e": 14966,
"s": 14917,
"text": "q = User.insert(name='Lata', age=20)\nq.execute()"
},
{
"code": null,
"e": 15047,
"s": 14966,
"text": "The query object is an equivalent INSERT query.q.sql() returns the query string."
},
{
"code": null,
"e": 15130,
"s": 15047,
"text": "print (q.sql())\n('INSERT INTO \"User\" (\"name\", \"age\") VALUES (?, ?)', ['Lata', 20])"
},
{
"code": null,
"e": 15217,
"s": 15130,
"text": "Here is the complete code that demonstrates the use of above ways of inserting record."
},
{
"code": null,
"e": 15594,
"s": 15217,
"text": "from peewee import *\ndb = SqliteDatabase('mydatabase.db')\nclass User (Model):\n name=TextField()\n age=IntegerField()\n class Meta:\n database=db\n db_table='User'\n\ndb.create_tables([User])\nrec1=User(name=\"Rajesh\", age=21)\nrec1.save()\na=User(name=\"Amar\", age=20)\na.save()\nUser.create(name=\"Kiran\", age=19)\nq = User.insert(name='Lata', age=20)\nq.execute()\ndb.close()"
},
{
"code": null,
"e": 15640,
"s": 15594,
"text": "We can verify the result in SQLiteStudio GUI."
},
{
"code": null,
"e": 15750,
"s": 15640,
"text": "In order to use multiple rows at once in the table, Peewee provides two methods: bulk_create and insert_many."
},
{
"code": null,
"e": 15889,
"s": 15750,
"text": "The insert_many() method generates equivalent INSERT query, using list of dictionary objects, each having field value pairs of one object."
},
{
"code": null,
"e": 15988,
"s": 15889,
"text": "rows=[{\"name\":\"Rajesh\", \"age\":21}, {\"name\":\"Amar\", \"age\":20}]\nq=User.insert_many(rows)\nq.execute()"
},
{
"code": null,
"e": 16061,
"s": 15988,
"text": "Here too, q.sql() returns the INSERT query string is obtained as below β"
},
{
"code": null,
"e": 16166,
"s": 16061,
"text": "print (q.sql())\n('INSERT INTO \"User\" (\"name\", \"age\") VALUES (?, ?), (?, ?)', ['Rajesh', 21, 'Amar', 20])"
},
{
"code": null,
"e": 16276,
"s": 16166,
"text": "This method takes a list argument that contains one or more unsaved instances of the model mapped to a table."
},
{
"code": null,
"e": 16357,
"s": 16276,
"text": "a=User(name=\"Kiran\", age=19)\nb=User(name='Lata', age=20)\nUser.bulk_create([a,b])"
},
{
"code": null,
"e": 16427,
"s": 16357,
"text": "Following code uses both approaches to perform bulk insert operation."
},
{
"code": null,
"e": 16819,
"s": 16427,
"text": "from peewee import *\ndb = SqliteDatabase('mydatabase.db')\nclass User (Model):\n name=TextField()\n age=IntegerField()\n class Meta:\n database=db\n db_table='User'\n\ndb.create_tables([User])\nrows=[{\"name\":\"Rajesh\", \"age\":21}, {\"name\":\"Amar\", \"age\":20}]\nq=User.insert_many(rows)\nq.execute()\na=User(name=\"Kiran\", age=19)\nb=User(name='Lata', age=20)\nUser.bulk_create([a,b])\ndb.close()"
},
{
"code": null,
"e": 17059,
"s": 16819,
"text": "Simplest and the most obvious way to retrieve data from tables is to call select() method of corresponding model. Inside select() method, we can specify one or more field attributes. However, if none is specified, all columns are selected."
},
{
"code": null,
"e": 17229,
"s": 17059,
"text": "Model.select() returns a list of model instances corresponding to rows. This is similar to the result set returned by SELECT query, which can be traversed by a for loop."
},
{
"code": null,
"e": 17526,
"s": 17229,
"text": "from peewee import *\ndb = SqliteDatabase('mydatabase.db')\nclass User (Model):\n name=TextField()\n age=IntegerField()\n class Meta:\n database=db\n db_table='User'\nrows=User.select()\nprint (rows.sql())\nfor row in rows:\n print (\"name: {} age: {}\".format(row.name, row.age))\ndb.close()"
},
{
"code": null,
"e": 17575,
"s": 17526,
"text": "The above script displays the following output β"
},
{
"code": null,
"e": 17729,
"s": 17575,
"text": "('SELECT \"t1\".\"id\", \"t1\".\"name\", \"t1\".\"age\" FROM \"User\" AS \"t1\"', [])\nname: Rajesh age: 21\nname: Amar age : 20\nname: Kiran age : 19\nname: Lata age : 20"
},
{
"code": null,
"e": 17855,
"s": 17729,
"text": "It is possible to retrieve data from SQLite table by using where clause. Peewee supports following list of logical operators."
},
{
"code": null,
"e": 17898,
"s": 17855,
"text": "Following code displays name with age>=20:"
},
{
"code": null,
"e": 18011,
"s": 17898,
"text": "rows=User.select().where (User.age>=20)\nfor row in rows:\n print (\"name: {} age: {}\".format(row.name, row.age))"
},
{
"code": null,
"e": 18078,
"s": 18011,
"text": "Following code displays only those name present in the names list."
},
{
"code": null,
"e": 18237,
"s": 18078,
"text": "names=['Anil', 'Amar', 'Kiran', 'Bala']\nrows=User.select().where (User.name << names)\nfor row in rows:\n print (\"name: {} age: {}\".format(row.name, row.age))"
},
{
"code": null,
"e": 18289,
"s": 18237,
"text": "The SELECT query thus generated by Peewee will be β"
},
{
"code": null,
"e": 18430,
"s": 18289,
"text": "('SELECT \"t1\".\"id\", \"t1\".\"name\", \"t1\".\"age\" FROM \"User\" AS \"t1\" WHERE \n (\"t1\".\"name\" IN (?, ?, ?, ?))', ['Anil', 'Amar', 'Kiran', 'Bala'])"
},
{
"code": null,
"e": 18468,
"s": 18430,
"text": "Resultant output will be as follows β"
},
{
"code": null,
"e": 18508,
"s": 18468,
"text": "name: Amar age: 20\nname: Kiran age: 19\n"
},
{
"code": null,
"e": 18628,
"s": 18508,
"text": "In addition to the above logical operators as defined in core Python, Peewee provides following methods for filtering β"
},
{
"code": null,
"e": 18640,
"s": 18628,
"text": ".in_(value)"
},
{
"code": null,
"e": 18655,
"s": 18640,
"text": ".not_in(value)"
},
{
"code": null,
"e": 18670,
"s": 18655,
"text": "NOT IN lookup."
},
{
"code": null,
"e": 18688,
"s": 18670,
"text": ".is_null(is_null)"
},
{
"code": null,
"e": 18735,
"s": 18688,
"text": "IS NULL or IS NOT NULL. Accepts boolean param."
},
{
"code": null,
"e": 18753,
"s": 18735,
"text": ".contains(substr)"
},
{
"code": null,
"e": 18785,
"s": 18753,
"text": "Wild-card search for substring."
},
{
"code": null,
"e": 18805,
"s": 18785,
"text": ".startswith(prefix)"
},
{
"code": null,
"e": 18846,
"s": 18805,
"text": "Search for values beginning with prefix."
},
{
"code": null,
"e": 18864,
"s": 18846,
"text": ".endswith(suffix)"
},
{
"code": null,
"e": 18902,
"s": 18864,
"text": "Search for values ending with suffix."
},
{
"code": null,
"e": 18922,
"s": 18902,
"text": ".between(low, high)"
},
{
"code": null,
"e": 18962,
"s": 18922,
"text": "Search for values between low and high."
},
{
"code": null,
"e": 18975,
"s": 18962,
"text": ".regexp(exp)"
},
{
"code": null,
"e": 19018,
"s": 18975,
"text": "Regular expression match (case-sensitive)."
},
{
"code": null,
"e": 19032,
"s": 19018,
"text": ".iregexp(exp)"
},
{
"code": null,
"e": 19077,
"s": 19032,
"text": "Regular expression match (case-insensitive)."
},
{
"code": null,
"e": 19093,
"s": 19077,
"text": ".bin_and(value)"
},
{
"code": null,
"e": 19105,
"s": 19093,
"text": "Binary AND."
},
{
"code": null,
"e": 19120,
"s": 19105,
"text": ".bin_or(value)"
},
{
"code": null,
"e": 19131,
"s": 19120,
"text": "Binary OR."
},
{
"code": null,
"e": 19146,
"s": 19131,
"text": ".concat(other)"
},
{
"code": null,
"e": 19191,
"s": 19146,
"text": "Concatenate two strings or objects using ||."
},
{
"code": null,
"e": 19203,
"s": 19191,
"text": ".distinct()"
},
{
"code": null,
"e": 19239,
"s": 19203,
"text": "Mark column for DISTINCT selection."
},
{
"code": null,
"e": 19259,
"s": 19239,
"text": ".collate(collation)"
},
{
"code": null,
"e": 19300,
"s": 19259,
"text": "Specify column with the given collation."
},
{
"code": null,
"e": 19312,
"s": 19300,
"text": ".cast(type)"
},
{
"code": null,
"e": 19360,
"s": 19312,
"text": "Cast the value of the column to the given type."
},
{
"code": null,
"e": 19477,
"s": 19360,
"text": "As an example of above methods, look at the following code. It retrieves names starting with βRβ or ending with βrβ."
},
{
"code": null,
"e": 19557,
"s": 19477,
"text": "rows=User.select().where (User.name.startswith('R') | User.name.endswith('r'))\n"
},
{
"code": null,
"e": 19589,
"s": 19557,
"text": "Equivalent SQL SELECT query is:"
},
{
"code": null,
"e": 19726,
"s": 19589,
"text": "('SELECT \"t1\".\"id\", \"t1\".\"name\", \"t1\".\"age\" FROM \"User\" AS \"t1\" WHERE \n ((\"t1\".\"name\" LIKE ?) OR (\"t1\".\"name\" LIKE ?))', ['R%', '%r'])"
},
{
"code": null,
"e": 19828,
"s": 19726,
"text": "Pythonβs built-in operators in, not in, and, or etc. will not work. Instead, use Peewee alternatives."
},
{
"code": null,
"e": 19842,
"s": 19828,
"text": "You can use β"
},
{
"code": null,
"e": 19907,
"s": 19842,
"text": ".in_() and .not_in() methods instead of in and not in operators."
},
{
"code": null,
"e": 19972,
"s": 19907,
"text": ".in_() and .not_in() methods instead of in and not in operators."
},
{
"code": null,
"e": 19990,
"s": 19972,
"text": "& instead of and."
},
{
"code": null,
"e": 20008,
"s": 19990,
"text": "& instead of and."
},
{
"code": null,
"e": 20025,
"s": 20008,
"text": "| instead of or."
},
{
"code": null,
"e": 20042,
"s": 20025,
"text": "| instead of or."
},
{
"code": null,
"e": 20060,
"s": 20042,
"text": "~ instead of not."
},
{
"code": null,
"e": 20078,
"s": 20060,
"text": "~ instead of not."
},
{
"code": null,
"e": 20104,
"s": 20078,
"text": ".is_null() instead of is."
},
{
"code": null,
"e": 20130,
"s": 20104,
"text": ".is_null() instead of is."
},
{
"code": null,
"e": 20147,
"s": 20130,
"text": "None or == None."
},
{
"code": null,
"e": 20164,
"s": 20147,
"text": "None or == None."
},
{
"code": null,
"e": 20661,
"s": 20164,
"text": "It is recommended that the table in a relational database, should have one of the columns applied with primary key constraint. Accordingly, Peewee Model class can also specify field attribute with primary-key argument set to True. However, if model class doesnβt have any primary key, Peewee automatically creates one with the name βidβ. Note that the User model defined above doesnβt have any field explicitly defined as primary key. Hence, the mapped User table in our database has an id field."
},
{
"code": null,
"e": 20765,
"s": 20661,
"text": "To define an auto-incrementing integer primary key, use AutoField object as one attribute in the model."
},
{
"code": null,
"e": 20905,
"s": 20765,
"text": "class User (Model):\n user_id=AutoField()\n name=TextField()\n age=IntegerField()\n class Meta:\n database=db\n db_table='User'"
},
{
"code": null,
"e": 20961,
"s": 20905,
"text": "This will translate into following CREATE TABLE query β"
},
{
"code": null,
"e": 21075,
"s": 20961,
"text": "CREATE TABLE User (\n user_id INTEGER NOT NULL\n PRIMARY KEY,\n name TEXT NOT NULL,\n age INTEGER NOT NULL\n);"
},
{
"code": null,
"e": 21243,
"s": 21075,
"text": "You can also assign any non-integer field as a primary key by setting primary_key parameter to True. Let us say we want to store certain alphanumeric value as user_id."
},
{
"code": null,
"e": 21399,
"s": 21243,
"text": "class User (Model):\n user_id=TextField(primary_key=True)\n name=TextField()\n age=IntegerField()\n class Meta:\n database=db\n db_table='User'"
},
{
"code": null,
"e": 21697,
"s": 21399,
"text": "However, when model contains non-integer field as primary key, the save() method of model instance doesnβt cause database driver to generate new ID automatically, hence we need to pass force_insert=True parameter. However, note that the create() method implicitly specifies force_insert parameter."
},
{
"code": null,
"e": 21816,
"s": 21697,
"text": "User.create(user_id='A001',name=\"Rajesh\", age=21)\nb=User(user_id='A002',name=\"Amar\", age=20)\nb.save(force_insert=True)"
},
{
"code": null,
"e": 21982,
"s": 21816,
"text": "The save() method also updates an existing row in the table, at which time, force_insert primary is not necessary, as ID with unique primary key is already existing."
},
{
"code": null,
"e": 22232,
"s": 21982,
"text": "Peewee allows feature of defining composite primary key. Object of CompositeKey class is defined as primary key in Meta class. In following example, a composite key consisting of name and city fields of User model has been assigned as composite key."
},
{
"code": null,
"e": 22416,
"s": 22232,
"text": "class User (Model):\n name=TextField()\n city=TextField()\n age=IntegerField()\n class Meta:\n database=db\n db_table='User'\n primary_key=CompositeKey('name', 'city')"
},
{
"code": null,
"e": 22475,
"s": 22416,
"text": "This model translates in the following CREATE TABLE query."
},
{
"code": null,
"e": 22614,
"s": 22475,
"text": "CREATE TABLE User (\n name TEXT NOT NULL,\n city TEXT NOT NULL,\n age INTEGER NOT NULL,\n PRIMARY KEY (\n name,\n city\n )\n);"
},
{
"code": null,
"e": 22722,
"s": 22614,
"text": "If you wish, the table should not have a primary key, then specify primary_key=False in modelβs Meta class."
},
{
"code": null,
"e": 22834,
"s": 22722,
"text": "Existing data can be modified by calling save() method on model instance as well as with update() class method."
},
{
"code": null,
"e": 22963,
"s": 22834,
"text": "Following example fetches a row from User table with the help of get() method and updates it by changing the value of age field."
},
{
"code": null,
"e": 23070,
"s": 22963,
"text": "row=User.get(User.name==\"Amar\")\nprint (\"name: {} age: {}\".format(row.name, row.age))\nrow.age=25\nrow.save()"
},
{
"code": null,
"e": 23183,
"s": 23070,
"text": "The update() method of Method class generates UPDATE query. The query objectβs execute() method is then invoked."
},
{
"code": null,
"e": 23275,
"s": 23183,
"text": "Following example uses update() method to change the age column of rows in which it is >20."
},
{
"code": null,
"e": 23357,
"s": 23275,
"text": "qry=User.update({User.age:25}).where(User.age>20)\nprint (qry.sql())\nqry.execute()"
},
{
"code": null,
"e": 23415,
"s": 23357,
"text": "The SQL query rendered by update() method is as follows β"
},
{
"code": null,
"e": 23482,
"s": 23415,
"text": "('UPDATE \"User\" SET \"age\" = ? WHERE (\"User\".\"age\" > ?)', [25, 20])"
},
{
"code": null,
"e": 23671,
"s": 23482,
"text": "Peewee also has a bulk_update() method to help update multiple model instance in a single query operation. The method requires model objects to be updated and list of fields to be updated."
},
{
"code": null,
"e": 23743,
"s": 23671,
"text": "Following example updates the age field of specified rows by new value."
},
{
"code": null,
"e": 23848,
"s": 23743,
"text": "rows=User.select()\nrows[0].age=25\nrows[2].age=23\nUser.bulk_update([rows[0], rows[2]], fields=[User.age])"
},
{
"code": null,
"e": 23949,
"s": 23848,
"text": "Running delete_instance() method on a model instance delete corresponding row from the mapped table."
},
{
"code": null,
"e": 24003,
"s": 23949,
"text": "obj=User.get(User.name==\"Amar\")\nobj.delete_instance()"
},
{
"code": null,
"e": 24157,
"s": 24003,
"text": "On the other hand, delete() is a class method defined in model class, which generates DELETE query. Executing it effectively deletes rows from the table."
},
{
"code": null,
"e": 24235,
"s": 24157,
"text": "db.create_tables([User])\nqry=User.delete().where (User.age==25)\nqry.execute()"
},
{
"code": null,
"e": 24305,
"s": 24235,
"text": "Concerned table in database shows effect of DELETE query as follows β"
},
{
"code": null,
"e": 24360,
"s": 24305,
"text": "('DELETE FROM \"User\" WHERE (\"User\".\"age\" = ?)', [25])\n"
},
{
"code": null,
"e": 24497,
"s": 24360,
"text": "By using Peewee ORM, it is possible to define a model which will create a table with index on single column as well as multiple columns."
},
{
"code": null,
"e": 24715,
"s": 24497,
"text": "As per the Field attribute definition, setting unique constraint to True will create an index on the mapped field. Similarly, passing index=True parameter to field constructor also create index on the specified field."
},
{
"code": null,
"e": 24861,
"s": 24715,
"text": "In following example, we have two fields in MyUser model, with username field having unique parameter set to True and email field has index=True."
},
{
"code": null,
"e": 25009,
"s": 24861,
"text": "class MyUser(Model):\n username = CharField(unique=True)\n email = CharField(index=True)\n class Meta:\n database=db\n db_table='MyUser'"
},
{
"code": null,
"e": 25101,
"s": 25009,
"text": "As a result, SQLiteStudio graphical user interface (GUI) shows indexes created as follows β"
},
{
"code": null,
"e": 25461,
"s": 25101,
"text": "In order to define a multi-column index, we need to add indexes attribute in Meta class inside definition of our model class. It is a tuple of 2-item tuples, one tuple for one index definition. Inside each 2-element tuple, the first part of which is a tuple of the names of the fields, the second part is set to True to make it unique, and otherwise is False."
},
{
"code": null,
"e": 25528,
"s": 25461,
"text": "We define MyUser model with a two-column unique index as follows β"
},
{
"code": null,
"e": 25728,
"s": 25528,
"text": "class MyUser (Model):\n name=TextField()\n city=TextField()\n age=IntegerField()\n class Meta:\n database=db\n db_table='MyUser'\n indexes=(\n (('name', 'city'), True),\n )"
},
{
"code": null,
"e": 25806,
"s": 25728,
"text": "Accordingly, SQLiteStudio shows index definition as in the following figure β"
},
{
"code": null,
"e": 25859,
"s": 25806,
"text": "Index can be built outside model definition as well."
},
{
"code": null,
"e": 25964,
"s": 25859,
"text": "You can also create index by manually providing SQL helper statement as parameter to add_index() method."
},
{
"code": null,
"e": 26023,
"s": 25964,
"text": "MyUser.add_index(SQL('CREATE INDEX idx on MyUser(name);'))"
},
{
"code": null,
"e": 26169,
"s": 26023,
"text": "Above method is particularly required when using SQLite. For MySQL and PostgreSQL, we can obtain Index object and use it with add_index() method."
},
{
"code": null,
"e": 26222,
"s": 26169,
"text": "ind=MyUser.index(MyUser.name)\nMyUser.add_index(ind)\n"
},
{
"code": null,
"e": 26500,
"s": 26222,
"text": "Constraints are restrictions imposed on the possible values that can be put in a field. One such constraint is primary key. When primary_key=True is specified in Field definition, each row can only store unique value β same value of the field cannot be repeated in another row."
},
{
"code": null,
"e": 26644,
"s": 26500,
"text": "If a field is not a primary key, still it can be constrained to store unique values in table. Field constructor also has constraints parameter."
},
{
"code": null,
"e": 26701,
"s": 26644,
"text": "Following example applies CHECK constraint on age field."
},
{
"code": null,
"e": 26872,
"s": 26701,
"text": "class MyUser (Model):\n name=TextField()\n city=TextField()\n age=IntegerField(constraints=[Check('name<10')])\n class Meta:\n database=db\n db_table='MyUser'"
},
{
"code": null,
"e": 26945,
"s": 26872,
"text": "This will generate following Data Definition Language (DDL) expression β"
},
{
"code": null,
"e": 27100,
"s": 26945,
"text": "CREATE TABLE MyUser (\n id INTEGER NOT NULL\n PRIMARY KEY,\n name TEXT NOT NULL,\n city TEXT NOT NULL,\n age INTEGER NOT NULL\n CHECK (name < 10)\n);"
},
{
"code": null,
"e": 27160,
"s": 27100,
"text": "As a result, if a new row with age<10 will result in error."
},
{
"code": null,
"e": 27266,
"s": 27160,
"text": "MyUser.create(name=\"Rajesh\", city=\"Mumbai\",age=9)\npeewee.IntegrityError: CHECK constraint failed: MyUser\n"
},
{
"code": null,
"e": 27368,
"s": 27266,
"text": "In the field definition, we can also use DEFAULT constraint as in following definition of city field."
},
{
"code": null,
"e": 27423,
"s": 27368,
"text": "city=TextField(constraints=[SQL(\"DEFAULT 'Mumbai'\")])\n"
},
{
"code": null,
"e": 27569,
"s": 27423,
"text": "So, the model object can be constructed with or without explicit value of city. If not used, city field will be filled by default value β Mumbai."
},
{
"code": null,
"e": 27820,
"s": 27569,
"text": "As mentioned earlier, Peewee supports MySQL database through MySQLDatabase class. However, unlike SQLite database, Peewee canβt create a MySql database. You need to create it manually or using functionality of DB-API compliant module such as pymysql."
},
{
"code": null,
"e": 27978,
"s": 27820,
"text": "First, you should have MySQL server installed in your machine. It can be a standalone MySQL server installed from https://dev.mysql.com/downloads/installer/."
},
{
"code": null,
"e": 28117,
"s": 27978,
"text": "You can also work on Apache bundled with MySQL (such as XAMPP downloaded and installed from https://www.apachefriends.org/download.html )."
},
{
"code": null,
"e": 28183,
"s": 28117,
"text": "Next, we install pymysql module, DB-API compatible Python driver."
},
{
"code": null,
"e": 28204,
"s": 28183,
"text": "pip install pymysql\n"
},
{
"code": null,
"e": 28302,
"s": 28204,
"text": "The create a new database named mydatabase. We shall use phpmyadmin interface available in XAMPP."
},
{
"code": null,
"e": 28383,
"s": 28302,
"text": "If you choose to create database programmatically, use following Python script β"
},
{
"code": null,
"e": 28531,
"s": 28383,
"text": "import pymysql\n\nconn = pymysql.connect(host='localhost', user='root', password='')\nconn.cursor().execute('CREATE DATABASE mydatabase')\nconn.close()"
},
{
"code": null,
"e": 28642,
"s": 28531,
"text": "Once a database is created on the server, we can now declare a model and thereby, create a mapped table in it."
},
{
"code": null,
"e": 28739,
"s": 28642,
"text": "The MySQLDatabase object requires server credentials such as host, port, user name and password."
},
{
"code": null,
"e": 29066,
"s": 28739,
"text": "from peewee import *\ndb = MySQLDatabase('mydatabase', host='localhost', port=3306, user='root', password='')\nclass MyUser (Model):\n name=TextField()\n city=TextField(constraints=[SQL(\"DEFAULT 'Mumbai'\")])\n age=IntegerField()\n class Meta:\n database=db\n db_table='MyUser'\ndb.connect()\ndb.create_tables([MyUser])"
},
{
"code": null,
"e": 29127,
"s": 29066,
"text": "The Phpmyadmin web interface now shows myuser table created."
},
{
"code": null,
"e": 29349,
"s": 29127,
"text": "Peewee supports PostgreSQL database as well. It has PostgresqlDatabase class for that purpose. In this chapter, we shall see how we can connect to Postgres database and create a table in it, with the help of Peewee model."
},
{
"code": null,
"e": 29534,
"s": 29349,
"text": "As in case of MySQL, it is not possible to create database on Postgres server with Peeweeβs functionality. The database has to be created manually using Postgres shell or PgAdmin tool."
},
{
"code": null,
"e": 29696,
"s": 29534,
"text": "First, we need to install Postgres server. For windows OS, we can download https://get.enterprisedb.com/postgresql/postgresql-13.1-1-windows-x64.exe and install."
},
{
"code": null,
"e": 29777,
"s": 29696,
"text": "Next, install Python driver for Postgres β Psycopg2 package using pip installer."
},
{
"code": null,
"e": 29799,
"s": 29777,
"text": "pip install psycopg2\n"
},
{
"code": null,
"e": 29978,
"s": 29799,
"text": "Then start the server, either from PgAdmin tool or psql shell. We are now in a position to create a database. Run following Python script to create mydatabase on Postgres server."
},
{
"code": null,
"e": 30140,
"s": 29978,
"text": "import psycopg2\n\nconn = psycopg2.connect(host='localhost', user='postgres', password='postgres')\nconn.cursor().execute('CREATE DATABASE mydatabase')\nconn.close()"
},
{
"code": null,
"e": 30228,
"s": 30140,
"text": "Check that the database is created. In psql shell, it can be verified with \\l command β"
},
{
"code": null,
"e": 30331,
"s": 30228,
"text": "To declare MyUser model and create a table of same name in above database, run following Python code β"
},
{
"code": null,
"e": 30677,
"s": 30331,
"text": "from peewee import *\n\ndb = PostgresqlDatabase('mydatabase', host='localhost', port=5432, user='postgres', password='postgres')\nclass MyUser (Model):\n name=TextField()\n city=TextField(constraints=[SQL(\"DEFAULT 'Mumbai'\")])\n age=IntegerField()\n class Meta:\n database=db\n db_table='MyUser'\n\ndb.connect()\ndb.create_tables([MyUser])"
},
{
"code": null,
"e": 30784,
"s": 30677,
"text": "We can verify that table is created. Inside the shell, connect to mydatabase and get list of tables in it."
},
{
"code": null,
"e": 30871,
"s": 30784,
"text": "To check structure of newly created MyUser database, run following query in the shell."
},
{
"code": null,
"e": 31101,
"s": 30871,
"text": "If your database is scheduled to vary at run-time, use DatabaseProxy helper to have better control over how you initialise it. The DatabaseProxy object is a placeholder with the help of which database can be selected in run-time."
},
{
"code": null,
"e": 31217,
"s": 31101,
"text": "In the following example, an appropriate database is selected depending on the applicationβs configuration setting."
},
{
"code": null,
"e": 31909,
"s": 31217,
"text": "from peewee import *\ndb_proxy = DatabaseProxy() # Create a proxy for our db.\n\nclass MyUser (Model):\n name=TextField()\n city=TextField(constraints=[SQL(\"DEFAULT 'Mumbai'\")])\n age=IntegerField()\n class Meta:\n database=db_proxy\n db_table='MyUser'\n\n# Based on configuration, use a different database.\nif app.config['TESTING']:\n db = SqliteDatabase(':memory:')\nelif app.config['DEBUG']:\n db = SqliteDatabase('mydatabase.db')\nelse:\n db = PostgresqlDatabase(\n 'mydatabase', host='localhost', port=5432, user='postgres', password='postgres'\n )\n\n# Configure our proxy to use the db we specified in config.\ndb_proxy.initialize(db)\ndb.connect()\ndb.create_tables([MyUser])"
},
{
"code": null,
"e": 32047,
"s": 31909,
"text": "You can also associate models to any database object during run-time using bind() method declared in both database class and model class."
},
{
"code": null,
"e": 32103,
"s": 32047,
"text": "Following example uses bind() method in database class."
},
{
"code": null,
"e": 32393,
"s": 32103,
"text": "from peewee import *\n\nclass MyUser (Model):\n name=TextField()\n city=TextField(constraints=[SQL(\"DEFAULT 'Mumbai'\")])\n age=IntegerField()\n\ndb = MySQLDatabase('mydatabase', host='localhost', port=3306, user='root', password='')\ndb.connect()\ndb.bind([MyUser])\ndb.create_tables([MyUser])"
},
{
"code": null,
"e": 32448,
"s": 32393,
"text": "The same bind() method is also defined in Model class."
},
{
"code": null,
"e": 32736,
"s": 32448,
"text": "from peewee import *\n\nclass MyUser (Model):\n name=TextField()\n city=TextField(constraints=[SQL(\"DEFAULT 'Mumbai'\")])\n age=IntegerField()\n\ndb = MySQLDatabase('mydatabase', host='localhost', port=3306, user='root', password='')\ndb.connect()\nMyUser.bind(db)\ndb.create_tables([MyUser])"
},
{
"code": null,
"e": 32901,
"s": 32736,
"text": "Database object is created with autoconnect parameter set as True by default. Instead, to manage database connection programmatically, it is initially set to False."
},
{
"code": null,
"e": 32953,
"s": 32901,
"text": "db=SqliteDatabase(\"mydatabase\", autoconnect=False)\n"
},
{
"code": null,
"e": 33062,
"s": 32953,
"text": "The database class has connect() method that establishes connection with the database present on the server."
},
{
"code": null,
"e": 33076,
"s": 33062,
"text": "db.connect()\n"
},
{
"code": null,
"e": 33161,
"s": 33076,
"text": "It is always recommended to close the connection at the end of operations performed."
},
{
"code": null,
"e": 33173,
"s": 33161,
"text": "db.close()\n"
},
{
"code": null,
"e": 33250,
"s": 33173,
"text": "If you try to open an already open connection, Peewee raises OperationError."
},
{
"code": null,
"e": 33545,
"s": 33250,
"text": ">>> db.connect()\nTrue\n>>> db.connect()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"c:\\peewee\\lib\\site-packages\\peewee.py\", line 3031, in connect\n raise OperationalError('Connection already opened.')\npeewee.OperationalError: Connection already opened."
},
{
"code": null,
"e": 33622,
"s": 33545,
"text": "To avoid this error, use reuse_if_open=True as argument to connect() method."
},
{
"code": null,
"e": 33664,
"s": 33622,
"text": ">>> db.connect(reuse_if_open=True)\nFalse\n"
},
{
"code": null,
"e": 33813,
"s": 33664,
"text": "Calling close() on already closed connection wonβt result error. You can however, check if the connection is already closed with is_closed() method."
},
{
"code": null,
"e": 33868,
"s": 33813,
"text": ">>> if db.is_closed()==True:\n db.connect()\n\nTrue\n>>>"
},
{
"code": null,
"e": 33984,
"s": 33868,
"text": "Instead of explicitly calling db.close() in the end, it is also possible to use database object as context_manager."
},
{
"code": null,
"e": 34272,
"s": 33984,
"text": "from peewee import *\n\ndb = SqliteDatabase('mydatabase.db', autoconnect=False)\n\nclass User (Model):\n user_id=TextField(primary_key=True)\n name=TextField()\n age=IntegerField()\n class Meta:\n database=db\n db_table='User'\nwith db:\n db.connect()\n db.create_tables([User])"
},
{
"code": null,
"e": 34403,
"s": 34272,
"text": "Peewee supports implementing different type of SQL JOIN queries. Its Model class has a join() method that returns a Join instance."
},
{
"code": null,
"e": 34432,
"s": 34403,
"text": "M1.joint(m2, join_type, on)\n"
},
{
"code": null,
"e": 34602,
"s": 34432,
"text": "The joins table mapped with M1 model to that of m2 model and returns Join class instance. The on parameter is None by default and is expression to use as join predicate."
},
{
"code": null,
"e": 34659,
"s": 34602,
"text": "Peewee supports following Join types (Default is INNER)."
},
{
"code": null,
"e": 34670,
"s": 34659,
"text": "JOIN.INNER"
},
{
"code": null,
"e": 34681,
"s": 34670,
"text": "JOIN.INNER"
},
{
"code": null,
"e": 34697,
"s": 34681,
"text": "JOIN.LEFT_OUTER"
},
{
"code": null,
"e": 34713,
"s": 34697,
"text": "JOIN.LEFT_OUTER"
},
{
"code": null,
"e": 34730,
"s": 34713,
"text": "JOIN.RIGHT_OUTER"
},
{
"code": null,
"e": 34747,
"s": 34730,
"text": "JOIN.RIGHT_OUTER"
},
{
"code": null,
"e": 34757,
"s": 34747,
"text": "JOIN.FULL"
},
{
"code": null,
"e": 34767,
"s": 34757,
"text": "JOIN.FULL"
},
{
"code": null,
"e": 34783,
"s": 34767,
"text": "JOIN.FULL_OUTER"
},
{
"code": null,
"e": 34799,
"s": 34783,
"text": "JOIN.FULL_OUTER"
},
{
"code": null,
"e": 34810,
"s": 34799,
"text": "JOIN.CROSS"
},
{
"code": null,
"e": 34821,
"s": 34810,
"text": "JOIN.CROSS"
},
{
"code": null,
"e": 34887,
"s": 34821,
"text": "To show use of join() method, we first declare following models β"
},
{
"code": null,
"e": 35355,
"s": 34887,
"text": "db = SqliteDatabase('mydatabase.db')\n\nclass BaseModel(Model):\n class Meta:\n database = db\n\nclass Item(BaseModel):\n itemname = TextField()\n price = IntegerField()\n\nclass Brand(BaseModel):\n brandname = TextField()\n item = ForeignKeyField(Item, backref='brands')\n\nclass Bill(BaseModel):\n item = ForeignKeyField(Item, backref='bills')\n brand = ForeignKeyField(Brand, backref='bills')\n qty = DecimalField()\n\ndb.create_tables([Item, Brand, Bill])"
},
{
"code": null,
"e": 35413,
"s": 35355,
"text": "Next, we populate these tables with following test data β"
},
{
"code": null,
"e": 35445,
"s": 35413,
"text": "The item table is given below β"
},
{
"code": null,
"e": 35478,
"s": 35445,
"text": "Given below is the brand table β"
},
{
"code": null,
"e": 35509,
"s": 35478,
"text": "The bill table is as follows β"
},
{
"code": null,
"e": 35604,
"s": 35509,
"text": "To perform a simple join operation between Brand and Item tables, execute the following code β"
},
{
"code": null,
"e": 35732,
"s": 35604,
"text": "qs=Brand.select().join(Item)\nfor q in qs:\nprint (\"Brand ID:{} Item Name: {} Price: {}\".format(q.id, q.brandname, q.item.price))"
},
{
"code": null,
"e": 35774,
"s": 35732,
"text": "The resultant output will be as follows β"
},
{
"code": null,
"e": 35975,
"s": 35774,
"text": "Brand ID:1 Item Name: Dell Price: 25000\nBrand ID:2 Item Name: Epson Price: 12000\nBrand ID:3 Item Name: HP Price: 25000\nBrand ID:4 Item Name: iBall Price: 4000\nBrand ID:5 Item Name: Sharp Price: 12000\n"
},
{
"code": null,
"e": 36119,
"s": 35975,
"text": "We have a Bill model having two foreign key relationships with item and brand models. To fetch data from all three tables, use following code β"
},
{
"code": null,
"e": 36302,
"s": 36119,
"text": "qs=Bill.select().join(Brand).join(Item)\nfor q in qs:\nprint (\"BillNo:{} Brand:{} Item:{} price:{} Quantity:{}\".format(q.id, \\\nq.brand.brandname, q.item.itemname, q.item.price, q.qty))"
},
{
"code": null,
"e": 36363,
"s": 36302,
"text": "Following output will be displayed, based on our test data β"
},
{
"code": null,
"e": 36529,
"s": 36363,
"text": "BillNo:1 Brand:HP Item:Laptop price:25000 Quantity:5\nBillNo:2 Brand:Epson Item:Printer price:12000 Quantity:2\nBillNo:3 Brand:iBall Item:Router price:4000 Quantity:5\n"
},
{
"code": null,
"e": 36722,
"s": 36529,
"text": "In SQL, a subquery is an embedded query in WHERE clause of another query. We can implement subquery as a model.select() as a parameter inside where attribute of outer model.select() statement."
},
{
"code": null,
"e": 36802,
"s": 36722,
"text": "To demonstrate use of subquery in Peewee, let us use defined following models β"
},
{
"code": null,
"e": 37139,
"s": 36802,
"text": "from peewee import *\ndb = SqliteDatabase('mydatabase.db')\n\nclass BaseModel(Model):\n class Meta:\n database = db\n\nclass Contacts(BaseModel):\n RollNo = IntegerField()\n Name = TextField()\n City = TextField()\n\nclass Branches(BaseModel):\n RollNo = IntegerField()\n Faculty = TextField()\n\ndb.create_tables([Contacts, Branches])"
},
{
"code": null,
"e": 37213,
"s": 37139,
"text": "After tables are created, they are populated with following sample data β"
},
{
"code": null,
"e": 37249,
"s": 37213,
"text": "The contacts table is given below β"
},
{
"code": null,
"e": 37433,
"s": 37249,
"text": "In order to display name and city from contact table only for RollNo registered for ETC faculty, following code generates a SELECT query with another SELECT query in its WHERE clause."
},
{
"code": null,
"e": 37737,
"s": 37433,
"text": "#this query is used as subquery\nfaculty=Branches.select(Branches.RollNo).where(Branches.Faculty==\"ETC\")\nnames=Contacts.select().where (Contacts.RollNo .in_(faculty))\n\nprint (\"RollNo and City for Faculty='ETC'\")\nfor name in names:\n print (\"RollNo:{} City:{}\".format(name.RollNo, name.City))\n\ndb.close()"
},
{
"code": null,
"e": 37783,
"s": 37737,
"text": "Above code will display the following result:"
},
{
"code": null,
"e": 37907,
"s": 37783,
"text": "RollNo and City for Faculty='ETC'\nRollNo:103 City:Indore\nRollNo:104 City:Nasik\nRollNo:108 City:Delhi\nRollNo:110 City:Nasik\n"
},
{
"code": null,
"e": 38152,
"s": 37907,
"text": "It is possible to select records from a table using order_by clause along with modelβs select() method. Additionally, by attaching desc() to the field attribute on which sorting is to be performed, records will be collected in descending order."
},
{
"code": null,
"e": 38236,
"s": 38152,
"text": "Following code display records from contact table in ascending order of City names."
},
{
"code": null,
"e": 38418,
"s": 38236,
"text": "rows=Contacts.select().order_by(Contacts.City)\nprint (\"Contact list in order of city\")\nfor row in rows:\n print (\"RollNo:{} Name: {} City:{}\".format(row.RollNo,row.Name, row.City))"
},
{
"code": null,
"e": 38503,
"s": 38418,
"text": "Here is the sorted list which is arranged according to ascending order of city name."
},
{
"code": null,
"e": 38872,
"s": 38503,
"text": "Contact list in order of city\nRollNo:107 Name: Beena City:Chennai\nRollNo:102 Name: Amar City:Delhi\nRollNo:108 Name: John City:Delhi\nRollNo:103 Name: Raam City:Indore\nRollNo:101 Name: Anil City:Mumbai\nRollNo:106 Name: Hema City:Nagpur\nRollNo:104 Name: Leena City:Nasik\nRollNo:109 Name: Jaya City:Nasik\nRollNo:110 Name: Raja City:Nasik\nRollNo:105 Name: Keshav City:Pune\n"
},
{
"code": null,
"e": 38936,
"s": 38872,
"text": "Following code displays list in descending order of Name field."
},
{
"code": null,
"e": 39136,
"s": 38936,
"text": "rows=Contacts.select().order_by(Contacts.Name.desc())\nprint (\"Contact list in descending order of Name\")\nfor row in rows:\n print (\"RollNo:{} Name: {} City:{}\".format(row.RollNo,row.Name, row.City))"
},
{
"code": null,
"e": 39163,
"s": 39136,
"text": "The output is as follows β"
},
{
"code": null,
"e": 39543,
"s": 39163,
"text": "Contact list in descending order of Name\nRollNo:110 Name: Raja City:Nasik\nRollNo:103 Name: Raam City:Indore\nRollNo:104 Name: Leena City:Nasik\nRollNo:105 Name: Keshav City:Pune\nRollNo:108 Name: John City:Delhi\nRollNo:109 Name: Jaya City:Nasik\nRollNo:106 Name: Hema City:Nagpur\nRollNo:107 Name: Beena City:Chennai\nRollNo:101 Name: Anil City:Mumbai\nRollNo:102 Name: Amar City:Delhi\n"
},
{
"code": null,
"e": 39724,
"s": 39543,
"text": "We can find number of records reported in any SELECT query by attaching count() method. For example, following statement returns number of rows in Contacts table with City=βNasikβ."
},
{
"code": null,
"e": 39797,
"s": 39724,
"text": "qry=Contacts.select().where (Contacts.City=='Nasik').count()\nprint (qry)"
},
{
"code": null,
"e": 39958,
"s": 39797,
"text": "SQL has GROUP BY clause in SELECT query. Peewee supports it in the form of group_by() method. Following code returns city wise count of names in Contacts table."
},
{
"code": null,
"e": 40339,
"s": 39958,
"text": "from peewee import *\n\ndb = SqliteDatabase('mydatabase.db')\nclass Contacts(BaseModel):\n RollNo = IntegerField()\n Name = TextField()\n City = TextField()\n class Meta:\n database = db\n\ndb.create_tables([Contacts])\n\nqry=Contacts.select(Contacts.City, fn.Count(Contacts.City).alias('count')).group_by(Contacts.City)\nprint (qry.sql())\nfor q in qry:\n print (q.City, q.count)"
},
{
"code": null,
"e": 40395,
"s": 40339,
"text": "The SELECT query emitted by Peewee will be as follows β"
},
{
"code": null,
"e": 40498,
"s": 40395,
"text": "('SELECT \"t1\".\"City\", Count(\"t1\".\"City\") AS \"count\" FROM \"contacts\" AS \"t1\" GROUP BY \"t1\".\"City\"', [])"
},
{
"code": null,
"e": 40568,
"s": 40498,
"text": "As per sample data in Contacts table, following output is displayed β"
},
{
"code": null,
"e": 40639,
"s": 40568,
"text": "Chennai 1\nDelhi 2\nIndore 1\nMumbai 1\nNagpur 1\nNasik 3\nPune 1\n"
},
{
"code": null,
"e": 40753,
"s": 40639,
"text": "American National Standards Institute (ANSI) Structured Query Language (SQL) standard defines many SQL functions."
},
{
"code": null,
"e": 40814,
"s": 40753,
"text": "Aggregate functions like the following are useful in Peewee."
},
{
"code": null,
"e": 40849,
"s": 40814,
"text": "AVG() - Returns the average value."
},
{
"code": null,
"e": 40884,
"s": 40849,
"text": "AVG() - Returns the average value."
},
{
"code": null,
"e": 40922,
"s": 40884,
"text": "COUNT() - Returns the number of rows."
},
{
"code": null,
"e": 40960,
"s": 40922,
"text": "COUNT() - Returns the number of rows."
},
{
"code": null,
"e": 40995,
"s": 40960,
"text": "FIRST() - Returns the first value."
},
{
"code": null,
"e": 41030,
"s": 40995,
"text": "FIRST() - Returns the first value."
},
{
"code": null,
"e": 41063,
"s": 41030,
"text": "LAST() - Returns the last value."
},
{
"code": null,
"e": 41096,
"s": 41063,
"text": "LAST() - Returns the last value."
},
{
"code": null,
"e": 41131,
"s": 41096,
"text": "MAX() - Returns the largest value."
},
{
"code": null,
"e": 41166,
"s": 41131,
"text": "MAX() - Returns the largest value."
},
{
"code": null,
"e": 41202,
"s": 41166,
"text": "MIN() - Returns the smallest value."
},
{
"code": null,
"e": 41238,
"s": 41202,
"text": "MIN() - Returns the smallest value."
},
{
"code": null,
"e": 41263,
"s": 41238,
"text": "SUM() - Returns the sum."
},
{
"code": null,
"e": 41288,
"s": 41263,
"text": "SUM() - Returns the sum."
},
{
"code": null,
"e": 41439,
"s": 41288,
"text": "In order to implement these SQL functions, Peewee has a SQL helper function fn(). In above example, we used it to find count of records for each city."
},
{
"code": null,
"e": 41508,
"s": 41439,
"text": "Following example builds a SELECT query that employs SUM() function."
},
{
"code": null,
"e": 41636,
"s": 41508,
"text": "Using Bill and Item tables from models defined earlier, we shall display sum of quantity of each item as entered in Bill table."
},
{
"code": null,
"e": 41682,
"s": 41636,
"text": "The item table with the data is given below β"
},
{
"code": null,
"e": 41713,
"s": 41682,
"text": "The bill table is as follows β"
},
{
"code": null,
"e": 41829,
"s": 41713,
"text": "We create a join between Bill and Item table, select item name from Item table and sum of quantity from Bill table."
},
{
"code": null,
"e": 42515,
"s": 41829,
"text": "from peewee import *\ndb = SqliteDatabase('mydatabase.db')\n\nclass BaseModel(Model):\n class Meta:\n database = db\n\nclass Item(BaseModel):\n itemname = TextField()\n price = IntegerField()\n\nclass Brand(BaseModel):\n brandname = TextField()\n item = ForeignKeyField(Item, backref='brands')\n\nclass Bill(BaseModel):\n item = ForeignKeyField(Item, backref='bills')\n brand = ForeignKeyField(Brand, backref='bills')\n qty = DecimalField()\n\ndb.create_tables([Item, Brand, Bill])\n\nqs=Bill.select(Item.itemname, fn.SUM(Bill.qty).alias('Sum'))\n .join(Item).group_by(Item.itemname)\nprint (qs)\nfor q in qs:\n print (\"Item: {} sum: {}\".format(q.item.itemname, q.Sum))\n\ndb.close()"
},
{
"code": null,
"e": 42566,
"s": 42515,
"text": "Above script executes the following SELECT query β"
},
{
"code": null,
"e": 42719,
"s": 42566,
"text": "SELECT \"t1\".\"itemname\", SUM(\"t2\".\"qty\") AS \"Sum\" FROM \"bill\" AS \"t2\" \nINNER JOIN \"item\" AS \"t1\" ON (\"t2\".\"item_id\" = \"t1\".\"id\") GROUP BY \"t1\".\"itemname\""
},
{
"code": null,
"e": 42759,
"s": 42719,
"text": "Accordingly, the output is as follows β"
},
{
"code": null,
"e": 42821,
"s": 42759,
"text": "Item: Laptop sum: 6\nItem: Printer sum: 8\nItem: Router sum: 8\n"
},
{
"code": null,
"e": 42946,
"s": 42821,
"text": "It is possible to iterate over the resultset without creating model instances. This may be achieved by using the following β"
},
{
"code": null,
"e": 42963,
"s": 42946,
"text": "tuples() method."
},
{
"code": null,
"e": 42980,
"s": 42963,
"text": "tuples() method."
},
{
"code": null,
"e": 42996,
"s": 42980,
"text": "dicts() method."
},
{
"code": null,
"e": 43012,
"s": 42996,
"text": "dicts() method."
},
{
"code": null,
"e": 43099,
"s": 43012,
"text": "To return data of fields in SELECT query as collection of tuples, use tuples() method."
},
{
"code": null,
"e": 43261,
"s": 43099,
"text": "qry=Contacts.select(Contacts.City, fn.Count(Contacts.City).alias('count'))\n .group_by(Contacts.City).tuples()\nlst=[]\nfor q in qry:\n lst.append(q)\nprint (lst)"
},
{
"code": null,
"e": 43289,
"s": 43261,
"text": "The output is given below β"
},
{
"code": null,
"e": 43422,
"s": 43289,
"text": "[\n ('Chennai', 1), \n ('Delhi', 2), \n ('Indore', 1), \n ('Mumbai', 1), \n ('Nagpur', 1), \n ('Nasik', 3), \n ('Pune', 1)\n]\n"
},
{
"code": null,
"e": 43467,
"s": 43422,
"text": "To obtain collection of dictionary objects β"
},
{
"code": null,
"e": 43553,
"s": 43467,
"text": "qs=Brand.select().join(Item).dicts()\nlst=[]\nfor q in qs:\n lst.append(q)\nprint (lst)"
},
{
"code": null,
"e": 43582,
"s": 43553,
"text": "The output is stated below β"
},
{
"code": null,
"e": 43820,
"s": 43582,
"text": "[\n {'id': 1, 'brandname': 'Dell', 'item': 1}, \n {'id': 2, 'brandname': 'Epson', 'item': 2}, \n {'id': 3, 'brandname': 'HP', 'item': 1}, \n {'id': 4, 'brandname': 'iBall', 'item': 3},\n {'id': 5, 'brandname': 'Sharp', 'item': 2}\n]\n"
},
{
"code": null,
"e": 44032,
"s": 43820,
"text": "Peewee has Expression class with the help of which we can add any customized operator in Peeweeβs list of operators. Constructor for Expression requires three arguments, left operand, operator and right operand."
},
{
"code": null,
"e": 44070,
"s": 44032,
"text": "op=Expression(left, operator, right)\n"
},
{
"code": null,
"e": 44184,
"s": 44070,
"text": "Using Expression class, we define a mod() function that accepts arguments for left and right and β%β as operator."
},
{
"code": null,
"e": 44307,
"s": 44184,
"text": "from peewee import Expression # the building block for expressions\n\ndef mod(lhs, rhs):\n return Expression(lhs, '%', rhs)"
},
{
"code": null,
"e": 44397,
"s": 44307,
"text": "We can use it in a SELECT query to obtain list of records in Contacts table with even id."
},
{
"code": null,
"e": 44883,
"s": 44397,
"text": "from peewee import *\ndb = SqliteDatabase('mydatabase.db')\n\nclass BaseModel(Model):\n class Meta:\n database = db\n\nclass Contacts(BaseModel):\n RollNo = IntegerField()\n Name = TextField()\n City = TextField()\n\ndb.create_tables([Contacts])\n\nfrom peewee import Expression # the building block for expressions\n\ndef mod(lhs, rhs):\n return Expression(lhs,'%', rhs)\nqry=Contacts.select().where (mod(Contacts.id,2)==0)\nprint (qry.sql())\nfor q in qry:\n print (q.id, q.Name, q.City)"
},
{
"code": null,
"e": 44951,
"s": 44883,
"text": "This code will emit following SQL query represented by the string β"
},
{
"code": null,
"e": 45073,
"s": 44951,
"text": "('SELECT \"t1\".\"id\", \"t1\".\"RollNo\", \"t1\".\"Name\", \"t1\".\"City\" FROM \"contacts\" AS \"t1\" WHERE ((\"t1\".\"id\" % ?) = ?)', [2, 0])"
},
{
"code": null,
"e": 45111,
"s": 45073,
"text": "Therefore, the output is as follows β"
},
{
"code": null,
"e": 45184,
"s": 45111,
"text": "2 Amar Delhi\n4 Leena Nasik\n6 Hema Nagpur\n8 John Delhi\n10 Raja Nasik\n"
},
{
"code": null,
"e": 45450,
"s": 45184,
"text": "Peeweeβs database class has atomic() method that creates a context manager. It starts a new transaction. Inside the context block, it is possible to commit or rollback the transaction depending upon whether it has been successfully done or it encountered exception."
},
{
"code": null,
"e": 45611,
"s": 45450,
"text": "with db.atomic() as transaction:\n try:\n User.create(name='Amar', age=20)\n transaction.commit()\n except DatabaseError:\n transaction.rollback()"
},
{
"code": null,
"e": 45655,
"s": 45611,
"text": "The atomic() can also be used as decorator."
},
{
"code": null,
"e": 45754,
"s": 45655,
"text": "@db.atomic()\ndef create_user(nm,n):\n return User.create(name=nm, age=n)\n\ncreate_user('Amar', 20)"
},
{
"code": null,
"e": 45814,
"s": 45754,
"text": "More than one atomic transaction blocks can also be nested."
},
{
"code": null,
"e": 45936,
"s": 45814,
"text": "with db.atomic() as txn1:\n User.create('name'='Amar', age=20)\n\n with db.atomic() as txn2:\n User.get(name='Amar')"
},
{
"code": null,
"e": 46107,
"s": 45936,
"text": "Pythonβs DB-API standard (recommended by PEP 249) specifies the types of Exception classes to be defined by any DB-API compliant module (such as pymysql, pyscopg2, etc.)."
},
{
"code": null,
"e": 46278,
"s": 46107,
"text": "Peewee API provides easy-to-use wrappers for these exceptions. PeeweeException is the base classes from which following Exception classes has been defined in Peewee API β"
},
{
"code": null,
"e": 46292,
"s": 46278,
"text": "DatabaseError"
},
{
"code": null,
"e": 46306,
"s": 46292,
"text": "DatabaseError"
},
{
"code": null,
"e": 46316,
"s": 46306,
"text": "DataError"
},
{
"code": null,
"e": 46326,
"s": 46316,
"text": "DataError"
},
{
"code": null,
"e": 46341,
"s": 46326,
"text": "IntegrityError"
},
{
"code": null,
"e": 46356,
"s": 46341,
"text": "IntegrityError"
},
{
"code": null,
"e": 46371,
"s": 46356,
"text": "InterfaceError"
},
{
"code": null,
"e": 46386,
"s": 46371,
"text": "InterfaceError"
},
{
"code": null,
"e": 46400,
"s": 46386,
"text": "InternalError"
},
{
"code": null,
"e": 46414,
"s": 46400,
"text": "InternalError"
},
{
"code": null,
"e": 46432,
"s": 46414,
"text": "NotSupportedError"
},
{
"code": null,
"e": 46450,
"s": 46432,
"text": "NotSupportedError"
},
{
"code": null,
"e": 46467,
"s": 46450,
"text": "OperationalError"
},
{
"code": null,
"e": 46484,
"s": 46467,
"text": "OperationalError"
},
{
"code": null,
"e": 46501,
"s": 46484,
"text": "ProgrammingError"
},
{
"code": null,
"e": 46518,
"s": 46501,
"text": "ProgrammingError"
},
{
"code": null,
"e": 46610,
"s": 46518,
"text": "Instead of DB-API specific exceptions to be tried, we can implement above ones from Peewee."
},
{
"code": null,
"e": 46836,
"s": 46610,
"text": "Peewee also provides a non-ORM API to access the databases. Instead of defining models and fields, we can bind the database tables and columns to Table and Column objects defined in Peewee and execute queries with their help."
},
{
"code": null,
"e": 47016,
"s": 46836,
"text": "To begin with, declare a Table object corresponding to the one in our database. You have to specify table name and list of columns. Optionally, a primary key can also be provided."
},
{
"code": null,
"e": 47078,
"s": 47016,
"text": "Contacts=Table('Contacts', ('id', 'RollNo', 'Name', 'City'))\n"
},
{
"code": null,
"e": 47143,
"s": 47078,
"text": "This table object is bound with the database with bind() method."
},
{
"code": null,
"e": 47171,
"s": 47143,
"text": "Contacts=Contacts.bind(db)\n"
},
{
"code": null,
"e": 47291,
"s": 47171,
"text": "Now, we can set up a SELECT query on this table object with select() method and iterate over the resultset as follows β"
},
{
"code": null,
"e": 47350,
"s": 47291,
"text": "names=Contacts.select()\nfor name in names:\n print (name)"
},
{
"code": null,
"e": 47400,
"s": 47350,
"text": "The rows are by default returned as dictionaries."
},
{
"code": null,
"e": 47999,
"s": 47400,
"text": "{'id': 1, 'RollNo': 101, 'Name': 'Anil', 'City': 'Mumbai'}\n{'id': 2, 'RollNo': 102, 'Name': 'Amar', 'City': 'Delhi'}\n{'id': 3, 'RollNo': 103, 'Name': 'Raam', 'City': 'Indore'}\n{'id': 4, 'RollNo': 104, 'Name': 'Leena', 'City': 'Nasik'}\n{'id': 5, 'RollNo': 105, 'Name': 'Keshav', 'City': 'Pune'}\n{'id': 6, 'RollNo': 106, 'Name': 'Hema', 'City': 'Nagpur'}\n{'id': 7, 'RollNo': 107, 'Name': 'Beena', 'City': 'Chennai'}\n{'id': 8, 'RollNo': 108, 'Name': 'John', 'City': 'Delhi'}\n{'id': 9, 'RollNo': 109, 'Name': 'Jaya', 'City': 'Nasik'}\n{'id': 10, 'RollNo': 110, 'Name': 'Raja', 'City': 'Nasik'}\n"
},
{
"code": null,
"e": 48066,
"s": 47999,
"text": "If needed, they can be obtained as tuples, namedtuples or objects."
},
{
"code": null,
"e": 48094,
"s": 48066,
"text": "The program is as follows β"
},
{
"code": null,
"e": 48162,
"s": 48094,
"text": "names=Contacts.select().tuples()\nfor name in names:\n print (name)"
},
{
"code": null,
"e": 48190,
"s": 48162,
"text": "The output is given below β"
},
{
"code": null,
"e": 48460,
"s": 48190,
"text": "(1, 101, 'Anil', 'Mumbai')\n(2, 102, 'Amar', 'Delhi')\n(3, 103, 'Raam', 'Indore')\n(4, 104, 'Leena', 'Nasik')\n(5, 105, 'Keshav', 'Pune')\n(6, 106, 'Hema', 'Nagpur')\n(7, 107, 'Beena', 'Chennai')\n(8, 108, 'John', 'Delhi')\n(9, 109, 'Jaya', 'Nasik')\n(10, 110, 'Raja', 'Nasik')\n"
},
{
"code": null,
"e": 48490,
"s": 48460,
"text": "The program is stated below β"
},
{
"code": null,
"e": 48563,
"s": 48490,
"text": "names=Contacts.select().namedtuples()\nfor name in names:\n print (name)"
},
{
"code": null,
"e": 48591,
"s": 48563,
"text": "The output is given below β"
},
{
"code": null,
"e": 49091,
"s": 48591,
"text": "Row(id=1, RollNo=101, Name='Anil', City='Mumbai')\nRow(id=2, RollNo=102, Name='Amar', City='Delhi')\nRow(id=3, RollNo=103, Name='Raam', City='Indore')\nRow(id=4, RollNo=104, Name='Leena', City='Nasik')\nRow(id=5, RollNo=105, Name='Keshav', City='Pune')\nRow(id=6, RollNo=106, Name='Hema', City='Nagpur')\nRow(id=7, RollNo=107, Name='Beena', City='Chennai')\nRow(id=8, RollNo=108, Name='John', City='Delhi')\nRow(id=9, RollNo=109, Name='Jaya', City='Nasik')\nRow(id=10, RollNo=110, Name='Raja', City='Nasik')\n"
},
{
"code": null,
"e": 49156,
"s": 49091,
"text": "To insert a new record, INSERT query is constructed as follows β"
},
{
"code": null,
"e": 49228,
"s": 49156,
"text": "id = Contacts.insert(RollNo=111, Name='Abdul', City='Surat').execute()\n"
},
{
"code": null,
"e": 49353,
"s": 49228,
"text": "If a list of records to be added is stored either as a list of dictionaries or as list of tuples, they can be added in bulk."
},
{
"code": null,
"e": 49524,
"s": 49353,
"text": "Records=[{βRollNoβ:112, βNameβ:βAjayβ, βCityβ:βMysoreβ}, \n {βRollNoβ:113, βNameβ:βMajidβ,βCityβ:βDelhiβ}}\n\nOr\n\nRecords=[(112, βAjayβ,βMysoreβ), (113, βMajidβ, βDelhiβ)}"
},
{
"code": null,
"e": 49565,
"s": 49524,
"text": "The INSERT query is written as follows β"
},
{
"code": null,
"e": 49601,
"s": 49565,
"text": "Contacts.insert(Records).execute()\n"
},
{
"code": null,
"e": 49752,
"s": 49601,
"text": "The Peewee Table object has update() method to implement SQL UPDATE query. To change City for all records from Nasik to Nagar, we use following query."
},
{
"code": null,
"e": 49825,
"s": 49752,
"text": "Contacts.update(City='Nagar').where((Contacts.City=='Nasik')).execute()\n"
},
{
"code": null,
"e": 49915,
"s": 49825,
"text": "Finally, Table class in Peewee also has delete() method to implement DELETE query in SQL."
},
{
"code": null,
"e": 49974,
"s": 49915,
"text": "Contacts.delete().where(Contacts.Name=='Abdul').execute()\n"
},
{
"code": null,
"e": 50251,
"s": 49974,
"text": "Peewee can work seamlessly with most of the Python web framework APIs. Whenever the Web Server Gateway Interface (WSGI) server receives a connection request from client, the connection with database is established, and then the connection is closed upon delivering a response."
},
{
"code": null,
"e": 50401,
"s": 50251,
"text": "While using in a Flask based web application, connection has an effect on @app.before_request decorator and is disconnected on @app.teardown_request."
},
{
"code": null,
"e": 50648,
"s": 50401,
"text": "from flask import Flask\nfrom peewee import *\n\ndb = SqliteDatabase('mydatabase.db')\napp = Flask(__name__)\n\n@app.before_request\ndef _db_connect():\n db.connect()\n\n@app.teardown_request\ndef _db_close(exc):\n if not db.is_closed():\n db.close()"
},
{
"code": null,
"e": 50729,
"s": 50648,
"text": "Peewee API can also be used in Django. To do so, add a middleware in Django app."
},
{
"code": null,
"e": 50988,
"s": 50729,
"text": "def PeeweeConnectionMiddleware(get_response):\n def middleware(request):\n db.connect()\n try:\n response = get_response(request)\n finally:\n if not db.is_closed():\n db.close()\n return response\n return middleware"
},
{
"code": null,
"e": 51037,
"s": 50988,
"text": "Middleware is added in Djangoβs settings module."
},
{
"code": null,
"e": 51229,
"s": 51037,
"text": "# settings.py\nMIDDLEWARE_CLASSES = (\n # Our custom middleware appears first in the list.\n 'my_blog.middleware.PeeweeConnectionMiddleware',\n #followed by default middleware list.\n ..\n)"
},
{
"code": null,
"e": 51324,
"s": 51229,
"text": "Peewee can be comfortably used with other frameworks such as Bottle, Pyramid and Tornado, etc."
},
{
"code": null,
"e": 51580,
"s": 51324,
"text": "Peewee comes with a Playhouse namespace. It is a collection of various extension modules. One of them is a playhouse.sqlite_ext module. It mainly defines SqliteExtDatabase class which inherits SqliteDatabase class, supports following additional features β"
},
{
"code": null,
"e": 51661,
"s": 51580,
"text": "The features of SQLite Extensions which are supported by Peewee are as follows β"
},
{
"code": null,
"e": 51679,
"s": 51661,
"text": "Full-text search."
},
{
"code": null,
"e": 51697,
"s": 51679,
"text": "Full-text search."
},
{
"code": null,
"e": 51754,
"s": 51697,
"text": "JavaScript Object Notation (JSON) extension integration."
},
{
"code": null,
"e": 51811,
"s": 51754,
"text": "JavaScript Object Notation (JSON) extension integration."
},
{
"code": null,
"e": 51844,
"s": 51811,
"text": "Closure table extension support."
},
{
"code": null,
"e": 51877,
"s": 51844,
"text": "Closure table extension support."
},
{
"code": null,
"e": 51901,
"s": 51877,
"text": "LSM1 extension support."
},
{
"code": null,
"e": 51925,
"s": 51901,
"text": "LSM1 extension support."
},
{
"code": null,
"e": 51955,
"s": 51925,
"text": "User-defined table functions."
},
{
"code": null,
"e": 51985,
"s": 51955,
"text": "User-defined table functions."
},
{
"code": null,
"e": 52048,
"s": 51985,
"text": "Support for online backups using backup API: backup_to_file()."
},
{
"code": null,
"e": 52111,
"s": 52048,
"text": "Support for online backups using backup API: backup_to_file()."
},
{
"code": null,
"e": 52164,
"s": 52111,
"text": "BLOB API support, for efficient binary data storage."
},
{
"code": null,
"e": 52217,
"s": 52164,
"text": "BLOB API support, for efficient binary data storage."
},
{
"code": null,
"e": 52309,
"s": 52217,
"text": "JSON data can be stored, if a special JSONField is declared as one of the field attributes."
},
{
"code": null,
"e": 52382,
"s": 52309,
"text": "class MyModel(Model):\n json_data = JSONField(json_dumps=my_json_dumps)"
},
{
"code": null,
"e": 52465,
"s": 52382,
"text": "To activate full-text search, the model can have DocIdField to define primary key."
},
{
"code": null,
"e": 52579,
"s": 52465,
"text": "class NoteIndex(FTSModel):\n docid = DocIDField()\n content = SearchField()\n\n class Meta:\n database = db"
},
{
"code": null,
"e": 52895,
"s": 52579,
"text": "FTSModel is a Subclass of VirtualModel which is available at http://docs.peewee-orm.com/en/latest/peewee/sqlite_ext.html#VirtualModel to be used with the FTS3 and FTS4 full-text search extensions. Sqlite will treat all column types as TEXT (although, you can store other data types, Sqlite will treat them as text)."
},
{
"code": null,
"e": 53003,
"s": 52895,
"text": "SearchField is a Field-class to be used for columns on models representing full-text search virtual tables."
},
{
"code": null,
"e": 53206,
"s": 53003,
"text": "SqliteDatabase supports AutoField for increasing primary key. However, SqliteExtDatabase supports AutoIncrementField to ensure that primary always increases monotonically, irrespective of row deletions."
},
{
"code": null,
"e": 53363,
"s": 53206,
"text": "SqliteQ module in playhouse namespace (playhouse.sqliteq) defines subclass of SqliteExeDatabase to handle serialised concurrent writes to a SQlite database."
},
{
"code": null,
"e": 53566,
"s": 53363,
"text": "On the other hand, playhouse.apsw module carries support for apsw sqlite driver. Another Python SQLite Wrapper (APSW) is fast and can handle nested transactions, that are managed explicitly by you code."
},
{
"code": null,
"e": 53756,
"s": 53566,
"text": "from apsw_ext import *\ndb = APSWDatabase('testdb')\n\nclass BaseModel(Model):\n class Meta:\n database = db\n\nclass MyModel(BaseModel):\n field1 = CharField()\n field2 = DateTimeField()"
},
{
"code": null,
"e": 54060,
"s": 53756,
"text": "Additional PostgreSQL functionality is enabled by helpers which are defined in playhouse.postgres_ext module. This module defines PostgresqlExtDatabase class and provides the following additional field types to be exclusively used for declaration of model to be mapped against PostgreSQL database table."
},
{
"code": null,
"e": 54145,
"s": 54060,
"text": "The features of PostgreSQL Extensions which are supported by Peewee are as follows β"
},
{
"code": null,
"e": 54188,
"s": 54145,
"text": "ArrayField field type, for storing arrays."
},
{
"code": null,
"e": 54231,
"s": 54188,
"text": "ArrayField field type, for storing arrays."
},
{
"code": null,
"e": 54284,
"s": 54231,
"text": "HStoreField field type, for storing key/value pairs."
},
{
"code": null,
"e": 54337,
"s": 54284,
"text": "HStoreField field type, for storing key/value pairs."
},
{
"code": null,
"e": 54394,
"s": 54337,
"text": "IntervalField field type, for storing timedelta objects."
},
{
"code": null,
"e": 54451,
"s": 54394,
"text": "IntervalField field type, for storing timedelta objects."
},
{
"code": null,
"e": 54496,
"s": 54451,
"text": "JSONField field type, for storing JSON data."
},
{
"code": null,
"e": 54541,
"s": 54496,
"text": "JSONField field type, for storing JSON data."
},
{
"code": null,
"e": 54598,
"s": 54541,
"text": "BinaryJSONField field type for the jsonb JSON data type."
},
{
"code": null,
"e": 54655,
"s": 54598,
"text": "BinaryJSONField field type for the jsonb JSON data type."
},
{
"code": null,
"e": 54716,
"s": 54655,
"text": "TSVectorField field type, for storing full-text search data."
},
{
"code": null,
"e": 54777,
"s": 54716,
"text": "TSVectorField field type, for storing full-text search data."
},
{
"code": null,
"e": 54838,
"s": 54777,
"text": "DateTimeTZField field type, a timezone-aware datetime field."
},
{
"code": null,
"e": 54899,
"s": 54838,
"text": "DateTimeTZField field type, a timezone-aware datetime field."
},
{
"code": null,
"e": 54974,
"s": 54899,
"text": "Additional Postgres-specific features in this module are meant to provide."
},
{
"code": null,
"e": 54990,
"s": 54974,
"text": "hstore support."
},
{
"code": null,
"e": 55006,
"s": 54990,
"text": "hstore support."
},
{
"code": null,
"e": 55027,
"s": 55006,
"text": "server-side cursors."
},
{
"code": null,
"e": 55048,
"s": 55027,
"text": "server-side cursors."
},
{
"code": null,
"e": 55066,
"s": 55048,
"text": "full-text search."
},
{
"code": null,
"e": 55084,
"s": 55066,
"text": "full-text search."
},
{
"code": null,
"e": 55283,
"s": 55084,
"text": "Postgres hstore is a key:value store that can be embedded in a table as one of the fields of type HStoreField. To enable hstore support, create database instance with register_hstore=True parameter."
},
{
"code": null,
"e": 55347,
"s": 55283,
"text": "db = PostgresqlExtDatabase('mydatabase', register_hstore=True)\n"
},
{
"code": null,
"e": 55384,
"s": 55347,
"text": "Define a model with one HStoreField."
},
{
"code": null,
"e": 55464,
"s": 55384,
"text": "class Vehicles(BaseExtModel):\n type = CharField()\n features = HStoreField()"
},
{
"code": null,
"e": 55501,
"s": 55464,
"text": "Create a model instance as follows β"
},
{
"code": null,
"e": 55589,
"s": 55501,
"text": "v=Vechicle.create(type='Car', specs:{'mfg':'Maruti', 'Fuel':'Petrol', 'model':'Alto'})\n"
},
{
"code": null,
"e": 55615,
"s": 55589,
"text": "To access hstore values β"
},
{
"code": null,
"e": 55670,
"s": 55615,
"text": "obj=Vehicle.get(Vehicle.id=v.id)\nprint (obj.features)\n"
},
{
"code": null,
"e": 55863,
"s": 55670,
"text": "Alternate implementation of MysqlDatabase class is provided by MySQLConnectorDatabase defined in playhouse.mysql_ext module. It uses Pythonβs DB-API compatible official mysql/python connector."
},
{
"code": null,
"e": 56005,
"s": 55863,
"text": "from playhouse.mysql_ext import MySQLConnectorDatabase\n\ndb = MySQLConnectorDatabase('mydatabase', host='localhost', user='root', password='')"
},
{
"code": null,
"e": 56270,
"s": 56005,
"text": "CockroachDB or Cockroach Database (CRDB) is developed by computer software company Cockroach Labs. It is a scalable, consistently-replicated, transactional datastore which is designed to store copies of data in multiple locations in order to deliver speedy access."
},
{
"code": null,
"e": 56510,
"s": 56270,
"text": "Peewee provides support to this database by way of CockroachDatabase class defined in playhouse.cockroachdb extension module. The module contains definition of CockroachDatabase as subclass of PostgresqlDatabase class from the core module."
},
{
"code": null,
"e": 56645,
"s": 56510,
"text": "Moreover, there is run_transaction() method which runs a function inside a transaction and provides automatic client-side retry logic."
},
{
"code": null,
"e": 56751,
"s": 56645,
"text": "The extension also has certain special field classes that are used as attribute in CRDB compatible model."
},
{
"code": null,
"e": 56853,
"s": 56751,
"text": "UUIDKeyField - A primary-key field that uses CRDBβs UUID type with a default randomly-generated UUID."
},
{
"code": null,
"e": 56955,
"s": 56853,
"text": "UUIDKeyField - A primary-key field that uses CRDBβs UUID type with a default randomly-generated UUID."
},
{
"code": null,
"e": 57045,
"s": 56955,
"text": "RowIDField - A primary-key field that uses CRDBβs INT type with a default unique_rowid()."
},
{
"code": null,
"e": 57135,
"s": 57045,
"text": "RowIDField - A primary-key field that uses CRDBβs INT type with a default unique_rowid()."
},
{
"code": null,
"e": 57185,
"s": 57135,
"text": "JSONField - Same as the Postgres BinaryJSONField."
},
{
"code": null,
"e": 57235,
"s": 57185,
"text": "JSONField - Same as the Postgres BinaryJSONField."
},
{
"code": null,
"e": 57327,
"s": 57235,
"text": "ArrayField - Same as the Postgres extension, but does not support multi-dimensional arrays."
},
{
"code": null,
"e": 57419,
"s": 57327,
"text": "ArrayField - Same as the Postgres extension, but does not support multi-dimensional arrays."
},
{
"code": null,
"e": 57426,
"s": 57419,
"text": " Print"
},
{
"code": null,
"e": 57437,
"s": 57426,
"text": " Add Notes"
}
] |
Java - Strings Class
|
Strings, which are widely used in Java programming, are a sequence of characters. In Java programming language, strings are treated as objects.
The Java platform provides the String class to create and manipulate strings.
The most direct way to create a string is to write β
String greeting = "Hello world!";
Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, "Hello world!'.
As with any other object, you can create String objects by using the new keyword and a constructor. The String class has 11 constructors that allow you to provide the initial value of the string using different sources, such as an array of characters.
public class StringDemo {
public static void main(String args[]) {
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println( helloString );
}
}
This will produce the following result β
hello.
Note β The String class is immutable, so that once it is created a String object cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters, then you should use String Buffer & String Builder Classes.
Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object.
The following program is an example of length(), method String class.
public class StringDemo {
public static void main(String args[]) {
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
System.out.println( "String Length is : " + len );
}
}
This will produce the following result β
String Length is : 17
The String class includes a method for concatenating two strings β
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals, as in β
"My name is ".concat("Zara");
Strings are more commonly concatenated with the + operator, as in β
"Hello," + " world" + "!"
which results in β
"Hello, world!"
Let us look at the following example β
public class StringDemo {
public static void main(String args[]) {
String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
}
}
This will produce the following result β
Dot saw I was Tod
You have printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object.
Using String's static format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example, instead of β
System.out.printf("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
You can write β
String fs;
fs = String.format("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
System.out.println(fs);
Here is the list of methods supported by String class β
Returns the character at the specified index.
Compares this String to another Object.
Compares two strings lexicographically.
Compares two strings lexicographically, ignoring case differences.
Concatenates the specified string to the end of this string.
Returns true if and only if this String represents the same sequence of characters as the specified StringBuffer.
Returns a String that represents the character sequence in the array specified.
Returns a String that represents the character sequence in the array specified.
Tests if this string ends with the specified suffix.
Compares this string to the specified object.
Compares this String to another String, ignoring case considerations.
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
Copies characters from this string into the destination character array.
Returns a hash code for this string.
Returns the index within this string of the first occurrence of the specified character.
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
Returns the index within this string of the first occurrence of the specified substring.
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
Returns a canonical representation for the string object.
Returns the index within this string of the last occurrence of the specified character.
Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
Returns the index within this string of the rightmost occurrence of the specified substring.
Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
Returns the length of this string.
Tells whether or not this string matches the given regular expression.
Tests if two string regions are equal.
Tests if two string regions are equal.
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
Replaces each substring of this string that matches the given regular expression with the given replacement.
Replaces the first substring of this string that matches the given regular expression with the given replacement.
Splits this string around matches of the given regular expression.
Splits this string around matches of the given regular expression.
Tests if this string starts with the specified prefix.
Tests if this string starts with the specified prefix beginning a specified index.
Returns a new character sequence that is a subsequence of this sequence.
Returns a new string that is a substring of this string.
Returns a new string that is a substring of this string.
Converts this string to a new character array.
Converts all of the characters in this String to lower case using the rules of the default locale.
Converts all of the characters in this String to lower case using the rules of the given Locale.
This object (which is already a string!) is itself returned.
Converts all of the characters in this String to upper case using the rules of the default locale.
Converts all of the characters in this String to upper case using the rules of the given Locale.
Returns a copy of the string, with leading and trailing whitespace omitted.
Returns the string representation of the passed data type argument.
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2521,
"s": 2377,
"text": "Strings, which are widely used in Java programming, are a sequence of characters. In Java programming language, strings are treated as objects."
},
{
"code": null,
"e": 2599,
"s": 2521,
"text": "The Java platform provides the String class to create and manipulate strings."
},
{
"code": null,
"e": 2652,
"s": 2599,
"text": "The most direct way to create a string is to write β"
},
{
"code": null,
"e": 2687,
"s": 2652,
"text": "String greeting = \"Hello world!\";\n"
},
{
"code": null,
"e": 2823,
"s": 2687,
"text": "Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, \"Hello world!'."
},
{
"code": null,
"e": 3075,
"s": 2823,
"text": "As with any other object, you can create String objects by using the new keyword and a constructor. The String class has 11 constructors that allow you to provide the initial value of the string using different sources, such as an array of characters."
},
{
"code": null,
"e": 3307,
"s": 3075,
"text": "public class StringDemo {\n\n public static void main(String args[]) {\n char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };\n String helloString = new String(helloArray); \n System.out.println( helloString );\n }\n}"
},
{
"code": null,
"e": 3348,
"s": 3307,
"text": "This will produce the following result β"
},
{
"code": null,
"e": 3356,
"s": 3348,
"text": "hello.\n"
},
{
"code": null,
"e": 3597,
"s": 3356,
"text": "Note β The String class is immutable, so that once it is created a String object cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters, then you should use String Buffer & String Builder Classes."
},
{
"code": null,
"e": 3824,
"s": 3597,
"text": "Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object."
},
{
"code": null,
"e": 3894,
"s": 3824,
"text": "The following program is an example of length(), method String class."
},
{
"code": null,
"e": 4113,
"s": 3894,
"text": "public class StringDemo {\n\n public static void main(String args[]) {\n String palindrome = \"Dot saw I was Tod\";\n int len = palindrome.length();\n System.out.println( \"String Length is : \" + len );\n }\n}"
},
{
"code": null,
"e": 4154,
"s": 4113,
"text": "This will produce the following result β"
},
{
"code": null,
"e": 4177,
"s": 4154,
"text": "String Length is : 17\n"
},
{
"code": null,
"e": 4244,
"s": 4177,
"text": "The String class includes a method for concatenating two strings β"
},
{
"code": null,
"e": 4270,
"s": 4244,
"text": "string1.concat(string2);\n"
},
{
"code": null,
"e": 4416,
"s": 4270,
"text": "This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals, as in β"
},
{
"code": null,
"e": 4447,
"s": 4416,
"text": "\"My name is \".concat(\"Zara\");\n"
},
{
"code": null,
"e": 4515,
"s": 4447,
"text": "Strings are more commonly concatenated with the + operator, as in β"
},
{
"code": null,
"e": 4542,
"s": 4515,
"text": "\"Hello,\" + \" world\" + \"!\"\n"
},
{
"code": null,
"e": 4561,
"s": 4542,
"text": "which results in β"
},
{
"code": null,
"e": 4578,
"s": 4561,
"text": "\"Hello, world!\"\n"
},
{
"code": null,
"e": 4617,
"s": 4578,
"text": "Let us look at the following example β"
},
{
"code": null,
"e": 4784,
"s": 4617,
"text": "public class StringDemo {\n\n public static void main(String args[]) {\n String string1 = \"saw I was \";\n System.out.println(\"Dot \" + string1 + \"Tod\");\n }\n}"
},
{
"code": null,
"e": 4825,
"s": 4784,
"text": "This will produce the following result β"
},
{
"code": null,
"e": 4844,
"s": 4825,
"text": "Dot saw I was Tod\n"
},
{
"code": null,
"e": 5045,
"s": 4844,
"text": "You have printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object."
},
{
"code": null,
"e": 5211,
"s": 5045,
"text": "Using String's static format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example, instead of β"
},
{
"code": null,
"e": 5438,
"s": 5211,
"text": "System.out.printf(\"The value of the float variable is \" +\n \"%f, while the value of the integer \" +\n \"variable is %d, and the string \" +\n \"is %s\", floatVar, intVar, stringVar);"
},
{
"code": null,
"e": 5454,
"s": 5438,
"text": "You can write β"
},
{
"code": null,
"e": 5720,
"s": 5454,
"text": "String fs;\nfs = String.format(\"The value of the float variable is \" +\n \"%f, while the value of the integer \" +\n \"variable is %d, and the string \" +\n \"is %s\", floatVar, intVar, stringVar);\nSystem.out.println(fs);"
},
{
"code": null,
"e": 5776,
"s": 5720,
"text": "Here is the list of methods supported by String class β"
},
{
"code": null,
"e": 5822,
"s": 5776,
"text": "Returns the character at the specified index."
},
{
"code": null,
"e": 5862,
"s": 5822,
"text": "Compares this String to another Object."
},
{
"code": null,
"e": 5902,
"s": 5862,
"text": "Compares two strings lexicographically."
},
{
"code": null,
"e": 5969,
"s": 5902,
"text": "Compares two strings lexicographically, ignoring case differences."
},
{
"code": null,
"e": 6030,
"s": 5969,
"text": "Concatenates the specified string to the end of this string."
},
{
"code": null,
"e": 6144,
"s": 6030,
"text": "Returns true if and only if this String represents the same sequence of characters as the specified StringBuffer."
},
{
"code": null,
"e": 6224,
"s": 6144,
"text": "Returns a String that represents the character sequence in the array specified."
},
{
"code": null,
"e": 6304,
"s": 6224,
"text": "Returns a String that represents the character sequence in the array specified."
},
{
"code": null,
"e": 6357,
"s": 6304,
"text": "Tests if this string ends with the specified suffix."
},
{
"code": null,
"e": 6403,
"s": 6357,
"text": "Compares this string to the specified object."
},
{
"code": null,
"e": 6473,
"s": 6403,
"text": "Compares this String to another String, ignoring case considerations."
},
{
"code": null,
"e": 6598,
"s": 6473,
"text": "Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array."
},
{
"code": null,
"e": 6710,
"s": 6598,
"text": "Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array."
},
{
"code": null,
"e": 6783,
"s": 6710,
"text": "Copies characters from this string into the destination character array."
},
{
"code": null,
"e": 6820,
"s": 6783,
"text": "Returns a hash code for this string."
},
{
"code": null,
"e": 6909,
"s": 6820,
"text": "Returns the index within this string of the first occurrence of the specified character."
},
{
"code": null,
"e": 7042,
"s": 6909,
"text": "Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index."
},
{
"code": null,
"e": 7131,
"s": 7042,
"text": "Returns the index within this string of the first occurrence of the specified substring."
},
{
"code": null,
"e": 7253,
"s": 7131,
"text": "Returns the index within this string of the first occurrence of the specified substring, starting at the specified index."
},
{
"code": null,
"e": 7311,
"s": 7253,
"text": "Returns a canonical representation for the string object."
},
{
"code": null,
"e": 7399,
"s": 7311,
"text": "Returns the index within this string of the last occurrence of the specified character."
},
{
"code": null,
"e": 7539,
"s": 7399,
"text": "Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index."
},
{
"code": null,
"e": 7632,
"s": 7539,
"text": "Returns the index within this string of the rightmost occurrence of the specified substring."
},
{
"code": null,
"e": 7772,
"s": 7632,
"text": "Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index."
},
{
"code": null,
"e": 7807,
"s": 7772,
"text": "Returns the length of this string."
},
{
"code": null,
"e": 7878,
"s": 7807,
"text": "Tells whether or not this string matches the given regular expression."
},
{
"code": null,
"e": 7917,
"s": 7878,
"text": "Tests if two string regions are equal."
},
{
"code": null,
"e": 7956,
"s": 7917,
"text": "Tests if two string regions are equal."
},
{
"code": null,
"e": 8058,
"s": 7956,
"text": "Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar."
},
{
"code": null,
"e": 8167,
"s": 8058,
"text": "Replaces each substring of this string that matches the given regular expression with the given replacement."
},
{
"code": null,
"e": 8281,
"s": 8167,
"text": "Replaces the first substring of this string that matches the given regular expression with the given replacement."
},
{
"code": null,
"e": 8348,
"s": 8281,
"text": "Splits this string around matches of the given regular expression."
},
{
"code": null,
"e": 8415,
"s": 8348,
"text": "Splits this string around matches of the given regular expression."
},
{
"code": null,
"e": 8470,
"s": 8415,
"text": "Tests if this string starts with the specified prefix."
},
{
"code": null,
"e": 8553,
"s": 8470,
"text": "Tests if this string starts with the specified prefix beginning a specified index."
},
{
"code": null,
"e": 8626,
"s": 8553,
"text": "Returns a new character sequence that is a subsequence of this sequence."
},
{
"code": null,
"e": 8683,
"s": 8626,
"text": "Returns a new string that is a substring of this string."
},
{
"code": null,
"e": 8740,
"s": 8683,
"text": "Returns a new string that is a substring of this string."
},
{
"code": null,
"e": 8787,
"s": 8740,
"text": "Converts this string to a new character array."
},
{
"code": null,
"e": 8886,
"s": 8787,
"text": "Converts all of the characters in this String to lower case using the rules of the default locale."
},
{
"code": null,
"e": 8983,
"s": 8886,
"text": "Converts all of the characters in this String to lower case using the rules of the given Locale."
},
{
"code": null,
"e": 9044,
"s": 8983,
"text": "This object (which is already a string!) is itself returned."
},
{
"code": null,
"e": 9143,
"s": 9044,
"text": "Converts all of the characters in this String to upper case using the rules of the default locale."
},
{
"code": null,
"e": 9240,
"s": 9143,
"text": "Converts all of the characters in this String to upper case using the rules of the given Locale."
},
{
"code": null,
"e": 9316,
"s": 9240,
"text": "Returns a copy of the string, with leading and trailing whitespace omitted."
},
{
"code": null,
"e": 9384,
"s": 9316,
"text": "Returns the string representation of the passed data type argument."
},
{
"code": null,
"e": 9417,
"s": 9384,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 9433,
"s": 9417,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 9466,
"s": 9433,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 9482,
"s": 9466,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 9517,
"s": 9482,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9531,
"s": 9517,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 9565,
"s": 9531,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 9579,
"s": 9565,
"text": " Tushar Kale"
},
{
"code": null,
"e": 9616,
"s": 9579,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 9631,
"s": 9616,
"text": " Monica Mittal"
},
{
"code": null,
"e": 9664,
"s": 9631,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 9683,
"s": 9664,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 9690,
"s": 9683,
"text": " Print"
},
{
"code": null,
"e": 9701,
"s": 9690,
"text": " Add Notes"
}
] |
PostgreSQL - Sub Queries
|
A subquery or Inner query or Nested query is a query within another PostgreSQL query and embedded within the WHERE clause.
A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE and DELETE statements along with the operators like =, <, >, >=, <=, IN, etc.
There are a few rules that subqueries must follow β
Subqueries must be enclosed within parentheses.
Subqueries must be enclosed within parentheses.
A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns.
A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns.
An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY can be used to perform the same function as the ORDER BY in a subquery.
An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY can be used to perform the same function as the ORDER BY in a subquery.
Subqueries that return more than one row can only be used with multiple value operators, such as the IN, EXISTS, NOT IN, ANY/SOME, ALL operator.
Subqueries that return more than one row can only be used with multiple value operators, such as the IN, EXISTS, NOT IN, ANY/SOME, ALL operator.
The BETWEEN operator cannot be used with a subquery; however, the BETWEEN can be used within the subquery.
The BETWEEN operator cannot be used with a subquery; however, the BETWEEN can be used within the subquery.
Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows β
SELECT column_name [, column_name ]
FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE])
Consider the COMPANY table having the following records β
id | name | age | address | salary
----+-------+-----+-----------+--------
1 | Paul | 32 | California| 20000
2 | Allen | 25 | Texas | 15000
3 | Teddy | 23 | Norway | 20000
4 | Mark | 25 | Rich-Mond | 65000
5 | David | 27 | Texas | 85000
6 | Kim | 22 | South-Hall| 45000
7 | James | 24 | Houston | 10000
(7 rows)
Now, let us check the following sub-query with SELECT statement β
testdb=# SELECT *
FROM COMPANY
WHERE ID IN (SELECT ID
FROM COMPANY
WHERE SALARY > 45000) ;
This would produce the following result β
id | name | age | address | salary
----+-------+-----+-------------+--------
4 | Mark | 25 | Rich-Mond | 65000
5 | David | 27 | Texas | 85000
(2 rows)
Subqueries also can be used with INSERT statements. The INSERT statement uses the data returned from the subquery to insert into another table. The selected data in the subquery can be modified with any of the character, date, or number functions.
The basic syntax is as follows β
INSERT INTO table_name [ (column1 [, column2 ]) ]
SELECT [ *|column1 [, column2 ] ]
FROM table1 [, table2 ]
[ WHERE VALUE OPERATOR ]
Consider a table COMPANY_BKP, with similar structure as COMPANY table and can be created using the same CREATE TABLE using COMPANY_BKP as the table name. Now, to copy complete COMPANY table into COMPANY_BKP, following is the syntax β
testdb=# INSERT INTO COMPANY_BKP
SELECT * FROM COMPANY
WHERE ID IN (SELECT ID
FROM COMPANY) ;
The subquery can be used in conjunction with the UPDATE statement. Either single or multiple columns in a table can be updated when using a subquery with the UPDATE statement.
The basic syntax is as follows β
UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Assuming, we have COMPANY_BKP table available, which is backup of the COMPANY table.
The following example updates SALARY by 0.50 times in the COMPANY table for all the customers, whose AGE is greater than or equal to 27 β
testdb=# UPDATE COMPANY
SET SALARY = SALARY * 0.50
WHERE AGE IN (SELECT AGE FROM COMPANY_BKP
WHERE AGE >= 27 );
This would affect two rows and finally the COMPANY table would have the following records β
id | name | age | address | salary
----+-------+-----+-------------+--------
2 | Allen | 25 | Texas | 15000
3 | Teddy | 23 | Norway | 20000
4 | Mark | 25 | Rich-Mond | 65000
6 | Kim | 22 | South-Hall | 45000
7 | James | 24 | Houston | 10000
1 | Paul | 32 | California | 10000
5 | David | 27 | Texas | 42500
(7 rows)
The subquery can be used in conjunction with the DELETE statement like with any other statements mentioned above.
The basic syntax is as follows β
DELETE FROM TABLE_NAME
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Assuming, we have COMPANY_BKP table available, which is a backup of the COMPANY table.
The following example deletes records from the COMPANY table for all the customers, whose AGE is greater than or equal to 27 β
testdb=# DELETE FROM COMPANY
WHERE AGE IN (SELECT AGE FROM COMPANY_BKP
WHERE AGE > 27 );
This would affect two rows and finally the COMPANY table would have the following records β
id | name | age | address | salary
----+-------+-----+-------------+--------
2 | Allen | 25 | Texas | 15000
3 | Teddy | 23 | Norway | 20000
4 | Mark | 25 | Rich-Mond | 65000
6 | Kim | 22 | South-Hall | 45000
7 | James | 24 | Houston | 10000
5 | David | 27 | Texas | 42500
(6 rows)
23 Lectures
1.5 hours
John Elder
49 Lectures
3.5 hours
Niyazi Erdogan
126 Lectures
10.5 hours
Abhishek And Pukhraj
35 Lectures
5 hours
Karthikeya T
5 Lectures
51 mins
Vinay Kumar
5 Lectures
52 mins
Vinay Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2948,
"s": 2825,
"text": "A subquery or Inner query or Nested query is a query within another PostgreSQL query and embedded within the WHERE clause."
},
{
"code": null,
"e": 3079,
"s": 2948,
"text": "A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved."
},
{
"code": null,
"e": 3212,
"s": 3079,
"text": "Subqueries can be used with the SELECT, INSERT, UPDATE and DELETE statements along with the operators like =, <, >, >=, <=, IN, etc."
},
{
"code": null,
"e": 3264,
"s": 3212,
"text": "There are a few rules that subqueries must follow β"
},
{
"code": null,
"e": 3312,
"s": 3264,
"text": "Subqueries must be enclosed within parentheses."
},
{
"code": null,
"e": 3360,
"s": 3312,
"text": "Subqueries must be enclosed within parentheses."
},
{
"code": null,
"e": 3514,
"s": 3360,
"text": "A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns."
},
{
"code": null,
"e": 3668,
"s": 3514,
"text": "A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns."
},
{
"code": null,
"e": 3840,
"s": 3668,
"text": "An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY can be used to perform the same function as the ORDER BY in a subquery."
},
{
"code": null,
"e": 4012,
"s": 3840,
"text": "An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY can be used to perform the same function as the ORDER BY in a subquery."
},
{
"code": null,
"e": 4157,
"s": 4012,
"text": "Subqueries that return more than one row can only be used with multiple value operators, such as the IN, EXISTS, NOT IN, ANY/SOME, ALL operator."
},
{
"code": null,
"e": 4302,
"s": 4157,
"text": "Subqueries that return more than one row can only be used with multiple value operators, such as the IN, EXISTS, NOT IN, ANY/SOME, ALL operator."
},
{
"code": null,
"e": 4409,
"s": 4302,
"text": "The BETWEEN operator cannot be used with a subquery; however, the BETWEEN can be used within the subquery."
},
{
"code": null,
"e": 4516,
"s": 4409,
"text": "The BETWEEN operator cannot be used with a subquery; however, the BETWEEN can be used within the subquery."
},
{
"code": null,
"e": 4612,
"s": 4516,
"text": "Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows β"
},
{
"code": null,
"e": 4790,
"s": 4612,
"text": "SELECT column_name [, column_name ]\nFROM table1 [, table2 ]\nWHERE column_name OPERATOR\n (SELECT column_name [, column_name ]\n FROM table1 [, table2 ]\n [WHERE])"
},
{
"code": null,
"e": 4848,
"s": 4790,
"text": "Consider the COMPANY table having the following records β"
},
{
"code": null,
"e": 5209,
"s": 4848,
"text": " id | name | age | address | salary\n----+-------+-----+-----------+--------\n 1 | Paul | 32 | California| 20000\n 2 | Allen | 25 | Texas | 15000\n 3 | Teddy | 23 | Norway | 20000\n 4 | Mark | 25 | Rich-Mond | 65000\n 5 | David | 27 | Texas | 85000\n 6 | Kim | 22 | South-Hall| 45000\n 7 | James | 24 | Houston | 10000\n(7 rows)"
},
{
"code": null,
"e": 5275,
"s": 5209,
"text": "Now, let us check the following sub-query with SELECT statement β"
},
{
"code": null,
"e": 5384,
"s": 5275,
"text": "testdb=# SELECT *\n FROM COMPANY\n WHERE ID IN (SELECT ID\n FROM COMPANY\n WHERE SALARY > 45000) ;"
},
{
"code": null,
"e": 5426,
"s": 5384,
"text": "This would produce the following result β"
},
{
"code": null,
"e": 5601,
"s": 5426,
"text": " id | name | age | address | salary\n----+-------+-----+-------------+--------\n 4 | Mark | 25 | Rich-Mond | 65000\n 5 | David | 27 | Texas | 85000\n(2 rows)\n"
},
{
"code": null,
"e": 5850,
"s": 5601,
"text": "Subqueries also can be used with INSERT statements. The INSERT statement uses the data returned from the subquery to insert into another table. The selected data in the subquery can be modified with any of the character, date, or number functions."
},
{
"code": null,
"e": 5883,
"s": 5850,
"text": "The basic syntax is as follows β"
},
{
"code": null,
"e": 6025,
"s": 5883,
"text": "INSERT INTO table_name [ (column1 [, column2 ]) ]\n SELECT [ *|column1 [, column2 ] ]\n FROM table1 [, table2 ]\n [ WHERE VALUE OPERATOR ]"
},
{
"code": null,
"e": 6259,
"s": 6025,
"text": "Consider a table COMPANY_BKP, with similar structure as COMPANY table and can be created using the same CREATE TABLE using COMPANY_BKP as the table name. Now, to copy complete COMPANY table into COMPANY_BKP, following is the syntax β"
},
{
"code": null,
"e": 6365,
"s": 6259,
"text": "testdb=# INSERT INTO COMPANY_BKP\n SELECT * FROM COMPANY\n WHERE ID IN (SELECT ID\n FROM COMPANY) ;"
},
{
"code": null,
"e": 6541,
"s": 6365,
"text": "The subquery can be used in conjunction with the UPDATE statement. Either single or multiple columns in a table can be updated when using a subquery with the UPDATE statement."
},
{
"code": null,
"e": 6574,
"s": 6541,
"text": "The basic syntax is as follows β"
},
{
"code": null,
"e": 6700,
"s": 6574,
"text": "UPDATE table\nSET column_name = new_value\n[ WHERE OPERATOR [ VALUE ]\n (SELECT COLUMN_NAME\n FROM TABLE_NAME)\n [ WHERE) ]\n"
},
{
"code": null,
"e": 6785,
"s": 6700,
"text": "Assuming, we have COMPANY_BKP table available, which is backup of the COMPANY table."
},
{
"code": null,
"e": 6923,
"s": 6785,
"text": "The following example updates SALARY by 0.50 times in the COMPANY table for all the customers, whose AGE is greater than or equal to 27 β"
},
{
"code": null,
"e": 7047,
"s": 6923,
"text": "testdb=# UPDATE COMPANY\n SET SALARY = SALARY * 0.50\n WHERE AGE IN (SELECT AGE FROM COMPANY_BKP\n WHERE AGE >= 27 );"
},
{
"code": null,
"e": 7139,
"s": 7047,
"text": "This would affect two rows and finally the COMPANY table would have the following records β"
},
{
"code": null,
"e": 7518,
"s": 7139,
"text": " id | name | age | address | salary\n----+-------+-----+-------------+--------\n 2 | Allen | 25 | Texas | 15000\n 3 | Teddy | 23 | Norway | 20000\n 4 | Mark | 25 | Rich-Mond | 65000\n 6 | Kim | 22 | South-Hall | 45000\n 7 | James | 24 | Houston | 10000\n 1 | Paul | 32 | California | 10000\n 5 | David | 27 | Texas | 42500\n(7 rows)"
},
{
"code": null,
"e": 7632,
"s": 7518,
"text": "The subquery can be used in conjunction with the DELETE statement like with any other statements mentioned above."
},
{
"code": null,
"e": 7665,
"s": 7632,
"text": "The basic syntax is as follows β"
},
{
"code": null,
"e": 7773,
"s": 7665,
"text": "DELETE FROM TABLE_NAME\n[ WHERE OPERATOR [ VALUE ]\n (SELECT COLUMN_NAME\n FROM TABLE_NAME)\n [ WHERE) ]\n"
},
{
"code": null,
"e": 7860,
"s": 7773,
"text": "Assuming, we have COMPANY_BKP table available, which is a backup of the COMPANY table."
},
{
"code": null,
"e": 7987,
"s": 7860,
"text": "The following example deletes records from the COMPANY table for all the customers, whose AGE is greater than or equal to 27 β"
},
{
"code": null,
"e": 8085,
"s": 7987,
"text": "testdb=# DELETE FROM COMPANY\n WHERE AGE IN (SELECT AGE FROM COMPANY_BKP\n WHERE AGE > 27 );"
},
{
"code": null,
"e": 8177,
"s": 8085,
"text": "This would affect two rows and finally the COMPANY table would have the following records β"
},
{
"code": null,
"e": 8515,
"s": 8177,
"text": " id | name | age | address | salary\n----+-------+-----+-------------+--------\n 2 | Allen | 25 | Texas | 15000\n 3 | Teddy | 23 | Norway | 20000\n 4 | Mark | 25 | Rich-Mond | 65000\n 6 | Kim | 22 | South-Hall | 45000\n 7 | James | 24 | Houston | 10000\n 5 | David | 27 | Texas | 42500\n(6 rows)"
},
{
"code": null,
"e": 8550,
"s": 8515,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8562,
"s": 8550,
"text": " John Elder"
},
{
"code": null,
"e": 8597,
"s": 8562,
"text": "\n 49 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 8613,
"s": 8597,
"text": " Niyazi Erdogan"
},
{
"code": null,
"e": 8650,
"s": 8613,
"text": "\n 126 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 8672,
"s": 8650,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 8705,
"s": 8672,
"text": "\n 35 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 8719,
"s": 8705,
"text": " Karthikeya T"
},
{
"code": null,
"e": 8750,
"s": 8719,
"text": "\n 5 Lectures \n 51 mins\n"
},
{
"code": null,
"e": 8763,
"s": 8750,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 8794,
"s": 8763,
"text": "\n 5 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8807,
"s": 8794,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 8814,
"s": 8807,
"text": " Print"
},
{
"code": null,
"e": 8825,
"s": 8814,
"text": " Add Notes"
}
] |
Embedded Systems - Addressing Modes
|
An addressing mode refers to how you are addressing a given memory location. There are five different ways or five addressing modes to execute this instruction which are as follows β
Immediate addressing mode
Direct addressing mode
Register direct addressing mode
Register indirect addressing mode
Indexed addressing mode
Let's begin with an example.
MOV A, #6AH
In general, we can write,
MOV A, #data
It is termed as immediate because 8-bit data is transferred immediately to the accumulator (destination operand).
The following illustration describes the above instruction and its execution. The opcode 74H is saved at 0202 address. The data 6AH is saved at 0203 address in the program memory. After reading the opcode 74H, the data at the next program memory address is transferred to accumulator A (E0H is the address of accumulator). Since the instruction is of 2-bytes and is executed in one cycle, the program counter will be incremented by 2 and will point to 0204 of the program memory.
Note β The '#' symbol before 6AH indicates that the operand is a data (8 bit). In the absence of '#', the hexadecimal number would be taken as an address.
This is another way of addressing an operand. Here, the address of the data (source data) is given as an operand. Letβs take an example.
MOV A, 04H
The register bank#0 (4th register) has the address 04H. When the MOV instruction is executed, the data stored in register 04H is moved to the accumulator. As the register 04H holds the data 1FH, 1FH is moved to the accumulator.
Note β We have not used '#' in direct addressing mode, unlike immediate mode. If we had used '#', the data value 04H would have been transferred to the accumulator instead of 1FH.
Now, take a look at the following illustration. It shows how the instruction gets executed.
As shown in the above illustration, this is a 2-byte instruction which requires 1 cycle to complete. The PC will be incremented by 2 and will point to 0204. The opcode for the instruction MOV A, address is E5H. When the instruction at 0202 is executed (E5H), the accumulator is made active and ready to receive data. Then the PC goes to the next address as 0203 and looks up the address of the location of 04H where the source data (to be transferred to accumulator) is located. At 04H, the control finds the data 1F and transfers it to the accumulator and hence the execution is completed.
In this addressing mode, we use the register name directly (as source operand). Let us try to understand with the help of an example.
MOV A, R4
At a time, the registers can take values from R0 to R7. There are 32 such registers. In order to use 32 registers with just 8 variables to address registers, register banks are used. There are 4 register banks named from 0 to 3. Each bank comprises of 8 registers named from R0 to R7.
At a time, a single register bank can be selected. Selection of a register bank is made possible through a Special Function Register (SFR) named Processor Status Word (PSW). PSW is an 8-bit SFR where each bit can be programmed as required. Bits are designated from PSW.0 to PSW.7. PSW.3 and PSW.4 are used to select register banks.
Now, take a look at the following illustration to get a clear understanding of how it works.
Opcode EC is used for MOV A, R4. The opcode is stored at the address 0202 and when it is executed, the control goes directly to R4 of the respected register bank (that is selected in PSW). If register bank #0 is selected, then the data from R4 of register bank #0 will be moved to the accumulator. Here 2F is stored at 04H. 04H represents the address of R4 of register bank #0.
Data (2F) movement is highlighted in bold. 2F is getting transferred to the accumulator from data memory location 0C H and is shown as dotted line. 0CH is the address location of Register 4 (R4) of register bank #1. The instruction above is 1 byte and requires 1 cycle for complete execution. What it means is, you can save program memory by using register direct addressing mode.
In this addressing mode, the address of the data is stored in the register as operand.
MOV A, @R0
Here the value inside R0 is considered as an address, which holds the data to be transferred to the accumulator. Example: If R0 has the value 20H, and data 2FH is stored at the address 20H, then the value 2FH will get transferred to the accumulator after executing this instruction. See the following illustration.
So the opcode for MOV A, @R0 is E6H. Assuming that the register bank #0 is selected, the R0 of register bank #0 holds the data 20H. Program control moves to 20H where it locates the data 2FH and it transfers 2FH to the accumulator. This is a 1-byte instruction and the program counter increments by 1 and moves to 0203 of the program memory.
Note β Only R0 and R1 are allowed to form a register indirect addressing instruction. In other words, the programmer can create an instruction either using @R0 or @R1. All register banks are allowed.
We will take two examples to understand the concept of indexed addressing mode. Take a look at the following instructions β
MOVC A, @A+DPTR
and
MOVC A, @A+PC
where DPTR is the data pointer and PC is the program counter (both are 16-bit registers). Consider the first example.
MOVC A, @A+DPTR
The source operand is @A+DPTR. It contains the source data from this location. Here we are adding the contents of DPTR with the current content of the accumulator. This addition will give a new address which is the address of the source data. The data pointed by this address is then transferred to the accumulator.
The opcode is 93H. DPTR has the value 01FE, where 01 is located in DPH (higher 8 bits) and FE is located in DPL (lower 8 bits). Accumulator has the value 02H. Then a 16-bit addition is performed and 01FE H+02H results in 0200 H. Data at the location 0200H will get transferred to the accumulator. The previous value inside the accumulator (02H) will be replaced with the new data from 0200H. The new data in the accumulator is highlighted in the illustration.
This is a 1-byte instruction with 2 cycles needed for execution and the execution time required for this instruction is high compared to previous instructions (which were all 1 cycle each).
The other example MOVC A, @A+PC works the same way as the above example. Instead of adding DPTR with the accumulator, here the data inside the program counter (PC) is added with the accumulator to obtain the target address.
65 Lectures
6.5 hours
Amit Rana
36 Lectures
4.5 hours
Amit Rana
33 Lectures
3 hours
Ashraf Said
23 Lectures
2 hours
Smart Logic Academy
66 Lectures
5.5 hours
NerdyElectronics
49 Lectures
8.5 hours
Rahul Shrivastava
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2066,
"s": 1883,
"text": "An addressing mode refers to how you are addressing a given memory location. There are five different ways or five addressing modes to execute this instruction which are as follows β"
},
{
"code": null,
"e": 2092,
"s": 2066,
"text": "Immediate addressing mode"
},
{
"code": null,
"e": 2115,
"s": 2092,
"text": "Direct addressing mode"
},
{
"code": null,
"e": 2147,
"s": 2115,
"text": "Register direct addressing mode"
},
{
"code": null,
"e": 2181,
"s": 2147,
"text": "Register indirect addressing mode"
},
{
"code": null,
"e": 2205,
"s": 2181,
"text": "Indexed addressing mode"
},
{
"code": null,
"e": 2234,
"s": 2205,
"text": "Let's begin with an example."
},
{
"code": null,
"e": 2248,
"s": 2234,
"text": "MOV A, #6AH \n"
},
{
"code": null,
"e": 2274,
"s": 2248,
"text": "In general, we can write,"
},
{
"code": null,
"e": 2288,
"s": 2274,
"text": "MOV A, #data\n"
},
{
"code": null,
"e": 2402,
"s": 2288,
"text": "It is termed as immediate because 8-bit data is transferred immediately to the accumulator (destination operand)."
},
{
"code": null,
"e": 2882,
"s": 2402,
"text": "The following illustration describes the above instruction and its execution. The opcode 74H is saved at 0202 address. The data 6AH is saved at 0203 address in the program memory. After reading the opcode 74H, the data at the next program memory address is transferred to accumulator A (E0H is the address of accumulator). Since the instruction is of 2-bytes and is executed in one cycle, the program counter will be incremented by 2 and will point to 0204 of the program memory."
},
{
"code": null,
"e": 3037,
"s": 2882,
"text": "Note β The '#' symbol before 6AH indicates that the operand is a data (8 bit). In the absence of '#', the hexadecimal number would be taken as an address."
},
{
"code": null,
"e": 3174,
"s": 3037,
"text": "This is another way of addressing an operand. Here, the address of the data (source data) is given as an operand. Letβs take an example."
},
{
"code": null,
"e": 3187,
"s": 3174,
"text": "MOV A, 04H \n"
},
{
"code": null,
"e": 3415,
"s": 3187,
"text": "The register bank#0 (4th register) has the address 04H. When the MOV instruction is executed, the data stored in register 04H is moved to the accumulator. As the register 04H holds the data 1FH, 1FH is moved to the accumulator."
},
{
"code": null,
"e": 3595,
"s": 3415,
"text": "Note β We have not used '#' in direct addressing mode, unlike immediate mode. If we had used '#', the data value 04H would have been transferred to the accumulator instead of 1FH."
},
{
"code": null,
"e": 3687,
"s": 3595,
"text": "Now, take a look at the following illustration. It shows how the instruction gets executed."
},
{
"code": null,
"e": 4278,
"s": 3687,
"text": "As shown in the above illustration, this is a 2-byte instruction which requires 1 cycle to complete. The PC will be incremented by 2 and will point to 0204. The opcode for the instruction MOV A, address is E5H. When the instruction at 0202 is executed (E5H), the accumulator is made active and ready to receive data. Then the PC goes to the next address as 0203 and looks up the address of the location of 04H where the source data (to be transferred to accumulator) is located. At 04H, the control finds the data 1F and transfers it to the accumulator and hence the execution is completed."
},
{
"code": null,
"e": 4412,
"s": 4278,
"text": "In this addressing mode, we use the register name directly (as source operand). Let us try to understand with the help of an example."
},
{
"code": null,
"e": 4424,
"s": 4412,
"text": "MOV A, R4 \n"
},
{
"code": null,
"e": 4709,
"s": 4424,
"text": "At a time, the registers can take values from R0 to R7. There are 32 such registers. In order to use 32 registers with just 8 variables to address registers, register banks are used. There are 4 register banks named from 0 to 3. Each bank comprises of 8 registers named from R0 to R7."
},
{
"code": null,
"e": 5041,
"s": 4709,
"text": "At a time, a single register bank can be selected. Selection of a register bank is made possible through a Special Function Register (SFR) named Processor Status Word (PSW). PSW is an 8-bit SFR where each bit can be programmed as required. Bits are designated from PSW.0 to PSW.7. PSW.3 and PSW.4 are used to select register banks."
},
{
"code": null,
"e": 5134,
"s": 5041,
"text": "Now, take a look at the following illustration to get a clear understanding of how it works."
},
{
"code": null,
"e": 5512,
"s": 5134,
"text": "Opcode EC is used for MOV A, R4. The opcode is stored at the address 0202 and when it is executed, the control goes directly to R4 of the respected register bank (that is selected in PSW). If register bank #0 is selected, then the data from R4 of register bank #0 will be moved to the accumulator. Here 2F is stored at 04H. 04H represents the address of R4 of register bank #0."
},
{
"code": null,
"e": 5893,
"s": 5512,
"text": "Data (2F) movement is highlighted in bold. 2F is getting transferred to the accumulator from data memory location 0C H and is shown as dotted line. 0CH is the address location of Register 4 (R4) of register bank #1. The instruction above is 1 byte and requires 1 cycle for complete execution. What it means is, you can save program memory by using register direct addressing mode."
},
{
"code": null,
"e": 5980,
"s": 5893,
"text": "In this addressing mode, the address of the data is stored in the register as operand."
},
{
"code": null,
"e": 5993,
"s": 5980,
"text": "MOV A, @R0 \n"
},
{
"code": null,
"e": 6308,
"s": 5993,
"text": "Here the value inside R0 is considered as an address, which holds the data to be transferred to the accumulator. Example: If R0 has the value 20H, and data 2FH is stored at the address 20H, then the value 2FH will get transferred to the accumulator after executing this instruction. See the following illustration."
},
{
"code": null,
"e": 6650,
"s": 6308,
"text": "So the opcode for MOV A, @R0 is E6H. Assuming that the register bank #0 is selected, the R0 of register bank #0 holds the data 20H. Program control moves to 20H where it locates the data 2FH and it transfers 2FH to the accumulator. This is a 1-byte instruction and the program counter increments by 1 and moves to 0203 of the program memory."
},
{
"code": null,
"e": 6850,
"s": 6650,
"text": "Note β Only R0 and R1 are allowed to form a register indirect addressing instruction. In other words, the programmer can create an instruction either using @R0 or @R1. All register banks are allowed."
},
{
"code": null,
"e": 6974,
"s": 6850,
"text": "We will take two examples to understand the concept of indexed addressing mode. Take a look at the following instructions β"
},
{
"code": null,
"e": 6990,
"s": 6974,
"text": "MOVC A, @A+DPTR"
},
{
"code": null,
"e": 6994,
"s": 6990,
"text": "and"
},
{
"code": null,
"e": 7008,
"s": 6994,
"text": "MOVC A, @A+PC"
},
{
"code": null,
"e": 7126,
"s": 7008,
"text": "where DPTR is the data pointer and PC is the program counter (both are 16-bit registers). Consider the first example."
},
{
"code": null,
"e": 7143,
"s": 7126,
"text": "MOVC A, @A+DPTR\n"
},
{
"code": null,
"e": 7459,
"s": 7143,
"text": "The source operand is @A+DPTR. It contains the source data from this location. Here we are adding the contents of DPTR with the current content of the accumulator. This addition will give a new address which is the address of the source data. The data pointed by this address is then transferred to the accumulator."
},
{
"code": null,
"e": 7919,
"s": 7459,
"text": "The opcode is 93H. DPTR has the value 01FE, where 01 is located in DPH (higher 8 bits) and FE is located in DPL (lower 8 bits). Accumulator has the value 02H. Then a 16-bit addition is performed and 01FE H+02H results in 0200 H. Data at the location 0200H will get transferred to the accumulator. The previous value inside the accumulator (02H) will be replaced with the new data from 0200H. The new data in the accumulator is highlighted in the illustration."
},
{
"code": null,
"e": 8109,
"s": 7919,
"text": "This is a 1-byte instruction with 2 cycles needed for execution and the execution time required for this instruction is high compared to previous instructions (which were all 1 cycle each)."
},
{
"code": null,
"e": 8333,
"s": 8109,
"text": "The other example MOVC A, @A+PC works the same way as the above example. Instead of adding DPTR with the accumulator, here the data inside the program counter (PC) is added with the accumulator to obtain the target address."
},
{
"code": null,
"e": 8368,
"s": 8333,
"text": "\n 65 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 8379,
"s": 8368,
"text": " Amit Rana"
},
{
"code": null,
"e": 8414,
"s": 8379,
"text": "\n 36 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 8425,
"s": 8414,
"text": " Amit Rana"
},
{
"code": null,
"e": 8458,
"s": 8425,
"text": "\n 33 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 8471,
"s": 8458,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8504,
"s": 8471,
"text": "\n 23 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 8525,
"s": 8504,
"text": " Smart Logic Academy"
},
{
"code": null,
"e": 8560,
"s": 8525,
"text": "\n 66 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 8578,
"s": 8560,
"text": " NerdyElectronics"
},
{
"code": null,
"e": 8613,
"s": 8578,
"text": "\n 49 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 8632,
"s": 8613,
"text": " Rahul Shrivastava"
},
{
"code": null,
"e": 8639,
"s": 8632,
"text": " Print"
},
{
"code": null,
"e": 8650,
"s": 8639,
"text": " Add Notes"
}
] |
Machine Learning for Radiology β Where to Begin | by Eric M. Baumel | Towards Data Science
|
Are you interested in getting started with machine learning for radiology? The constellation of new terms can be overwhelming: Deep Learning, TensorFlow, Scikit-Learn, Keras, Pandas, Python and Anaconda. There is a head-spinning amount of new information to get under your belt before you can get started.
Personally, I want to be able use machine learning (ML) capabilities in some of my iOS apps using Appleβs CoreML framework as well. This means another set of complexities to navigate before you can actually get down to work. Once we have our tools configured properly, the job will be easier.
The dominant language in machine learning is Python. There is an entire ecosystem that you need to get familiar with before you can start working on the many great tutorials out there.
There are a myriad amount of resources online as well as books to help you get started (a job for another post). Letβs see what we need to do to take our first steps.
Photo by Malte Wingen on Unsplash
βGive me six hours to chop down a tree and I will spend the first four sharpening the axe.β
- Abraham Lincoln (probably never said this)
Letβs talk
The most common development language for ML is Python. If you donβt know Python, many of the resources for ML beginners start off with quick Python intros.
This post is not intended to teach Python, but to demonstrate one developerβs path to getting started with the vast ML tool chain.
The first thing you need to do is download Python and the necessary Python tools for machine learning.
Hello, Unix
We need to use the command line interface to install and manage our Python tools.
Enough bash to be dangerous:
In Linux or a Mac, we use the Terminal. You can find the program at Finder>Applications>Utilities>Terminal .
In Windows, we use the Command Prompt. You click on the Windows icon>Windows System>Command Prompt or click on the Windows icon and type cmd .
Before the cursor you see a string of text which refers to:machinename:directory username$
You type after the dollar sign.
Here are some common commands:
List files in current directory: lsShow hidden files as well: ls -aNavigate to a new directory: cd <directory_path>To go to home directory: cd ~ or just type: cd Go navigate up one level: cd ..To go to the last folder you were in: cd -
To show the current working directory: pwd
The Up Arrow retypes the last command. You can travel back to previous commands by pressing the Up Arrow over again.
Clear the window: clear
Open a file in a text editor, ex: atom <filename>
To cancel an application (ex. ping) Ctrl-C
Python
Python is an interpreted language, so it is read line by line, rather than a compiled language, where you have to bake the cake before you can use it.
There are two separate versions of Python currently available, Python 2.7 and Python 3. Python 2.7 will be reaching end of life January 1, 2020, and Python 3.x is not backwards-compatible. So why would you want to use an older version? Unfortunately some of the frameworks only support 2.7, and many tutorials in books and online were written specifically for that version. How do we deal with this?
Fortunately you can have both flavors of Python on your computer, and run different virtual environments in different folders on your hard drive, so you can do most of your ML work in, say Python 3.7, and have version 2.7 in different folders if you have a project that requires a library that only works on 2.7.
There are several ways to manage the different Python virtual environments using virtualenv, Python Environment Wrapper (pew), venv, pyvenv. The easiest is to use Conda, which installed with Python when you use Anaconda.
Anaconda
Anaconda is an open-source platform that is perhaps the easiest way to get started with Python machine learning on Linux, Mac OS X and Windows. It helps you manage the programing environments, and includes common Python packages used in data science. You can download the distribution for your platform at https://www.anaconda.com/distribution/ .
Once you install the appropriate version of Python for your system, you will want to set up some environments.
Conda
Conda is the Python package manager and environment management system used by Anaconda. Conda installs most, but not all of the packages you need. The rest can be installed through the command line using pipβ more about that later.
To see the packages in your current environment:
conda list env
Which version of Conda you are running:
conda -version
(if below 4.1.0 β then you can update Conda with conda update conda)
You can create an environment with the Anaconda Navigator by choosing Environments from the left menu and then clicking the Create button.
You can also create the environment from the command line. For example here we create an environment named βpy27β using Python 2.7:
conda create -n py27 python=2.7
To activate an environment:
conda activate <your_env_name>
To deactivate the current environment:
conda deactivate
To remove an environment:
conda remove -name <your_env_name> -all
To list all of your Conda environments:
conda info --envs
The environment with the asterisk is the current active environment.
To see the packages in your current environment:
conda list env
Which version of Conda you are running:
conda -version
(if below 4.1.0 β then you can update Conda with conda update conda)
Two of the major machine learning packages TensorFlow and Keras should be installed using pip. For Appleβs machine learning frameworks, you would also install Turi Create.
The Scientific Stack
There is a set of Python packages referred to as the scientific stack that are useful across multiple disciplines. These include:
NumPy http://www.numpy.org/ β library for efficient handling of arrays and matricesSciPy https://www.scipy.org/ β collection of packages with math and science capabilitiesmatplatlib https://matplotlib.org/ β the standard 2D plotting library in Pythonpandas https://pandas.pydata.org/ β library of matrix-like data structures, labeled indices, time functions, etc.Scikit-learn https://scikit-learn.org/stable/ β library of machine learning algorithmsJupyter https://jupyter.org/ β an interactive Python shell in a web-based notebookSeaborn https://seaborn.pydata.org/index.html β statistical data visualizationsBokeh https://bokeh.pydata.org/en/latest/ β interactive data visualizationsPyTables https://www.pytables.org/ β a Python wrapper for HDF5 library
You can install these packages and their dependencies using Anaconda. In your newly created environment search for the package you want.
Then you select them from the list by checking the box and clicking apply.
As I mentioned earlier, you use pip to install TensorFlow and Keras (and Turi Create for Appleβs CoreML).
pip
pip is pythonβs standard package manager https://pypi.org/project/pip/
pip install β upgrade pip
To install a package with pip:
pip install <package_name>
Editing Python Files
You interact with python in Terminal on a Mac or Console in Windows. To write your code, most people use a code editor such as Atom https://atom.io/ or Sublime Text https://www.sublimetext.com/ . There are whole religious wars over code editors, but life is too short for that.
My favorite (and free) text editor is Atom https://atom.io/ , from the GitHub folks. A cool feature of Atom is that you can extend the app with features such as an integrated Terminal window.
Once installed, you can add this feature by going to Settings / Install Packages and search for platformio-ide-terminal
Running Python Files
At the command prompt ($ or >) type python <filename.py>
To exit python use exit()or Ctrl-D (Ctrl-Z in Windows)
To see which python version you are currently using, type:
python --version or python -V
To see where the Python installation you are using is located, type:
which python
Environment Files
An environment file is a file in your projectβs root directory that lists all the included packages and their version numbers specific to your projectβs environment. This allows you to share projects with others, and for you to reuse in other projects.
You create the file using:
conda env export -file environment.yaml
You recreate the Conda environment and its packages using:
conda env create -n <conda-env> -f environment.yaml
In some projects or tutorials you will see requirements.txt which is utilized by pip as the package manager instead of the environment.yaml used by Conda.
These are created by freezing the environment:
pip freeze > requirements.txt
To reconstitue, use:
pip install -r requirements.txt
Jupyter Notebooks
Jupyter Notebook https://jupyter.org/ is an open-source web browser based application. This allows you to run your python code directly in a more user friendly environemnt and see the results step by step. It is great for teaching, as you can add text and images in between your code cells in markup cells. The application is extensible, so you can add many other useful features.
You also can install Jupyter Notebook with the Anaconda Navigator:
Type the following at the prompt to create a new Jupyter Notebook app in your browser:
jupyter notebook
To launch a specific notebook:
jupyter notebook <notebook-name>
By the way, it is not recommended to run multiple instances of the Jupyter Notebook App simultaneously.
To run a cell, click on the Run button in the Jupyter toolbar or type Shift + Enter.To shut down a notebook, close the Terminal window or type:
jupyter notebook stop
or press Ctrl+C
OK, so now what?
Now that our axe is sharpened, how can you get started on actual radiology informatics.
Here are a few links to get you stared:
Machine Learning for Medical Imaging https://pubs.rsna.org/doi/10.1148/rg.2017160130Deep Learning: A Primer for Radiologists https://pubs.rsna.org/doi/10.1148/rg.2017170077
For a deeper dive, here are two entire journal issues devoted to the subject:
JACR March 2018 Volume 15 Number 3PB Special Issue Data Science: Big Data, Machine Learning and Artificial Intelligence
JDI June 2018 Volume 31 Number 3 Special Focus Issue on Open Source Software
If you are still awake at this point, here are some useful GitHub refences:
https://github.com/ImagingInformatics/machine-learning
https://github.com/slowvak/MachineLearningForMedicalImages
Letβs Get Started!
A really terrific introduction is in the above mentioned Journal of Digital Imaging, June 2018:
Hello World Deep Learning in Medical Imaging JDI (2018) 31: 283β289 Lakhani, Paras, Gray, Daniel L., Pett, Carl R., Nagy, Paul, Shih, George
Instead of creating a prototypical Cat v. Dog classifier, you create a chest v. abdomen x-ray classifier (CXR v. KUB)! This is a great place to start your AI journey.
All of the above is a lot to unpack, but I hope this introduction will help get you started. I am far from an expert, and wrote this initially as a memory aid for myself. The more practitioners that have a basic undestanding of the process, the better.
Best of luck!
|
[
{
"code": null,
"e": 478,
"s": 172,
"text": "Are you interested in getting started with machine learning for radiology? The constellation of new terms can be overwhelming: Deep Learning, TensorFlow, Scikit-Learn, Keras, Pandas, Python and Anaconda. There is a head-spinning amount of new information to get under your belt before you can get started."
},
{
"code": null,
"e": 771,
"s": 478,
"text": "Personally, I want to be able use machine learning (ML) capabilities in some of my iOS apps using Appleβs CoreML framework as well. This means another set of complexities to navigate before you can actually get down to work. Once we have our tools configured properly, the job will be easier."
},
{
"code": null,
"e": 956,
"s": 771,
"text": "The dominant language in machine learning is Python. There is an entire ecosystem that you need to get familiar with before you can start working on the many great tutorials out there."
},
{
"code": null,
"e": 1123,
"s": 956,
"text": "There are a myriad amount of resources online as well as books to help you get started (a job for another post). Letβs see what we need to do to take our first steps."
},
{
"code": null,
"e": 1157,
"s": 1123,
"text": "Photo by Malte Wingen on Unsplash"
},
{
"code": null,
"e": 1249,
"s": 1157,
"text": "βGive me six hours to chop down a tree and I will spend the first four sharpening the axe.β"
},
{
"code": null,
"e": 1294,
"s": 1249,
"text": "- Abraham Lincoln (probably never said this)"
},
{
"code": null,
"e": 1305,
"s": 1294,
"text": "Letβs talk"
},
{
"code": null,
"e": 1461,
"s": 1305,
"text": "The most common development language for ML is Python. If you donβt know Python, many of the resources for ML beginners start off with quick Python intros."
},
{
"code": null,
"e": 1592,
"s": 1461,
"text": "This post is not intended to teach Python, but to demonstrate one developerβs path to getting started with the vast ML tool chain."
},
{
"code": null,
"e": 1695,
"s": 1592,
"text": "The first thing you need to do is download Python and the necessary Python tools for machine learning."
},
{
"code": null,
"e": 1707,
"s": 1695,
"text": "Hello, Unix"
},
{
"code": null,
"e": 1789,
"s": 1707,
"text": "We need to use the command line interface to install and manage our Python tools."
},
{
"code": null,
"e": 1818,
"s": 1789,
"text": "Enough bash to be dangerous:"
},
{
"code": null,
"e": 1927,
"s": 1818,
"text": "In Linux or a Mac, we use the Terminal. You can find the program at Finder>Applications>Utilities>Terminal ."
},
{
"code": null,
"e": 2070,
"s": 1927,
"text": "In Windows, we use the Command Prompt. You click on the Windows icon>Windows System>Command Prompt or click on the Windows icon and type cmd ."
},
{
"code": null,
"e": 2161,
"s": 2070,
"text": "Before the cursor you see a string of text which refers to:machinename:directory username$"
},
{
"code": null,
"e": 2193,
"s": 2161,
"text": "You type after the dollar sign."
},
{
"code": null,
"e": 2224,
"s": 2193,
"text": "Here are some common commands:"
},
{
"code": null,
"e": 2460,
"s": 2224,
"text": "List files in current directory: lsShow hidden files as well: ls -aNavigate to a new directory: cd <directory_path>To go to home directory: cd ~ or just type: cd Go navigate up one level: cd ..To go to the last folder you were in: cd -"
},
{
"code": null,
"e": 2503,
"s": 2460,
"text": "To show the current working directory: pwd"
},
{
"code": null,
"e": 2620,
"s": 2503,
"text": "The Up Arrow retypes the last command. You can travel back to previous commands by pressing the Up Arrow over again."
},
{
"code": null,
"e": 2644,
"s": 2620,
"text": "Clear the window: clear"
},
{
"code": null,
"e": 2694,
"s": 2644,
"text": "Open a file in a text editor, ex: atom <filename>"
},
{
"code": null,
"e": 2737,
"s": 2694,
"text": "To cancel an application (ex. ping) Ctrl-C"
},
{
"code": null,
"e": 2744,
"s": 2737,
"text": "Python"
},
{
"code": null,
"e": 2895,
"s": 2744,
"text": "Python is an interpreted language, so it is read line by line, rather than a compiled language, where you have to bake the cake before you can use it."
},
{
"code": null,
"e": 3295,
"s": 2895,
"text": "There are two separate versions of Python currently available, Python 2.7 and Python 3. Python 2.7 will be reaching end of life January 1, 2020, and Python 3.x is not backwards-compatible. So why would you want to use an older version? Unfortunately some of the frameworks only support 2.7, and many tutorials in books and online were written specifically for that version. How do we deal with this?"
},
{
"code": null,
"e": 3608,
"s": 3295,
"text": "Fortunately you can have both flavors of Python on your computer, and run different virtual environments in different folders on your hard drive, so you can do most of your ML work in, say Python 3.7, and have version 2.7 in different folders if you have a project that requires a library that only works on 2.7."
},
{
"code": null,
"e": 3829,
"s": 3608,
"text": "There are several ways to manage the different Python virtual environments using virtualenv, Python Environment Wrapper (pew), venv, pyvenv. The easiest is to use Conda, which installed with Python when you use Anaconda."
},
{
"code": null,
"e": 3838,
"s": 3829,
"text": "Anaconda"
},
{
"code": null,
"e": 4185,
"s": 3838,
"text": "Anaconda is an open-source platform that is perhaps the easiest way to get started with Python machine learning on Linux, Mac OS X and Windows. It helps you manage the programing environments, and includes common Python packages used in data science. You can download the distribution for your platform at https://www.anaconda.com/distribution/ ."
},
{
"code": null,
"e": 4296,
"s": 4185,
"text": "Once you install the appropriate version of Python for your system, you will want to set up some environments."
},
{
"code": null,
"e": 4302,
"s": 4296,
"text": "Conda"
},
{
"code": null,
"e": 4534,
"s": 4302,
"text": "Conda is the Python package manager and environment management system used by Anaconda. Conda installs most, but not all of the packages you need. The rest can be installed through the command line using pipβ more about that later."
},
{
"code": null,
"e": 4583,
"s": 4534,
"text": "To see the packages in your current environment:"
},
{
"code": null,
"e": 4598,
"s": 4583,
"text": "conda list env"
},
{
"code": null,
"e": 4638,
"s": 4598,
"text": "Which version of Conda you are running:"
},
{
"code": null,
"e": 4653,
"s": 4638,
"text": "conda -version"
},
{
"code": null,
"e": 4722,
"s": 4653,
"text": "(if below 4.1.0 β then you can update Conda with conda update conda)"
},
{
"code": null,
"e": 4861,
"s": 4722,
"text": "You can create an environment with the Anaconda Navigator by choosing Environments from the left menu and then clicking the Create button."
},
{
"code": null,
"e": 4993,
"s": 4861,
"text": "You can also create the environment from the command line. For example here we create an environment named βpy27β using Python 2.7:"
},
{
"code": null,
"e": 5025,
"s": 4993,
"text": "conda create -n py27 python=2.7"
},
{
"code": null,
"e": 5053,
"s": 5025,
"text": "To activate an environment:"
},
{
"code": null,
"e": 5084,
"s": 5053,
"text": "conda activate <your_env_name>"
},
{
"code": null,
"e": 5123,
"s": 5084,
"text": "To deactivate the current environment:"
},
{
"code": null,
"e": 5140,
"s": 5123,
"text": "conda deactivate"
},
{
"code": null,
"e": 5166,
"s": 5140,
"text": "To remove an environment:"
},
{
"code": null,
"e": 5206,
"s": 5166,
"text": "conda remove -name <your_env_name> -all"
},
{
"code": null,
"e": 5246,
"s": 5206,
"text": "To list all of your Conda environments:"
},
{
"code": null,
"e": 5264,
"s": 5246,
"text": "conda info --envs"
},
{
"code": null,
"e": 5333,
"s": 5264,
"text": "The environment with the asterisk is the current active environment."
},
{
"code": null,
"e": 5382,
"s": 5333,
"text": "To see the packages in your current environment:"
},
{
"code": null,
"e": 5397,
"s": 5382,
"text": "conda list env"
},
{
"code": null,
"e": 5437,
"s": 5397,
"text": "Which version of Conda you are running:"
},
{
"code": null,
"e": 5452,
"s": 5437,
"text": "conda -version"
},
{
"code": null,
"e": 5521,
"s": 5452,
"text": "(if below 4.1.0 β then you can update Conda with conda update conda)"
},
{
"code": null,
"e": 5693,
"s": 5521,
"text": "Two of the major machine learning packages TensorFlow and Keras should be installed using pip. For Appleβs machine learning frameworks, you would also install Turi Create."
},
{
"code": null,
"e": 5714,
"s": 5693,
"text": "The Scientific Stack"
},
{
"code": null,
"e": 5844,
"s": 5714,
"text": "There is a set of Python packages referred to as the scientific stack that are useful across multiple disciplines. These include:"
},
{
"code": null,
"e": 6600,
"s": 5844,
"text": "NumPy http://www.numpy.org/ β library for efficient handling of arrays and matricesSciPy https://www.scipy.org/ β collection of packages with math and science capabilitiesmatplatlib https://matplotlib.org/ β the standard 2D plotting library in Pythonpandas https://pandas.pydata.org/ β library of matrix-like data structures, labeled indices, time functions, etc.Scikit-learn https://scikit-learn.org/stable/ β library of machine learning algorithmsJupyter https://jupyter.org/ β an interactive Python shell in a web-based notebookSeaborn https://seaborn.pydata.org/index.html β statistical data visualizationsBokeh https://bokeh.pydata.org/en/latest/ β interactive data visualizationsPyTables https://www.pytables.org/ β a Python wrapper for HDF5 library"
},
{
"code": null,
"e": 6737,
"s": 6600,
"text": "You can install these packages and their dependencies using Anaconda. In your newly created environment search for the package you want."
},
{
"code": null,
"e": 6812,
"s": 6737,
"text": "Then you select them from the list by checking the box and clicking apply."
},
{
"code": null,
"e": 6918,
"s": 6812,
"text": "As I mentioned earlier, you use pip to install TensorFlow and Keras (and Turi Create for Appleβs CoreML)."
},
{
"code": null,
"e": 6922,
"s": 6918,
"text": "pip"
},
{
"code": null,
"e": 6993,
"s": 6922,
"text": "pip is pythonβs standard package manager https://pypi.org/project/pip/"
},
{
"code": null,
"e": 7019,
"s": 6993,
"text": "pip install β upgrade pip"
},
{
"code": null,
"e": 7050,
"s": 7019,
"text": "To install a package with pip:"
},
{
"code": null,
"e": 7077,
"s": 7050,
"text": "pip install <package_name>"
},
{
"code": null,
"e": 7098,
"s": 7077,
"text": "Editing Python Files"
},
{
"code": null,
"e": 7376,
"s": 7098,
"text": "You interact with python in Terminal on a Mac or Console in Windows. To write your code, most people use a code editor such as Atom https://atom.io/ or Sublime Text https://www.sublimetext.com/ . There are whole religious wars over code editors, but life is too short for that."
},
{
"code": null,
"e": 7568,
"s": 7376,
"text": "My favorite (and free) text editor is Atom https://atom.io/ , from the GitHub folks. A cool feature of Atom is that you can extend the app with features such as an integrated Terminal window."
},
{
"code": null,
"e": 7688,
"s": 7568,
"text": "Once installed, you can add this feature by going to Settings / Install Packages and search for platformio-ide-terminal"
},
{
"code": null,
"e": 7709,
"s": 7688,
"text": "Running Python Files"
},
{
"code": null,
"e": 7766,
"s": 7709,
"text": "At the command prompt ($ or >) type python <filename.py>"
},
{
"code": null,
"e": 7821,
"s": 7766,
"text": "To exit python use exit()or Ctrl-D (Ctrl-Z in Windows)"
},
{
"code": null,
"e": 7880,
"s": 7821,
"text": "To see which python version you are currently using, type:"
},
{
"code": null,
"e": 7910,
"s": 7880,
"text": "python --version or python -V"
},
{
"code": null,
"e": 7979,
"s": 7910,
"text": "To see where the Python installation you are using is located, type:"
},
{
"code": null,
"e": 7992,
"s": 7979,
"text": "which python"
},
{
"code": null,
"e": 8010,
"s": 7992,
"text": "Environment Files"
},
{
"code": null,
"e": 8263,
"s": 8010,
"text": "An environment file is a file in your projectβs root directory that lists all the included packages and their version numbers specific to your projectβs environment. This allows you to share projects with others, and for you to reuse in other projects."
},
{
"code": null,
"e": 8290,
"s": 8263,
"text": "You create the file using:"
},
{
"code": null,
"e": 8330,
"s": 8290,
"text": "conda env export -file environment.yaml"
},
{
"code": null,
"e": 8389,
"s": 8330,
"text": "You recreate the Conda environment and its packages using:"
},
{
"code": null,
"e": 8441,
"s": 8389,
"text": "conda env create -n <conda-env> -f environment.yaml"
},
{
"code": null,
"e": 8596,
"s": 8441,
"text": "In some projects or tutorials you will see requirements.txt which is utilized by pip as the package manager instead of the environment.yaml used by Conda."
},
{
"code": null,
"e": 8643,
"s": 8596,
"text": "These are created by freezing the environment:"
},
{
"code": null,
"e": 8673,
"s": 8643,
"text": "pip freeze > requirements.txt"
},
{
"code": null,
"e": 8694,
"s": 8673,
"text": "To reconstitue, use:"
},
{
"code": null,
"e": 8726,
"s": 8694,
"text": "pip install -r requirements.txt"
},
{
"code": null,
"e": 8744,
"s": 8726,
"text": "Jupyter Notebooks"
},
{
"code": null,
"e": 9125,
"s": 8744,
"text": "Jupyter Notebook https://jupyter.org/ is an open-source web browser based application. This allows you to run your python code directly in a more user friendly environemnt and see the results step by step. It is great for teaching, as you can add text and images in between your code cells in markup cells. The application is extensible, so you can add many other useful features."
},
{
"code": null,
"e": 9192,
"s": 9125,
"text": "You also can install Jupyter Notebook with the Anaconda Navigator:"
},
{
"code": null,
"e": 9279,
"s": 9192,
"text": "Type the following at the prompt to create a new Jupyter Notebook app in your browser:"
},
{
"code": null,
"e": 9296,
"s": 9279,
"text": "jupyter notebook"
},
{
"code": null,
"e": 9327,
"s": 9296,
"text": "To launch a specific notebook:"
},
{
"code": null,
"e": 9360,
"s": 9327,
"text": "jupyter notebook <notebook-name>"
},
{
"code": null,
"e": 9464,
"s": 9360,
"text": "By the way, it is not recommended to run multiple instances of the Jupyter Notebook App simultaneously."
},
{
"code": null,
"e": 9608,
"s": 9464,
"text": "To run a cell, click on the Run button in the Jupyter toolbar or type Shift + Enter.To shut down a notebook, close the Terminal window or type:"
},
{
"code": null,
"e": 9630,
"s": 9608,
"text": "jupyter notebook stop"
},
{
"code": null,
"e": 9646,
"s": 9630,
"text": "or press Ctrl+C"
},
{
"code": null,
"e": 9663,
"s": 9646,
"text": "OK, so now what?"
},
{
"code": null,
"e": 9751,
"s": 9663,
"text": "Now that our axe is sharpened, how can you get started on actual radiology informatics."
},
{
"code": null,
"e": 9791,
"s": 9751,
"text": "Here are a few links to get you stared:"
},
{
"code": null,
"e": 9964,
"s": 9791,
"text": "Machine Learning for Medical Imaging https://pubs.rsna.org/doi/10.1148/rg.2017160130Deep Learning: A Primer for Radiologists https://pubs.rsna.org/doi/10.1148/rg.2017170077"
},
{
"code": null,
"e": 10042,
"s": 9964,
"text": "For a deeper dive, here are two entire journal issues devoted to the subject:"
},
{
"code": null,
"e": 10162,
"s": 10042,
"text": "JACR March 2018 Volume 15 Number 3PB Special Issue Data Science: Big Data, Machine Learning and Artificial Intelligence"
},
{
"code": null,
"e": 10239,
"s": 10162,
"text": "JDI June 2018 Volume 31 Number 3 Special Focus Issue on Open Source Software"
},
{
"code": null,
"e": 10315,
"s": 10239,
"text": "If you are still awake at this point, here are some useful GitHub refences:"
},
{
"code": null,
"e": 10370,
"s": 10315,
"text": "https://github.com/ImagingInformatics/machine-learning"
},
{
"code": null,
"e": 10429,
"s": 10370,
"text": "https://github.com/slowvak/MachineLearningForMedicalImages"
},
{
"code": null,
"e": 10448,
"s": 10429,
"text": "Letβs Get Started!"
},
{
"code": null,
"e": 10544,
"s": 10448,
"text": "A really terrific introduction is in the above mentioned Journal of Digital Imaging, June 2018:"
},
{
"code": null,
"e": 10685,
"s": 10544,
"text": "Hello World Deep Learning in Medical Imaging JDI (2018) 31: 283β289 Lakhani, Paras, Gray, Daniel L., Pett, Carl R., Nagy, Paul, Shih, George"
},
{
"code": null,
"e": 10852,
"s": 10685,
"text": "Instead of creating a prototypical Cat v. Dog classifier, you create a chest v. abdomen x-ray classifier (CXR v. KUB)! This is a great place to start your AI journey."
},
{
"code": null,
"e": 11105,
"s": 10852,
"text": "All of the above is a lot to unpack, but I hope this introduction will help get you started. I am far from an expert, and wrote this initially as a memory aid for myself. The more practitioners that have a basic undestanding of the process, the better."
}
] |
JSON | modify an array value of a JSON object - GeeksforGeeks
|
06 Jun, 2018
The arrays in JSON (JavaScript Object Notation) are similar to arrays in Javascript. Arrays in JSON can have values of following types:
null
boolean
number
string
array
object
The arrays in JavaScript can have all these but it can also have other valid JavaScript expressions which are not allowed in JSON.
Array value of a JSON object can be modified. It can be simply done by modifying the value present at a given index.
Example: Modifying the value present at an index in array
<!DOCTYPE html><html><body><p id = "GFG">< /p> <script> var myObj, i, x = "";myObj = { // stored the values "words":[ "I", "am", "Good" ]}; // modifying the value present at index 2myObj.words[2] = "bad"; for (i in myObj.words) { // Displaying the modified content x += myObj.words[i] + "<br>"; } document.getElementById("GFG").innerHTML = x; </script></body></html>
Output :
I
am
bad
Note: If value is modified at an index which is out of the array size, then the new modification will not replace anything in the original information but rather will be an add-on.
Example: Modifying the value of index which is out of the array size.
<!DOCTYPE html><html><body><p id = "GFG"></p> <script> var myObj, i, x = "";myObj = { // stored values "words":[ "I", "am", "Good" ] }; // trying to change a value at// an index out of array sizemyObj.words[3] = "bad"; for (i in myObj.words) { // display the modification x += myObj.words[i] + "<br>";} document.getElementById("GFG").innerHTML = x; </script></body></html>
Output :
I
am
Good
bad
javascript-array
JSON
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Difference Between PUT and PATCH Request
JavaScript | console.log() with Examples
How to read a local text file using JavaScript?
Node.js | fs.writeFileSync() Method
|
[
{
"code": null,
"e": 26469,
"s": 26441,
"text": "\n06 Jun, 2018"
},
{
"code": null,
"e": 26605,
"s": 26469,
"text": "The arrays in JSON (JavaScript Object Notation) are similar to arrays in Javascript. Arrays in JSON can have values of following types:"
},
{
"code": null,
"e": 26610,
"s": 26605,
"text": "null"
},
{
"code": null,
"e": 26618,
"s": 26610,
"text": "boolean"
},
{
"code": null,
"e": 26625,
"s": 26618,
"text": "number"
},
{
"code": null,
"e": 26632,
"s": 26625,
"text": "string"
},
{
"code": null,
"e": 26638,
"s": 26632,
"text": "array"
},
{
"code": null,
"e": 26645,
"s": 26638,
"text": "object"
},
{
"code": null,
"e": 26776,
"s": 26645,
"text": "The arrays in JavaScript can have all these but it can also have other valid JavaScript expressions which are not allowed in JSON."
},
{
"code": null,
"e": 26893,
"s": 26776,
"text": "Array value of a JSON object can be modified. It can be simply done by modifying the value present at a given index."
},
{
"code": null,
"e": 26951,
"s": 26893,
"text": "Example: Modifying the value present at an index in array"
},
{
"code": "<!DOCTYPE html><html><body><p id = \"GFG\">< /p> <script> var myObj, i, x = \"\";myObj = { // stored the values \"words\":[ \"I\", \"am\", \"Good\" ]}; // modifying the value present at index 2myObj.words[2] = \"bad\"; for (i in myObj.words) { // Displaying the modified content x += myObj.words[i] + \"<br>\"; } document.getElementById(\"GFG\").innerHTML = x; </script></body></html> ",
"e": 27365,
"s": 26951,
"text": null
},
{
"code": null,
"e": 27374,
"s": 27365,
"text": "Output :"
},
{
"code": null,
"e": 27384,
"s": 27374,
"text": "I\nam\nbad\n"
},
{
"code": null,
"e": 27565,
"s": 27384,
"text": "Note: If value is modified at an index which is out of the array size, then the new modification will not replace anything in the original information but rather will be an add-on."
},
{
"code": null,
"e": 27635,
"s": 27565,
"text": "Example: Modifying the value of index which is out of the array size."
},
{
"code": "<!DOCTYPE html><html><body><p id = \"GFG\"></p> <script> var myObj, i, x = \"\";myObj = { // stored values \"words\":[ \"I\", \"am\", \"Good\" ] }; // trying to change a value at// an index out of array sizemyObj.words[3] = \"bad\"; for (i in myObj.words) { // display the modification x += myObj.words[i] + \"<br>\";} document.getElementById(\"GFG\").innerHTML = x; </script></body></html> ",
"e": 28056,
"s": 27635,
"text": null
},
{
"code": null,
"e": 28065,
"s": 28056,
"text": "Output :"
},
{
"code": null,
"e": 28080,
"s": 28065,
"text": "I\nam\nGood\nbad\n"
},
{
"code": null,
"e": 28097,
"s": 28080,
"text": "javascript-array"
},
{
"code": null,
"e": 28102,
"s": 28097,
"text": "JSON"
},
{
"code": null,
"e": 28113,
"s": 28102,
"text": "JavaScript"
},
{
"code": null,
"e": 28211,
"s": 28113,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28251,
"s": 28211,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28296,
"s": 28251,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28357,
"s": 28296,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28429,
"s": 28357,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28481,
"s": 28429,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 28527,
"s": 28481,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 28568,
"s": 28527,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28609,
"s": 28568,
"text": "JavaScript | console.log() with Examples"
},
{
"code": null,
"e": 28657,
"s": 28609,
"text": "How to read a local text file using JavaScript?"
}
] |
Backing up a Docker Container - GeeksforGeeks
|
28 Oct, 2020
If you are a Docker Developer, you would surely know how important it is to backup your Docker Container file system. If you are working on an important Docker Application, it becomes very necessary to backup all the files and folders related to it so that in case anything goes wrong, you can get back all those files. It also helps you in managing different versions of your project and also sharing the files and folders of your project among your team members.
In this article, we are going to see how can we back up a Docker Container by saving it as a tar file in your local system. We will also see how you can push that Docker Image Backup directly into your Docker Hub accounts for ease of sharing. Follow the below steps to backup a docker container:
For our example, we are going to create an Ubuntu Container with a single file inside it.
sudo docker run -it ubuntu bash
After you fire up the bash, use the below command to create a file.
echo "geeksforgeeks" > geeksforgeeks.txt
ls
Creating a Container and File
You will need the Container ID in order to create the backup.
sudo docker container ls
Note that if the container is not running, you can start the Container using the below command.
sudo docker start <container-id>
Copying Container ID
To create a snapshot, you need to commit the Container.
sudo docker commit -p 6cb599fe30ea my-backup
Committing the Container
You can use this command, to save the backup as a Tar File in your local machine.
sudo docker save -o ~/my-backup.tar my-backup
Saving Backup
You will find the backup Tar file in your Home Directory.
Tar File
In order to push it back to the Docker Hub, you need to have an account on Docker Hub.
Login using your command line and push the Tar File.
sudo docker login
sudo docker push my-backup:latest
Pushing Image
To conclude, in this article we saw how to create a backup of a Docker Image into a Tar File and pushing it into a Docker Hub account for ease of sharing.
Docker Container
linux
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Copying Files to and from Docker Containers
Markov Decision Process
Q-Learning in Python
Fuzzy Logic | Introduction
An introduction to Machine Learning
Basics of API Testing Using Postman
Principal Component Analysis with Python
ML | What is Machine Learning ?
OpenCV - Overview
Deep Learning | Introduction to Long Short Term Memory
|
[
{
"code": null,
"e": 25417,
"s": 25389,
"text": "\n28 Oct, 2020"
},
{
"code": null,
"e": 25882,
"s": 25417,
"text": "If you are a Docker Developer, you would surely know how important it is to backup your Docker Container file system. If you are working on an important Docker Application, it becomes very necessary to backup all the files and folders related to it so that in case anything goes wrong, you can get back all those files. It also helps you in managing different versions of your project and also sharing the files and folders of your project among your team members."
},
{
"code": null,
"e": 26178,
"s": 25882,
"text": "In this article, we are going to see how can we back up a Docker Container by saving it as a tar file in your local system. We will also see how you can push that Docker Image Backup directly into your Docker Hub accounts for ease of sharing. Follow the below steps to backup a docker container:"
},
{
"code": null,
"e": 26268,
"s": 26178,
"text": "For our example, we are going to create an Ubuntu Container with a single file inside it."
},
{
"code": null,
"e": 26301,
"s": 26268,
"text": "sudo docker run -it ubuntu bash\n"
},
{
"code": null,
"e": 26369,
"s": 26301,
"text": "After you fire up the bash, use the below command to create a file."
},
{
"code": null,
"e": 26414,
"s": 26369,
"text": "echo \"geeksforgeeks\" > geeksforgeeks.txt\nls\n"
},
{
"code": null,
"e": 26444,
"s": 26414,
"text": "Creating a Container and File"
},
{
"code": null,
"e": 26506,
"s": 26444,
"text": "You will need the Container ID in order to create the backup."
},
{
"code": null,
"e": 26532,
"s": 26506,
"text": "sudo docker container ls\n"
},
{
"code": null,
"e": 26628,
"s": 26532,
"text": "Note that if the container is not running, you can start the Container using the below command."
},
{
"code": null,
"e": 26662,
"s": 26628,
"text": "sudo docker start <container-id>\n"
},
{
"code": null,
"e": 26683,
"s": 26662,
"text": "Copying Container ID"
},
{
"code": null,
"e": 26739,
"s": 26683,
"text": "To create a snapshot, you need to commit the Container."
},
{
"code": null,
"e": 26785,
"s": 26739,
"text": "sudo docker commit -p 6cb599fe30ea my-backup\n"
},
{
"code": null,
"e": 26810,
"s": 26785,
"text": "Committing the Container"
},
{
"code": null,
"e": 26892,
"s": 26810,
"text": "You can use this command, to save the backup as a Tar File in your local machine."
},
{
"code": null,
"e": 26939,
"s": 26892,
"text": "sudo docker save -o ~/my-backup.tar my-backup\n"
},
{
"code": null,
"e": 26953,
"s": 26939,
"text": "Saving Backup"
},
{
"code": null,
"e": 27011,
"s": 26953,
"text": "You will find the backup Tar file in your Home Directory."
},
{
"code": null,
"e": 27020,
"s": 27011,
"text": "Tar File"
},
{
"code": null,
"e": 27107,
"s": 27020,
"text": "In order to push it back to the Docker Hub, you need to have an account on Docker Hub."
},
{
"code": null,
"e": 27160,
"s": 27107,
"text": "Login using your command line and push the Tar File."
},
{
"code": null,
"e": 27213,
"s": 27160,
"text": "sudo docker login\nsudo docker push my-backup:latest\n"
},
{
"code": null,
"e": 27227,
"s": 27213,
"text": "Pushing Image"
},
{
"code": null,
"e": 27382,
"s": 27227,
"text": "To conclude, in this article we saw how to create a backup of a Docker Image into a Tar File and pushing it into a Docker Hub account for ease of sharing."
},
{
"code": null,
"e": 27399,
"s": 27382,
"text": "Docker Container"
},
{
"code": null,
"e": 27405,
"s": 27399,
"text": "linux"
},
{
"code": null,
"e": 27431,
"s": 27405,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 27529,
"s": 27431,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27573,
"s": 27529,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 27597,
"s": 27573,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 27618,
"s": 27597,
"text": "Q-Learning in Python"
},
{
"code": null,
"e": 27645,
"s": 27618,
"text": "Fuzzy Logic | Introduction"
},
{
"code": null,
"e": 27681,
"s": 27645,
"text": "An introduction to Machine Learning"
},
{
"code": null,
"e": 27717,
"s": 27681,
"text": "Basics of API Testing Using Postman"
},
{
"code": null,
"e": 27758,
"s": 27717,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 27790,
"s": 27758,
"text": "ML | What is Machine Learning ?"
},
{
"code": null,
"e": 27808,
"s": 27790,
"text": "OpenCV - Overview"
}
] |
Bootstrap Buttons with Examples - GeeksforGeeks
|
28 Apr, 2022
Bootstrap provides us with different classes that can be used with different tags, such as <button>, <a>, <input>, and <label> to apply custom button styles. Bootstrap also provides classes that can be used for changing the state and size of buttons, also, it provides classes for applying toggle, checkbox, and radio buttons like effects.
Solid Buttons: Bootstrap provides us with a series of classes that corresponds to different solid button styles. These classes are listed below:
Note: We must use an additional btn class with the classes mentioned above and that follows.
Example:
HTML
<!DOCTYPE html><html lang="en"><head> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Hello, world!</title> <!-- Custom CSS --> <style> h1 { color: green; text-align: center; } div.one { margin-top: 40px; text-align: center; } button { margin-top: 10px; } </style></head><body> <div class="container"> <h1>GeeksForGeeks</h1> <!-- Bootstrap Button Classes --> <div class="one"> <button type="button" class="btn btn-primary"> Primary</button> <button type="button" class="btn btn-secondary"> Secondary</button> <button type="button" class="btn btn-success"> Success</button> <button type="button" class="btn btn-danger"> Danger</button> <button type="button" class="btn btn-warning"> Warning</button> <button type="button" class="btn btn-info"> Info</button> <button type="button" class="btn btn-light"> Light</button> <button type="button" class="btn btn-dark"> Dark</button> <button type="button" class="btn btn-link"> Link</button> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script></body></html>
Output:
Outlined Buttons:Bootstrap provides us with a series of classes that can be used when we need to use outline-styled buttons in our project, that is buttons without background color. The outline button classes remove any background color or background image style applied to the button(s). These classes are listed below:
Example:
HTML
<!DOCTYPE html><html><head> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Hello, world!</title> <!-- Custom CSS --> <style> h1 { color: green; text-align: center; } div.one { margin-top: 40px; text-align: center; } button { margin-top: 10px; } </style></head><body> <div class="container"> <h1>GeeksForGeeks</h1> <!-- Bootstrap Button Classes --> <div class="one"> <button type="button" class="btn btn-outline-primary"> Primary</button> <button type="button" class="btn btn-outline-secondary"> Secondary</button> <button type="button" class="btn btn-outline-success"> Success</button> <button type="button" class="btn btn-outline-danger"> Danger</button> <button type="button" class="btn btn-outline-warning"> Warning</button> <button type="button" class="btn btn-outline-info"> Info</button> <button type="button" class="btn btn-outline-light"> Light</button> <button type="button" class="btn btn-outline-dark"> Dark</button> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script></body></html>
Output:
Changing Size:Bootstrap provides us with different classes that allow changing the size of the button. These classes are listed below:
btn-lg: This class is used to make a button(s) large in size.
Example:
HTML
<!DOCTYPE html><html><head> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Hello, world!</title> <!-- Custom CSS --> <style> h1 { color: green; text-align: center; } div.one { margin-top: 40px; text-align: center; } button { margin-top: 10px; } </style></head><body> <div class="container"> <h1>GeeksForGeeks</h1> <!-- Bootstrap Button Classes --> <div class="one"> <button type="button" class="btn btn-primary btn-lg"> Primary</button> <button type="button" class="btn btn-outline-secondary btn-lg"> Secondary</button> <button type="button" class="btn btn-success btn-lg"> Success</button> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script></body></html>
Output:
btn-sm: This class is used to make a button(s) small in size.
Example:
HTML
<!DOCTYPE html><html><head> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Hello, world!</title> <!-- Custom CSS --> <style> h1 { color: green; text-align: center; } div.one { margin-top: 40px; text-align: center; } button { margin-top: 10px; } </style></head><body> <div class="container"> <h1>GeeksForGeeks</h1> <!-- Bootstrap Button Classes --> <div class="one"> <button type="button" class="btn btn-primary btn-sm"> Primary</button> <button type="button" class="btn btn-outline-secondary btn-sm"> Secondary</button> <button type="button" class="btn btn-success btn-sm"> Success</button> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script></body></html>
Output:
btn-block: This class is used to make the button(s) occupy the entire width of their parent element.
Example:
HTML
<!DOCTYPE html><html><head> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Hello, world!</title> <!-- Custom CSS --> <style> h1 { color: green; text-align: center; } div.one { margin-top: 40px; text-align: center; } button { margin-top: 10px; } </style></head><body> <div class="container"> <h1>GeeksForGeeks</h1> <!-- Bootstrap Button Classes --> <div class="one"> <button type="button" class="btn btn-primary btn-block"> Primary</button> <button type="button" class="btn btn-outline-secondary btn-block"> Secondary</button> <button type="button" class="btn btn-success btn-block"> Success</button> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script></body></html>
Output:
Changing State:Bootstrap provides us with βactiveβ and βdisabledβ classes to change the state of the button.
active: This class is used to make buttons and links appear inactive state, i.e., with a dark background, dark border, and an inset shadow.
Example:
HTML
<!DOCTYPE html><html><head> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Hello, world!</title> <!-- Custom CSS --> <style> h1 { color: green; text-align: center; } div.one { margin-top: 40px; text-align: center; } a, button { margin-top: 10px; } </style></head><body> <div class="container"> <h1>GeeksForGeeks</h1> <!-- Bootstrap Button Classes --> <div class="one"> <button type="button" class="btn btn-primary active"> Primary Button</button> <a href="#" class="btn btn-warning active" role="button" aria-pressed="true"> Warning Link</a> <button type="button" class="btn btn-success active"> Success Button</button> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script></body></html>
Note: When <a> tag is used we should insert role=βbuttonβ attribute-value pair within the tag, and if the button is active, than, we use aria-pressed=βtrueβ attribute-value pair within the <a> tag and set class value to active (class=βactiveβ).
Output:
disabled: This class is used to make buttons and links appear in a disabled state, i.e., with lighter background color and outset appearance.
Example:
HTML
<!DOCTYPE html><html><head> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Hello, world!</title> <!-- Custom CSS --> <style> h1 { color: green; text-align: center; } div.one { margin-top: 40px; text-align: center; } a, button { margin-top: 10px; } </style></head><body> <div class="container"> <h1>GeeksForGeeks</h1> <!-- Bootstrap Button Classes --> <div class="one"> <button type="button" class="btn btn-primary disabled"> Primary Button</button> <a href="#" class="btn btn-warning disabled" role="button" aria-disabled="true" tabindex="-1"> Warning Link</a> <button type="button" class="btn btn-success disabled"> Success Button</button> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script></body></html>
Note: When <a> is used tag we should insert role=βbuttonβ attribute-value pair within the tag. When using βdisabledβ class with <a> tag we should insert aria-disabled=βtrueβ and tabindex=β-1β²β² attribute-value pair with in the <a> tag. Also, we can make <button> disable by just adding βdisabledβ attribute within the <button> tag, without using βdisabledβ class of Bootstrap.
Output:
Toggle State:We can make the button to toggle its state by adding data-toggle=βbuttonβ attribute-value pair to <button> tag. We can also preset the toggle state of the button to active by adding the βactiveβ class and aria-pressed=βtrueβ attribute-value pair to the <button> tag.
Example:
HTML
<!DOCTYPE html><html><head> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Hello, world!</title> <!-- Custom CSS --> <style> h1 { color: green; text-align: center; } div.one { margin-top: 40px; text-align: center; } a, button { margin-top: 10px; } </style></head><body> <div class="container"> <h1>GeeksForGeeks</h1> <!-- Bootstrap Button Classes --> <div class="one"> <button type="button" data-toggle="button" class="btn btn-primary" aria-pressed="false"> Primary Button</button> <button type="button" data-toggle="button" class="btn btn-success" aria-pressed="false"> Success Button</button> <button type="button" data-toggle="button" class="btn btn-primary active" aria-pressed="true"> Primary Button</button> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script></body></html>
Note: The third button is preset to active.
Output:
Check Box Styled Buttons:To get a check box styled buttons, we need to use <input> tag with type=βcheckboxβ attribute-value pair, which is surrounded by <label> tag with class value set to βbtnβ and one of the class from the solid or the outline button class mentioned above. The <label> tag in turn is surrounded by <div> tag with class value set to βbtn-group-toggleβ (class=βbtn-group-toggleβ) and data-toggle=βbuttonsβ attribute-pair is also required within the <div> tag. Following example will clear the procedure:
Example:
HTML
<!DOCTYPE html><html><head> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Hello, world!</title> <!-- Custom CSS --> <style> h1 { color: green; text-align: center; } div.one { margin-top: 40px; text-align: center; } a, button { margin-top: 10px; } </style></head><body> <div class="container"> <h1>GeeksForGeeks</h1> <!-- Bootstrap Button Classes --> <div class="one"> <div class="btn-group-toggle" data-toggle="buttons"> <label class="btn btn-primary"> <input type="checkbox" autocomplete="off"> Unchecked</label> <label class="btn btn-primary active"> <input type="checkbox" checked autocomplete="off"> Checked</label> <label class="btn btn-primary"> <input type="checkbox" autocomplete="off"> Unchecked</label> </div> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script></body></html>
Note: To make the button checked by default, we need to add the βactiveβ class within the <label> tag of the input control and also put the βcheckedβ attribute within the <input> tag.Output:
Radio Styled Buttons:To get a radio styled buttons, we need to use <input> tag with type=βradioβ attribute-value pair and other essential attribute-value combination for the working of radio button, as usual. The <input> tag is in turn surrounded by <label> tag with class value set to βbtnβ and one of the class from the solid or the outline button classes as mentioned above. The <label> tag in turn is surrounded by <div> tag with class value set to βbtn-group btn-group-toggleβ (class=βbtn-group btn-group-toggleβ) and data-toggle=βbuttonsβ attribute-pair is also required within the <div> tag. Following example will clear the procedure:
Example:
HTML
<!DOCTYPE html><html><head> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Hello, world!</title> <!-- Custom CSS --> <style> h1 { color: green; text-align: center; } div.one { margin-top: 40px; text-align: center; } a, button { margin-top: 10px; } </style></head><body> <div class="container"> <h1>GeeksForGeeks</h1> <!-- Bootstrap Button Classes --> <div class="one"> <div class="btn-group btn-group-toggle" data-toggle="buttons"> <label class="btn btn-primary"> <input type="radio" name="options" id="option1" autocomplete="off"> Radio Button</label> <label class="btn btn-primary active"> <input type="radio" name="options" id="option2" autocomplete="off" checked> Active Radio Button</label> <label class="btn btn-primary"> <input type="radio" name="options" id="option3" autocomplete="off"> Radio Button</label> </div> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script></body></html>
Note: To make the button checked by default, we need to add the βactiveβ class within the <label> tag of the input control and also put the βcheckedβ attribute within the <input> tag.
Output:
Supported Browser:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
ysachin2314
sahilintern
Bootstrap
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to change navigation bar color in Bootstrap ?
Form validation using jQuery
How to pass data into a bootstrap modal?
How to align navbar items to the right in Bootstrap 4 ?
How to Show Images on Click using HTML ?
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": 29685,
"s": 29657,
"text": "\n28 Apr, 2022"
},
{
"code": null,
"e": 30025,
"s": 29685,
"text": "Bootstrap provides us with different classes that can be used with different tags, such as <button>, <a>, <input>, and <label> to apply custom button styles. Bootstrap also provides classes that can be used for changing the state and size of buttons, also, it provides classes for applying toggle, checkbox, and radio buttons like effects."
},
{
"code": null,
"e": 30170,
"s": 30025,
"text": "Solid Buttons: Bootstrap provides us with a series of classes that corresponds to different solid button styles. These classes are listed below:"
},
{
"code": null,
"e": 30263,
"s": 30170,
"text": "Note: We must use an additional btn class with the classes mentioned above and that follows."
},
{
"code": null,
"e": 30272,
"s": 30263,
"text": "Example:"
},
{
"code": null,
"e": 30277,
"s": 30272,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Hello, world!</title> <!-- Custom CSS --> <style> h1 { color: green; text-align: center; } div.one { margin-top: 40px; text-align: center; } button { margin-top: 10px; } </style></head><body> <div class=\"container\"> <h1>GeeksForGeeks</h1> <!-- Bootstrap Button Classes --> <div class=\"one\"> <button type=\"button\" class=\"btn btn-primary\"> Primary</button> <button type=\"button\" class=\"btn btn-secondary\"> Secondary</button> <button type=\"button\" class=\"btn btn-success\"> Success</button> <button type=\"button\" class=\"btn btn-danger\"> Danger</button> <button type=\"button\" class=\"btn btn-warning\"> Warning</button> <button type=\"button\" class=\"btn btn-info\"> Info</button> <button type=\"button\" class=\"btn btn-light\"> Light</button> <button type=\"button\" class=\"btn btn-dark\"> Dark</button> <button type=\"button\" class=\"btn btn-link\"> Link</button> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script></body></html>",
"e": 32562,
"s": 30277,
"text": null
},
{
"code": null,
"e": 32570,
"s": 32562,
"text": "Output:"
},
{
"code": null,
"e": 32891,
"s": 32570,
"text": "Outlined Buttons:Bootstrap provides us with a series of classes that can be used when we need to use outline-styled buttons in our project, that is buttons without background color. The outline button classes remove any background color or background image style applied to the button(s). These classes are listed below:"
},
{
"code": null,
"e": 32900,
"s": 32891,
"text": "Example:"
},
{
"code": null,
"e": 32905,
"s": 32900,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Hello, world!</title> <!-- Custom CSS --> <style> h1 { color: green; text-align: center; } div.one { margin-top: 40px; text-align: center; } button { margin-top: 10px; } </style></head><body> <div class=\"container\"> <h1>GeeksForGeeks</h1> <!-- Bootstrap Button Classes --> <div class=\"one\"> <button type=\"button\" class=\"btn btn-outline-primary\"> Primary</button> <button type=\"button\" class=\"btn btn-outline-secondary\"> Secondary</button> <button type=\"button\" class=\"btn btn-outline-success\"> Success</button> <button type=\"button\" class=\"btn btn-outline-danger\"> Danger</button> <button type=\"button\" class=\"btn btn-outline-warning\"> Warning</button> <button type=\"button\" class=\"btn btn-outline-info\"> Info</button> <button type=\"button\" class=\"btn btn-outline-light\"> Light</button> <button type=\"button\" class=\"btn btn-outline-dark\"> Dark</button> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script></body></html>",
"e": 35312,
"s": 32905,
"text": null
},
{
"code": null,
"e": 35320,
"s": 35312,
"text": "Output:"
},
{
"code": null,
"e": 35455,
"s": 35320,
"text": "Changing Size:Bootstrap provides us with different classes that allow changing the size of the button. These classes are listed below:"
},
{
"code": null,
"e": 35517,
"s": 35455,
"text": "btn-lg: This class is used to make a button(s) large in size."
},
{
"code": null,
"e": 35526,
"s": 35517,
"text": "Example:"
},
{
"code": null,
"e": 35531,
"s": 35526,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Hello, world!</title> <!-- Custom CSS --> <style> h1 { color: green; text-align: center; } div.one { margin-top: 40px; text-align: center; } button { margin-top: 10px; } </style></head><body> <div class=\"container\"> <h1>GeeksForGeeks</h1> <!-- Bootstrap Button Classes --> <div class=\"one\"> <button type=\"button\" class=\"btn btn-primary btn-lg\"> Primary</button> <button type=\"button\" class=\"btn btn-outline-secondary btn-lg\"> Secondary</button> <button type=\"button\" class=\"btn btn-success btn-lg\"> Success</button> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script></body></html>",
"e": 37376,
"s": 35531,
"text": null
},
{
"code": null,
"e": 37384,
"s": 37376,
"text": "Output:"
},
{
"code": null,
"e": 37446,
"s": 37384,
"text": "btn-sm: This class is used to make a button(s) small in size."
},
{
"code": null,
"e": 37455,
"s": 37446,
"text": "Example:"
},
{
"code": null,
"e": 37460,
"s": 37455,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Hello, world!</title> <!-- Custom CSS --> <style> h1 { color: green; text-align: center; } div.one { margin-top: 40px; text-align: center; } button { margin-top: 10px; } </style></head><body> <div class=\"container\"> <h1>GeeksForGeeks</h1> <!-- Bootstrap Button Classes --> <div class=\"one\"> <button type=\"button\" class=\"btn btn-primary btn-sm\"> Primary</button> <button type=\"button\" class=\"btn btn-outline-secondary btn-sm\"> Secondary</button> <button type=\"button\" class=\"btn btn-success btn-sm\"> Success</button> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script></body></html>",
"e": 39305,
"s": 37460,
"text": null
},
{
"code": null,
"e": 39313,
"s": 39305,
"text": "Output:"
},
{
"code": null,
"e": 39414,
"s": 39313,
"text": "btn-block: This class is used to make the button(s) occupy the entire width of their parent element."
},
{
"code": null,
"e": 39423,
"s": 39414,
"text": "Example:"
},
{
"code": null,
"e": 39428,
"s": 39423,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Hello, world!</title> <!-- Custom CSS --> <style> h1 { color: green; text-align: center; } div.one { margin-top: 40px; text-align: center; } button { margin-top: 10px; } </style></head><body> <div class=\"container\"> <h1>GeeksForGeeks</h1> <!-- Bootstrap Button Classes --> <div class=\"one\"> <button type=\"button\" class=\"btn btn-primary btn-block\"> Primary</button> <button type=\"button\" class=\"btn btn-outline-secondary btn-block\"> Secondary</button> <button type=\"button\" class=\"btn btn-success btn-block\"> Success</button> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script></body></html>",
"e": 41282,
"s": 39428,
"text": null
},
{
"code": null,
"e": 41290,
"s": 41282,
"text": "Output:"
},
{
"code": null,
"e": 41399,
"s": 41290,
"text": "Changing State:Bootstrap provides us with βactiveβ and βdisabledβ classes to change the state of the button."
},
{
"code": null,
"e": 41539,
"s": 41399,
"text": "active: This class is used to make buttons and links appear inactive state, i.e., with a dark background, dark border, and an inset shadow."
},
{
"code": null,
"e": 41548,
"s": 41539,
"text": "Example:"
},
{
"code": null,
"e": 41553,
"s": 41548,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Hello, world!</title> <!-- Custom CSS --> <style> h1 { color: green; text-align: center; } div.one { margin-top: 40px; text-align: center; } a, button { margin-top: 10px; } </style></head><body> <div class=\"container\"> <h1>GeeksForGeeks</h1> <!-- Bootstrap Button Classes --> <div class=\"one\"> <button type=\"button\" class=\"btn btn-primary active\"> Primary Button</button> <a href=\"#\" class=\"btn btn-warning active\" role=\"button\" aria-pressed=\"true\"> Warning Link</a> <button type=\"button\" class=\"btn btn-success active\"> Success Button</button> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script></body></html>",
"e": 43430,
"s": 41553,
"text": null
},
{
"code": null,
"e": 43675,
"s": 43430,
"text": "Note: When <a> tag is used we should insert role=βbuttonβ attribute-value pair within the tag, and if the button is active, than, we use aria-pressed=βtrueβ attribute-value pair within the <a> tag and set class value to active (class=βactiveβ)."
},
{
"code": null,
"e": 43683,
"s": 43675,
"text": "Output:"
},
{
"code": null,
"e": 43825,
"s": 43683,
"text": "disabled: This class is used to make buttons and links appear in a disabled state, i.e., with lighter background color and outset appearance."
},
{
"code": null,
"e": 43834,
"s": 43825,
"text": "Example:"
},
{
"code": null,
"e": 43839,
"s": 43834,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Hello, world!</title> <!-- Custom CSS --> <style> h1 { color: green; text-align: center; } div.one { margin-top: 40px; text-align: center; } a, button { margin-top: 10px; } </style></head><body> <div class=\"container\"> <h1>GeeksForGeeks</h1> <!-- Bootstrap Button Classes --> <div class=\"one\"> <button type=\"button\" class=\"btn btn-primary disabled\"> Primary Button</button> <a href=\"#\" class=\"btn btn-warning disabled\" role=\"button\" aria-disabled=\"true\" tabindex=\"-1\"> Warning Link</a> <button type=\"button\" class=\"btn btn-success disabled\"> Success Button</button> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script></body></html>",
"e": 45737,
"s": 43839,
"text": null
},
{
"code": null,
"e": 46113,
"s": 45737,
"text": "Note: When <a> is used tag we should insert role=βbuttonβ attribute-value pair within the tag. When using βdisabledβ class with <a> tag we should insert aria-disabled=βtrueβ and tabindex=β-1β²β² attribute-value pair with in the <a> tag. Also, we can make <button> disable by just adding βdisabledβ attribute within the <button> tag, without using βdisabledβ class of Bootstrap."
},
{
"code": null,
"e": 46121,
"s": 46113,
"text": "Output:"
},
{
"code": null,
"e": 46401,
"s": 46121,
"text": "Toggle State:We can make the button to toggle its state by adding data-toggle=βbuttonβ attribute-value pair to <button> tag. We can also preset the toggle state of the button to active by adding the βactiveβ class and aria-pressed=βtrueβ attribute-value pair to the <button> tag."
},
{
"code": null,
"e": 46410,
"s": 46401,
"text": "Example:"
},
{
"code": null,
"e": 46415,
"s": 46410,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Hello, world!</title> <!-- Custom CSS --> <style> h1 { color: green; text-align: center; } div.one { margin-top: 40px; text-align: center; } a, button { margin-top: 10px; } </style></head><body> <div class=\"container\"> <h1>GeeksForGeeks</h1> <!-- Bootstrap Button Classes --> <div class=\"one\"> <button type=\"button\" data-toggle=\"button\" class=\"btn btn-primary\" aria-pressed=\"false\"> Primary Button</button> <button type=\"button\" data-toggle=\"button\" class=\"btn btn-success\" aria-pressed=\"false\"> Success Button</button> <button type=\"button\" data-toggle=\"button\" class=\"btn btn-primary active\" aria-pressed=\"true\"> Primary Button</button> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script></body></html>",
"e": 48378,
"s": 46415,
"text": null
},
{
"code": null,
"e": 48423,
"s": 48378,
"text": "Note: The third button is preset to active. "
},
{
"code": null,
"e": 48431,
"s": 48423,
"text": "Output:"
},
{
"code": null,
"e": 48952,
"s": 48431,
"text": "Check Box Styled Buttons:To get a check box styled buttons, we need to use <input> tag with type=βcheckboxβ attribute-value pair, which is surrounded by <label> tag with class value set to βbtnβ and one of the class from the solid or the outline button class mentioned above. The <label> tag in turn is surrounded by <div> tag with class value set to βbtn-group-toggleβ (class=βbtn-group-toggleβ) and data-toggle=βbuttonsβ attribute-pair is also required within the <div> tag. Following example will clear the procedure:"
},
{
"code": null,
"e": 48961,
"s": 48952,
"text": "Example:"
},
{
"code": null,
"e": 48966,
"s": 48961,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Hello, world!</title> <!-- Custom CSS --> <style> h1 { color: green; text-align: center; } div.one { margin-top: 40px; text-align: center; } a, button { margin-top: 10px; } </style></head><body> <div class=\"container\"> <h1>GeeksForGeeks</h1> <!-- Bootstrap Button Classes --> <div class=\"one\"> <div class=\"btn-group-toggle\" data-toggle=\"buttons\"> <label class=\"btn btn-primary\"> <input type=\"checkbox\" autocomplete=\"off\"> Unchecked</label> <label class=\"btn btn-primary active\"> <input type=\"checkbox\" checked autocomplete=\"off\"> Checked</label> <label class=\"btn btn-primary\"> <input type=\"checkbox\" autocomplete=\"off\"> Unchecked</label> </div> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script></body></html>",
"e": 51006,
"s": 48966,
"text": null
},
{
"code": null,
"e": 51197,
"s": 51006,
"text": "Note: To make the button checked by default, we need to add the βactiveβ class within the <label> tag of the input control and also put the βcheckedβ attribute within the <input> tag.Output:"
},
{
"code": null,
"e": 51840,
"s": 51197,
"text": "Radio Styled Buttons:To get a radio styled buttons, we need to use <input> tag with type=βradioβ attribute-value pair and other essential attribute-value combination for the working of radio button, as usual. The <input> tag is in turn surrounded by <label> tag with class value set to βbtnβ and one of the class from the solid or the outline button classes as mentioned above. The <label> tag in turn is surrounded by <div> tag with class value set to βbtn-group btn-group-toggleβ (class=βbtn-group btn-group-toggleβ) and data-toggle=βbuttonsβ attribute-pair is also required within the <div> tag. Following example will clear the procedure:"
},
{
"code": null,
"e": 51849,
"s": 51840,
"text": "Example:"
},
{
"code": null,
"e": 51854,
"s": 51849,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Hello, world!</title> <!-- Custom CSS --> <style> h1 { color: green; text-align: center; } div.one { margin-top: 40px; text-align: center; } a, button { margin-top: 10px; } </style></head><body> <div class=\"container\"> <h1>GeeksForGeeks</h1> <!-- Bootstrap Button Classes --> <div class=\"one\"> <div class=\"btn-group btn-group-toggle\" data-toggle=\"buttons\"> <label class=\"btn btn-primary\"> <input type=\"radio\" name=\"options\" id=\"option1\" autocomplete=\"off\"> Radio Button</label> <label class=\"btn btn-primary active\"> <input type=\"radio\" name=\"options\" id=\"option2\" autocomplete=\"off\" checked> Active Radio Button</label> <label class=\"btn btn-primary\"> <input type=\"radio\" name=\"options\" id=\"option3\" autocomplete=\"off\"> Radio Button</label> </div> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\" integrity=\"sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\" integrity=\"sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k\" crossorigin=\"anonymous\"></script></body></html>",
"e": 54117,
"s": 51854,
"text": null
},
{
"code": null,
"e": 54301,
"s": 54117,
"text": "Note: To make the button checked by default, we need to add the βactiveβ class within the <label> tag of the input control and also put the βcheckedβ attribute within the <input> tag."
},
{
"code": null,
"e": 54309,
"s": 54301,
"text": "Output:"
},
{
"code": null,
"e": 54328,
"s": 54309,
"text": "Supported Browser:"
},
{
"code": null,
"e": 54342,
"s": 54328,
"text": "Google Chrome"
},
{
"code": null,
"e": 54360,
"s": 54342,
"text": "Internet Explorer"
},
{
"code": null,
"e": 54368,
"s": 54360,
"text": "Firefox"
},
{
"code": null,
"e": 54374,
"s": 54368,
"text": "Opera"
},
{
"code": null,
"e": 54381,
"s": 54374,
"text": "Safari"
},
{
"code": null,
"e": 54393,
"s": 54381,
"text": "ysachin2314"
},
{
"code": null,
"e": 54405,
"s": 54393,
"text": "sahilintern"
},
{
"code": null,
"e": 54415,
"s": 54405,
"text": "Bootstrap"
},
{
"code": null,
"e": 54432,
"s": 54415,
"text": "Web Technologies"
},
{
"code": null,
"e": 54530,
"s": 54432,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 54580,
"s": 54530,
"text": "How to change navigation bar color in Bootstrap ?"
},
{
"code": null,
"e": 54609,
"s": 54580,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 54650,
"s": 54609,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 54706,
"s": 54650,
"text": "How to align navbar items to the right in Bootstrap 4 ?"
},
{
"code": null,
"e": 54747,
"s": 54706,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 54787,
"s": 54747,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 54820,
"s": 54787,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 54865,
"s": 54820,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 54908,
"s": 54865,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Count rectangles generated in a given rectangle by lines drawn parallel to X and Y axis from a given set of points - GeeksforGeeks
|
27 Dec, 2021
Given a 2D array rectangle[][] representing vertices of a rectangle {(0, 0), (L, 0), (0, B), (L, B)} of dimensions L * B, and another 2D-array, points[][] of size N in a Cartesian coordinate system. Draw a horizontal line parallel to the X-axis and a vertical line parallel to the Y-axis from each point of the given array. The task is to count all possible rectangles present within the given rectangle.
Examples :
Input: Rectangle[][] = {{0, 0}, {5, 0}, {0, 5}, {5, 5}}, points[][] ={{1, 2}, {3, 4}} Output: 9 Explanation: Draw a horizontal line and a vertical line at points{1, 2} and points{3,4}.
_ _ _ _ _
5|_|_ _|_ _|
4| | |3,4|
3|_|_ _|_ _|
2| |1,2| |
1|_|_ _|_ _|
0 1 2 3 4 5
Therefore, the required output is 9.
Input: Rectangle[][] = {{0, 0}, {4, 0}, {0, 5}, {4, 5}}, points[][] = {{1, 3}, {2, 3}, {3, 3}} Output: 12
Approach: The idea is to traverse the array and count all distinct horizontal and vertical lines passing through the given points[][] array. Finally, return the value of multiplication of (count of the distinct horizontal line β 1) * (count of vertical lines β 1). Follow the steps below to solve the problem:
Create two set, say cntHor, cntVer to store all the distinct horizontal lines and vertical lines passing through points[][] array.
Traverse the points[][] array.
Count all distinct horizontal lines using the count of elements in cntHor.
Count all distinct vertical lines using the count of elements in cntVer.
Finally, print the value of (count of elements in cntHor β 1) * (count of elements in cntVer β 1).
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to get the count// of rectanglesint cntRect(int points[][2], int N, int rectangle[][2]){ // Store distinct // horizontal lines unordered_set<int> cntHor; // Store distinct // Vertical lines unordered_set<int> cntVer; // Insert horizontal line // passing through 0 cntHor.insert(0); // Insert vertical line // passing through 0. cntVer.insert(0); // Insert horizontal line // passing through rectangle[3][0] cntHor.insert(rectangle[3][0]); // Insert vertical line // passing through rectangle[3][1] cntVer.insert(rectangle[3][1]); // Insert all horizontal and // vertical lines passing through // the given array for (int i = 0; i < N; i++) { // Insert all horizontal lines cntHor.insert(points[i][0]); // Insert all vertical lines cntVer.insert(points[i][1]); } return (cntHor.size() - 1) * (cntVer.size() - 1);} // Driver Codeint main(){ int rectangle[][2] = {{0, 0}, {0, 5}, {5, 0}, {5, 5}}; int points[][2] = {{1, 2}, {3, 4}}; int N = sizeof(points) / sizeof(points[0]); cout<<cntRect(points, N, rectangle);}
// Java program to implement// the above approachimport java.io.*;import java.util.*; class GFG{ // Function to get the count// of rectanglespublic static int cntRect(int points[][], int N, int rectangle[][]){ // Store distinct // horizontal lines HashSet<Integer> cntHor = new HashSet<>(); // Store distinct // Vertical lines HashSet<Integer> cntVer = new HashSet<>(); // Insert horizontal line // passing through 0 cntHor.add(0); // Insert vertical line // passing through 0. cntVer.add(0); // Insert horizontal line // passing through rectangle[3][0] cntHor.add(rectangle[3][0]); // Insert vertical line // passing through rectangle[3][1] cntVer.add(rectangle[3][1]); // Insert all horizontal and // vertical lines passing through // the given array for(int i = 0; i < N; i++) { // Insert all horizontal lines cntHor.add(points[i][0]); // Insert all vertical lines cntVer.add(points[i][1]); } return (cntHor.size() - 1) * (cntVer.size() - 1);} // Driver Codepublic static void main(String args[]){ int rectangle[][] = { { 0, 0 }, { 0, 5 }, { 5, 0 }, { 5, 5 } }; int points[][] = { { 1, 2 }, { 3, 4 } }; int N = points.length; System.out.println(cntRect(points, N, rectangle));}} // This code is contributed by hemanth gadarla
# Python3 program to implement# the above approach # Function to get the count# of rectanglesdef cntRect(points, N, rectangle): # Store distinct # horizontal lines cntHor = set([]) # Store distinct # Vertical lines cntVer = set([]) # Insert horizontal line # passing through 0 cntHor.add(0) # Insert vertical line # passing through 0. cntVer.add(0) # Insert horizontal line # passing through rectangle[3][0] cntHor.add(rectangle[3][0]) # Insert vertical line # passing through rectangle[3][1] cntVer.add(rectangle[3][1]) # Insert all horizontal and # vertical lines passing through # the given array for i in range (N): # Insert all horizontal lines cntHor.add(points[i][0]) # Insert all vertical lines cntVer.add(points[i][1]) return ((len(cntHor) - 1) * (len(cntVer) - 1)) # Driver Codeif __name__ == "__main__": rectangle = [[0, 0], [0, 5], [5, 0], [5, 5]] points = [[1, 2], [3, 4]] N = len(points) print (cntRect(points, N, rectangle)) # This code is contributed by Chitranayal
// C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to get the count// of rectanglespublic static int cntRect(int [,]points, int N, int [,]rectangle){ // Store distinct // horizontal lines HashSet<int> cntHor = new HashSet<int>(); // Store distinct // Vertical lines HashSet<int> cntVer = new HashSet<int>(); // Insert horizontal line // passing through 0 cntHor.Add(0); // Insert vertical line // passing through 0. cntVer.Add(0); // Insert horizontal line // passing through rectangle[3,0] cntHor.Add(rectangle[3, 0]); // Insert vertical line // passing through rectangle[3,1] cntVer.Add(rectangle[3, 1]); // Insert all horizontal and // vertical lines passing through // the given array for(int i = 0; i < N; i++) { // Insert all horizontal lines cntHor.Add(points[i, 0]); // Insert all vertical lines cntVer.Add(points[i, 1]); } return (cntHor.Count - 1) * (cntVer.Count - 1);} // Driver Codepublic static void Main(String []args){ int [,]rectangle = {{0, 0}, {0, 5}, {5, 0}, {5, 5}}; int [,]points = {{1, 2}, {3, 4}}; int N = points.GetLength(0); Console.WriteLine(cntRect(points, N, rectangle));}} // This code is contributed by 29AjayKumar
<script>// Javascript program to implement// the above approach // Function to get the count// of rectanglesfunction cntRect(points, N, rectangle){ // Store distinct // horizontal lines var cntHor = new Set(); // Store distinct // Vertical lines var cntVer = new Set(); // Insert horizontal line // passing through 0 cntHor.add(0); // Insert vertical line // passing through 0. cntVer.add(0); // Insert horizontal line // passing through rectangle[3][0] cntHor.add(rectangle[3][0]); // Insert vertical line // passing through rectangle[3][1] cntVer.add(rectangle[3][1]); // Insert all horizontal and // vertical lines passing through // the given array for (var i = 0; i < N; i++) { // Insert all horizontal lines cntHor.add(points[i][0]); // Insert all vertical lines cntVer.add(points[i][1]); } return (cntHor.size - 1) * (cntVer.size - 1);} // Driver Codevar rectangle = [[0, 0], [0, 5], [5, 0], [5, 5]];var points = [[1, 2], [3, 4]]; var N = points.length;document.write( cntRect(points, N, rectangle)); // This code is contributed by noob2000. </script>
9
Time Complexity: O(N)Auxiliary Space: O(N)
hemanthswarna1506
29AjayKumar
ukasp
noob2000
kk773572498
square-rectangle
Combinatorial
Geometric
Hash
Mathematical
Matrix
Hash
Mathematical
Matrix
Combinatorial
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ways to sum to N using Natural Numbers up to K with repetitions allowed
Generate all possible combinations of K numbers that sums to N
Combinations with repetitions
Largest substring with same Characters
Generate all possible combinations of at most X characters from a given array
Closest Pair of Points using Divide and Conquer algorithm
How to check if a given point lies inside or outside a polygon?
Program for distance between two points on earth
How to check if two given line segments intersect?
Find if two rectangles overlap
|
[
{
"code": null,
"e": 26697,
"s": 26669,
"text": "\n27 Dec, 2021"
},
{
"code": null,
"e": 27102,
"s": 26697,
"text": "Given a 2D array rectangle[][] representing vertices of a rectangle {(0, 0), (L, 0), (0, B), (L, B)} of dimensions L * B, and another 2D-array, points[][] of size N in a Cartesian coordinate system. Draw a horizontal line parallel to the X-axis and a vertical line parallel to the Y-axis from each point of the given array. The task is to count all possible rectangles present within the given rectangle."
},
{
"code": null,
"e": 27113,
"s": 27102,
"text": "Examples :"
},
{
"code": null,
"e": 27300,
"s": 27113,
"text": "Input: Rectangle[][] = {{0, 0}, {5, 0}, {0, 5}, {5, 5}}, points[][] ={{1, 2}, {3, 4}} Output: 9 Explanation: Draw a horizontal line and a vertical line at points{1, 2} and points{3,4}. "
},
{
"code": null,
"e": 27392,
"s": 27300,
"text": " _ _ _ _ _ \n5|_|_ _|_ _|\n4| | |3,4|\n3|_|_ _|_ _| \n2| |1,2| |\n1|_|_ _|_ _|\n 0 1 2 3 4 5"
},
{
"code": null,
"e": 27430,
"s": 27392,
"text": "Therefore, the required output is 9. "
},
{
"code": null,
"e": 27538,
"s": 27430,
"text": "Input: Rectangle[][] = {{0, 0}, {4, 0}, {0, 5}, {4, 5}}, points[][] = {{1, 3}, {2, 3}, {3, 3}} Output: 12 "
},
{
"code": null,
"e": 27848,
"s": 27538,
"text": "Approach: The idea is to traverse the array and count all distinct horizontal and vertical lines passing through the given points[][] array. Finally, return the value of multiplication of (count of the distinct horizontal line β 1) * (count of vertical lines β 1). Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 27979,
"s": 27848,
"text": "Create two set, say cntHor, cntVer to store all the distinct horizontal lines and vertical lines passing through points[][] array."
},
{
"code": null,
"e": 28010,
"s": 27979,
"text": "Traverse the points[][] array."
},
{
"code": null,
"e": 28085,
"s": 28010,
"text": "Count all distinct horizontal lines using the count of elements in cntHor."
},
{
"code": null,
"e": 28158,
"s": 28085,
"text": "Count all distinct vertical lines using the count of elements in cntVer."
},
{
"code": null,
"e": 28257,
"s": 28158,
"text": "Finally, print the value of (count of elements in cntHor β 1) * (count of elements in cntVer β 1)."
},
{
"code": null,
"e": 28308,
"s": 28257,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28312,
"s": 28308,
"text": "C++"
},
{
"code": null,
"e": 28317,
"s": 28312,
"text": "Java"
},
{
"code": null,
"e": 28325,
"s": 28317,
"text": "Python3"
},
{
"code": null,
"e": 28328,
"s": 28325,
"text": "C#"
},
{
"code": null,
"e": 28339,
"s": 28328,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to get the count// of rectanglesint cntRect(int points[][2], int N, int rectangle[][2]){ // Store distinct // horizontal lines unordered_set<int> cntHor; // Store distinct // Vertical lines unordered_set<int> cntVer; // Insert horizontal line // passing through 0 cntHor.insert(0); // Insert vertical line // passing through 0. cntVer.insert(0); // Insert horizontal line // passing through rectangle[3][0] cntHor.insert(rectangle[3][0]); // Insert vertical line // passing through rectangle[3][1] cntVer.insert(rectangle[3][1]); // Insert all horizontal and // vertical lines passing through // the given array for (int i = 0; i < N; i++) { // Insert all horizontal lines cntHor.insert(points[i][0]); // Insert all vertical lines cntVer.insert(points[i][1]); } return (cntHor.size() - 1) * (cntVer.size() - 1);} // Driver Codeint main(){ int rectangle[][2] = {{0, 0}, {0, 5}, {5, 0}, {5, 5}}; int points[][2] = {{1, 2}, {3, 4}}; int N = sizeof(points) / sizeof(points[0]); cout<<cntRect(points, N, rectangle);}",
"e": 29681,
"s": 28339,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.io.*;import java.util.*; class GFG{ // Function to get the count// of rectanglespublic static int cntRect(int points[][], int N, int rectangle[][]){ // Store distinct // horizontal lines HashSet<Integer> cntHor = new HashSet<>(); // Store distinct // Vertical lines HashSet<Integer> cntVer = new HashSet<>(); // Insert horizontal line // passing through 0 cntHor.add(0); // Insert vertical line // passing through 0. cntVer.add(0); // Insert horizontal line // passing through rectangle[3][0] cntHor.add(rectangle[3][0]); // Insert vertical line // passing through rectangle[3][1] cntVer.add(rectangle[3][1]); // Insert all horizontal and // vertical lines passing through // the given array for(int i = 0; i < N; i++) { // Insert all horizontal lines cntHor.add(points[i][0]); // Insert all vertical lines cntVer.add(points[i][1]); } return (cntHor.size() - 1) * (cntVer.size() - 1);} // Driver Codepublic static void main(String args[]){ int rectangle[][] = { { 0, 0 }, { 0, 5 }, { 5, 0 }, { 5, 5 } }; int points[][] = { { 1, 2 }, { 3, 4 } }; int N = points.length; System.out.println(cntRect(points, N, rectangle));}} // This code is contributed by hemanth gadarla",
"e": 31146,
"s": 29681,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Function to get the count# of rectanglesdef cntRect(points, N, rectangle): # Store distinct # horizontal lines cntHor = set([]) # Store distinct # Vertical lines cntVer = set([]) # Insert horizontal line # passing through 0 cntHor.add(0) # Insert vertical line # passing through 0. cntVer.add(0) # Insert horizontal line # passing through rectangle[3][0] cntHor.add(rectangle[3][0]) # Insert vertical line # passing through rectangle[3][1] cntVer.add(rectangle[3][1]) # Insert all horizontal and # vertical lines passing through # the given array for i in range (N): # Insert all horizontal lines cntHor.add(points[i][0]) # Insert all vertical lines cntVer.add(points[i][1]) return ((len(cntHor) - 1) * (len(cntVer) - 1)) # Driver Codeif __name__ == \"__main__\": rectangle = [[0, 0], [0, 5], [5, 0], [5, 5]] points = [[1, 2], [3, 4]] N = len(points) print (cntRect(points, N, rectangle)) # This code is contributed by Chitranayal",
"e": 32333,
"s": 31146,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to get the count// of rectanglespublic static int cntRect(int [,]points, int N, int [,]rectangle){ // Store distinct // horizontal lines HashSet<int> cntHor = new HashSet<int>(); // Store distinct // Vertical lines HashSet<int> cntVer = new HashSet<int>(); // Insert horizontal line // passing through 0 cntHor.Add(0); // Insert vertical line // passing through 0. cntVer.Add(0); // Insert horizontal line // passing through rectangle[3,0] cntHor.Add(rectangle[3, 0]); // Insert vertical line // passing through rectangle[3,1] cntVer.Add(rectangle[3, 1]); // Insert all horizontal and // vertical lines passing through // the given array for(int i = 0; i < N; i++) { // Insert all horizontal lines cntHor.Add(points[i, 0]); // Insert all vertical lines cntVer.Add(points[i, 1]); } return (cntHor.Count - 1) * (cntVer.Count - 1);} // Driver Codepublic static void Main(String []args){ int [,]rectangle = {{0, 0}, {0, 5}, {5, 0}, {5, 5}}; int [,]points = {{1, 2}, {3, 4}}; int N = points.GetLength(0); Console.WriteLine(cntRect(points, N, rectangle));}} // This code is contributed by 29AjayKumar",
"e": 33677,
"s": 32333,
"text": null
},
{
"code": "<script>// Javascript program to implement// the above approach // Function to get the count// of rectanglesfunction cntRect(points, N, rectangle){ // Store distinct // horizontal lines var cntHor = new Set(); // Store distinct // Vertical lines var cntVer = new Set(); // Insert horizontal line // passing through 0 cntHor.add(0); // Insert vertical line // passing through 0. cntVer.add(0); // Insert horizontal line // passing through rectangle[3][0] cntHor.add(rectangle[3][0]); // Insert vertical line // passing through rectangle[3][1] cntVer.add(rectangle[3][1]); // Insert all horizontal and // vertical lines passing through // the given array for (var i = 0; i < N; i++) { // Insert all horizontal lines cntHor.add(points[i][0]); // Insert all vertical lines cntVer.add(points[i][1]); } return (cntHor.size - 1) * (cntVer.size - 1);} // Driver Codevar rectangle = [[0, 0], [0, 5], [5, 0], [5, 5]];var points = [[1, 2], [3, 4]]; var N = points.length;document.write( cntRect(points, N, rectangle)); // This code is contributed by noob2000. </script>",
"e": 34928,
"s": 33677,
"text": null
},
{
"code": null,
"e": 34930,
"s": 34928,
"text": "9"
},
{
"code": null,
"e": 34976,
"s": 34932,
"text": "Time Complexity: O(N)Auxiliary Space: O(N) "
},
{
"code": null,
"e": 34994,
"s": 34976,
"text": "hemanthswarna1506"
},
{
"code": null,
"e": 35006,
"s": 34994,
"text": "29AjayKumar"
},
{
"code": null,
"e": 35012,
"s": 35006,
"text": "ukasp"
},
{
"code": null,
"e": 35021,
"s": 35012,
"text": "noob2000"
},
{
"code": null,
"e": 35033,
"s": 35021,
"text": "kk773572498"
},
{
"code": null,
"e": 35050,
"s": 35033,
"text": "square-rectangle"
},
{
"code": null,
"e": 35064,
"s": 35050,
"text": "Combinatorial"
},
{
"code": null,
"e": 35074,
"s": 35064,
"text": "Geometric"
},
{
"code": null,
"e": 35079,
"s": 35074,
"text": "Hash"
},
{
"code": null,
"e": 35092,
"s": 35079,
"text": "Mathematical"
},
{
"code": null,
"e": 35099,
"s": 35092,
"text": "Matrix"
},
{
"code": null,
"e": 35104,
"s": 35099,
"text": "Hash"
},
{
"code": null,
"e": 35117,
"s": 35104,
"text": "Mathematical"
},
{
"code": null,
"e": 35124,
"s": 35117,
"text": "Matrix"
},
{
"code": null,
"e": 35138,
"s": 35124,
"text": "Combinatorial"
},
{
"code": null,
"e": 35148,
"s": 35138,
"text": "Geometric"
},
{
"code": null,
"e": 35246,
"s": 35148,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35318,
"s": 35246,
"text": "Ways to sum to N using Natural Numbers up to K with repetitions allowed"
},
{
"code": null,
"e": 35381,
"s": 35318,
"text": "Generate all possible combinations of K numbers that sums to N"
},
{
"code": null,
"e": 35411,
"s": 35381,
"text": "Combinations with repetitions"
},
{
"code": null,
"e": 35450,
"s": 35411,
"text": "Largest substring with same Characters"
},
{
"code": null,
"e": 35528,
"s": 35450,
"text": "Generate all possible combinations of at most X characters from a given array"
},
{
"code": null,
"e": 35586,
"s": 35528,
"text": "Closest Pair of Points using Divide and Conquer algorithm"
},
{
"code": null,
"e": 35650,
"s": 35586,
"text": "How to check if a given point lies inside or outside a polygon?"
},
{
"code": null,
"e": 35699,
"s": 35650,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 35750,
"s": 35699,
"text": "How to check if two given line segments intersect?"
}
] |
Pipelining and Addressing modes - GeeksforGeeks
|
19 Nov, 2018
Pipeline will have to be stalled till Ei stage of l4 completes,
as Ei stage will tell whether to take branch or not.
After that l4(WO) and l9(Fi) can go in parallel and later the
following instructions.
So, till l4(Ei) completes : 7 cycles * (10 + 1 ) ns = 77ns
From l4(WO) or l9(Fi) to l12(WO) : 8 cycles * (10 + 1)ns = 88ns
Total = 77 + 88 = 165 ns
R1βc, R2βd, R2βR1+R2, R1βe, R2βR1-R2Now to calculate the rest of the expression we must load a and b into the registers but we need thecontent of R2 later.So we must use another Register.R1βa, R3βb, R1βR1-R3, R1βR1+R2
Source: http://clweb.csa.iisc.ernet.in/rahulsharma/gate2011key.html
Pipeline registers overhead is not counted in normal
time execution
So the total count will be
5+6+11+8= 30 [without pipeline]
Now, for pipeline, each stage will be of 11 n-sec (+ 1 n-sec for overhead).
and, in steady state output is produced after every pipeline cycle. Here,
in this case 11 n-sec. After adding 1n-sec overhead, We will get 12 n-sec
of constant output producing cycle.
dividing 30/12 we get 2.5
Instruction Meaning of instruction
I0 :MUL R2 ,R0 ,R1 R2 Β¬ R0 *R1
I1 :DIV R5 ,R3 ,R4 R5 Β¬ R3/R4
I2 :ADD R2 ,R5 ,R2 R2 Β¬ R5+R2
I3 :SUB R5 ,R2 ,R6 R5 Β¬ R2-R6
The program below uses six temporary variables a, b, c, d, e, f.
a = 1
b = 10
c = 20
d = a+b
e = c+d
f = c+e
b = c+e
e = b+f
d = 5+e
return d+f
Assuming that all operations take their operands from registers, what is the minimum number of registers needed to execute this program without spilling?
2
3
4
6
All of the given expressions use at-most 3 variables, so we never need more than 3 registers. See http://en.wikipedia.org/wiki/Register_allocation It requires minimum of 3 registers. Principle of Register Allocation : If a variable needs to be allocated to a register, the system checks for any free register available, if it finds one, it allocates. If there is no free register, then it checks for a register that contains a dead variable ( a variable whose value is not going to be used in the future ), and if it finds one then it allocates. Otherwise, it goes for Spilling ( it checks for a register whose value is needed after the longest time, saves its value into the memory, and then use that register for current allocation, later when the old value of the register is needed, the system gets it from the memory where it was saved and allocate it in any register which is available ). But here we should not apply spilling as directed in the question. Let's allocate the registers for the variables. a = 1 ( let's say register R1 is allocated for variable 'a' ) b = 10 ( R2 for 'b' , because value of 'a' is going to be used in the future, hence can not replace variable of 'a' by that of 'b' in R1) c = 20 ( R3 for 'c', because values of 'a' and 'b' are going to be used in the future, hence can not replace variable 'a' or 'b' by 'c' in R1 or R2 respectively) d = a+b ( now, 'd' can be assigned to R1 because R1 contains a dead variable which is 'a' and it is so-called because it is not going to be used in future, i.e. no subsequent expression uses the value of variable 'a') e = c+d ( 'e' can be assigned to R1, because currently R1 contains value of variable 'd' which is not going to be used in the subsequent expression.) Note: an already calculated value of a variable is used only by READ operation ( not WRITE), hence we have to see only on the RHS side of the subsequent expressions whether the variable is going to be used or not. f = c+e ( ' f ' can be assigned to R2, because vaule of 'b' in register R2 is not going to be used in subsequent expressions, hence R2 can be used to allocate for ' f ' replacing 'b' ) b = c+e ( ' b ' can be assigned to R3, because value of 'c' in R3 is not being used later ) e = b+f ( here 'e' is already in R1, so no allocation here, direct assignment ) d = 5+e ( 'd' can be assigned to either R1 or R3, because values in both are not used further, let's assign in R1 ) return d+f ( no allocation here, simply contents of registers R1 and R2 are added and returned) hence we need only 3 registers, R1 R2 and R3.
I. It is useful in creating self-relocating code.
II. If it is included in an Instruction Set Architecture,
then an additional ALU is required for effective address
calculation.
III.The amount of increment depends on the size of the data
item accessed.
I. It must be a trap instruction
II. It must be a privileged instruction
III. An exception cannot be allowed to occur during
execution of an RFE instruction
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
C Program For Finding Length Of A Linked List
How to calculate MOVING AVERAGE in a Pandas DataFrame?
How to Convert Categorical Variable to Numeric in Pandas?
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
How to Fix: KeyError in Pandas
C Program to read contents of Whole File
How to Append Pandas DataFrame to Existing CSV File?
How to Replace Values in a List in Python?
|
[
{
"code": null,
"e": 28855,
"s": 28827,
"text": "\n19 Nov, 2018"
},
{
"code": null,
"e": 29209,
"s": 28855,
"text": "Pipeline will have to be stalled till Ei stage of l4 completes, \nas Ei stage will tell whether to take branch or not. \n\nAfter that l4(WO) and l9(Fi) can go in parallel and later the\nfollowing instructions.\nSo, till l4(Ei) completes : 7 cycles * (10 + 1 ) ns = 77ns\nFrom l4(WO) or l9(Fi) to l12(WO) : 8 cycles * (10 + 1)ns = 88ns\nTotal = 77 + 88 = 165 ns"
},
{
"code": null,
"e": 29431,
"s": 29209,
"text": "R1βc, R2βd, R2βR1+R2, R1βe, R2βR1-R2Now to calculate the rest of the expression we must load a and b into the registers but we need thecontent of R2 later.So we must use another Register.R1βa, R3βb, R1βR1-R3, R1βR1+R2"
},
{
"code": null,
"e": 29499,
"s": 29431,
"text": "Source: http://clweb.csa.iisc.ernet.in/rahulsharma/gate2011key.html"
},
{
"code": null,
"e": 29918,
"s": 29499,
"text": "Pipeline registers overhead is not counted in normal \ntime execution\n\nSo the total count will be\n\n5+6+11+8= 30 [without pipeline]\n\nNow, for pipeline, each stage will be of 11 n-sec (+ 1 n-sec for overhead).\nand, in steady state output is produced after every pipeline cycle. Here,\nin this case 11 n-sec. After adding 1n-sec overhead, We will get 12 n-sec\nof constant output producing cycle.\n\ndividing 30/12 we get 2.5 "
},
{
"code": null,
"e": 30123,
"s": 29918,
"text": " Instruction Meaning of instruction\n I0 :MUL R2 ,R0 ,R1\t R2 Β¬ R0 *R1\n I1 :DIV R5 ,R3 ,R4 \t R5 Β¬ R3/R4\n I2 :ADD R2 ,R5 ,R2\t R2 Β¬ R5+R2\n I3 :SUB R5 ,R2 ,R6\t R5 Β¬ R2-R6"
},
{
"code": null,
"e": 30190,
"s": 30123,
"text": "The program below uses six temporary variables a, b, c, d, e, f. "
},
{
"code": null,
"e": 30311,
"s": 30190,
"text": " \n a = 1\n b = 10\n c = 20\n d = a+b\n e = c+d\n f = c+e\n b = c+e\n e = b+f\n d = 5+e\n return d+f"
},
{
"code": null,
"e": 30466,
"s": 30311,
"text": "Assuming that all operations take their operands from registers, what is the minimum number of registers needed to execute this program without spilling? "
},
{
"code": null,
"e": 30469,
"s": 30466,
"text": "2 "
},
{
"code": null,
"e": 30472,
"s": 30469,
"text": "3 "
},
{
"code": null,
"e": 30475,
"s": 30472,
"text": "4 "
},
{
"code": null,
"e": 30478,
"s": 30475,
"text": "6 "
},
{
"code": null,
"e": 33071,
"s": 30478,
"text": "All of the given expressions use at-most 3 variables, so we never need more than 3 registers. See http://en.wikipedia.org/wiki/Register_allocation It requires minimum of 3 registers. Principle of Register Allocation : If a variable needs to be allocated to a register, the system checks for any free register available, if it finds one, it allocates. If there is no free register, then it checks for a register that contains a dead variable ( a variable whose value is not going to be used in the future ), and if it finds one then it allocates. Otherwise, it goes for Spilling ( it checks for a register whose value is needed after the longest time, saves its value into the memory, and then use that register for current allocation, later when the old value of the register is needed, the system gets it from the memory where it was saved and allocate it in any register which is available ). But here we should not apply spilling as directed in the question. Let's allocate the registers for the variables. a = 1 ( let's say register R1 is allocated for variable 'a' ) b = 10 ( R2 for 'b' , because value of 'a' is going to be used in the future, hence can not replace variable of 'a' by that of 'b' in R1) c = 20 ( R3 for 'c', because values of 'a' and 'b' are going to be used in the future, hence can not replace variable 'a' or 'b' by 'c' in R1 or R2 respectively) d = a+b ( now, 'd' can be assigned to R1 because R1 contains a dead variable which is 'a' and it is so-called because it is not going to be used in future, i.e. no subsequent expression uses the value of variable 'a') e = c+d ( 'e' can be assigned to R1, because currently R1 contains value of variable 'd' which is not going to be used in the subsequent expression.) Note: an already calculated value of a variable is used only by READ operation ( not WRITE), hence we have to see only on the RHS side of the subsequent expressions whether the variable is going to be used or not. f = c+e ( ' f ' can be assigned to R2, because vaule of 'b' in register R2 is not going to be used in subsequent expressions, hence R2 can be used to allocate for ' f ' replacing 'b' ) b = c+e ( ' b ' can be assigned to R3, because value of 'c' in R3 is not being used later ) e = b+f ( here 'e' is already in R1, so no allocation here, direct assignment ) d = 5+e ( 'd' can be assigned to either R1 or R3, because values in both are not used further, let's assign in R1 ) return d+f ( no allocation here, simply contents of registers R1 and R2 are added and returned) hence we need only 3 registers, R1 R2 and R3. "
},
{
"code": null,
"e": 33340,
"s": 33071,
"text": "I. It is useful in creating self-relocating code.\nII. If it is included in an Instruction Set Architecture, \n then an additional ALU is required for effective address \n calculation.\nIII.The amount of increment depends on the size of the data\n item accessed."
},
{
"code": null,
"e": 33507,
"s": 33340,
"text": "I. It must be a trap instruction\nII. It must be a privileged instruction\nIII. An exception cannot be allowed to occur during \n execution of an RFE instruction "
},
{
"code": null,
"e": 33605,
"s": 33507,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 33658,
"s": 33605,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 33704,
"s": 33658,
"text": "C Program For Finding Length Of A Linked List"
},
{
"code": null,
"e": 33759,
"s": 33704,
"text": "How to calculate MOVING AVERAGE in a Pandas DataFrame?"
},
{
"code": null,
"e": 33817,
"s": 33759,
"text": "How to Convert Categorical Variable to Numeric in Pandas?"
},
{
"code": null,
"e": 33879,
"s": 33817,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 33959,
"s": 33879,
"text": "How to Fix: SyntaxError: positional argument follows keyword argument in Python"
},
{
"code": null,
"e": 33990,
"s": 33959,
"text": "How to Fix: KeyError in Pandas"
},
{
"code": null,
"e": 34031,
"s": 33990,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 34084,
"s": 34031,
"text": "How to Append Pandas DataFrame to Existing CSV File?"
}
] |
JavaScript Error() constructor - GeeksforGeeks
|
14 Aug, 2021
Javascript Error() constructor is used to create a new error object. Error objects are arising at runtime errors. The error object also uses as the base object for the exceptions defined by the user.
Syntax:
new Error([message[, fileName[, lineNumber]]])
Parameters:
message: It contains information about this error object which is in human-readable form. An error message can be set using javascript Error message property. It is an optional parameter.
fileName: It is the name of the file for this error object. If no name is provided than fileName is equal to the name of file containing the the code that called the Error() constructor. It is an optional parameter.
lineNumber: It is the value for the lineNumber property on the created Error object. If no number is provided Than the lineNumber is equal to the line number containing the Error() constructor invocation. It is an optional parameter.
Example 1: Creating error object using new keyword.
Javascript
<script>try { const error = new Error('This object is created using new keyword') document.write("Error object created successfully using new keyword");} catch(err) { document.write(err.message);}</script>
Output:
Error object created successfully using new keyword
Example 2: Creating error object using function call.
Javascript
<script>try { const error = Error('This is created is using function call') document.write("Error object created successfully using function call");} catch(err) { document.write(err.message);}</script>
Output:
Error object created successfully using function call
Supported Browsers:
Google Chrome
Firefox
Edge
Internet Explorer
Opera
Safari
surinderdawra388
JavaScript-Errors
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26545,
"s": 26517,
"text": "\n14 Aug, 2021"
},
{
"code": null,
"e": 26745,
"s": 26545,
"text": "Javascript Error() constructor is used to create a new error object. Error objects are arising at runtime errors. The error object also uses as the base object for the exceptions defined by the user."
},
{
"code": null,
"e": 26753,
"s": 26745,
"text": "Syntax:"
},
{
"code": null,
"e": 26800,
"s": 26753,
"text": "new Error([message[, fileName[, lineNumber]]])"
},
{
"code": null,
"e": 26812,
"s": 26800,
"text": "Parameters:"
},
{
"code": null,
"e": 27000,
"s": 26812,
"text": "message: It contains information about this error object which is in human-readable form. An error message can be set using javascript Error message property. It is an optional parameter."
},
{
"code": null,
"e": 27216,
"s": 27000,
"text": "fileName: It is the name of the file for this error object. If no name is provided than fileName is equal to the name of file containing the the code that called the Error() constructor. It is an optional parameter."
},
{
"code": null,
"e": 27450,
"s": 27216,
"text": "lineNumber: It is the value for the lineNumber property on the created Error object. If no number is provided Than the lineNumber is equal to the line number containing the Error() constructor invocation. It is an optional parameter."
},
{
"code": null,
"e": 27502,
"s": 27450,
"text": "Example 1: Creating error object using new keyword."
},
{
"code": null,
"e": 27513,
"s": 27502,
"text": "Javascript"
},
{
"code": "<script>try { const error = new Error('This object is created using new keyword') document.write(\"Error object created successfully using new keyword\");} catch(err) { document.write(err.message);}</script>",
"e": 27729,
"s": 27513,
"text": null
},
{
"code": null,
"e": 27737,
"s": 27729,
"text": "Output:"
},
{
"code": null,
"e": 27789,
"s": 27737,
"text": "Error object created successfully using new keyword"
},
{
"code": null,
"e": 27843,
"s": 27789,
"text": "Example 2: Creating error object using function call."
},
{
"code": null,
"e": 27854,
"s": 27843,
"text": "Javascript"
},
{
"code": "<script>try { const error = Error('This is created is using function call') document.write(\"Error object created successfully using function call\");} catch(err) { document.write(err.message);}</script>",
"e": 28067,
"s": 27854,
"text": null
},
{
"code": null,
"e": 28075,
"s": 28067,
"text": "Output:"
},
{
"code": null,
"e": 28129,
"s": 28075,
"text": "Error object created successfully using function call"
},
{
"code": null,
"e": 28149,
"s": 28129,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 28163,
"s": 28149,
"text": "Google Chrome"
},
{
"code": null,
"e": 28171,
"s": 28163,
"text": "Firefox"
},
{
"code": null,
"e": 28176,
"s": 28171,
"text": "Edge"
},
{
"code": null,
"e": 28194,
"s": 28176,
"text": "Internet Explorer"
},
{
"code": null,
"e": 28200,
"s": 28194,
"text": "Opera"
},
{
"code": null,
"e": 28207,
"s": 28200,
"text": "Safari"
},
{
"code": null,
"e": 28224,
"s": 28207,
"text": "surinderdawra388"
},
{
"code": null,
"e": 28242,
"s": 28224,
"text": "JavaScript-Errors"
},
{
"code": null,
"e": 28249,
"s": 28242,
"text": "Picked"
},
{
"code": null,
"e": 28260,
"s": 28249,
"text": "JavaScript"
},
{
"code": null,
"e": 28277,
"s": 28260,
"text": "Web Technologies"
},
{
"code": null,
"e": 28375,
"s": 28277,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28415,
"s": 28375,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28476,
"s": 28415,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28517,
"s": 28476,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28539,
"s": 28517,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 28593,
"s": 28539,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 28633,
"s": 28593,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28666,
"s": 28633,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28709,
"s": 28666,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28771,
"s": 28709,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Merge multiple Jupyter Notebooks together with Python | by Satyam Kumar | Towards Data Science
|
Jupyter Notebook is considered an integral part of any Data Scientistβs toolbox. Jupyter Notebook also referred to as IPython Notebooks is a web application based on the server-client structure.
Jupyter Notebook provides an easy-to-use interactive data science environment that supports various programming languages. It is of great use for prototyping and offers interactive computing by combining code, text, and visualizations.
It is common to use multiple Jupyter Notebooks for any project development. Sometimes requirement arises to merge several notebooks together and you need to manually do copy-pasting cells of the notebook together, which becomes a tedious task.
In this article, you can read how to merge several IPython Notebooks together and efficiently, writing few lines of Python code.
A Jupyter Notebook is saved as a JSON file format. This JSON file has all the notebook contents, including text, code, outputs, and plots. The figures, images, and videos are encoded as base64 strings. The basic structure of the Jupyter Notebook JSON file is:
{ "cells": [], "metadata": {}, "nbformat": 4, "nbformat_minor": 4}
metadata: A dictionary that contains information about the kernel and language used.
nbformat, nbformat_minor: Notebook format versions (4.0).
cells: Cell is the most important component of JSON file, that contains information about each cell. Each cell is represented by a dictionary having the following components:
{"cell_type": "code", // can be code, markdown or raw"execution_count": null, // null or an integer"metadata": {}, // metadata of the cell: tags,editable,collapsed"outputs": [], // result of code or rendered markdown"source": [] // the input code or source markdown}
The basic idea to merge several Jupyter Notebooks together is to manipulate the contents of the notebook and merge the JSON file together to create one single notebook.
nbconvert is a Python tool that gives researchers the flexibility to deliver information in a timely way across different formats. It can be used to merge the contents of several JSON files. Letβs start with the merging of the notebook using the following steps.
Import nbconvert library: import nbconvert
Read all the IPython Notebooks using .read() function of nbconvert, which reads the notebook in JSON format.
# Reading the notebooksfirst_notebook = nbformat.read(file1, 4)second_notebook = nbformat.read(file2, 4)third_notebook = nbformat.read(file3, 4)
Create a new notebook that will have the merged contents of the above three notebooks. The metadata of the new notebook will be the same as that of the earlier one.
# Creating a new notebookfinal_notebook = nbformat.v4.new_notebook(metadata=first_notebook.metadata)
Concat all the values for the cell key in each of the JSON files. + keyword can be used to merge the dictionary values across the cell key of three IPython Notebooks.
# Concatenating the notebooksfinal_notebook.cells = first_notebook.cells + second_notebook.cells + second_notebook.cells
Finally, save the newly created IPyton Notebook using the .write function from nbconvert library.
# Saving the new notebook nbformat.write(final_notebook, 'final_notebook.ipynb')
The new file having the contents of each of the notebooks is saved to the desired location in few lines of Python code.
In this article, we have discussed how to combine multiple IPython Notebook files into a single notebook using the nbconvert tool. Depending on oneβs requirement, they can make changes to the script and merge the notebooks in an easy and efficient manner.
nbconvert can be used to convert notebooks to other static formats including HTML, LaTeX, etc. It is an interesting package and one can go through the documentation page to get an understanding.
[1] NbConvert Documentation: https://nbconvert.readthedocs.io/en/latest/
Thank You for Reading
|
[
{
"code": null,
"e": 367,
"s": 172,
"text": "Jupyter Notebook is considered an integral part of any Data Scientistβs toolbox. Jupyter Notebook also referred to as IPython Notebooks is a web application based on the server-client structure."
},
{
"code": null,
"e": 603,
"s": 367,
"text": "Jupyter Notebook provides an easy-to-use interactive data science environment that supports various programming languages. It is of great use for prototyping and offers interactive computing by combining code, text, and visualizations."
},
{
"code": null,
"e": 847,
"s": 603,
"text": "It is common to use multiple Jupyter Notebooks for any project development. Sometimes requirement arises to merge several notebooks together and you need to manually do copy-pasting cells of the notebook together, which becomes a tedious task."
},
{
"code": null,
"e": 976,
"s": 847,
"text": "In this article, you can read how to merge several IPython Notebooks together and efficiently, writing few lines of Python code."
},
{
"code": null,
"e": 1236,
"s": 976,
"text": "A Jupyter Notebook is saved as a JSON file format. This JSON file has all the notebook contents, including text, code, outputs, and plots. The figures, images, and videos are encoded as base64 strings. The basic structure of the Jupyter Notebook JSON file is:"
},
{
"code": null,
"e": 1303,
"s": 1236,
"text": "{ \"cells\": [], \"metadata\": {}, \"nbformat\": 4, \"nbformat_minor\": 4}"
},
{
"code": null,
"e": 1388,
"s": 1303,
"text": "metadata: A dictionary that contains information about the kernel and language used."
},
{
"code": null,
"e": 1446,
"s": 1388,
"text": "nbformat, nbformat_minor: Notebook format versions (4.0)."
},
{
"code": null,
"e": 1621,
"s": 1446,
"text": "cells: Cell is the most important component of JSON file, that contains information about each cell. Each cell is represented by a dictionary having the following components:"
},
{
"code": null,
"e": 1888,
"s": 1621,
"text": "{\"cell_type\": \"code\", // can be code, markdown or raw\"execution_count\": null, // null or an integer\"metadata\": {}, // metadata of the cell: tags,editable,collapsed\"outputs\": [], // result of code or rendered markdown\"source\": [] // the input code or source markdown}"
},
{
"code": null,
"e": 2057,
"s": 1888,
"text": "The basic idea to merge several Jupyter Notebooks together is to manipulate the contents of the notebook and merge the JSON file together to create one single notebook."
},
{
"code": null,
"e": 2320,
"s": 2057,
"text": "nbconvert is a Python tool that gives researchers the flexibility to deliver information in a timely way across different formats. It can be used to merge the contents of several JSON files. Letβs start with the merging of the notebook using the following steps."
},
{
"code": null,
"e": 2363,
"s": 2320,
"text": "Import nbconvert library: import nbconvert"
},
{
"code": null,
"e": 2472,
"s": 2363,
"text": "Read all the IPython Notebooks using .read() function of nbconvert, which reads the notebook in JSON format."
},
{
"code": null,
"e": 2617,
"s": 2472,
"text": "# Reading the notebooksfirst_notebook = nbformat.read(file1, 4)second_notebook = nbformat.read(file2, 4)third_notebook = nbformat.read(file3, 4)"
},
{
"code": null,
"e": 2782,
"s": 2617,
"text": "Create a new notebook that will have the merged contents of the above three notebooks. The metadata of the new notebook will be the same as that of the earlier one."
},
{
"code": null,
"e": 2883,
"s": 2782,
"text": "# Creating a new notebookfinal_notebook = nbformat.v4.new_notebook(metadata=first_notebook.metadata)"
},
{
"code": null,
"e": 3050,
"s": 2883,
"text": "Concat all the values for the cell key in each of the JSON files. + keyword can be used to merge the dictionary values across the cell key of three IPython Notebooks."
},
{
"code": null,
"e": 3171,
"s": 3050,
"text": "# Concatenating the notebooksfinal_notebook.cells = first_notebook.cells + second_notebook.cells + second_notebook.cells"
},
{
"code": null,
"e": 3269,
"s": 3171,
"text": "Finally, save the newly created IPyton Notebook using the .write function from nbconvert library."
},
{
"code": null,
"e": 3350,
"s": 3269,
"text": "# Saving the new notebook nbformat.write(final_notebook, 'final_notebook.ipynb')"
},
{
"code": null,
"e": 3470,
"s": 3350,
"text": "The new file having the contents of each of the notebooks is saved to the desired location in few lines of Python code."
},
{
"code": null,
"e": 3726,
"s": 3470,
"text": "In this article, we have discussed how to combine multiple IPython Notebook files into a single notebook using the nbconvert tool. Depending on oneβs requirement, they can make changes to the script and merge the notebooks in an easy and efficient manner."
},
{
"code": null,
"e": 3921,
"s": 3726,
"text": "nbconvert can be used to convert notebooks to other static formats including HTML, LaTeX, etc. It is an interesting package and one can go through the documentation page to get an understanding."
},
{
"code": null,
"e": 3994,
"s": 3921,
"text": "[1] NbConvert Documentation: https://nbconvert.readthedocs.io/en/latest/"
}
] |
Batch Script - ECHO
|
This batch command displays messages, or turns command echoing on or off.
ECHO βstringβ
The following example shows the different variants of the dir command.
Rem Turns the echo on so that each command will be shown as executed
echo on
echo "Hello World"
Rem Turns the echo off so that each command will not be shown when executed
@echo off
echo "Hello World"
Rem Displays the contents of the PATH variable
echo %PATH%
The following output will be displayed in the command prompt.
C:\>Rem Turns the echo on so that each command will be shown as executed
C:\>echo on
C:\>echo "Hello World"
"Hello World"
C:\>Rem Turns the echo off so that each command will not be shown when executed
"Hello World"
C:\Users\ADMINI~1\AppData\Local\Temp
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2243,
"s": 2169,
"text": "This batch command displays messages, or turns command echoing on or off."
},
{
"code": null,
"e": 2258,
"s": 2243,
"text": "ECHO βstringβ\n"
},
{
"code": null,
"e": 2329,
"s": 2258,
"text": "The following example shows the different variants of the dir command."
},
{
"code": null,
"e": 2598,
"s": 2329,
"text": "Rem Turns the echo on so that each command will be shown as executed \necho on \necho \"Hello World\" \n\nRem Turns the echo off so that each command will not be shown when executed \n@echo off \necho \"Hello World\" \n\nRem Displays the contents of the PATH variable \necho %PATH%"
},
{
"code": null,
"e": 2660,
"s": 2598,
"text": "The following output will be displayed in the command prompt."
},
{
"code": null,
"e": 2918,
"s": 2660,
"text": "C:\\>Rem Turns the echo on so that each command will be shown as executed\n\nC:\\>echo on\n\nC:\\>echo \"Hello World\"\n\"Hello World\"\n\nC:\\>Rem Turns the echo off so that each command will not be shown when executed\n\n\"Hello World\"\nC:\\Users\\ADMINI~1\\AppData\\Local\\Temp\n"
},
{
"code": null,
"e": 2925,
"s": 2918,
"text": " Print"
},
{
"code": null,
"e": 2936,
"s": 2925,
"text": " Add Notes"
}
] |
Check if a given string is made up of two alternating characters in C++
|
Here we will see how to check a string is made up of alternating characters or not. If a string is like XYXYXY, it is valid, if a string is like ABCD, that is invalid.
The approach is simple. We will check whether all ith character and i+2 th character are same or not. if they are not same, then return false, otherwise return true.
Live Demo
#include <iostream>
using namespace std;
bool hasAlternateChars(string str){
for (int i = 0; i < str.length() - 2; i++) {
if (str[i] != str[i + 2]) {
return false;
}
}
if (str[0] == str[1])
return false;
return true;
}
int main() {
string str = "XYXYXYX";
if(hasAlternateChars(str)){
cout << "Valid String";
}else{
cout << "Not a Valid String";
}
}
Valid String
|
[
{
"code": null,
"e": 1230,
"s": 1062,
"text": "Here we will see how to check a string is made up of alternating characters or not. If a string is like XYXYXY, it is valid, if a string is like ABCD, that is invalid."
},
{
"code": null,
"e": 1396,
"s": 1230,
"text": "The approach is simple. We will check whether all ith character and i+2 th character are same or not. if they are not same, then return false, otherwise return true."
},
{
"code": null,
"e": 1407,
"s": 1396,
"text": " Live Demo"
},
{
"code": null,
"e": 1820,
"s": 1407,
"text": "#include <iostream>\nusing namespace std;\nbool hasAlternateChars(string str){\n for (int i = 0; i < str.length() - 2; i++) {\n if (str[i] != str[i + 2]) {\n return false;\n }\n } \n if (str[0] == str[1])\n return false; \n return true;\n}\nint main() {\n string str = \"XYXYXYX\";\n if(hasAlternateChars(str)){\n cout << \"Valid String\";\n }else{\n cout << \"Not a Valid String\";\n }\n}"
},
{
"code": null,
"e": 1833,
"s": 1820,
"text": "Valid String"
}
] |
Size of Binary Tree | Practice | GeeksforGeeks
|
Given a binary tree of size N, you have to count number of nodes in it. For example, count of nodes in below tree is 4.
1
/ \
10 39
/
5
Input:
First line of input contains the number of test cases T. For each test case, there will be only a single line of input which is a string representing the tree as described below:
The values in the string are in the order of level order traversal of the tree where, numbers denote node values, and a character βNβ denotes NULL child.
For example:
For the above tree, the string will be: 1 2 3 N N 4 6 N 5 N N 7 N
The values in the string are in the order of level order traversal of the tree where, numbers denote node values, and a character βNβ denotes NULL child.
The values in the string are in the order of level order traversal of the tree where, numbers denote node values, and a character βNβ denotes NULL child.
For example:
For the above tree, the string will be: 1 2 3 N N 4 6 N 5 N N 7 N
For example:
For the above tree, the string will be: 1 2 3 N N 4 6 N 5 N N 7 N
Output:
For each testcase in new line, print the number of nodes.
User Task:
Since this is a functional problem you don't have to worry about input, you just have to complete the function getSize().
Constraints:
1 <= T <= 30
1 <= N <= 104
Example:
Input:
2
1 2 3
10 5 9 N 1 3 6
Output:
3
6
Explanation:
Testcase 2: Given Tree is :
10
/ \
5 9
\ / \
1 3 6
There are six nodes in the tree .
0
shakshamkaushik11 day ago
class Tree{public static int getSize(Node root){ if(root == null){ return 0; } int left = getSize(root.left); int right = getSize(root.right); return left+right+1; }}
0
rahulvishwas26023 days ago
The easy way to get size of a Binary Tree
int getSize(Node* node){ // Your code here if(node==NULL){ return 0; } return getSize(node->left)+getSize(node->right)+1;}
0
ershubhamkewat2 weeks ago
Java solution
if(root==null){
return 0;
}else{
return 1+getSize(root.left)+getSize(root.right);
}
0
harshscode2 weeks ago
if(root==NULL) return 0; if(root->left==NULL and root->right==NULL) return 1; return (1+getSize(root->left)+getSize(root->right));
0
mayank20212 weeks ago
C++ : 0.06/1.12void helper(Node* node, int &ans){ if(node) { ans++; helper(node->left, ans); helper(node->right, ans); } }
int getSize(Node* node){ int ans=0; helper(node, ans); return ans;}
+1
00thirt13n3 weeks ago
1-line C++:
int getSize(Node* node)
{
return node==NULL?0:(1+getSize(node->left)+getSize(node->right));
}
0
00thirt13n3 weeks ago
Simple C++ Solution:
void anyorder(Node* root, int &size){
if(!root) return;
if(root) size++;
anyorder(root->left, size);
anyorder(root->right, size);
}
int getSize(Node* node)
{
int size=0;
anyorder(node, size);
return size;
}
0
rajpateriya1 month ago
public static int getSize(Node root){ if(root == null) { return 0; } int count=0; //keeping postordr trevrsal in mind; count+=getSize(root.left); count+= getSize(root.right); count++; return count;
}
0
dsaconquered1 month ago
int getSize(Node* node){ // Your code here if(node==nullptr) return 0; else{ return 1+getSize(node->left)+getSize(node->right); }}
0
ilihaspatel441 month ago
/* simple C++ implementation vote me on top left small arrow bar if you like it */
int getSize(Node* node)
{
if(node==NULL){
return 0;
}
else{
int count=0;
count++;
count+=getSize(node->left);
count+=getSize(node->right);
return count;
}
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 358,
"s": 238,
"text": "Given a binary tree of size N, you have to count number of nodes in it. For example, count of nodes in below tree is 4."
},
{
"code": null,
"e": 402,
"s": 358,
"text": " 1\n / \\\n 10 39\n /\n5"
},
{
"code": null,
"e": 589,
"s": 402,
"text": "Input:\nFirst line of input contains the number of test cases T. For each test case, there will be only a single line of input which is a string representing the tree as described below: "
},
{
"code": null,
"e": 830,
"s": 589,
"text": "\n\nThe values in the string are in the order of level order traversal of the tree where, numbers denote node values, and a character βNβ denotes NULL child.\n\n\nFor example:\n\n\tFor the above tree, the string will be: 1 2 3 N N 4 6 N 5 N N 7 N\n\n"
},
{
"code": null,
"e": 986,
"s": 830,
"text": "\nThe values in the string are in the order of level order traversal of the tree where, numbers denote node values, and a character βNβ denotes NULL child.\n"
},
{
"code": null,
"e": 1140,
"s": 986,
"text": "The values in the string are in the order of level order traversal of the tree where, numbers denote node values, and a character βNβ denotes NULL child."
},
{
"code": null,
"e": 1223,
"s": 1140,
"text": "\nFor example:\n\n\tFor the above tree, the string will be: 1 2 3 N N 4 6 N 5 N N 7 N\n"
},
{
"code": null,
"e": 1304,
"s": 1223,
"text": "For example:\n\n\tFor the above tree, the string will be: 1 2 3 N N 4 6 N 5 N N 7 N"
},
{
"code": null,
"e": 1370,
"s": 1304,
"text": "Output:\nFor each testcase in new line, print the number of nodes."
},
{
"code": null,
"e": 1503,
"s": 1370,
"text": "User Task:\nSince this is a functional problem you don't have to worry about input, you just have to complete the function getSize()."
},
{
"code": null,
"e": 1583,
"s": 1503,
"text": "Constraints:\n1 <= T <= 30\n1 <= N <= 104\nExample:\nInput:\n2\n1 2 3\n10 5 9 N 1 3 6 "
},
{
"code": null,
"e": 1595,
"s": 1583,
"text": "Output:\n3\n6"
},
{
"code": null,
"e": 1877,
"s": 1595,
"text": "Explanation:\nTestcase 2: Given Tree is :\n 10\n / \\\n 5 9\n \\ / \\\n 1 3 6\nThere are six nodes in the tree .\n "
},
{
"code": null,
"e": 1879,
"s": 1877,
"text": "0"
},
{
"code": null,
"e": 1905,
"s": 1879,
"text": "shakshamkaushik11 day ago"
},
{
"code": null,
"e": 2105,
"s": 1905,
"text": "class Tree{public static int getSize(Node root){ if(root == null){ return 0; } int left = getSize(root.left); int right = getSize(root.right); return left+right+1; }} "
},
{
"code": null,
"e": 2107,
"s": 2105,
"text": "0"
},
{
"code": null,
"e": 2134,
"s": 2107,
"text": "rahulvishwas26023 days ago"
},
{
"code": null,
"e": 2176,
"s": 2134,
"text": "The easy way to get size of a Binary Tree"
},
{
"code": null,
"e": 2308,
"s": 2176,
"text": "int getSize(Node* node){ // Your code here if(node==NULL){ return 0; } return getSize(node->left)+getSize(node->right)+1;}"
},
{
"code": null,
"e": 2310,
"s": 2308,
"text": "0"
},
{
"code": null,
"e": 2336,
"s": 2310,
"text": "ershubhamkewat2 weeks ago"
},
{
"code": null,
"e": 2350,
"s": 2336,
"text": "Java solution"
},
{
"code": null,
"e": 2473,
"s": 2352,
"text": " if(root==null){\n return 0;\n }else{\n return 1+getSize(root.left)+getSize(root.right);\n }"
},
{
"code": null,
"e": 2475,
"s": 2473,
"text": "0"
},
{
"code": null,
"e": 2497,
"s": 2475,
"text": "harshscode2 weeks ago"
},
{
"code": null,
"e": 2635,
"s": 2497,
"text": " if(root==NULL) return 0; if(root->left==NULL and root->right==NULL) return 1; return (1+getSize(root->left)+getSize(root->right));"
},
{
"code": null,
"e": 2637,
"s": 2635,
"text": "0"
},
{
"code": null,
"e": 2659,
"s": 2637,
"text": "mayank20212 weeks ago"
},
{
"code": null,
"e": 2813,
"s": 2659,
"text": "C++ : 0.06/1.12void helper(Node* node, int &ans){ if(node) { ans++; helper(node->left, ans); helper(node->right, ans); } }"
},
{
"code": null,
"e": 2884,
"s": 2813,
"text": "int getSize(Node* node){ int ans=0; helper(node, ans); return ans;}"
},
{
"code": null,
"e": 2887,
"s": 2884,
"text": "+1"
},
{
"code": null,
"e": 2909,
"s": 2887,
"text": "00thirt13n3 weeks ago"
},
{
"code": null,
"e": 2921,
"s": 2909,
"text": "1-line C++:"
},
{
"code": null,
"e": 3019,
"s": 2921,
"text": "int getSize(Node* node)\n{\n return node==NULL?0:(1+getSize(node->left)+getSize(node->right));\n}"
},
{
"code": null,
"e": 3021,
"s": 3019,
"text": "0"
},
{
"code": null,
"e": 3043,
"s": 3021,
"text": "00thirt13n3 weeks ago"
},
{
"code": null,
"e": 3064,
"s": 3043,
"text": "Simple C++ Solution:"
},
{
"code": null,
"e": 3296,
"s": 3064,
"text": "void anyorder(Node* root, int &size){\n if(!root) return;\n if(root) size++;\n anyorder(root->left, size);\n anyorder(root->right, size);\n}\nint getSize(Node* node)\n{\n int size=0;\n anyorder(node, size);\n return size;\n}"
},
{
"code": null,
"e": 3298,
"s": 3296,
"text": "0"
},
{
"code": null,
"e": 3321,
"s": 3298,
"text": "rajpateriya1 month ago"
},
{
"code": null,
"e": 3561,
"s": 3321,
"text": "public static int getSize(Node root){ if(root == null) { return 0; } int count=0; //keeping postordr trevrsal in mind; count+=getSize(root.left); count+= getSize(root.right); count++; return count;"
},
{
"code": null,
"e": 3566,
"s": 3561,
"text": " }"
},
{
"code": null,
"e": 3568,
"s": 3566,
"text": "0"
},
{
"code": null,
"e": 3592,
"s": 3568,
"text": "dsaconquered1 month ago"
},
{
"code": null,
"e": 3746,
"s": 3592,
"text": "int getSize(Node* node){ // Your code here if(node==nullptr) return 0; else{ return 1+getSize(node->left)+getSize(node->right); }}"
},
{
"code": null,
"e": 3748,
"s": 3746,
"text": "0"
},
{
"code": null,
"e": 3773,
"s": 3748,
"text": "ilihaspatel441 month ago"
},
{
"code": null,
"e": 4075,
"s": 3773,
"text": "/* simple C++ implementation vote me on top left small arrow bar if you like it */\nint getSize(Node* node)\n{\n if(node==NULL){\n return 0;\n }\n else{\n int count=0;\n count++;\n count+=getSize(node->left);\n count+=getSize(node->right);\n return count;\n }\n \n \n}"
},
{
"code": null,
"e": 4221,
"s": 4075,
"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": 4257,
"s": 4221,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4267,
"s": 4257,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4277,
"s": 4267,
"text": "\nContest\n"
},
{
"code": null,
"e": 4340,
"s": 4277,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4488,
"s": 4340,
"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": 4696,
"s": 4488,
"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": 4802,
"s": 4696,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
CICS - Handle Abend
|
If a program abends due to some reasons like input-output error, then it can be handled using Handle Abend CICS command. Following is the syntax of Handle Abend command β
EXEC CICS HANDLE ABEND
PROGRAM(name)
LABEL(Label)
CANCEL
RESET
END-EXEC
Program name or label name is used to transfer the control to the program or paragraph if abend occurs. CANCEL is used to cancel previous HANDLE CONDITIONS. RESET is used to re-activate the previously cancelled HANDLE ABEND.
Following is the example of Handle Abend β
IDENTIFICATION DIVISION.
PROGRAM-ID. HELLO.
PROCEDURE DIVISION.
EXEC CICS HANDLE ABEND
LABEL (X0000-HANDLE-ABEND-PARA)
END-EXEC.
X0000-HANDLE-ABEND-PARA.
DISPLAY 'Program Abended'.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2097,
"s": 1926,
"text": "If a program abends due to some reasons like input-output error, then it can be handled using Handle Abend CICS command. Following is the syntax of Handle Abend command β"
},
{
"code": null,
"e": 2195,
"s": 2097,
"text": "EXEC CICS HANDLE ABEND\n PROGRAM(name) \n LABEL(Label) \n CANCEL \n RESET\nEND-EXEC\n"
},
{
"code": null,
"e": 2420,
"s": 2195,
"text": "Program name or label name is used to transfer the control to the program or paragraph if abend occurs. CANCEL is used to cancel previous HANDLE CONDITIONS. RESET is used to re-activate the previously cancelled HANDLE ABEND."
},
{
"code": null,
"e": 2463,
"s": 2420,
"text": "Following is the example of Handle Abend β"
},
{
"code": null,
"e": 2738,
"s": 2463,
"text": "IDENTIFICATION DIVISION. \nPROGRAM-ID. HELLO. \nPROCEDURE DIVISION.\n\nEXEC CICS HANDLE ABEND\n LABEL (X0000-HANDLE-ABEND-PARA)\nEND-EXEC.\n\nX0000-HANDLE-ABEND-PARA.\nDISPLAY 'Program Abended'."
},
{
"code": null,
"e": 2745,
"s": 2738,
"text": " Print"
},
{
"code": null,
"e": 2756,
"s": 2745,
"text": " Add Notes"
}
] |
Introduction to Latent Matrix Factorization Recommender Systems | by Tumas Rackaitis | Towards Data Science
|
Latent Matrix Factorization is an incredibly powerful method to use when creating a Recommender System. Ever since Latent Matrix Factorization was shown to outperform other recommendation methods in the Netflix Recommendation contest, its been a cornerstone in building Recommender Systems. This article will aim to give you some intuition for when to use Latent Matrix Factorization for Recommendation, while also giving some intuition behind why it works. If youβd like to see a full implementation, you can go to my Kaggle kernel: Probabilistic Matrix Factorization.
Before starting, letβs first review the problem weβre trying to solve. Latent Matrix Factorization is an algorithm tackling the Recommendation Problem: Given a set of m users and n items, and set of ratings from user for some items, try to recommend the top items for each user. There are many flavors and alternate deviations of this problem, most of which add more dimensions to the problem, like adding tags. What makes Latent Matrix Factorization powerful is that it yields really strong results from the core problem, and can be a good foundation to build from.
When working with an User-Item matrix of ratings, and reading an article on matrix factorization, the first place to look is in linear algebra. That intuition is correct, but its not exactly what youβd expect.
Traditional Linear Algebra is the bedrock of Machine Learning, and that is because most machine learning applications have something Recommender Systems do not: a data-set without NaNs(incomplete data entries). For example, whenever youβre constructing a model, NaNs, or missing data, are pruned in the data pre-processing step, as most functions cannot work with unfilled values. Functions like Principal Component Analysis are undefined if there are missing values. However, Recommender Systems cannot work if you get rid of NaNs. Those NaNs exist for a reason: not every user has rated every item, and its a bit nonsensical to expect them to. Working with Sparse data is something that can be very different β and thatβs what makes Recommendation an interesting problem.
Sparsity complicates matters. Singular Value Decomposition, a factorization of a m x n Matrix into its singular and orthogonal values, is undefined if any of the entries in the Matrix are undefined. This means we cannot explicitly factorize the Matrix in such a way where we can find which we can find which diagonal(or latent) factors carry the most weight in the data set.
Instead, weβre going to approximate the best factorization of the Matrix, using a technique called Probabilistic Matrix Factorization. This technique is accredited to Simon Funk who used this technique in his FunkSVD algorithm to get very successful in the Netflix contest. For more reading, check out Simonβs original post.
Iβll explain the algorithm, then explain the intuition.
Weβll first initialize two matrices from a Gaussian Distribution(alternatively, randomly initialize them). The first one will be a m x k matrix P while the second will be a k x n matrix Q. When these two matrices multiply with each other, they result in an m x n matrix, which is exactly the size of our Rating matrix in which we are trying to predict. The dimension k is one of our hyper-parameters, which represents the amount of latent factors weβre using to estimate the ratings matrix. Generally, k is between 10β250, but donβt take my word for it β use a line search(or grid search) to find the optimal value for your application.
With our Matrices P, Q, weβll optimize their values by using Stochastic Gradient Descent. Therefore, youβll have two more hyper-parameters to optimize, learning rate and epochs. For each Epoch, weβre going to iterate through every known rating in our original m x n matrix.
Then, weβll get a error or residual value e by subtracting the original rating value by the dot product of the original ratingsβ userβs row in P and its itemβs column in Q.
In normal Stochastic Gradient Descent fashion, weβll update both of the matrices P and Q simultaneously by adding the current row for P and Q by the learning rate times the product of the error times the other Matrixβs values.
Here it is in python. View it fully in my Kaggle Kernel.
#randomly initialize user/item factors from a Gaussian P = np.random.normal(0,.1,(train.n_users,self.num_factors)) Q = np.random.normal(0,.1,(train.n_items,self.num_factors)) #print('fit')for epoch in range(self.num_epochs): for u,i,r_ui in train.all_ratings(): residual = r_ui - np.dot(P[u],Q[i]) temp = P[u,:] # we want to update them at the same time, so we make a temporary variable. P[u,:] += self.alpha * residual * Q[i] Q[i,:] += self.alpha * residual * tempself.P = P self.Q = Qself.trainset = train
Now that we have the algorithm, why does it work and how do we interpret itβs results?
Latent factors represent categories that are present in the data. For k=5 latent factors for a movie data-set, those could represent action, romance, sci-fi, comedy, and horror. With a higher k, you have more specific categories. Whats going is we are trying to predict a user uβs rating of item i. Therefore, we look at P to find a vector representing user u, and their preferences or βaffinityβ toward all of the latent factors. Then, we look at Q to find a vector representing item i and itβs βaffinityβ toward all the latent factors. We get the dot product of these two vectors, which will return us a sense of how much the user likes the item in context of the latent factors.
A great deal of information and inspiration came from this paper on Probabilistic Matrix Factorization and from chapter 3 in Recommender Systems: The Textbook by Charu Aggarwal.
You can find a python implementation here.
|
[
{
"code": null,
"e": 742,
"s": 172,
"text": "Latent Matrix Factorization is an incredibly powerful method to use when creating a Recommender System. Ever since Latent Matrix Factorization was shown to outperform other recommendation methods in the Netflix Recommendation contest, its been a cornerstone in building Recommender Systems. This article will aim to give you some intuition for when to use Latent Matrix Factorization for Recommendation, while also giving some intuition behind why it works. If youβd like to see a full implementation, you can go to my Kaggle kernel: Probabilistic Matrix Factorization."
},
{
"code": null,
"e": 1309,
"s": 742,
"text": "Before starting, letβs first review the problem weβre trying to solve. Latent Matrix Factorization is an algorithm tackling the Recommendation Problem: Given a set of m users and n items, and set of ratings from user for some items, try to recommend the top items for each user. There are many flavors and alternate deviations of this problem, most of which add more dimensions to the problem, like adding tags. What makes Latent Matrix Factorization powerful is that it yields really strong results from the core problem, and can be a good foundation to build from."
},
{
"code": null,
"e": 1519,
"s": 1309,
"text": "When working with an User-Item matrix of ratings, and reading an article on matrix factorization, the first place to look is in linear algebra. That intuition is correct, but its not exactly what youβd expect."
},
{
"code": null,
"e": 2293,
"s": 1519,
"text": "Traditional Linear Algebra is the bedrock of Machine Learning, and that is because most machine learning applications have something Recommender Systems do not: a data-set without NaNs(incomplete data entries). For example, whenever youβre constructing a model, NaNs, or missing data, are pruned in the data pre-processing step, as most functions cannot work with unfilled values. Functions like Principal Component Analysis are undefined if there are missing values. However, Recommender Systems cannot work if you get rid of NaNs. Those NaNs exist for a reason: not every user has rated every item, and its a bit nonsensical to expect them to. Working with Sparse data is something that can be very different β and thatβs what makes Recommendation an interesting problem."
},
{
"code": null,
"e": 2668,
"s": 2293,
"text": "Sparsity complicates matters. Singular Value Decomposition, a factorization of a m x n Matrix into its singular and orthogonal values, is undefined if any of the entries in the Matrix are undefined. This means we cannot explicitly factorize the Matrix in such a way where we can find which we can find which diagonal(or latent) factors carry the most weight in the data set."
},
{
"code": null,
"e": 2993,
"s": 2668,
"text": "Instead, weβre going to approximate the best factorization of the Matrix, using a technique called Probabilistic Matrix Factorization. This technique is accredited to Simon Funk who used this technique in his FunkSVD algorithm to get very successful in the Netflix contest. For more reading, check out Simonβs original post."
},
{
"code": null,
"e": 3049,
"s": 2993,
"text": "Iβll explain the algorithm, then explain the intuition."
},
{
"code": null,
"e": 3686,
"s": 3049,
"text": "Weβll first initialize two matrices from a Gaussian Distribution(alternatively, randomly initialize them). The first one will be a m x k matrix P while the second will be a k x n matrix Q. When these two matrices multiply with each other, they result in an m x n matrix, which is exactly the size of our Rating matrix in which we are trying to predict. The dimension k is one of our hyper-parameters, which represents the amount of latent factors weβre using to estimate the ratings matrix. Generally, k is between 10β250, but donβt take my word for it β use a line search(or grid search) to find the optimal value for your application."
},
{
"code": null,
"e": 3960,
"s": 3686,
"text": "With our Matrices P, Q, weβll optimize their values by using Stochastic Gradient Descent. Therefore, youβll have two more hyper-parameters to optimize, learning rate and epochs. For each Epoch, weβre going to iterate through every known rating in our original m x n matrix."
},
{
"code": null,
"e": 4133,
"s": 3960,
"text": "Then, weβll get a error or residual value e by subtracting the original rating value by the dot product of the original ratingsβ userβs row in P and its itemβs column in Q."
},
{
"code": null,
"e": 4360,
"s": 4133,
"text": "In normal Stochastic Gradient Descent fashion, weβll update both of the matrices P and Q simultaneously by adding the current row for P and Q by the learning rate times the product of the error times the other Matrixβs values."
},
{
"code": null,
"e": 4417,
"s": 4360,
"text": "Here it is in python. View it fully in my Kaggle Kernel."
},
{
"code": null,
"e": 5027,
"s": 4417,
"text": "#randomly initialize user/item factors from a Gaussian P = np.random.normal(0,.1,(train.n_users,self.num_factors)) Q = np.random.normal(0,.1,(train.n_items,self.num_factors)) #print('fit')for epoch in range(self.num_epochs): for u,i,r_ui in train.all_ratings(): residual = r_ui - np.dot(P[u],Q[i]) temp = P[u,:] # we want to update them at the same time, so we make a temporary variable. P[u,:] += self.alpha * residual * Q[i] Q[i,:] += self.alpha * residual * tempself.P = P self.Q = Qself.trainset = train"
},
{
"code": null,
"e": 5114,
"s": 5027,
"text": "Now that we have the algorithm, why does it work and how do we interpret itβs results?"
},
{
"code": null,
"e": 5796,
"s": 5114,
"text": "Latent factors represent categories that are present in the data. For k=5 latent factors for a movie data-set, those could represent action, romance, sci-fi, comedy, and horror. With a higher k, you have more specific categories. Whats going is we are trying to predict a user uβs rating of item i. Therefore, we look at P to find a vector representing user u, and their preferences or βaffinityβ toward all of the latent factors. Then, we look at Q to find a vector representing item i and itβs βaffinityβ toward all the latent factors. We get the dot product of these two vectors, which will return us a sense of how much the user likes the item in context of the latent factors."
},
{
"code": null,
"e": 5974,
"s": 5796,
"text": "A great deal of information and inspiration came from this paper on Probabilistic Matrix Factorization and from chapter 3 in Recommender Systems: The Textbook by Charu Aggarwal."
}
] |
How to parse JSON Data into React Table Component ? - GeeksforGeeks
|
29 Sep, 2021
React JS is a front-end library used to build UI components. In this article, we will learn how to parse JSON Data into React Table Component.
Approach: We will parse a Json file consisting of objects with id, name and city associated uniquely. Now we will parse this data and display it in a table created by react. We will use .map() function to parse each object of JSON file and return <tr> component with JSON object as table data.
Below is the step-by-step implementation of the above approach.
Step 1: Open the terminal and create react app.
npx create-react-app my-first-app
Step 2: Change the directory to that folder by executing the command.
cd my-first-app
Project Structure: It will look like the following.
Make a folder named βMyPracticeβ in src
Step 3: Creating a JSON Object File here and Save it as data.json. In this file, we will create multiple objects with id, name, and city.
File Name: data.json
[
{
"id":1,
"name":"Akshit",
"city":"Moradabad"
},
{
"id":2,
"name":"Nikita",
"city":"Lucknow"
},
{
"id":3,
"name":"Deeksha",
"city":"Noida"
},
{
"id":4,
"name":"Ritesh",
"city":"Delhi"
},
{
"id":5,
"name":"Somya",
"city":"Gurugram"
},
{
"id":6,
"name":"Eshika",
"city":"Mumbai"
},
{
"id":7,
"name":"Kalpana",
"city":"Rampur"
},
{
"id":8,
"name":"Parul",
"city":"Chandigarh"
},
{
"id":9,
"name":"Himani",
"city":"Dehradun"
}
]
Step 4: Create JsonDataDisplay Component and import data from data.json file in this. In this component, we will map each object from JSON file and pass it to function. This function will return a table-row with object_data as table-data
File Name: GeekTable.jsx
Javascript
import React from 'react'import JsonData from './data.json' function JsonDataDisplay(){ const DisplayData=JsonData.map( (info)=>{ return( <tr> <td>{info.id}</td> <td>{info.name}</td> <td>{info.city}</td> </tr> ) } ) return( <div> <table class="table table-striped"> <thead> <tr> <th>Sr.NO</th> <th>Name</th> <th>City</th> </tr> </thead> <tbody> {DisplayData} </tbody> </table> </div> ) } export default JsonDataDisplay;
Step 5: Export this component in App.js. This will render component on the localhost
File Name: App.js
Javascript
import JsonDataDisplay from './MyPractice/GeekTable'function App() { return ( <div className="App"> <h1>Hello Geeks!!!</h1> <JsonDataDisplay/> </div> );} export default App;
Step to run the application: Open the terminal and type the following command.
npm start
Output:
akshitsaxenaa09
Blogathon-2021
React-Questions
Blogathon
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create a Table With Multiple Foreign Keys in SQL?
How to Import JSON Data into SQL Server?
Stratified Sampling in Pandas
How to Install Tkinter in Windows?
Python program to convert XML to Dictionary
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS Functional Components
|
[
{
"code": null,
"e": 26007,
"s": 25979,
"text": "\n29 Sep, 2021"
},
{
"code": null,
"e": 26152,
"s": 26007,
"text": "React JS is a front-end library used to build UI components. In this article, we will learn how to parse JSON Data into React Table Component. "
},
{
"code": null,
"e": 26447,
"s": 26152,
"text": "Approach: We will parse a Json file consisting of objects with id, name and city associated uniquely. Now we will parse this data and display it in a table created by react. We will use .map() function to parse each object of JSON file and return <tr> component with JSON object as table data."
},
{
"code": null,
"e": 26511,
"s": 26447,
"text": "Below is the step-by-step implementation of the above approach."
},
{
"code": null,
"e": 26559,
"s": 26511,
"text": "Step 1: Open the terminal and create react app."
},
{
"code": null,
"e": 26593,
"s": 26559,
"text": "npx create-react-app my-first-app"
},
{
"code": null,
"e": 26667,
"s": 26597,
"text": "Step 2: Change the directory to that folder by executing the command."
},
{
"code": null,
"e": 26685,
"s": 26669,
"text": "cd my-first-app"
},
{
"code": null,
"e": 26739,
"s": 26687,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 26781,
"s": 26741,
"text": "Make a folder named βMyPracticeβ in src"
},
{
"code": null,
"e": 26921,
"s": 26783,
"text": "Step 3: Creating a JSON Object File here and Save it as data.json. In this file, we will create multiple objects with id, name, and city."
},
{
"code": null,
"e": 26944,
"s": 26923,
"text": "File Name: data.json"
},
{
"code": null,
"e": 27697,
"s": 26946,
"text": "[\n\n {\n \"id\":1,\n \"name\":\"Akshit\",\n \"city\":\"Moradabad\"\n },\n \n {\n \"id\":2,\n \"name\":\"Nikita\",\n \"city\":\"Lucknow\"\n },\n \n {\n \"id\":3,\n \"name\":\"Deeksha\",\n \"city\":\"Noida\"\n },\n \n {\n \"id\":4,\n \"name\":\"Ritesh\",\n \"city\":\"Delhi\"\n },\n \n {\n \"id\":5,\n \"name\":\"Somya\",\n \"city\":\"Gurugram\"\n },\n \n {\n \"id\":6,\n \"name\":\"Eshika\",\n \"city\":\"Mumbai\"\n },\n {\n \"id\":7,\n \"name\":\"Kalpana\",\n \"city\":\"Rampur\"\n },\n \n {\n \"id\":8,\n \"name\":\"Parul\",\n \"city\":\"Chandigarh\"\n },\n \n {\n \"id\":9,\n \"name\":\"Himani\",\n \"city\":\"Dehradun\"\n }\n]"
},
{
"code": null,
"e": 27937,
"s": 27699,
"text": "Step 4: Create JsonDataDisplay Component and import data from data.json file in this. In this component, we will map each object from JSON file and pass it to function. This function will return a table-row with object_data as table-data"
},
{
"code": null,
"e": 27964,
"s": 27939,
"text": "File Name: GeekTable.jsx"
},
{
"code": null,
"e": 27977,
"s": 27966,
"text": "Javascript"
},
{
"code": "import React from 'react'import JsonData from './data.json' function JsonDataDisplay(){ const DisplayData=JsonData.map( (info)=>{ return( <tr> <td>{info.id}</td> <td>{info.name}</td> <td>{info.city}</td> </tr> ) } ) return( <div> <table class=\"table table-striped\"> <thead> <tr> <th>Sr.NO</th> <th>Name</th> <th>City</th> </tr> </thead> <tbody> {DisplayData} </tbody> </table> </div> ) } export default JsonDataDisplay;",
"e": 28814,
"s": 27977,
"text": null
},
{
"code": null,
"e": 28903,
"s": 28818,
"text": "Step 5: Export this component in App.js. This will render component on the localhost"
},
{
"code": null,
"e": 28923,
"s": 28905,
"text": "File Name: App.js"
},
{
"code": null,
"e": 28936,
"s": 28925,
"text": "Javascript"
},
{
"code": "import JsonDataDisplay from './MyPractice/GeekTable'function App() { return ( <div className=\"App\"> <h1>Hello Geeks!!!</h1> <JsonDataDisplay/> </div> );} export default App;",
"e": 29129,
"s": 28936,
"text": null
},
{
"code": null,
"e": 29208,
"s": 29129,
"text": "Step to run the application: Open the terminal and type the following command."
},
{
"code": null,
"e": 29218,
"s": 29208,
"text": "npm start"
},
{
"code": null,
"e": 29226,
"s": 29218,
"text": "Output:"
},
{
"code": null,
"e": 29242,
"s": 29226,
"text": "akshitsaxenaa09"
},
{
"code": null,
"e": 29257,
"s": 29242,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 29273,
"s": 29257,
"text": "React-Questions"
},
{
"code": null,
"e": 29283,
"s": 29273,
"text": "Blogathon"
},
{
"code": null,
"e": 29291,
"s": 29283,
"text": "ReactJS"
},
{
"code": null,
"e": 29308,
"s": 29291,
"text": "Web Technologies"
},
{
"code": null,
"e": 29406,
"s": 29308,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29463,
"s": 29406,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 29504,
"s": 29463,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 29534,
"s": 29504,
"text": "Stratified Sampling in Pandas"
},
{
"code": null,
"e": 29569,
"s": 29534,
"text": "How to Install Tkinter in Windows?"
},
{
"code": null,
"e": 29613,
"s": 29569,
"text": "Python program to convert XML to Dictionary"
},
{
"code": null,
"e": 29656,
"s": 29613,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29701,
"s": 29656,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 29766,
"s": 29701,
"text": "How to pass data from child component to its parent in ReactJS ?"
},
{
"code": null,
"e": 29834,
"s": 29766,
"text": "How to pass data from one component to other component in ReactJS ?"
}
] |
How to handle missing values of categorical variables in Python? - GeeksforGeeks
|
28 Sep, 2021
Machine Learning is the field of study that gives computers the capability to learn without being explicitly programmed. Often we come across datasets in which some values are missing from the columns. This causes problems when we apply a machine learning model to the dataset. This increases the chances of error when we are training the machine learning model.
The dataset we are using is:
Python3
# import modulesimport pandas as pdimport numpy as np # assign datasetdf = pd.read_csv("train.csv", header=None)df.head
Counting the missing data:
Python3
# counting number of values of all the columnscnt_missing = (df[[1, 2, 3, 4, 5, 6, 7, 8]] == 0).sum()print(cnt_missing)
We see that for 1,2,3,4,5 column the data is missing. Now we will replace all 0 values with NaN.
Python
from numpy import nandf[[1, 2, 3, 4, 5]] = df[[1, 2, 3, 4, 5]].replace(0, nan)df.head(10)
Handling missing data is important, so we will remove this problem by following approaches:
The first method is to simply remove the rows having the missing data.
Python3
# printing initial shapeprint(df.shape)df.dropna(inplace=True) # final shape of the data with# missing rows removedprint(df.shape)
But in this, the problem that arises is that when we have small datasets and if we remove rows with missing data then the dataset becomes very small and the machine learning model will not give good results on a small dataset.
So to avoid this problem we have a second method. The next method is to input the missing values. We do this by either replacing the missing value with some random value or with the median/mean of the rest of the data.
We first impute missing values by the mean of the data.
Python3
# filling missing values# with mean column valuesdf.fillna(df.mean(), inplace=True)df.sample(10)
We can also do this by using SimpleImputer class. SimpleImputer is a scikit-learn class which is helpful in handling the missing data in the predictive model dataset. It replaces the NaN values with a specified placeholder.It is implemented by the use of the SimpleImputer() method which takes the following arguments:
SimpleImputer(missing_values, strategy, fill_value)
missing_values : The missing_values placeholder which has to be imputed. By default is NaN.
strategy : The data which will replace the NaN values from the dataset. The strategy argument can take the values β βmean'(default), βmedianβ, βmost_frequentβ and βconstantβ.
fill_value : The constant value to be given to the NaN data using the constant strategy.
Python3
# import modulesfrom numpy import isnanfrom sklearn.impute import SimpleImputer value = df.values # defining the imputerimputer = SimpleImputer(missing_values=nan, strategy='mean') # transform the datasettransformed_values = imputer.fit_transform(value) # count the number of NaN values in each columnprint("Missing:", isnan(transformed_values).sum())
We first impute missing values by the median of the data. Median is the middle value of a set of data. To determine the median value in a sequence of numbers, the numbers must first be arranged in ascending order.
Python3
# filling missing values# with mean column valuesdf.fillna(df.median(), inplace=True)df.head(10)
We can also do this by using SimpleImputer class.
Python3
# import modulesfrom numpy import isnanfrom sklearn.impute import SimpleImputervalue = df.values # defining the imputerimputer = SimpleImputer(missing_values=nan, strategy='median') # transform the datasettransformed_values = imputer.fit_transform(value) # count the number of NaN values in each columnprint("Missing:", isnan(transformed_values).sum())
We first impute missing values by the mode of the data. The mode is the value that occurs most frequently in a set of observations. For example, {6, 3, 9, 6, 6, 5, 9, 3} the Mode is 6, as it occurs most often.
Python3
# filling missing values# with mean column valuesdf.fillna(df.mode(), inplace=True)df.sample(10)
We can also do this by using SimpleImputer class.
Python3
# import modulesfrom numpy import isnanfrom sklearn.impute import SimpleImputervalue = df.values # defining the imputerimputer = SimpleImputer(missing_values=nan, strategy='most_frequent') # transform the datasettransformed_values = imputer.fit_transform(value) # count the number of NaN values in each columnprint("Missing:", isnan(transformed_values).sum())
simmytarika5
Picked
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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": "\n28 Sep, 2021"
},
{
"code": null,
"e": 25901,
"s": 25537,
"text": "Machine Learning is the field of study that gives computers the capability to learn without being explicitly programmed. Often we come across datasets in which some values are missing from the columns. This causes problems when we apply a machine learning model to the dataset. This increases the chances of error when we are training the machine learning model. "
},
{
"code": null,
"e": 25930,
"s": 25901,
"text": "The dataset we are using is:"
},
{
"code": null,
"e": 25938,
"s": 25930,
"text": "Python3"
},
{
"code": "# import modulesimport pandas as pdimport numpy as np # assign datasetdf = pd.read_csv(\"train.csv\", header=None)df.head",
"e": 26058,
"s": 25938,
"text": null
},
{
"code": null,
"e": 26085,
"s": 26058,
"text": "Counting the missing data:"
},
{
"code": null,
"e": 26093,
"s": 26085,
"text": "Python3"
},
{
"code": "# counting number of values of all the columnscnt_missing = (df[[1, 2, 3, 4, 5, 6, 7, 8]] == 0).sum()print(cnt_missing)",
"e": 26231,
"s": 26093,
"text": null
},
{
"code": null,
"e": 26328,
"s": 26231,
"text": "We see that for 1,2,3,4,5 column the data is missing. Now we will replace all 0 values with NaN."
},
{
"code": null,
"e": 26335,
"s": 26328,
"text": "Python"
},
{
"code": "from numpy import nandf[[1, 2, 3, 4, 5]] = df[[1, 2, 3, 4, 5]].replace(0, nan)df.head(10)",
"e": 26425,
"s": 26335,
"text": null
},
{
"code": null,
"e": 26517,
"s": 26425,
"text": "Handling missing data is important, so we will remove this problem by following approaches:"
},
{
"code": null,
"e": 26588,
"s": 26517,
"text": "The first method is to simply remove the rows having the missing data."
},
{
"code": null,
"e": 26596,
"s": 26588,
"text": "Python3"
},
{
"code": "# printing initial shapeprint(df.shape)df.dropna(inplace=True) # final shape of the data with# missing rows removedprint(df.shape)",
"e": 26727,
"s": 26596,
"text": null
},
{
"code": null,
"e": 26955,
"s": 26727,
"text": "But in this, the problem that arises is that when we have small datasets and if we remove rows with missing data then the dataset becomes very small and the machine learning model will not give good results on a small dataset. "
},
{
"code": null,
"e": 27174,
"s": 26955,
"text": "So to avoid this problem we have a second method. The next method is to input the missing values. We do this by either replacing the missing value with some random value or with the median/mean of the rest of the data."
},
{
"code": null,
"e": 27230,
"s": 27174,
"text": "We first impute missing values by the mean of the data."
},
{
"code": null,
"e": 27238,
"s": 27230,
"text": "Python3"
},
{
"code": "# filling missing values# with mean column valuesdf.fillna(df.mean(), inplace=True)df.sample(10)",
"e": 27335,
"s": 27238,
"text": null
},
{
"code": null,
"e": 27654,
"s": 27335,
"text": "We can also do this by using SimpleImputer class. SimpleImputer is a scikit-learn class which is helpful in handling the missing data in the predictive model dataset. It replaces the NaN values with a specified placeholder.It is implemented by the use of the SimpleImputer() method which takes the following arguments:"
},
{
"code": null,
"e": 27707,
"s": 27654,
"text": "SimpleImputer(missing_values, strategy, fill_value) "
},
{
"code": null,
"e": 27799,
"s": 27707,
"text": "missing_values : The missing_values placeholder which has to be imputed. By default is NaN."
},
{
"code": null,
"e": 27974,
"s": 27799,
"text": "strategy : The data which will replace the NaN values from the dataset. The strategy argument can take the values β βmean'(default), βmedianβ, βmost_frequentβ and βconstantβ."
},
{
"code": null,
"e": 28063,
"s": 27974,
"text": "fill_value : The constant value to be given to the NaN data using the constant strategy."
},
{
"code": null,
"e": 28071,
"s": 28063,
"text": "Python3"
},
{
"code": "# import modulesfrom numpy import isnanfrom sklearn.impute import SimpleImputer value = df.values # defining the imputerimputer = SimpleImputer(missing_values=nan, strategy='mean') # transform the datasettransformed_values = imputer.fit_transform(value) # count the number of NaN values in each columnprint(\"Missing:\", isnan(transformed_values).sum())",
"e": 28446,
"s": 28071,
"text": null
},
{
"code": null,
"e": 28665,
"s": 28451,
"text": "We first impute missing values by the median of the data. Median is the middle value of a set of data. To determine the median value in a sequence of numbers, the numbers must first be arranged in ascending order."
},
{
"code": null,
"e": 28675,
"s": 28667,
"text": "Python3"
},
{
"code": "# filling missing values# with mean column valuesdf.fillna(df.median(), inplace=True)df.head(10)",
"e": 28772,
"s": 28675,
"text": null
},
{
"code": null,
"e": 28827,
"s": 28777,
"text": "We can also do this by using SimpleImputer class."
},
{
"code": null,
"e": 28837,
"s": 28829,
"text": "Python3"
},
{
"code": "# import modulesfrom numpy import isnanfrom sklearn.impute import SimpleImputervalue = df.values # defining the imputerimputer = SimpleImputer(missing_values=nan, strategy='median') # transform the datasettransformed_values = imputer.fit_transform(value) # count the number of NaN values in each columnprint(\"Missing:\", isnan(transformed_values).sum())",
"e": 29213,
"s": 28837,
"text": null
},
{
"code": null,
"e": 29423,
"s": 29213,
"text": "We first impute missing values by the mode of the data. The mode is the value that occurs most frequently in a set of observations. For example, {6, 3, 9, 6, 6, 5, 9, 3} the Mode is 6, as it occurs most often."
},
{
"code": null,
"e": 29431,
"s": 29423,
"text": "Python3"
},
{
"code": "# filling missing values# with mean column valuesdf.fillna(df.mode(), inplace=True)df.sample(10)",
"e": 29528,
"s": 29431,
"text": null
},
{
"code": null,
"e": 29583,
"s": 29533,
"text": "We can also do this by using SimpleImputer class."
},
{
"code": null,
"e": 29593,
"s": 29585,
"text": "Python3"
},
{
"code": "# import modulesfrom numpy import isnanfrom sklearn.impute import SimpleImputervalue = df.values # defining the imputerimputer = SimpleImputer(missing_values=nan, strategy='most_frequent') # transform the datasettransformed_values = imputer.fit_transform(value) # count the number of NaN values in each columnprint(\"Missing:\", isnan(transformed_values).sum())",
"e": 29976,
"s": 29593,
"text": null
},
{
"code": null,
"e": 29989,
"s": 29976,
"text": "simmytarika5"
},
{
"code": null,
"e": 29996,
"s": 29989,
"text": "Picked"
},
{
"code": null,
"e": 30010,
"s": 29996,
"text": "Python-pandas"
},
{
"code": null,
"e": 30017,
"s": 30010,
"text": "Python"
},
{
"code": null,
"e": 30115,
"s": 30017,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30147,
"s": 30115,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30189,
"s": 30147,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30231,
"s": 30189,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30258,
"s": 30231,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 30314,
"s": 30258,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30336,
"s": 30314,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 30375,
"s": 30336,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 30406,
"s": 30375,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30435,
"s": 30406,
"text": "Create a directory in Python"
}
] |
C Program for Reverse a linked list - GeeksforGeeks
|
20 Dec, 2018
Given pointer to the head node of a linked list, the task is to reverse the linked list. We need to reverse the list by changing links between nodes.
Examples:
Input : Head of following linked list
1->2->3->4->NULL
Output : Linked list should be changed to,
4->3->2->1->NULL
Input : Head of following linked list
1->2->3->4->5->NULL
Output : Linked list should be changed to,
5->4->3->2->1->NULL
Input : NULL
Output : NULL
Input : 1->NULL
Output : 1->NULL
Iterative Method
C
#include<stdio.h>#include<stdlib.h> /* Link list node */struct Node{ int data; struct Node* next;}; /* Function to reverse the linked list */static void reverse(struct Node** head_ref){ struct Node* prev = NULL; struct Node* current = *head_ref; struct Node* next; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } *head_ref = prev;} /* Function to push a node */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print linked list */void printList(struct Node *head){ struct Node *temp = head; while(temp != NULL) { printf("%d ", temp->data); temp = temp->next; }} /* Driver program to test above function*/int main(){ /* Start with the empty list */ struct Node* head = NULL; push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 85); printf("Given linked list\n"); printList(head); reverse(&head); printf("\nReversed Linked list \n"); printList(head); getchar();}
void recursiveReverse(struct Node** head_ref){ struct Node* first; struct Node* rest; /* empty list */ if (*head_ref == NULL) return; /* suppose first = {1, 2, 3}, rest = {2, 3} */ first = *head_ref; rest = first->next; /* List has only one node */ if (rest == NULL) return; /* reverse the rest list and put the first element at the end */ recursiveReverse(&rest); first->next->next = first; /* tricky step -- see the diagram */ first->next = NULL; /* fix the head pointer */ *head_ref = rest; }
A Simpler and Tail Recursive Method
C++
// A simple and tail recursive C++ program to reverse// a linked list#include<bits/stdc++.h>using namespace std; struct Node{ int data; struct Node *next;}; void reverseUtil(Node *curr, Node *prev, Node **head); // This function mainly calls reverseUtil()// with prev as NULLvoid reverse(Node **head){ if (!head) return; reverseUtil(*head, NULL, head);} // A simple and tail recursive function to reverse// a linked list. prev is passed as NULL initially.void reverseUtil(Node *curr, Node *prev, Node **head){ /* If last node mark it head*/ if (!curr->next) { *head = curr; /* Update next to prev node */ curr->next = prev; return; } /* Save curr->next node for recursive call */ node *next = curr->next; /* and update next ..*/ curr->next = prev; reverseUtil(next, curr, head);} // A utility function to create a new nodeNode *newNode(int key){ Node *temp = new Node; temp->data = key; temp->next = NULL; return temp;} // A utility function to print a linked listvoid printlist(Node *head){ while(head != NULL) { cout << head->data << " "; head = head->next; } cout << endl;} // Driver program to test above functionsint main(){ Node *head1 = newNode(1); head1->next = newNode(2); head1->next->next = newNode(3); head1->next->next->next = newNode(4); head1->next->next->next->next = newNode(5); head1->next->next->next->next->next = newNode(6); head1->next->next->next->next->next->next = newNode(7); head1->next->next->next->next->next->next->next = newNode(8); cout << "Given linked list\n"; printlist(head1); reverse(&head1); cout << "\nReversed linked list\n"; printlist(head1); return 0;}
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
Exit codes in C/C++ with Examples
C program to find the length of a string
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
Handling multiple clients on server with multithreading using Socket Programming in C/C++
Regular expressions in C
Conditional wait and signal in multi-threading
Create n-child process from same parent process using fork() in C
How to store words in an array in C?
|
[
{
"code": null,
"e": 26175,
"s": 26147,
"text": "\n20 Dec, 2018"
},
{
"code": null,
"e": 26325,
"s": 26175,
"text": "Given pointer to the head node of a linked list, the task is to reverse the linked list. We need to reverse the list by changing links between nodes."
},
{
"code": null,
"e": 26335,
"s": 26325,
"text": "Examples:"
},
{
"code": null,
"e": 26668,
"s": 26335,
"text": "Input : Head of following linked list \n 1->2->3->4->NULL\nOutput : Linked list should be changed to,\n 4->3->2->1->NULL\n\nInput : Head of following linked list \n 1->2->3->4->5->NULL\nOutput : Linked list should be changed to,\n 5->4->3->2->1->NULL\n\nInput : NULL\nOutput : NULL\n\nInput : 1->NULL\nOutput : 1->NULL\n"
},
{
"code": null,
"e": 26685,
"s": 26668,
"text": "Iterative Method"
},
{
"code": null,
"e": 26687,
"s": 26685,
"text": "C"
},
{
"code": "#include<stdio.h>#include<stdlib.h> /* Link list node */struct Node{ int data; struct Node* next;}; /* Function to reverse the linked list */static void reverse(struct Node** head_ref){ struct Node* prev = NULL; struct Node* current = *head_ref; struct Node* next; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } *head_ref = prev;} /* Function to push a node */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print linked list */void printList(struct Node *head){ struct Node *temp = head; while(temp != NULL) { printf(\"%d \", temp->data); temp = temp->next; }} /* Driver program to test above function*/int main(){ /* Start with the empty list */ struct Node* head = NULL; push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 85); printf(\"Given linked list\\n\"); printList(head); reverse(&head); printf(\"\\nReversed Linked list \\n\"); printList(head); getchar();}",
"e": 28188,
"s": 26687,
"text": null
},
{
"code": "void recursiveReverse(struct Node** head_ref){ struct Node* first; struct Node* rest; /* empty list */ if (*head_ref == NULL) return; /* suppose first = {1, 2, 3}, rest = {2, 3} */ first = *head_ref; rest = first->next; /* List has only one node */ if (rest == NULL) return; /* reverse the rest list and put the first element at the end */ recursiveReverse(&rest); first->next->next = first; /* tricky step -- see the diagram */ first->next = NULL; /* fix the head pointer */ *head_ref = rest; }",
"e": 28801,
"s": 28188,
"text": null
},
{
"code": null,
"e": 28837,
"s": 28801,
"text": "A Simpler and Tail Recursive Method"
},
{
"code": null,
"e": 28841,
"s": 28837,
"text": "C++"
},
{
"code": "// A simple and tail recursive C++ program to reverse// a linked list#include<bits/stdc++.h>using namespace std; struct Node{ int data; struct Node *next;}; void reverseUtil(Node *curr, Node *prev, Node **head); // This function mainly calls reverseUtil()// with prev as NULLvoid reverse(Node **head){ if (!head) return; reverseUtil(*head, NULL, head);} // A simple and tail recursive function to reverse// a linked list. prev is passed as NULL initially.void reverseUtil(Node *curr, Node *prev, Node **head){ /* If last node mark it head*/ if (!curr->next) { *head = curr; /* Update next to prev node */ curr->next = prev; return; } /* Save curr->next node for recursive call */ node *next = curr->next; /* and update next ..*/ curr->next = prev; reverseUtil(next, curr, head);} // A utility function to create a new nodeNode *newNode(int key){ Node *temp = new Node; temp->data = key; temp->next = NULL; return temp;} // A utility function to print a linked listvoid printlist(Node *head){ while(head != NULL) { cout << head->data << \" \"; head = head->next; } cout << endl;} // Driver program to test above functionsint main(){ Node *head1 = newNode(1); head1->next = newNode(2); head1->next->next = newNode(3); head1->next->next->next = newNode(4); head1->next->next->next->next = newNode(5); head1->next->next->next->next->next = newNode(6); head1->next->next->next->next->next->next = newNode(7); head1->next->next->next->next->next->next->next = newNode(8); cout << \"Given linked list\\n\"; printlist(head1); reverse(&head1); cout << \"\\nReversed linked list\\n\"; printlist(head1); return 0;}",
"e": 30606,
"s": 28841,
"text": null
},
{
"code": null,
"e": 30617,
"s": 30606,
"text": "C Programs"
},
{
"code": null,
"e": 30715,
"s": 30617,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30756,
"s": 30715,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 30787,
"s": 30756,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 30821,
"s": 30787,
"text": "Exit codes in C/C++ with Examples"
},
{
"code": null,
"e": 30862,
"s": 30821,
"text": "C program to find the length of a string"
},
{
"code": null,
"e": 30933,
"s": 30862,
"text": "C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 31023,
"s": 30933,
"text": "Handling multiple clients on server with multithreading using Socket Programming in C/C++"
},
{
"code": null,
"e": 31048,
"s": 31023,
"text": "Regular expressions in C"
},
{
"code": null,
"e": 31095,
"s": 31048,
"text": "Conditional wait and signal in multi-threading"
},
{
"code": null,
"e": 31161,
"s": 31095,
"text": "Create n-child process from same parent process using fork() in C"
}
] |
Check if a number is multiple of 5 without using / and % operators - GeeksforGeeks
|
05 May, 2022
Given a positive number n, write a function isMultipleof5(int n) that returns true if n is multiple of 5, otherwise false. You are not allowed to use % and / operators.
Method 1 (Repeatedly subtract 5 from n) Run a loop and subtract 5 from n in the loop while n is greater than 0. After the loop terminates, check whether n is 0. If n becomes 0 then n is multiple of 5, otherwise not.
Below is the implementation of the above approach:
C++
C
Java
Python3
C#
PHP
Javascript
#include <iostream>using namespace std; // assumes that n is a positive integerbool isMultipleof5 (int n){ while ( n > 0 ) n = n - 5; if ( n == 0 ) return true; return false;} // Driver Codeint main(){ int n = 19; if ( isMultipleof5(n) == true ) cout << n <<" is multiple of 5"; else cout << n << " is not a multiple of 5"; return 0;} // This code is contributed by SHUBHAMSINGH10
#include<stdio.h> // assumes that n is a positive integerbool isMultipleof5 (int n){ while ( n > 0 ) n = n - 5; if ( n == 0 ) return true; return false;} // Driver Codeint main(){ int n = 19; if ( isMultipleof5(n) == true ) printf("%d is multiple of 5\n", n); else printf("%d is not a multiple of 5\n", n); return 0;}
// Java code to check if a number// is multiple of 5 without using// '/' and '%' operatorsclass GFG{ // assumes that n is a positive integerstatic boolean isMultipleof5 (int n){ while (n > 0) n = n - 5; if (n == 0) return true; return false;} // Driver Codepublic static void main(String[] args){ int n = 19; if (isMultipleof5(n) == true) System.out.printf("%d is multiple of 5\n", n); else System.out.printf("%d is not a multiple of 5\n", n);}} // This code is contributed by Smitha DInesh Semwal
# Python code to check# if a number is multiple of# 5 without using / and % # Assumes that n is a positive integerdef isMultipleof5(n): while ( n > 0 ): n = n - 5 if ( n == 0 ): return 1 return 0 # Driver Codei = 19if ( isMultipleof5(i) == 1 ): print (i, "is multiple of 5")else: print (i, "is not a multiple of 5") # This code is contributed# by Sumit Sudhakar
// C# code to check if a number// is multiple of 5 without using /// and % operatorsusing System; class GFG{ // assumes that n is a positive integerstatic bool isMultipleof5 (int n){ while (n > 0) n = n - 5; if (n == 0) return true; return false;} // Driver Codepublic static void Main(){ int n = 19; if (isMultipleof5(n) == true) Console.Write(n + " is multiple of 5\n"); else Console.Write(n + " is not a multiple of 5\n");}} // This code is contributed by nitin mittal.
<?php// assumes that n is a positive integerfunction isMultipleof5 ($n){ while ( $n > 0 ) $n = $n - 5; if ( $n == 0 ) return true; return false;} // Driver Code $n = 19; if ( isMultipleof5($n) == true ) echo("$n is multiple of 5"); else echo("$n is not a multiple of 5" ); // This code is contributed by nitin mittal.?>
<script> // JavaScript program for the above approach // assumes that n is a positive integerfunction isMultipleof5 (n){ while (n > 0) n = n - 5; if (n == 0) return true; return false;} // Driver Code let n = 19; if (isMultipleof5(n) == true) document.write(n + " is multiple of 5\n"); else document.write(n + " is not a multiple of 5\n"); </script>
19 is not a multiple of 5
Time Complexity: O(n / 5)Auxiliary Space: O(1)
Method 2 (Convert to string and check the last character) Convert n to a string and check the last character of the string. If the last character is β5β or β0β then n is a multiple of 5, otherwise not.
Below is the implementation of the above approach:
C++
C
Java
Python3
C#
PHP
Javascript
#include <bits/stdc++.h>using namespace std; // Assuming that integer takes 4 bytes, there// can be maximum 10 digits in a integer#define MAX 20 bool isMultipleof5(int n){ // in-built method to convert integer to string string str = to_string(n); int len = str.size(); // Check the last character of string if (str[len - 1] == '5' || str[len - 1] == '0') return true; return false;} // Driver Codeint main(){ int n = 19; if (isMultipleof5(n) == true) cout << n << " is multiple of 5" << endl; else cout << n << " is not multiple of 5" << endl; return 0;} // This code is contributed by SHUBHAMSINGH10
#include<stdio.h>#include<stdlib.h>#include<string.h>#include <stdbool.h> // Assuming that integer takes 4 bytes, there// can be maximum 10 digits in a integer# define MAX 11 bool isMultipleof5(int n){ char str[MAX]; // in-built method to convert integer to string sprintf(str, "%d", n); int len = strlen(str); printf("%d\n", len); // Check the last character of string if ( str[len - 1] == '5' || str[len - 1] == '0' ) return true; return false;} // Driver Codeint main(){ int n = 19; if ( isMultipleof5(n) == true ) printf("%d is multiple of 5\n", n); else printf("%d is not a multiple of 5\n", n); return 0;}
// Assuming that integer// takes 4 bytes, there// can be maximum 10// digits in a integerclass GFG{static int MAX = 11; static boolean isMultipleof5(int n){ // in-built method to convert integer to string String str = Integer.toString(n); int len = str.length(); // Check the last // character of string if (str.charAt(len - 1) == '5' || str.charAt(len - 1) == '0' ) return true; return false;} // Driver Codepublic static void main(String[] args){ int n = 19; if ( isMultipleof5(n) == true ) System.out.println(n +" is multiple " + "of 5"); else System.out.println(n +" is not a " + "multiple of 5");}} // This code is contributed by mits
# Assuming that integer# takes 4 bytes, there# can be maximum 10# digits in a integerMAX = 11; def isMultipleof5(n): # in-built method to convert integer to string s = str(n); l = len(s); # Check the last # character of string if (s[l - 1] == '5' or s[l - 1] == '0'): return True; return False; # Driver Coden = 19;if (isMultipleof5(n) == True ): print(n, "is multiple of 5");else: print(n, "is not a multiple of 5"); # This code is contributed by mits
using System; // Assuming that integer// takes 4 bytes, there// can be maximum 10// digits in a integerclass GFG{ static bool isMultipleof5(int n){ // in-built method to convert integer to string String str = n.ToString(); int len = str.Length; // Check the last // character of string if (str[len - 1] == '5' || str[len - 1] == '0' ) return true; return false;} // Driver Codestatic void Main(){ int n = 19; if ( isMultipleof5(n) == true ) Console.WriteLine("{0} is " + "multiple of 5", n); else Console.WriteLine("{0} is not a " + "multiple of 5", n);}} // This code is contributed by mits
<?php// Assuming that integer// takes 4 bytes, there// can be maximum 10// digits in a integer$MAX = 11; function isMultipleof5($n){ global $MAX; $str = (string)$n; $len = strlen($str); // Check the last // character of string if ($str[$len - 1] == '5' || $str[$len - 1] == '0') return true; return false;} // Driver Code$n = 19;if (isMultipleof5($n) == true ) echo "$n is multiple of 5";else echo "$n is not a multiple of 5"; // This code is contributed by mits?>
<script> // Assuming that integer// takes 4 bytes, there// can be maximum 10// digits in a integerMAX = 11; function isMultipleof5(n){ str = Array(n).fill(''); var len = str.length; // Check the last // character of string if (str[len - 1] == '5' || str[len - 1] == '0' ) return true; return false;} // Driver Codevar n = 19;if ( isMultipleof5(n) == true ) document.write(n +" is multiple " + "of 5");else document.write(n +" is not a " + "multiple of 5"); // This code is contributed by Amit Katiyar</script>
19 is not multiple of 5
Time Complexity: O(1)Auxiliary Space: O(MAX)
Thanks to Baban_Rathore for suggesting this method.Method 3 (Set last digit as 0 and use floating point trick) A number n can be a multiple of 5 in two cases. When last digit of n is 5 or 10. If last bit in binary equivalent of n is set (which can be the case when last digit is 5) then we multiply by 2 using n<<=1 to make sure that if the number is multiple of 5 then we have the last digit as 0. Once we do that, our work is to just check if the last digit is 0 or not, which we can do using float and integer comparison trick.
Below is the implementation of the above approach:
C++
C
Java
Python3
C#
PHP
Javascript
#include <iostream>using namespace std;bool isMultipleof5(int n){ // If n is a multiple of 5 then we // make sure that last digit of n is 0 if ( (n & 1) == 1 ) n <<= 1; float x = n; x = ( (int)(x * 0.1) ) * 10; // If last digit of n is 0 then n // will be equal to (int)x if ( (int)x == n ) return true; return false;} // Driver Codeint main(){ int i = 19; if ( isMultipleof5(i) == true ) cout << i <<" is multiple of 5\n"; else cout << i << " is not a multiple of 5\n"; getchar(); return 0;} // This code is contributed by shubhamsingh10
#include<stdio.h> bool isMultipleof5(int n){ // If n is a multiple of 5 then we // make sure that last digit of n is 0 if ( (n & 1) == 1 ) n <<= 1; float x = n; x = ( (int)(x * 0.1) ) * 10; // If last digit of n is 0 then n // will be equal to (int)x if ( (int)x == n ) return true; return false;} // Driver Codeint main(){ int i = 19; if ( isMultipleof5(i) == true ) printf("%d is multiple of 5\n", i); else printf("%d is not a multiple of 5\n", i); getchar(); return 0;}
// Java code to check if// a number is multiple of// 5 without using / and %class GFG{static boolean isMultipleof5(int n){ // If n is a multiple of 5 // then we make sure that // last digit of n is 0 if ((n & 1) == 1) n <<= 1; float x = n; x = ((int)(x * 0.1)) * 10; // If last digit of n is // 0 then n will be equal // to (int)x if ((int)x == n) return true; return false;} // Driver Codepublic static void main(String[] args){ int i = 19; if (isMultipleof5(i) == true) System.out.println(i + "is multiple of 5"); else System.out.println(i + " is not a " + "multiple of 5");}} // This code is contributed// by mits
# Python code to check# if a number is multiple of# 5 without using / and % def isMultipleof5(n): # If n is a multiple of 5 then we # make sure that last digit of n is 0 if ( (n & 1) == 1 ): n <<= 1; x = n x = ( (int)(x * 0.1) ) * 10 # If last digit of n is 0 # then n will be equal to x if ( x == n ): return 1 return 0 # Driver Codei = 19if ( isMultipleof5(i) == 1 ): print (i, "is multiple of 5")else: print (i, "is not a multiple of 5") # This code is contributed# by Sumit Sudhakar
// C# code to check if// a number is multiple of// 5 without using / and %class GFG{static bool isMultipleof5(int n){ // If n is a multiple of 5 // then we make sure that // last digit of n is 0 if ((n & 1) == 1) n <<= 1; float x = n; x = ((int)(x * 0.1)) * 10; // If last digit of n is // 0 then n will be equal // to (int)x if ((int)x == n) return true; return false;} // Driver Codepublic static void Main(){ int i = 19; if (isMultipleof5(i) == true) System.Console.WriteLine(i + "is multiple of 5"); else System.Console.WriteLine(i + " is not a " + "multiple of 5");}} // This code is contributed// by mits
<?phpfunction isMultipleof5($n){ // If n is a multiple of 5 // then we make sure that // last digit of n is 0 if (($n & 1) == 1 ) $n <<= 1; $x = $n; $x = ((int)($x * 0.1)) * 10; // If last digit of n // is 0 then n will be // equal to (int)x if ( (int)($x) == $n ) return true; return false;} // Driver Code$i = 19;if ( isMultipleof5($i) == true ) echo "$i is multiple of 5\n";else echo "$i is not a multiple of 5\n"; // This code is contributed by mits?>
<script>// JavaScript code to check if// a number is multiple of// 5 without using / and %function isMultipleof5( n){ // If n is a multiple of 5 then we // make sure that last digit of n is 0 if ( (n & 1) == 1 ) n <<= 1; x = ( (int)(x * 0.1) ) * 10; // If last digit of n is 0 then n // will be equal to (int)x if ( (int)(x == n)) return true; return false;} // Driver Code i = 19; if ( isMultipleof5 == true) document.write( i + " is multiple of 5\n"); else document.write( i + " is not a multiple of 5\n"); // This code is contributed by simranarora5sos </script>
19 is not a multiple of 5
Time Complexity: O(1)Auxiliary Space: O(1)
Thanks to darkprince for suggesting this method.Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem.
Smitha Dinesh Semwal
nitin mittal
Mithun Kumar
SHUBHAMSINGH10
code_hunt
amit143katiyar
simranarora5sos
kapoorsagar226
subhammahato348
subham348
souravmahato348
arorakashish0911
harendrakumar123
Mathematical
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
Program to find GCD or HCF of two numbers
Sieve of Eratosthenes
Print all possible combinations of r elements in a given array of size n
Operators in C / C++
The Knight's tour problem | Backtracking-1
Program for factorial of a number
Program for Decimal to Binary Conversion
|
[
{
"code": null,
"e": 26554,
"s": 26526,
"text": "\n05 May, 2022"
},
{
"code": null,
"e": 26724,
"s": 26554,
"text": "Given a positive number n, write a function isMultipleof5(int n) that returns true if n is multiple of 5, otherwise false. You are not allowed to use % and / operators. "
},
{
"code": null,
"e": 26941,
"s": 26724,
"text": "Method 1 (Repeatedly subtract 5 from n) Run a loop and subtract 5 from n in the loop while n is greater than 0. After the loop terminates, check whether n is 0. If n becomes 0 then n is multiple of 5, otherwise not. "
},
{
"code": null,
"e": 26992,
"s": 26941,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26996,
"s": 26992,
"text": "C++"
},
{
"code": null,
"e": 26998,
"s": 26996,
"text": "C"
},
{
"code": null,
"e": 27003,
"s": 26998,
"text": "Java"
},
{
"code": null,
"e": 27011,
"s": 27003,
"text": "Python3"
},
{
"code": null,
"e": 27014,
"s": 27011,
"text": "C#"
},
{
"code": null,
"e": 27018,
"s": 27014,
"text": "PHP"
},
{
"code": null,
"e": 27029,
"s": 27018,
"text": "Javascript"
},
{
"code": "#include <iostream>using namespace std; // assumes that n is a positive integerbool isMultipleof5 (int n){ while ( n > 0 ) n = n - 5; if ( n == 0 ) return true; return false;} // Driver Codeint main(){ int n = 19; if ( isMultipleof5(n) == true ) cout << n <<\" is multiple of 5\"; else cout << n << \" is not a multiple of 5\"; return 0;} // This code is contributed by SHUBHAMSINGH10",
"e": 27462,
"s": 27029,
"text": null
},
{
"code": "#include<stdio.h> // assumes that n is a positive integerbool isMultipleof5 (int n){ while ( n > 0 ) n = n - 5; if ( n == 0 ) return true; return false;} // Driver Codeint main(){ int n = 19; if ( isMultipleof5(n) == true ) printf(\"%d is multiple of 5\\n\", n); else printf(\"%d is not a multiple of 5\\n\", n); return 0;}",
"e": 27832,
"s": 27462,
"text": null
},
{
"code": "// Java code to check if a number// is multiple of 5 without using// '/' and '%' operatorsclass GFG{ // assumes that n is a positive integerstatic boolean isMultipleof5 (int n){ while (n > 0) n = n - 5; if (n == 0) return true; return false;} // Driver Codepublic static void main(String[] args){ int n = 19; if (isMultipleof5(n) == true) System.out.printf(\"%d is multiple of 5\\n\", n); else System.out.printf(\"%d is not a multiple of 5\\n\", n);}} // This code is contributed by Smitha DInesh Semwal",
"e": 28382,
"s": 27832,
"text": null
},
{
"code": "# Python code to check# if a number is multiple of# 5 without using / and % # Assumes that n is a positive integerdef isMultipleof5(n): while ( n > 0 ): n = n - 5 if ( n == 0 ): return 1 return 0 # Driver Codei = 19if ( isMultipleof5(i) == 1 ): print (i, \"is multiple of 5\")else: print (i, \"is not a multiple of 5\") # This code is contributed# by Sumit Sudhakar",
"e": 28784,
"s": 28382,
"text": null
},
{
"code": "// C# code to check if a number// is multiple of 5 without using /// and % operatorsusing System; class GFG{ // assumes that n is a positive integerstatic bool isMultipleof5 (int n){ while (n > 0) n = n - 5; if (n == 0) return true; return false;} // Driver Codepublic static void Main(){ int n = 19; if (isMultipleof5(n) == true) Console.Write(n + \" is multiple of 5\\n\"); else Console.Write(n + \" is not a multiple of 5\\n\");}} // This code is contributed by nitin mittal.",
"e": 29309,
"s": 28784,
"text": null
},
{
"code": "<?php// assumes that n is a positive integerfunction isMultipleof5 ($n){ while ( $n > 0 ) $n = $n - 5; if ( $n == 0 ) return true; return false;} // Driver Code $n = 19; if ( isMultipleof5($n) == true ) echo(\"$n is multiple of 5\"); else echo(\"$n is not a multiple of 5\" ); // This code is contributed by nitin mittal.?>",
"e": 29685,
"s": 29309,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // assumes that n is a positive integerfunction isMultipleof5 (n){ while (n > 0) n = n - 5; if (n == 0) return true; return false;} // Driver Code let n = 19; if (isMultipleof5(n) == true) document.write(n + \" is multiple of 5\\n\"); else document.write(n + \" is not a multiple of 5\\n\"); </script>",
"e": 30083,
"s": 29685,
"text": null
},
{
"code": null,
"e": 30109,
"s": 30083,
"text": "19 is not a multiple of 5"
},
{
"code": null,
"e": 30156,
"s": 30109,
"text": "Time Complexity: O(n / 5)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 30359,
"s": 30156,
"text": "Method 2 (Convert to string and check the last character) Convert n to a string and check the last character of the string. If the last character is β5β or β0β then n is a multiple of 5, otherwise not. "
},
{
"code": null,
"e": 30410,
"s": 30359,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 30414,
"s": 30410,
"text": "C++"
},
{
"code": null,
"e": 30416,
"s": 30414,
"text": "C"
},
{
"code": null,
"e": 30421,
"s": 30416,
"text": "Java"
},
{
"code": null,
"e": 30429,
"s": 30421,
"text": "Python3"
},
{
"code": null,
"e": 30432,
"s": 30429,
"text": "C#"
},
{
"code": null,
"e": 30436,
"s": 30432,
"text": "PHP"
},
{
"code": null,
"e": 30447,
"s": 30436,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // Assuming that integer takes 4 bytes, there// can be maximum 10 digits in a integer#define MAX 20 bool isMultipleof5(int n){ // in-built method to convert integer to string string str = to_string(n); int len = str.size(); // Check the last character of string if (str[len - 1] == '5' || str[len - 1] == '0') return true; return false;} // Driver Codeint main(){ int n = 19; if (isMultipleof5(n) == true) cout << n << \" is multiple of 5\" << endl; else cout << n << \" is not multiple of 5\" << endl; return 0;} // This code is contributed by SHUBHAMSINGH10",
"e": 31103,
"s": 30447,
"text": null
},
{
"code": "#include<stdio.h>#include<stdlib.h>#include<string.h>#include <stdbool.h> // Assuming that integer takes 4 bytes, there// can be maximum 10 digits in a integer# define MAX 11 bool isMultipleof5(int n){ char str[MAX]; // in-built method to convert integer to string sprintf(str, \"%d\", n); int len = strlen(str); printf(\"%d\\n\", len); // Check the last character of string if ( str[len - 1] == '5' || str[len - 1] == '0' ) return true; return false;} // Driver Codeint main(){ int n = 19; if ( isMultipleof5(n) == true ) printf(\"%d is multiple of 5\\n\", n); else printf(\"%d is not a multiple of 5\\n\", n); return 0;}",
"e": 31799,
"s": 31103,
"text": null
},
{
"code": "// Assuming that integer// takes 4 bytes, there// can be maximum 10// digits in a integerclass GFG{static int MAX = 11; static boolean isMultipleof5(int n){ // in-built method to convert integer to string String str = Integer.toString(n); int len = str.length(); // Check the last // character of string if (str.charAt(len - 1) == '5' || str.charAt(len - 1) == '0' ) return true; return false;} // Driver Codepublic static void main(String[] args){ int n = 19; if ( isMultipleof5(n) == true ) System.out.println(n +\" is multiple \" + \"of 5\"); else System.out.println(n +\" is not a \" + \"multiple of 5\");}} // This code is contributed by mits",
"e": 32580,
"s": 31799,
"text": null
},
{
"code": "# Assuming that integer# takes 4 bytes, there# can be maximum 10# digits in a integerMAX = 11; def isMultipleof5(n): # in-built method to convert integer to string s = str(n); l = len(s); # Check the last # character of string if (s[l - 1] == '5' or s[l - 1] == '0'): return True; return False; # Driver Coden = 19;if (isMultipleof5(n) == True ): print(n, \"is multiple of 5\");else: print(n, \"is not a multiple of 5\"); # This code is contributed by mits",
"e": 33079,
"s": 32580,
"text": null
},
{
"code": "using System; // Assuming that integer// takes 4 bytes, there// can be maximum 10// digits in a integerclass GFG{ static bool isMultipleof5(int n){ // in-built method to convert integer to string String str = n.ToString(); int len = str.Length; // Check the last // character of string if (str[len - 1] == '5' || str[len - 1] == '0' ) return true; return false;} // Driver Codestatic void Main(){ int n = 19; if ( isMultipleof5(n) == true ) Console.WriteLine(\"{0} is \" + \"multiple of 5\", n); else Console.WriteLine(\"{0} is not a \" + \"multiple of 5\", n);}} // This code is contributed by mits",
"e": 33798,
"s": 33079,
"text": null
},
{
"code": "<?php// Assuming that integer// takes 4 bytes, there// can be maximum 10// digits in a integer$MAX = 11; function isMultipleof5($n){ global $MAX; $str = (string)$n; $len = strlen($str); // Check the last // character of string if ($str[$len - 1] == '5' || $str[$len - 1] == '0') return true; return false;} // Driver Code$n = 19;if (isMultipleof5($n) == true ) echo \"$n is multiple of 5\";else echo \"$n is not a multiple of 5\"; // This code is contributed by mits?>",
"e": 34323,
"s": 33798,
"text": null
},
{
"code": "<script> // Assuming that integer// takes 4 bytes, there// can be maximum 10// digits in a integerMAX = 11; function isMultipleof5(n){ str = Array(n).fill(''); var len = str.length; // Check the last // character of string if (str[len - 1] == '5' || str[len - 1] == '0' ) return true; return false;} // Driver Codevar n = 19;if ( isMultipleof5(n) == true ) document.write(n +\" is multiple \" + \"of 5\");else document.write(n +\" is not a \" + \"multiple of 5\"); // This code is contributed by Amit Katiyar</script>",
"e": 34961,
"s": 34323,
"text": null
},
{
"code": null,
"e": 34985,
"s": 34961,
"text": "19 is not multiple of 5"
},
{
"code": null,
"e": 35030,
"s": 34985,
"text": "Time Complexity: O(1)Auxiliary Space: O(MAX)"
},
{
"code": null,
"e": 35562,
"s": 35030,
"text": "Thanks to Baban_Rathore for suggesting this method.Method 3 (Set last digit as 0 and use floating point trick) A number n can be a multiple of 5 in two cases. When last digit of n is 5 or 10. If last bit in binary equivalent of n is set (which can be the case when last digit is 5) then we multiply by 2 using n<<=1 to make sure that if the number is multiple of 5 then we have the last digit as 0. Once we do that, our work is to just check if the last digit is 0 or not, which we can do using float and integer comparison trick. "
},
{
"code": null,
"e": 35613,
"s": 35562,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 35617,
"s": 35613,
"text": "C++"
},
{
"code": null,
"e": 35619,
"s": 35617,
"text": "C"
},
{
"code": null,
"e": 35624,
"s": 35619,
"text": "Java"
},
{
"code": null,
"e": 35632,
"s": 35624,
"text": "Python3"
},
{
"code": null,
"e": 35635,
"s": 35632,
"text": "C#"
},
{
"code": null,
"e": 35639,
"s": 35635,
"text": "PHP"
},
{
"code": null,
"e": 35650,
"s": 35639,
"text": "Javascript"
},
{
"code": "#include <iostream>using namespace std;bool isMultipleof5(int n){ // If n is a multiple of 5 then we // make sure that last digit of n is 0 if ( (n & 1) == 1 ) n <<= 1; float x = n; x = ( (int)(x * 0.1) ) * 10; // If last digit of n is 0 then n // will be equal to (int)x if ( (int)x == n ) return true; return false;} // Driver Codeint main(){ int i = 19; if ( isMultipleof5(i) == true ) cout << i <<\" is multiple of 5\\n\"; else cout << i << \" is not a multiple of 5\\n\"; getchar(); return 0;} // This code is contributed by shubhamsingh10",
"e": 36271,
"s": 35650,
"text": null
},
{
"code": "#include<stdio.h> bool isMultipleof5(int n){ // If n is a multiple of 5 then we // make sure that last digit of n is 0 if ( (n & 1) == 1 ) n <<= 1; float x = n; x = ( (int)(x * 0.1) ) * 10; // If last digit of n is 0 then n // will be equal to (int)x if ( (int)x == n ) return true; return false;} // Driver Codeint main(){ int i = 19; if ( isMultipleof5(i) == true ) printf(\"%d is multiple of 5\\n\", i); else printf(\"%d is not a multiple of 5\\n\", i); getchar(); return 0;}",
"e": 36826,
"s": 36271,
"text": null
},
{
"code": "// Java code to check if// a number is multiple of// 5 without using / and %class GFG{static boolean isMultipleof5(int n){ // If n is a multiple of 5 // then we make sure that // last digit of n is 0 if ((n & 1) == 1) n <<= 1; float x = n; x = ((int)(x * 0.1)) * 10; // If last digit of n is // 0 then n will be equal // to (int)x if ((int)x == n) return true; return false;} // Driver Codepublic static void main(String[] args){ int i = 19; if (isMultipleof5(i) == true) System.out.println(i + \"is multiple of 5\"); else System.out.println(i + \" is not a \" + \"multiple of 5\");}} // This code is contributed// by mits",
"e": 37551,
"s": 36826,
"text": null
},
{
"code": "# Python code to check# if a number is multiple of# 5 without using / and % def isMultipleof5(n): # If n is a multiple of 5 then we # make sure that last digit of n is 0 if ( (n & 1) == 1 ): n <<= 1; x = n x = ( (int)(x * 0.1) ) * 10 # If last digit of n is 0 # then n will be equal to x if ( x == n ): return 1 return 0 # Driver Codei = 19if ( isMultipleof5(i) == 1 ): print (i, \"is multiple of 5\")else: print (i, \"is not a multiple of 5\") # This code is contributed# by Sumit Sudhakar",
"e": 38101,
"s": 37551,
"text": null
},
{
"code": "// C# code to check if// a number is multiple of// 5 without using / and %class GFG{static bool isMultipleof5(int n){ // If n is a multiple of 5 // then we make sure that // last digit of n is 0 if ((n & 1) == 1) n <<= 1; float x = n; x = ((int)(x * 0.1)) * 10; // If last digit of n is // 0 then n will be equal // to (int)x if ((int)x == n) return true; return false;} // Driver Codepublic static void Main(){ int i = 19; if (isMultipleof5(i) == true) System.Console.WriteLine(i + \"is multiple of 5\"); else System.Console.WriteLine(i + \" is not a \" + \"multiple of 5\");}} // This code is contributed// by mits",
"e": 38827,
"s": 38101,
"text": null
},
{
"code": "<?phpfunction isMultipleof5($n){ // If n is a multiple of 5 // then we make sure that // last digit of n is 0 if (($n & 1) == 1 ) $n <<= 1; $x = $n; $x = ((int)($x * 0.1)) * 10; // If last digit of n // is 0 then n will be // equal to (int)x if ( (int)($x) == $n ) return true; return false;} // Driver Code$i = 19;if ( isMultipleof5($i) == true ) echo \"$i is multiple of 5\\n\";else echo \"$i is not a multiple of 5\\n\"; // This code is contributed by mits?>",
"e": 39347,
"s": 38827,
"text": null
},
{
"code": "<script>// JavaScript code to check if// a number is multiple of// 5 without using / and %function isMultipleof5( n){ // If n is a multiple of 5 then we // make sure that last digit of n is 0 if ( (n & 1) == 1 ) n <<= 1; x = ( (int)(x * 0.1) ) * 10; // If last digit of n is 0 then n // will be equal to (int)x if ( (int)(x == n)) return true; return false;} // Driver Code i = 19; if ( isMultipleof5 == true) document.write( i + \" is multiple of 5\\n\"); else document.write( i + \" is not a multiple of 5\\n\"); // This code is contributed by simranarora5sos </script>",
"e": 40012,
"s": 39347,
"text": null
},
{
"code": null,
"e": 40038,
"s": 40012,
"text": "19 is not a multiple of 5"
},
{
"code": null,
"e": 40081,
"s": 40038,
"text": "Time Complexity: O(1)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 40248,
"s": 40081,
"text": "Thanks to darkprince for suggesting this method.Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem. "
},
{
"code": null,
"e": 40269,
"s": 40248,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 40282,
"s": 40269,
"text": "nitin mittal"
},
{
"code": null,
"e": 40295,
"s": 40282,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 40310,
"s": 40295,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 40320,
"s": 40310,
"text": "code_hunt"
},
{
"code": null,
"e": 40335,
"s": 40320,
"text": "amit143katiyar"
},
{
"code": null,
"e": 40351,
"s": 40335,
"text": "simranarora5sos"
},
{
"code": null,
"e": 40366,
"s": 40351,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 40382,
"s": 40366,
"text": "subhammahato348"
},
{
"code": null,
"e": 40392,
"s": 40382,
"text": "subham348"
},
{
"code": null,
"e": 40408,
"s": 40392,
"text": "souravmahato348"
},
{
"code": null,
"e": 40425,
"s": 40408,
"text": "arorakashish0911"
},
{
"code": null,
"e": 40442,
"s": 40425,
"text": "harendrakumar123"
},
{
"code": null,
"e": 40455,
"s": 40442,
"text": "Mathematical"
},
{
"code": null,
"e": 40468,
"s": 40455,
"text": "Mathematical"
},
{
"code": null,
"e": 40566,
"s": 40468,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40590,
"s": 40566,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 40633,
"s": 40590,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 40647,
"s": 40633,
"text": "Prime Numbers"
},
{
"code": null,
"e": 40689,
"s": 40647,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 40711,
"s": 40689,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 40784,
"s": 40711,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 40805,
"s": 40784,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 40848,
"s": 40805,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 40882,
"s": 40848,
"text": "Program for factorial of a number"
}
] |
How to make vertical scrollable rows in bootstrap? - GeeksforGeeks
|
05 May, 2022
Here is the task to make vertically scrollable in a bootstrap row.
It can be done by the following approach:
Approach:
Making all the div element in next line using position: absolute; property (arrange all div column-wise).
Adding the scroll bar to all the div element using overflow-y: scroll; property.
Example:
HTML
<!DOCTYPE html><html lang="en"><head> <title> How to make vertical scrollable in a bootstrap row? </title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <style> .vertical-scrollable>.row { position: absolute; top: 120px; bottom: 100px; left: 180px; width: 50%; overflow-y: scroll; } .col-sm-8 { color: white; font-size: 24px; padding-bottom: 20px; padding-top: 18px; } .col-sm-8:nth-child(2n+1) { background: green; } .col-sm-8:nth-child(2n+2) { background: black; } </style></head><body> <center> <div class="container"> <h1 style="text-align:center;color:green;"> GeeksforGeeks </h1> <h3> To make vertical scrollable in a bootstrap row? </h3> <div class="container vertical-scrollable"> <div class="row text-center"> <div class="col-sm-8"> 1 </div> <div class="col-sm-8"> 2 </div> <div class="col-sm-8"> 3 </div> <div class="col-sm-8"> 4 </div> <div class="col-sm-8"> 5 </div> <div class="col-sm-8"> 6 </div> <div class="col-sm-8"> 7 </div> </div> </div> </div> </center></body></html>
Output:
sahilintern
Bootstrap-Misc
Bootstrap
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to change navigation bar color in Bootstrap ?
Form validation using jQuery
How to pass data into a bootstrap modal?
How to align navbar items to the right in Bootstrap 4 ?
How to Show Images on Click using HTML ?
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": 29685,
"s": 29657,
"text": "\n05 May, 2022"
},
{
"code": null,
"e": 29752,
"s": 29685,
"text": "Here is the task to make vertically scrollable in a bootstrap row."
},
{
"code": null,
"e": 29794,
"s": 29752,
"text": "It can be done by the following approach:"
},
{
"code": null,
"e": 29804,
"s": 29794,
"text": "Approach:"
},
{
"code": null,
"e": 29910,
"s": 29804,
"text": "Making all the div element in next line using position: absolute; property (arrange all div column-wise)."
},
{
"code": null,
"e": 29991,
"s": 29910,
"text": "Adding the scroll bar to all the div element using overflow-y: scroll; property."
},
{
"code": null,
"e": 30000,
"s": 29991,
"text": "Example:"
},
{
"code": null,
"e": 30005,
"s": 30000,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title> How to make vertical scrollable in a bootstrap row? </title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\"> <style> .vertical-scrollable>.row { position: absolute; top: 120px; bottom: 100px; left: 180px; width: 50%; overflow-y: scroll; } .col-sm-8 { color: white; font-size: 24px; padding-bottom: 20px; padding-top: 18px; } .col-sm-8:nth-child(2n+1) { background: green; } .col-sm-8:nth-child(2n+2) { background: black; } </style></head><body> <center> <div class=\"container\"> <h1 style=\"text-align:center;color:green;\"> GeeksforGeeks </h1> <h3> To make vertical scrollable in a bootstrap row? </h3> <div class=\"container vertical-scrollable\"> <div class=\"row text-center\"> <div class=\"col-sm-8\"> 1 </div> <div class=\"col-sm-8\"> 2 </div> <div class=\"col-sm-8\"> 3 </div> <div class=\"col-sm-8\"> 4 </div> <div class=\"col-sm-8\"> 5 </div> <div class=\"col-sm-8\"> 6 </div> <div class=\"col-sm-8\"> 7 </div> </div> </div> </div> </center></body></html>",
"e": 31980,
"s": 30005,
"text": null
},
{
"code": null,
"e": 31988,
"s": 31980,
"text": "Output:"
},
{
"code": null,
"e": 32000,
"s": 31988,
"text": "sahilintern"
},
{
"code": null,
"e": 32015,
"s": 32000,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 32025,
"s": 32015,
"text": "Bootstrap"
},
{
"code": null,
"e": 32042,
"s": 32025,
"text": "Web Technologies"
},
{
"code": null,
"e": 32069,
"s": 32042,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 32167,
"s": 32069,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32217,
"s": 32167,
"text": "How to change navigation bar color in Bootstrap ?"
},
{
"code": null,
"e": 32246,
"s": 32217,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 32287,
"s": 32246,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 32343,
"s": 32287,
"text": "How to align navbar items to the right in Bootstrap 4 ?"
},
{
"code": null,
"e": 32384,
"s": 32343,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 32424,
"s": 32384,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32457,
"s": 32424,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32502,
"s": 32457,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 32545,
"s": 32502,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Find cubic root of a number - GeeksforGeeks
|
28 Jun, 2021
Given a number n, find the cube root of n.Examples:
Input: n = 3
Output: Cubic Root is 1.442250
Input: n = 8
Output: Cubic Root is 2.000000
We can use binary search. First we define error e. Let us say 0.0000001 in our case. The main steps of our algorithm for calculating the cubic root of a number n are:
Initialize start = 0 and end = nCalculate mid = (start + end)/2Check if the absolute value of (n β mid*mid*mid) < e. If this condition holds true then mid is our answer so return mid. If (mid*mid*mid)>n then set end=midIf (mid*mid*mid)<n set start=mid.
Initialize start = 0 and end = n
Calculate mid = (start + end)/2
Check if the absolute value of (n β mid*mid*mid) < e. If this condition holds true then mid is our answer so return mid.
If (mid*mid*mid)>n then set end=mid
If (mid*mid*mid)<n set start=mid.
Below is the implementation of above idea.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find cubic root of a number// using Binary Search#include <bits/stdc++.h>using namespace std; // Returns the absolute value of n-mid*mid*middouble diff(double n,double mid){ if (n > (mid*mid*mid)) return (n-(mid*mid*mid)); else return ((mid*mid*mid) - n);} // Returns cube root of a no ndouble cubicRoot(double n){ // Set start and end for binary search double start = 0, end = n; // Set precision double e = 0.0000001; while (true) { double mid = (start + end)/2; double error = diff(n, mid); // If error is less than e then mid is // our answer so return mid if (error <= e) return mid; // If mid*mid*mid is greater than n set // end = mid if ((mid*mid*mid) > n) end = mid; // If mid*mid*mid is less than n set // start = mid else start = mid; }} // Driver codeint main(){ double n = 3; printf("Cubic root of %lf is %lf\n", n, cubicRoot(n)); return 0;}
// Java program to find cubic root of a number// using Binary Searchimport java.io.*; class GFG{ // Returns the absolute value of n-mid*mid*mid static double diff(double n,double mid) { if (n > (mid*mid*mid)) return (n-(mid*mid*mid)); else return ((mid*mid*mid) - n); } // Returns cube root of a no n static double cubicRoot(double n) { // Set start and end for binary search double start = 0, end = n; // Set precision double e = 0.0000001; while (true) { double mid = (start + end)/2; double error = diff(n, mid); // If error is less than e then mid is // our answer so return mid if (error <= e) return mid; // If mid*mid*mid is greater than n set // end = mid if ((mid*mid*mid) > n) end = mid; // If mid*mid*mid is less than n set // start = mid else start = mid; } } // Driver program to test above function public static void main (String[] args) { double n = 3; System.out.println("Cube root of "+n+" is "+cubicRoot(n)); }} // This code is contributed by Pramod Kumar
# Python 3 program to find cubic root# of a number using Binary Search # Returns the absolute value of# n-mid*mid*middef diff(n, mid) : if (n > (mid * mid * mid)) : return (n - (mid * mid * mid)) else : return ((mid * mid * mid) - n) # Returns cube root of a no ndef cubicRoot(n) : # Set start and end for binary # search start = 0 end = n # Set precision e = 0.0000001 while (True) : mid = (start + end) / 2 error = diff(n, mid) # If error is less than e # then mid is our answer # so return mid if (error <= e) : return mid # If mid*mid*mid is greater # than n set end = mid if ((mid * mid * mid) > n) : end = mid # If mid*mid*mid is less # than n set start = mid else : start = mid # Driver coden = 3print("Cubic root of", n, "is", round(cubicRoot(n),6)) # This code is contributed by Nikita Tiwari.
// C# program to find cubic root// of a number using Binary Searchusing System; class GFG { // Returns the absolute value // of n - mid * mid * mid static double diff(double n, double mid) { if (n > (mid * mid * mid)) return (n-(mid * mid * mid)); else return ((mid * mid * mid) - n); } // Returns cube root of a no. n static double cubicRoot(double n) { // Set start and end for // binary search double start = 0, end = n; // Set precision double e = 0.0000001; while (true) { double mid = (start + end) / 2; double error = diff(n, mid); // If error is less than e then // mid is our answer so return mid if (error <= e) return mid; // If mid * mid * mid is greater // than n set end = mid if ((mid * mid * mid) > n) end = mid; // If mid*mid*mid is less than // n set start = mid else start = mid; } } // Driver Code public static void Main () { double n = 3; Console.Write("Cube root of "+ n + " is "+cubicRoot(n)); }} // This code is contributed by nitin mittal.
<?php// PHP program to find cubic root// of a number using Binary Search // Returns the absolute value// of n - mid * mid * midfunction diff($n,$mid){ if ($n > ($mid * $mid * $mid)) return ($n - ($mid * $mid * $mid)); else return (($mid * $mid * $mid) - $n);} // Returns cube root of a no nfunction cubicRoot($n){ // Set start and end // for binary search $start = 0; $end = $n; // Set precision $e = 0.0000001; while (true) { $mid = (($start + $end)/2); $error = diff($n, $mid); // If error is less // than e then mid is // our answer so return mid if ($error <= $e) return $mid; // If mid*mid*mid is // greater than n set // end = mid if (($mid * $mid * $mid) > $n) $end = $mid; // If mid*mid*mid is // less than n set // start = mid else $start = $mid; }} // Driver Code $n = 3; echo("Cubic root of $n is "); echo(cubicRoot($n)); // This code is contributed by nitin mittal.?>
<script> // Javascript program to find cubic root of a number// using Binary Search // Returns the absolute value of n-mid*mid*mid function diff(n, mid) { if (n > (mid*mid*mid)) return (n-(mid*mid*mid)); else return ((mid*mid*mid) - n); } // Returns cube root of a no n function cubicRoot(n) { // Set start and end for binary search let start = 0, end = n; // Set precision let e = 0.0000001; while (true) { let mid = (start + end)/2; let error = diff(n, mid); // If error is less than e then mid is // our answer so return mid if (error <= e) return mid; // If mid*mid*mid is greater than n set // end = mid if ((mid*mid*mid) > n) end = mid; // If mid*mid*mid is less than n set // start = mid else start = mid; } } // Driver Code let n = 3; document.write("Cube root of "+n+" is "+cubicRoot(n)); </script>
Output:
Cubic root of 3.000000 is 1.442250
Time Complexity : O(Log n)This article is contributed by Madhur Modi .If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
splevel62
Binary Search
Divide and Conquer
Mathematical
Mathematical
Divide and Conquer
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count number of occurrences (or frequency) in a sorted array
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Quick Sort vs Merge Sort
Closest Pair of Points using Divide and Conquer algorithm
Find a peak element
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": 25511,
"s": 25483,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 25565,
"s": 25511,
"text": "Given a number n, find the cube root of n.Examples: "
},
{
"code": null,
"e": 25655,
"s": 25565,
"text": "Input: n = 3\nOutput: Cubic Root is 1.442250\n\nInput: n = 8\nOutput: Cubic Root is 2.000000"
},
{
"code": null,
"e": 25826,
"s": 25657,
"text": "We can use binary search. First we define error e. Let us say 0.0000001 in our case. The main steps of our algorithm for calculating the cubic root of a number n are: "
},
{
"code": null,
"e": 26080,
"s": 25826,
"text": "Initialize start = 0 and end = nCalculate mid = (start + end)/2Check if the absolute value of (n β mid*mid*mid) < e. If this condition holds true then mid is our answer so return mid. If (mid*mid*mid)>n then set end=midIf (mid*mid*mid)<n set start=mid."
},
{
"code": null,
"e": 26113,
"s": 26080,
"text": "Initialize start = 0 and end = n"
},
{
"code": null,
"e": 26145,
"s": 26113,
"text": "Calculate mid = (start + end)/2"
},
{
"code": null,
"e": 26268,
"s": 26145,
"text": "Check if the absolute value of (n β mid*mid*mid) < e. If this condition holds true then mid is our answer so return mid. "
},
{
"code": null,
"e": 26304,
"s": 26268,
"text": "If (mid*mid*mid)>n then set end=mid"
},
{
"code": null,
"e": 26338,
"s": 26304,
"text": "If (mid*mid*mid)<n set start=mid."
},
{
"code": null,
"e": 26383,
"s": 26338,
"text": "Below is the implementation of above idea. "
},
{
"code": null,
"e": 26387,
"s": 26383,
"text": "C++"
},
{
"code": null,
"e": 26392,
"s": 26387,
"text": "Java"
},
{
"code": null,
"e": 26400,
"s": 26392,
"text": "Python3"
},
{
"code": null,
"e": 26403,
"s": 26400,
"text": "C#"
},
{
"code": null,
"e": 26407,
"s": 26403,
"text": "PHP"
},
{
"code": null,
"e": 26418,
"s": 26407,
"text": "Javascript"
},
{
"code": "// C++ program to find cubic root of a number// using Binary Search#include <bits/stdc++.h>using namespace std; // Returns the absolute value of n-mid*mid*middouble diff(double n,double mid){ if (n > (mid*mid*mid)) return (n-(mid*mid*mid)); else return ((mid*mid*mid) - n);} // Returns cube root of a no ndouble cubicRoot(double n){ // Set start and end for binary search double start = 0, end = n; // Set precision double e = 0.0000001; while (true) { double mid = (start + end)/2; double error = diff(n, mid); // If error is less than e then mid is // our answer so return mid if (error <= e) return mid; // If mid*mid*mid is greater than n set // end = mid if ((mid*mid*mid) > n) end = mid; // If mid*mid*mid is less than n set // start = mid else start = mid; }} // Driver codeint main(){ double n = 3; printf(\"Cubic root of %lf is %lf\\n\", n, cubicRoot(n)); return 0;}",
"e": 27466,
"s": 26418,
"text": null
},
{
"code": "// Java program to find cubic root of a number// using Binary Searchimport java.io.*; class GFG{ // Returns the absolute value of n-mid*mid*mid static double diff(double n,double mid) { if (n > (mid*mid*mid)) return (n-(mid*mid*mid)); else return ((mid*mid*mid) - n); } // Returns cube root of a no n static double cubicRoot(double n) { // Set start and end for binary search double start = 0, end = n; // Set precision double e = 0.0000001; while (true) { double mid = (start + end)/2; double error = diff(n, mid); // If error is less than e then mid is // our answer so return mid if (error <= e) return mid; // If mid*mid*mid is greater than n set // end = mid if ((mid*mid*mid) > n) end = mid; // If mid*mid*mid is less than n set // start = mid else start = mid; } } // Driver program to test above function public static void main (String[] args) { double n = 3; System.out.println(\"Cube root of \"+n+\" is \"+cubicRoot(n)); }} // This code is contributed by Pramod Kumar",
"e": 28762,
"s": 27466,
"text": null
},
{
"code": "# Python 3 program to find cubic root# of a number using Binary Search # Returns the absolute value of# n-mid*mid*middef diff(n, mid) : if (n > (mid * mid * mid)) : return (n - (mid * mid * mid)) else : return ((mid * mid * mid) - n) # Returns cube root of a no ndef cubicRoot(n) : # Set start and end for binary # search start = 0 end = n # Set precision e = 0.0000001 while (True) : mid = (start + end) / 2 error = diff(n, mid) # If error is less than e # then mid is our answer # so return mid if (error <= e) : return mid # If mid*mid*mid is greater # than n set end = mid if ((mid * mid * mid) > n) : end = mid # If mid*mid*mid is less # than n set start = mid else : start = mid # Driver coden = 3print(\"Cubic root of\", n, \"is\", round(cubicRoot(n),6)) # This code is contributed by Nikita Tiwari.",
"e": 29795,
"s": 28762,
"text": null
},
{
"code": "// C# program to find cubic root// of a number using Binary Searchusing System; class GFG { // Returns the absolute value // of n - mid * mid * mid static double diff(double n, double mid) { if (n > (mid * mid * mid)) return (n-(mid * mid * mid)); else return ((mid * mid * mid) - n); } // Returns cube root of a no. n static double cubicRoot(double n) { // Set start and end for // binary search double start = 0, end = n; // Set precision double e = 0.0000001; while (true) { double mid = (start + end) / 2; double error = diff(n, mid); // If error is less than e then // mid is our answer so return mid if (error <= e) return mid; // If mid * mid * mid is greater // than n set end = mid if ((mid * mid * mid) > n) end = mid; // If mid*mid*mid is less than // n set start = mid else start = mid; } } // Driver Code public static void Main () { double n = 3; Console.Write(\"Cube root of \"+ n + \" is \"+cubicRoot(n)); }} // This code is contributed by nitin mittal.",
"e": 31123,
"s": 29795,
"text": null
},
{
"code": "<?php// PHP program to find cubic root// of a number using Binary Search // Returns the absolute value// of n - mid * mid * midfunction diff($n,$mid){ if ($n > ($mid * $mid * $mid)) return ($n - ($mid * $mid * $mid)); else return (($mid * $mid * $mid) - $n);} // Returns cube root of a no nfunction cubicRoot($n){ // Set start and end // for binary search $start = 0; $end = $n; // Set precision $e = 0.0000001; while (true) { $mid = (($start + $end)/2); $error = diff($n, $mid); // If error is less // than e then mid is // our answer so return mid if ($error <= $e) return $mid; // If mid*mid*mid is // greater than n set // end = mid if (($mid * $mid * $mid) > $n) $end = $mid; // If mid*mid*mid is // less than n set // start = mid else $start = $mid; }} // Driver Code $n = 3; echo(\"Cubic root of $n is \"); echo(cubicRoot($n)); // This code is contributed by nitin mittal.?>",
"e": 32235,
"s": 31123,
"text": null
},
{
"code": "<script> // Javascript program to find cubic root of a number// using Binary Search // Returns the absolute value of n-mid*mid*mid function diff(n, mid) { if (n > (mid*mid*mid)) return (n-(mid*mid*mid)); else return ((mid*mid*mid) - n); } // Returns cube root of a no n function cubicRoot(n) { // Set start and end for binary search let start = 0, end = n; // Set precision let e = 0.0000001; while (true) { let mid = (start + end)/2; let error = diff(n, mid); // If error is less than e then mid is // our answer so return mid if (error <= e) return mid; // If mid*mid*mid is greater than n set // end = mid if ((mid*mid*mid) > n) end = mid; // If mid*mid*mid is less than n set // start = mid else start = mid; } } // Driver Code let n = 3; document.write(\"Cube root of \"+n+\" is \"+cubicRoot(n)); </script>",
"e": 33376,
"s": 32235,
"text": null
},
{
"code": null,
"e": 33385,
"s": 33376,
"text": "Output: "
},
{
"code": null,
"e": 33420,
"s": 33385,
"text": "Cubic root of 3.000000 is 1.442250"
},
{
"code": null,
"e": 33866,
"s": 33420,
"text": "Time Complexity : O(Log n)This article is contributed by Madhur Modi .If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 33879,
"s": 33866,
"text": "nitin mittal"
},
{
"code": null,
"e": 33889,
"s": 33879,
"text": "splevel62"
},
{
"code": null,
"e": 33903,
"s": 33889,
"text": "Binary Search"
},
{
"code": null,
"e": 33922,
"s": 33903,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 33935,
"s": 33922,
"text": "Mathematical"
},
{
"code": null,
"e": 33948,
"s": 33935,
"text": "Mathematical"
},
{
"code": null,
"e": 33967,
"s": 33948,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 33981,
"s": 33967,
"text": "Binary Search"
},
{
"code": null,
"e": 34079,
"s": 33981,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34140,
"s": 34079,
"text": "Count number of occurrences (or frequency) in a sorted array"
},
{
"code": null,
"e": 34202,
"s": 34140,
"text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)"
},
{
"code": null,
"e": 34227,
"s": 34202,
"text": "Quick Sort vs Merge Sort"
},
{
"code": null,
"e": 34285,
"s": 34227,
"text": "Closest Pair of Points using Divide and Conquer algorithm"
},
{
"code": null,
"e": 34305,
"s": 34285,
"text": "Find a peak element"
},
{
"code": null,
"e": 34335,
"s": 34305,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 34395,
"s": 34335,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 34410,
"s": 34395,
"text": "C++ Data Types"
},
{
"code": null,
"e": 34453,
"s": 34410,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Maximum product of subsequence of size k - GeeksforGeeks
|
04 May, 2021
Given an array A[] of n integers, the task is to find a subsequence of size k whose product is maximum among all possible k sized subsequences of the given array.Constraints
1 <= n <= 10^5
1 <= k <= n
Examples:
Input : A[] = {1, 2, 0, 3},
k = 2
Output : 6
Explanation : Subsequence containing elements
{2, 3} gives maximum product : 2*3 = 6
Input : A[] = {1, 2, -1, -3, -6, 4},
k = 4
Output : 144
Explanation : Subsequence containing {2, -3,
-6, 4} gives maximum product : 2*(-3)*(-6)*4
= 144
Following are different cases that arise in this problem.
CASE I: if the maximum element of A is 0 and k is odd Here if we donβt include 0 in subsequence then product will be less than 0, Since the product of an odd number of negative integers gives a negative integer. Hence 0 must be included in the subsequence. Since 0 is present in subsequence, the product of subsequence is 0. Answer = 0.
CASE II: if maximum element of A is negative and k is odd. Here the product will be less than 0, Since the product of an odd number of negative integers gives a negative integer. So to get the maximum product, we take the product of the smallest (absolute value wise) k elements. Since absolute value wise : | A[n-1] | > | A[n-2] | ... > | A[0] |. Hence we take product of A[n-1], A[n-2], A[n-3], .... A[n-k] Answer = A[n-1] * A[n-2] * ..... * A[n-k]
CASE III: if maximum element of A is positive and k is odd. Here in subsequence of k size if all elements are < 0 then product will be less than 0, Since the product of an odd number of negative integers gives a negative integer. Hence, at least one element must be a positive integer in the subsequence. To get max product max positive number should be present in the subsequence. Now we need to add k-1 more elements to the subsequence. Since k is odd, k-1 becomes even. So the problem boils down to case IV. Answer = A[n-1] * Answer from CASE IV.
CASE IV: if k is even. Since k is even, we always add a pair in subsequence. So total pairs required to be added in subsequence is k/2. So for simplicity, our new k is k/2. Now since A is sorted, pair with the maximum product will always be either A[0]*A[1] OR A[n-1]*A[n-2]. In case of doubt about the previous statement think about negative numbers
Now,
if A[0]*A[1] > A[n-1]*A[n-2],
second max product pair will be
either A[2]*A[3] OR A[n-1]*[n-2].
else second max product pair will be
either A[0]*A[1] OR A[n-3]*[n-4].
Here is implementation of above solution
C++
Java
Python 3
C#
PHP
Javascript
// C++ code to find maximum possible product of// sub-sequence of size k from given array of n// integers#include <algorithm> // for sorting#include <iostream>using namespace std; // Required functionint maxProductSubarrayOfSizeK(int A[], int n, int k){ // sorting given input array sort(A, A + n); // variable to store final product of all element // of sub-sequence of size k int product = 1; // CASE I // If max element is 0 and // k is odd then max product will be 0 if (A[n - 1] == 0 && (k & 1)) return 0; // CASE II // If all elements are negative and // k is odd then max product will be // product of rightmost-subarray of size k if (A[n - 1] <= 0 && (k & 1)) { for (int i = n - 1; i >= n - k; i--) product *= A[i]; return product; } // else // i is current left pointer index int i = 0; // j is current right pointer index int j = n - 1; // CASE III // if k is odd and rightmost element in // sorted array is positive then it // must come in subsequence // Multiplying A[j] with product and // correspondingly changing j if (k & 1) { product *= A[j]; j--; k--; } // CASE IV // Now k is even // Now we deal with pairs // Each time a pair is multiplied to product // ie.. two elements are added to subsequence each time // Effectively k becomes half // Hence, k >>= 1 means k /= 2 k >>= 1; // Now finding k corresponding pairs // to get maximum possible value of product for (int itr = 0; itr < k; itr++) { // product from left pointers int left_product = A[i] * A[i + 1]; // product from right pointers int right_product = A[j] * A[j - 1]; // Taking the max product from two choices // Correspondingly changing the pointer's position if (left_product > right_product) { product *= left_product; i += 2; } else { product *= right_product; j -= 2; } } // Finally return product return product;} // Driver Code to test above functionint main(){ int A[] = { 1, 2, -1, -3, -6, 4 }; int n = sizeof(A) / sizeof(A[0]); int k = 4; cout << maxProductSubarrayOfSizeK(A, n, k); return 0;}
// Java program to find maximum possible product of// sub-sequence of size k from given array of n// integersimport java.io.*;import java.util.*; class GFG { // Function to find maximum possible product static int maxProductSubarrayOfSizeK(int A[], int n, int k) { // sorting given input array Arrays.sort(A); // variable to store final product of all element // of sub-sequence of size k int product = 1; // CASE I // If max element is 0 and // k is odd then max product will be 0 if (A[n - 1] == 0 && k % 2 != 0) return 0; // CASE II // If all elements are negative and // k is odd then max product will be // product of rightmost-subarray of size k if (A[n - 1] <= 0 && k % 2 != 0) { for (int i = n - 1; i >= n - k; i--) product *= A[i]; return product; } // else // i is current left pointer index int i = 0; // j is current right pointer index int j = n - 1; // CASE III // if k is odd and rightmost element in // sorted array is positive then it // must come in subsequence // Multiplying A[j] with product and // correspondingly changing j if (k % 2 != 0) { product *= A[j]; j--; k--; } // CASE IV // Now k is even // Now we deal with pairs // Each time a pair is multiplied to product // ie.. two elements are added to subsequence each time // Effectively k becomes half // Hence, k >>= 1 means k /= 2 k >>= 1; // Now finding k corresponding pairs // to get maximum possible value of product for (int itr = 0; itr < k; itr++) { // product from left pointers int left_product = A[i] * A[i + 1]; // product from right pointers int right_product = A[j] * A[j - 1]; // Taking the max product from two choices // Correspondingly changing the pointer's position if (left_product > right_product) { product *= left_product; i += 2; } else { product *= right_product; j -= 2; } } // Finally return product return product; } // driver program public static void main(String[] args) { int A[] = { 1, 2, -1, -3, -6, 4 }; int n = A.length; int k = 4; System.out.println(maxProductSubarrayOfSizeK(A, n, k)); }} // Contributed by Pramod Kumar
# Python 3 code to find maximum possible# product of sub-sequence of size k from# given array of n integers # Required functiondef maxProductSubarrayOfSizeK(A, n, k): # sorting given input array A.sort() # variable to store final product of # all element of sub-sequence of size k product = 1 # CASE I # If max element is 0 and # k is odd then max product will be 0 if (A[n - 1] == 0 and (k & 1)): return 0 # CASE II # If all elements are negative and # k is odd then max product will be # product of rightmost-subarray of size k if (A[n - 1] <= 0 and (k & 1)) : for i in range(n - 1, n - k + 1, -1): product *= A[i] return product # else # i is current left pointer index i = 0 # j is current right pointer index j = n - 1 # CASE III # if k is odd and rightmost element in # sorted array is positive then it # must come in subsequence # Multiplying A[j] with product and # correspondingly changing j if (k & 1): product *= A[j] j-= 1 k-=1 # CASE IV # Now k is even. So, Now we deal with pairs # Each time a pair is multiplied to product # ie.. two elements are added to subsequence # each time. Effectively k becomes half # Hence, k >>= 1 means k /= 2 k >>= 1 # Now finding k corresponding pairs to get # maximum possible value of product for itr in range( k) : # product from left pointers left_product = A[i] * A[i + 1] # product from right pointers right_product = A[j] * A[j - 1] # Taking the max product from two # choices. Correspondingly changing # the pointer's position if (left_product > right_product) : product *= left_product i += 2 else : product *= right_product j -= 2 # Finally return product return product # Driver Codeif __name__ == "__main__": A = [ 1, 2, -1, -3, -6, 4 ] n = len(A) k = 4 print(maxProductSubarrayOfSizeK(A, n, k)) # This code is contributed by ita_c
// C# program to find maximum possible// product of sub-sequence of size k// from given array of n integersusing System; class GFG { // Function to find maximum possible product static int maxProductSubarrayOfSizeK(int[] A, int n, int k) { // sorting given input array Array.Sort(A); // variable to store final product of // all element of sub-sequence of size k int product = 1; int i; // CASE I // If max element is 0 and // k is odd then max product will be 0 if (A[n - 1] == 0 && k % 2 != 0) return 0; // CASE II // If all elements are negative and // k is odd then max product will be // product of rightmost-subarray of size k if (A[n - 1] <= 0 && k % 2 != 0) { for (i = n - 1; i >= n - k; i--) product *= A[i]; return product; } // else // i is current left pointer index i = 0; // j is current right pointer index int j = n - 1; // CASE III // if k is odd and rightmost element in // sorted array is positive then it // must come in subsequence // Multiplying A[j] with product and // correspondingly changing j if (k % 2 != 0) { product *= A[j]; j--; k--; } // CASE IV // Now k is even // Now we deal with pairs // Each time a pair is multiplied to // product i.e.. two elements are added to // subsequence each time Effectively k becomes half // Hence, k >>= 1 means k /= 2 k >>= 1; // Now finding k corresponding pairs // to get maximum possible value of product for (int itr = 0; itr < k; itr++) { // product from left pointers int left_product = A[i] * A[i + 1]; // product from right pointers int right_product = A[j] * A[j - 1]; // Taking the max product from two choices // Correspondingly changing the pointer's position if (left_product > right_product) { product *= left_product; i += 2; } else { product *= right_product; j -= 2; } } // Finally return product return product; } // driver program public static void Main() { int[] A = { 1, 2, -1, -3, -6, 4 }; int n = A.Length; int k = 4; Console.WriteLine(maxProductSubarrayOfSizeK(A, n, k)); }} // This code is contributed by vt_m.
<?php// PHP code to find maximum possible product of// sub-sequence of size k from given array of n// integers // Required function function maxProductSubarrayOfSizeK($A, $n, $k){ // sorting given input array sort($A); // variable to store final product of all element // of sub-sequence of size k $product = 1; // CASE I // If max element is 0 and // k is odd then max product will be 0 if ($A[$n - 1] == 0 && ($k & 1)) return 0; // CASE II // If all elements are negative and // k is odd then max product will be // product of rightmost-subarray of size k if ($A[$n - 1] <= 0 && ($k & 1)) { for ($i = $n - 1; $i >= $n - $k; $i--) $product *= $A[$i]; return $product; } // else // i is current left pointer index $i = 0; // j is current right pointer index $j = $n - 1; // CASE III // if k is odd and rightmost element in // sorted array is positive then it // must come in subsequence // Multiplying A[j] with product and // correspondingly changing j if ($k & 1) { $product *= $A[$j]; $j--; $k--; } // CASE IV // Now k is even // Now we deal with pairs // Each time a pair is multiplied to product // ie.. two elements are added to subsequence each time // Effectively k becomes half // Hence, k >>= 1 means k /= 2 $k >>= 1; // Now finding k corresponding pairs // to get maximum possible value of product for ($itr = 0; $itr < $k; $itr++) { // product from left pointers $left_product = $A[$i] * $A[$i + 1]; // product from right pointers $right_product = $A[$j] * $A[$j - 1]; // Taking the max product from two choices // Correspondingly changing the pointer's position if ($left_product > $right_product) { $product *= $left_product; $i += 2; } else { $product *= $right_product; $j -= 2; } } // Finally return product return $product;} // Driver Code $A = array(1, 2, -1, -3, -6, 4 ); $n = count($A); $k = 4; echo maxProductSubarrayOfSizeK($A, $n, $k); // This code is contributed by ajit.?>
<script> // Javascript program to find maximum possible // product of sub-sequence of size k // from given array of n integers // Function to find maximum possible product function maxProductSubarrayOfSizeK(A, n, k) { // sorting given input array A.sort(function(a, b){return a - b}); // variable to store final product of // all element of sub-sequence of size k let product = 1; let i; // CASE I // If max element is 0 and // k is odd then max product will be 0 if (A[n - 1] == 0 && k % 2 != 0) return 0; // CASE II // If all elements are negative and // k is odd then max product will be // product of rightmost-subarray of size k if (A[n - 1] <= 0 && k % 2 != 0) { for (i = n - 1; i >= n - k; i--) product *= A[i]; return product; } // else // i is current left pointer index i = 0; // j is current right pointer index let j = n - 1; // CASE III // if k is odd and rightmost element in // sorted array is positive then it // must come in subsequence // Multiplying A[j] with product and // correspondingly changing j if (k % 2 != 0) { product *= A[j]; j--; k--; } // CASE IV // Now k is even // Now we deal with pairs // Each time a pair is multiplied to // product i.e.. two elements are added to // subsequence each time Effectively k becomes half // Hence, k >>= 1 means k /= 2 k >>= 1; // Now finding k corresponding pairs // to get maximum possible value of product for (let itr = 0; itr < k; itr++) { // product from left pointers let left_product = A[i] * A[i + 1]; // product from right pointers let right_product = A[j] * A[j - 1]; // Taking the max product from two choices // Correspondingly changing the pointer's position if (left_product > right_product) { product *= left_product; i += 2; } else { product *= right_product; j -= 2; } } // Finally return product return product; } let A = [ 1, 2, -1, -3, -6, 4 ]; let n = A.length; let k = 4; document.write(maxProductSubarrayOfSizeK(A, n, k)); </script>
Output:
144
Time Complexity : O(n * log n) O(n * log n) from sorting + O(k) from one traversal in array = O(n * log n) Auxiliary Space : O(1)This article is contributed by Pratik Chhajer. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
ukasp
Akanksha_Rai
jit_t
ManasChhabra2
divyeshrabadiya07
subsequence
Arrays
Sorting
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
|
[
{
"code": null,
"e": 25841,
"s": 25813,
"text": "\n04 May, 2021"
},
{
"code": null,
"e": 26017,
"s": 25841,
"text": "Given an array A[] of n integers, the task is to find a subsequence of size k whose product is maximum among all possible k sized subsequences of the given array.Constraints "
},
{
"code": null,
"e": 26044,
"s": 26017,
"text": "1 <= n <= 10^5\n1 <= k <= n"
},
{
"code": null,
"e": 26056,
"s": 26044,
"text": "Examples: "
},
{
"code": null,
"e": 26363,
"s": 26056,
"text": "Input : A[] = {1, 2, 0, 3}, \n k = 2\nOutput : 6\nExplanation : Subsequence containing elements\n{2, 3} gives maximum product : 2*3 = 6\n\nInput : A[] = {1, 2, -1, -3, -6, 4}, \n k = 4\nOutput : 144\nExplanation : Subsequence containing {2, -3, \n-6, 4} gives maximum product : 2*(-3)*(-6)*4 \n= 144"
},
{
"code": null,
"e": 26424,
"s": 26365,
"text": "Following are different cases that arise in this problem. "
},
{
"code": null,
"e": 26761,
"s": 26424,
"text": "CASE I: if the maximum element of A is 0 and k is odd Here if we donβt include 0 in subsequence then product will be less than 0, Since the product of an odd number of negative integers gives a negative integer. Hence 0 must be included in the subsequence. Since 0 is present in subsequence, the product of subsequence is 0. Answer = 0."
},
{
"code": null,
"e": 27212,
"s": 26761,
"text": "CASE II: if maximum element of A is negative and k is odd. Here the product will be less than 0, Since the product of an odd number of negative integers gives a negative integer. So to get the maximum product, we take the product of the smallest (absolute value wise) k elements. Since absolute value wise : | A[n-1] | > | A[n-2] | ... > | A[0] |. Hence we take product of A[n-1], A[n-2], A[n-3], .... A[n-k] Answer = A[n-1] * A[n-2] * ..... * A[n-k]"
},
{
"code": null,
"e": 27762,
"s": 27212,
"text": "CASE III: if maximum element of A is positive and k is odd. Here in subsequence of k size if all elements are < 0 then product will be less than 0, Since the product of an odd number of negative integers gives a negative integer. Hence, at least one element must be a positive integer in the subsequence. To get max product max positive number should be present in the subsequence. Now we need to add k-1 more elements to the subsequence. Since k is odd, k-1 becomes even. So the problem boils down to case IV. Answer = A[n-1] * Answer from CASE IV."
},
{
"code": null,
"e": 28114,
"s": 27762,
"text": "CASE IV: if k is even. Since k is even, we always add a pair in subsequence. So total pairs required to be added in subsequence is k/2. So for simplicity, our new k is k/2. Now since A is sorted, pair with the maximum product will always be either A[0]*A[1] OR A[n-1]*A[n-2]. In case of doubt about the previous statement think about negative numbers "
},
{
"code": null,
"e": 28319,
"s": 28114,
"text": "Now,\n if A[0]*A[1] > A[n-1]*A[n-2],\n second max product pair will be \n either A[2]*A[3] OR A[n-1]*[n-2].\n else second max product pair will be\n either A[0]*A[1] OR A[n-3]*[n-4]. "
},
{
"code": null,
"e": 28362,
"s": 28319,
"text": "Here is implementation of above solution "
},
{
"code": null,
"e": 28366,
"s": 28362,
"text": "C++"
},
{
"code": null,
"e": 28371,
"s": 28366,
"text": "Java"
},
{
"code": null,
"e": 28380,
"s": 28371,
"text": "Python 3"
},
{
"code": null,
"e": 28383,
"s": 28380,
"text": "C#"
},
{
"code": null,
"e": 28387,
"s": 28383,
"text": "PHP"
},
{
"code": null,
"e": 28398,
"s": 28387,
"text": "Javascript"
},
{
"code": "// C++ code to find maximum possible product of// sub-sequence of size k from given array of n// integers#include <algorithm> // for sorting#include <iostream>using namespace std; // Required functionint maxProductSubarrayOfSizeK(int A[], int n, int k){ // sorting given input array sort(A, A + n); // variable to store final product of all element // of sub-sequence of size k int product = 1; // CASE I // If max element is 0 and // k is odd then max product will be 0 if (A[n - 1] == 0 && (k & 1)) return 0; // CASE II // If all elements are negative and // k is odd then max product will be // product of rightmost-subarray of size k if (A[n - 1] <= 0 && (k & 1)) { for (int i = n - 1; i >= n - k; i--) product *= A[i]; return product; } // else // i is current left pointer index int i = 0; // j is current right pointer index int j = n - 1; // CASE III // if k is odd and rightmost element in // sorted array is positive then it // must come in subsequence // Multiplying A[j] with product and // correspondingly changing j if (k & 1) { product *= A[j]; j--; k--; } // CASE IV // Now k is even // Now we deal with pairs // Each time a pair is multiplied to product // ie.. two elements are added to subsequence each time // Effectively k becomes half // Hence, k >>= 1 means k /= 2 k >>= 1; // Now finding k corresponding pairs // to get maximum possible value of product for (int itr = 0; itr < k; itr++) { // product from left pointers int left_product = A[i] * A[i + 1]; // product from right pointers int right_product = A[j] * A[j - 1]; // Taking the max product from two choices // Correspondingly changing the pointer's position if (left_product > right_product) { product *= left_product; i += 2; } else { product *= right_product; j -= 2; } } // Finally return product return product;} // Driver Code to test above functionint main(){ int A[] = { 1, 2, -1, -3, -6, 4 }; int n = sizeof(A) / sizeof(A[0]); int k = 4; cout << maxProductSubarrayOfSizeK(A, n, k); return 0;}",
"e": 30704,
"s": 28398,
"text": null
},
{
"code": "// Java program to find maximum possible product of// sub-sequence of size k from given array of n// integersimport java.io.*;import java.util.*; class GFG { // Function to find maximum possible product static int maxProductSubarrayOfSizeK(int A[], int n, int k) { // sorting given input array Arrays.sort(A); // variable to store final product of all element // of sub-sequence of size k int product = 1; // CASE I // If max element is 0 and // k is odd then max product will be 0 if (A[n - 1] == 0 && k % 2 != 0) return 0; // CASE II // If all elements are negative and // k is odd then max product will be // product of rightmost-subarray of size k if (A[n - 1] <= 0 && k % 2 != 0) { for (int i = n - 1; i >= n - k; i--) product *= A[i]; return product; } // else // i is current left pointer index int i = 0; // j is current right pointer index int j = n - 1; // CASE III // if k is odd and rightmost element in // sorted array is positive then it // must come in subsequence // Multiplying A[j] with product and // correspondingly changing j if (k % 2 != 0) { product *= A[j]; j--; k--; } // CASE IV // Now k is even // Now we deal with pairs // Each time a pair is multiplied to product // ie.. two elements are added to subsequence each time // Effectively k becomes half // Hence, k >>= 1 means k /= 2 k >>= 1; // Now finding k corresponding pairs // to get maximum possible value of product for (int itr = 0; itr < k; itr++) { // product from left pointers int left_product = A[i] * A[i + 1]; // product from right pointers int right_product = A[j] * A[j - 1]; // Taking the max product from two choices // Correspondingly changing the pointer's position if (left_product > right_product) { product *= left_product; i += 2; } else { product *= right_product; j -= 2; } } // Finally return product return product; } // driver program public static void main(String[] args) { int A[] = { 1, 2, -1, -3, -6, 4 }; int n = A.length; int k = 4; System.out.println(maxProductSubarrayOfSizeK(A, n, k)); }} // Contributed by Pramod Kumar",
"e": 33350,
"s": 30704,
"text": null
},
{
"code": "# Python 3 code to find maximum possible# product of sub-sequence of size k from# given array of n integers # Required functiondef maxProductSubarrayOfSizeK(A, n, k): # sorting given input array A.sort() # variable to store final product of # all element of sub-sequence of size k product = 1 # CASE I # If max element is 0 and # k is odd then max product will be 0 if (A[n - 1] == 0 and (k & 1)): return 0 # CASE II # If all elements are negative and # k is odd then max product will be # product of rightmost-subarray of size k if (A[n - 1] <= 0 and (k & 1)) : for i in range(n - 1, n - k + 1, -1): product *= A[i] return product # else # i is current left pointer index i = 0 # j is current right pointer index j = n - 1 # CASE III # if k is odd and rightmost element in # sorted array is positive then it # must come in subsequence # Multiplying A[j] with product and # correspondingly changing j if (k & 1): product *= A[j] j-= 1 k-=1 # CASE IV # Now k is even. So, Now we deal with pairs # Each time a pair is multiplied to product # ie.. two elements are added to subsequence # each time. Effectively k becomes half # Hence, k >>= 1 means k /= 2 k >>= 1 # Now finding k corresponding pairs to get # maximum possible value of product for itr in range( k) : # product from left pointers left_product = A[i] * A[i + 1] # product from right pointers right_product = A[j] * A[j - 1] # Taking the max product from two # choices. Correspondingly changing # the pointer's position if (left_product > right_product) : product *= left_product i += 2 else : product *= right_product j -= 2 # Finally return product return product # Driver Codeif __name__ == \"__main__\": A = [ 1, 2, -1, -3, -6, 4 ] n = len(A) k = 4 print(maxProductSubarrayOfSizeK(A, n, k)) # This code is contributed by ita_c",
"e": 35452,
"s": 33350,
"text": null
},
{
"code": "// C# program to find maximum possible// product of sub-sequence of size k// from given array of n integersusing System; class GFG { // Function to find maximum possible product static int maxProductSubarrayOfSizeK(int[] A, int n, int k) { // sorting given input array Array.Sort(A); // variable to store final product of // all element of sub-sequence of size k int product = 1; int i; // CASE I // If max element is 0 and // k is odd then max product will be 0 if (A[n - 1] == 0 && k % 2 != 0) return 0; // CASE II // If all elements are negative and // k is odd then max product will be // product of rightmost-subarray of size k if (A[n - 1] <= 0 && k % 2 != 0) { for (i = n - 1; i >= n - k; i--) product *= A[i]; return product; } // else // i is current left pointer index i = 0; // j is current right pointer index int j = n - 1; // CASE III // if k is odd and rightmost element in // sorted array is positive then it // must come in subsequence // Multiplying A[j] with product and // correspondingly changing j if (k % 2 != 0) { product *= A[j]; j--; k--; } // CASE IV // Now k is even // Now we deal with pairs // Each time a pair is multiplied to // product i.e.. two elements are added to // subsequence each time Effectively k becomes half // Hence, k >>= 1 means k /= 2 k >>= 1; // Now finding k corresponding pairs // to get maximum possible value of product for (int itr = 0; itr < k; itr++) { // product from left pointers int left_product = A[i] * A[i + 1]; // product from right pointers int right_product = A[j] * A[j - 1]; // Taking the max product from two choices // Correspondingly changing the pointer's position if (left_product > right_product) { product *= left_product; i += 2; } else { product *= right_product; j -= 2; } } // Finally return product return product; } // driver program public static void Main() { int[] A = { 1, 2, -1, -3, -6, 4 }; int n = A.Length; int k = 4; Console.WriteLine(maxProductSubarrayOfSizeK(A, n, k)); }} // This code is contributed by vt_m.",
"e": 38139,
"s": 35452,
"text": null
},
{
"code": "<?php// PHP code to find maximum possible product of// sub-sequence of size k from given array of n// integers // Required function function maxProductSubarrayOfSizeK($A, $n, $k){ // sorting given input array sort($A); // variable to store final product of all element // of sub-sequence of size k $product = 1; // CASE I // If max element is 0 and // k is odd then max product will be 0 if ($A[$n - 1] == 0 && ($k & 1)) return 0; // CASE II // If all elements are negative and // k is odd then max product will be // product of rightmost-subarray of size k if ($A[$n - 1] <= 0 && ($k & 1)) { for ($i = $n - 1; $i >= $n - $k; $i--) $product *= $A[$i]; return $product; } // else // i is current left pointer index $i = 0; // j is current right pointer index $j = $n - 1; // CASE III // if k is odd and rightmost element in // sorted array is positive then it // must come in subsequence // Multiplying A[j] with product and // correspondingly changing j if ($k & 1) { $product *= $A[$j]; $j--; $k--; } // CASE IV // Now k is even // Now we deal with pairs // Each time a pair is multiplied to product // ie.. two elements are added to subsequence each time // Effectively k becomes half // Hence, k >>= 1 means k /= 2 $k >>= 1; // Now finding k corresponding pairs // to get maximum possible value of product for ($itr = 0; $itr < $k; $itr++) { // product from left pointers $left_product = $A[$i] * $A[$i + 1]; // product from right pointers $right_product = $A[$j] * $A[$j - 1]; // Taking the max product from two choices // Correspondingly changing the pointer's position if ($left_product > $right_product) { $product *= $left_product; $i += 2; } else { $product *= $right_product; $j -= 2; } } // Finally return product return $product;} // Driver Code $A = array(1, 2, -1, -3, -6, 4 ); $n = count($A); $k = 4; echo maxProductSubarrayOfSizeK($A, $n, $k); // This code is contributed by ajit.?>",
"e": 40382,
"s": 38139,
"text": null
},
{
"code": "<script> // Javascript program to find maximum possible // product of sub-sequence of size k // from given array of n integers // Function to find maximum possible product function maxProductSubarrayOfSizeK(A, n, k) { // sorting given input array A.sort(function(a, b){return a - b}); // variable to store final product of // all element of sub-sequence of size k let product = 1; let i; // CASE I // If max element is 0 and // k is odd then max product will be 0 if (A[n - 1] == 0 && k % 2 != 0) return 0; // CASE II // If all elements are negative and // k is odd then max product will be // product of rightmost-subarray of size k if (A[n - 1] <= 0 && k % 2 != 0) { for (i = n - 1; i >= n - k; i--) product *= A[i]; return product; } // else // i is current left pointer index i = 0; // j is current right pointer index let j = n - 1; // CASE III // if k is odd and rightmost element in // sorted array is positive then it // must come in subsequence // Multiplying A[j] with product and // correspondingly changing j if (k % 2 != 0) { product *= A[j]; j--; k--; } // CASE IV // Now k is even // Now we deal with pairs // Each time a pair is multiplied to // product i.e.. two elements are added to // subsequence each time Effectively k becomes half // Hence, k >>= 1 means k /= 2 k >>= 1; // Now finding k corresponding pairs // to get maximum possible value of product for (let itr = 0; itr < k; itr++) { // product from left pointers let left_product = A[i] * A[i + 1]; // product from right pointers let right_product = A[j] * A[j - 1]; // Taking the max product from two choices // Correspondingly changing the pointer's position if (left_product > right_product) { product *= left_product; i += 2; } else { product *= right_product; j -= 2; } } // Finally return product return product; } let A = [ 1, 2, -1, -3, -6, 4 ]; let n = A.length; let k = 4; document.write(maxProductSubarrayOfSizeK(A, n, k)); </script>",
"e": 42953,
"s": 40382,
"text": null
},
{
"code": null,
"e": 42963,
"s": 42953,
"text": "Output: "
},
{
"code": null,
"e": 42967,
"s": 42963,
"text": "144"
},
{
"code": null,
"e": 43519,
"s": 42967,
"text": "Time Complexity : O(n * log n) O(n * log n) from sorting + O(k) from one traversal in array = O(n * log n) Auxiliary Space : O(1)This article is contributed by Pratik Chhajer. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 43524,
"s": 43519,
"text": "vt_m"
},
{
"code": null,
"e": 43530,
"s": 43524,
"text": "ukasp"
},
{
"code": null,
"e": 43543,
"s": 43530,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 43549,
"s": 43543,
"text": "jit_t"
},
{
"code": null,
"e": 43563,
"s": 43549,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 43581,
"s": 43563,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 43593,
"s": 43581,
"text": "subsequence"
},
{
"code": null,
"e": 43600,
"s": 43593,
"text": "Arrays"
},
{
"code": null,
"e": 43608,
"s": 43600,
"text": "Sorting"
},
{
"code": null,
"e": 43615,
"s": 43608,
"text": "Arrays"
},
{
"code": null,
"e": 43623,
"s": 43615,
"text": "Sorting"
},
{
"code": null,
"e": 43721,
"s": 43623,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43789,
"s": 43721,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 43833,
"s": 43789,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 43881,
"s": 43833,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 43904,
"s": 43881,
"text": "Introduction to Arrays"
}
] |
ML - Candidate Elimination Algorithm - GeeksforGeeks
|
17 Mar, 2021
The candidate elimination algorithm incrementally builds the version space given a hypothesis space H and a set E of examples. The examples are added one by one; each example possibly shrinks the version space by removing the hypotheses that are inconsistent with the example. The candidate elimination algorithm does this by updating the general and specific boundary for each new example.
You can consider this as an extended form of Find-S algorithm.
Consider both positive and negative examples.
Actually, positive examples are used here as Find-S algorithm (Basically they are generalizing from the specification).
While the negative example is specified from generalize form.
Terms Used:
Concept learning: Concept learning is basically learning task of the machine (Learn by Train data)
General Hypothesis: Not Specifying features to learn the machine.
G = {β?β, β?β,β?β,β?β...}: Number of attributes
Specific Hypothesis: Specifying features to learn machine (Specific feature)
S= {βpiβ,βpiβ,βpiβ...}: Number of pi depends on number of attributes.
Version Space: It is intermediate of general hypothesis and Specific hypothesis. It not only just written one hypothesis but a set of all possible hypothesis based on training data-set.
Algorithm:
Step1: Load Data set
Step2: Initialize General Hypothesis and Specific Hypothesis.
Step3: For each training example
Step4: If example is positive example
if attribute_value == hypothesis_value:
Do nothing
else:
replace attribute value with '?' (Basically generalizing it)
Step5: If example is Negative example
Make generalize hypothesis more specific.
Example:
Consider the dataset given below:
Algorithmic steps:
Initially : G = [[?, ?, ?, ?, ?, ?], [?, ?, ?, ?, ?, ?], [?, ?, ?, ?, ?, ?],
[?, ?, ?, ?, ?, ?], [?, ?, ?, ?, ?, ?], [?, ?, ?, ?, ?, ?]]
S = [Null, Null, Null, Null, Null, Null]
For instance 1 : <'sunny','warm','normal','strong','warm ','same'> and positive output.
G1 = G
S1 = ['sunny','warm','normal','strong','warm ','same']
For instance 2 : <'sunny','warm','high','strong','warm ','same'> and positive output.
G2 = G
S2 = ['sunny','warm',?,'strong','warm ','same']
For instance 3 : <'rainy','cold','high','strong','warm ','change'> and negative output.
G3 = [['sunny', ?, ?, ?, ?, ?], [?, 'warm', ?, ?, ?, ?], [?, ?, ?, ?, ?, ?],
[?, ?, ?, ?, ?, ?], [?, ?, ?, ?, ?, ?], [?, ?, ?, ?, ?, 'same']]
S3 = S2
For instance 4 : <'sunny','warm','high','strong','cool','change'> and positive output.
G4 = G3
S4 = ['sunny','warm',?,'strong', ?, ?]
At last, by synchronizing the G4 and S4 algorithm produce the output.
G = [['sunny', ?, ?, ?, ?, ?], [?, 'warm', ?, ?, ?, ?]]
S = ['sunny','warm',?,'strong', ?, ?]
pintoshibani8
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Reinforcement learning
Activation functions in Neural Networks
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
ML | Underfitting and Overfitting
Search Algorithms in AI
Clustering in Machine Learning
Intuition of Adam Optimizer
Elbow Method for optimal value of k in KMeans
|
[
{
"code": null,
"e": 25873,
"s": 25845,
"text": "\n17 Mar, 2021"
},
{
"code": null,
"e": 26265,
"s": 25873,
"text": "The candidate elimination algorithm incrementally builds the version space given a hypothesis space H and a set E of examples. The examples are added one by one; each example possibly shrinks the version space by removing the hypotheses that are inconsistent with the example. The candidate elimination algorithm does this by updating the general and specific boundary for each new example. "
},
{
"code": null,
"e": 26328,
"s": 26265,
"text": "You can consider this as an extended form of Find-S algorithm."
},
{
"code": null,
"e": 26374,
"s": 26328,
"text": "Consider both positive and negative examples."
},
{
"code": null,
"e": 26494,
"s": 26374,
"text": "Actually, positive examples are used here as Find-S algorithm (Basically they are generalizing from the specification)."
},
{
"code": null,
"e": 26556,
"s": 26494,
"text": "While the negative example is specified from generalize form."
},
{
"code": null,
"e": 26570,
"s": 26556,
"text": "Terms Used: "
},
{
"code": null,
"e": 26669,
"s": 26570,
"text": "Concept learning: Concept learning is basically learning task of the machine (Learn by Train data)"
},
{
"code": null,
"e": 26735,
"s": 26669,
"text": "General Hypothesis: Not Specifying features to learn the machine."
},
{
"code": null,
"e": 26783,
"s": 26735,
"text": "G = {β?β, β?β,β?β,β?β...}: Number of attributes"
},
{
"code": null,
"e": 26860,
"s": 26783,
"text": "Specific Hypothesis: Specifying features to learn machine (Specific feature)"
},
{
"code": null,
"e": 26930,
"s": 26860,
"text": "S= {βpiβ,βpiβ,βpiβ...}: Number of pi depends on number of attributes."
},
{
"code": null,
"e": 27116,
"s": 26930,
"text": "Version Space: It is intermediate of general hypothesis and Specific hypothesis. It not only just written one hypothesis but a set of all possible hypothesis based on training data-set."
},
{
"code": null,
"e": 27127,
"s": 27116,
"text": "Algorithm:"
},
{
"code": null,
"e": 27551,
"s": 27127,
"text": "Step1: Load Data set\nStep2: Initialize General Hypothesis and Specific Hypothesis.\nStep3: For each training example \nStep4: If example is positive example \n if attribute_value == hypothesis_value:\n Do nothing \n else:\n replace attribute value with '?' (Basically generalizing it)\nStep5: If example is Negative example \n Make generalize hypothesis more specific.\n\n\n\n\n\n"
},
{
"code": null,
"e": 27560,
"s": 27551,
"text": "Example:"
},
{
"code": null,
"e": 27594,
"s": 27560,
"text": "Consider the dataset given below:"
},
{
"code": null,
"e": 27613,
"s": 27594,
"text": "Algorithmic steps:"
},
{
"code": null,
"e": 28740,
"s": 27613,
"text": "Initially : G = [[?, ?, ?, ?, ?, ?], [?, ?, ?, ?, ?, ?], [?, ?, ?, ?, ?, ?], \n [?, ?, ?, ?, ?, ?], [?, ?, ?, ?, ?, ?], [?, ?, ?, ?, ?, ?]]\n S = [Null, Null, Null, Null, Null, Null]\n \nFor instance 1 : <'sunny','warm','normal','strong','warm ','same'> and positive output.\n G1 = G\n S1 = ['sunny','warm','normal','strong','warm ','same']\n \nFor instance 2 : <'sunny','warm','high','strong','warm ','same'> and positive output.\n G2 = G\n S2 = ['sunny','warm',?,'strong','warm ','same']\n \nFor instance 3 : <'rainy','cold','high','strong','warm ','change'> and negative output.\n G3 = [['sunny', ?, ?, ?, ?, ?], [?, 'warm', ?, ?, ?, ?], [?, ?, ?, ?, ?, ?], \n [?, ?, ?, ?, ?, ?], [?, ?, ?, ?, ?, ?], [?, ?, ?, ?, ?, 'same']]\n S3 = S2 \n \nFor instance 4 : <'sunny','warm','high','strong','cool','change'> and positive output.\n G4 = G3\n S4 = ['sunny','warm',?,'strong', ?, ?] \n \nAt last, by synchronizing the G4 and S4 algorithm produce the output.\n\n\n"
},
{
"code": null,
"e": 28839,
"s": 28740,
"text": "G = [['sunny', ?, ?, ?, ?, ?], [?, 'warm', ?, ?, ?, ?]]\nS = ['sunny','warm',?,'strong', ?, ?] \n\n\n\n"
},
{
"code": null,
"e": 28853,
"s": 28839,
"text": "pintoshibani8"
},
{
"code": null,
"e": 28870,
"s": 28853,
"text": "Machine Learning"
},
{
"code": null,
"e": 28887,
"s": 28870,
"text": "Machine Learning"
},
{
"code": null,
"e": 28985,
"s": 28887,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29008,
"s": 28985,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 29031,
"s": 29008,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 29071,
"s": 29031,
"text": "Activation functions in Neural Networks"
},
{
"code": null,
"e": 29112,
"s": 29071,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 29145,
"s": 29112,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 29179,
"s": 29145,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 29203,
"s": 29179,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 29234,
"s": 29203,
"text": "Clustering in Machine Learning"
},
{
"code": null,
"e": 29262,
"s": 29234,
"text": "Intuition of Adam Optimizer"
}
] |
How to generate a n-digit number using JavaScript ? - GeeksforGeeks
|
09 Jan, 2020
The task is to generate an n-Digit random number with the help of JavaScript.
Below two approaches are discussed. In the first example, it uses the minimum and the maximum number of those many digits, while the second one uses the substring concept to trim the digit.You can also generate random numbers in the given range using JavaScript.
Approach 1: Get the minimum and maximum number of n digits in variable min and max respectively. Then generate a random number using Math.random()(value lies between 0 and 1). Multiply the number by (max-min+1), get its floor value and then add min value to it.
Example: This example implements the above approach.<!DOCTYPE HTML><html><head> <title> Generate a n-digit number using JavaScript </title> <style> body { text-align: center; } h1 { color: green; } #geeks { color: green; font-size: 29px; font-weight: bold; } </style></head> <body> <h1> GeeksforGeeks </h1> <p> <!-- min and max are 5 digit so--> Click on the button to generate random 5 digit number </p> <button onclick="gfg();"> click here </button> <p id="geeks"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('geeks'); function gfg() { var minm = 10000; var maxm = 99999; down.innerHTML = Math.floor(Math .random() * (maxm - minm + 1)) + minm; } </script></body> </html>
<!DOCTYPE HTML><html><head> <title> Generate a n-digit number using JavaScript </title> <style> body { text-align: center; } h1 { color: green; } #geeks { color: green; font-size: 29px; font-weight: bold; } </style></head> <body> <h1> GeeksforGeeks </h1> <p> <!-- min and max are 5 digit so--> Click on the button to generate random 5 digit number </p> <button onclick="gfg();"> click here </button> <p id="geeks"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('geeks'); function gfg() { var minm = 10000; var maxm = 99999; down.innerHTML = Math.floor(Math .random() * (maxm - minm + 1)) + minm; } </script></body> </html>
Output:
Approach 2: Use Math.random() method to generate a random number between 0 and 1. Now we will use .substring() method to get a part of the random number after converting it to string.
Example: This example implements the above approach.<!DOCTYPE HTML><html> <head> <title> Generate a n-digit number using JavaScript </title> <style> body { text-align: center; } h1 { color: green; } #geeks { color: green; font-size: 29px; font-weight: bold; } </style></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <p> Click on the button to generate random 6 digit number </p> <button onclick="gfg();"> click here </button> <p id="geeks"> </p> <script> var down = document.getElementById('geeks'); function gfg() { down.innerHTML = ("" + Math.random()).substring(2, 8); } </script></body> </html>
<!DOCTYPE HTML><html> <head> <title> Generate a n-digit number using JavaScript </title> <style> body { text-align: center; } h1 { color: green; } #geeks { color: green; font-size: 29px; font-weight: bold; } </style></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <p> Click on the button to generate random 6 digit number </p> <button onclick="gfg();"> click here </button> <p id="geeks"> </p> <script> var down = document.getElementById('geeks'); function gfg() { down.innerHTML = ("" + Math.random()).substring(2, 8); } </script></body> </html>
Output:
CSS-Misc
HTML-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26545,
"s": 26517,
"text": "\n09 Jan, 2020"
},
{
"code": null,
"e": 26623,
"s": 26545,
"text": "The task is to generate an n-Digit random number with the help of JavaScript."
},
{
"code": null,
"e": 26886,
"s": 26623,
"text": "Below two approaches are discussed. In the first example, it uses the minimum and the maximum number of those many digits, while the second one uses the substring concept to trim the digit.You can also generate random numbers in the given range using JavaScript."
},
{
"code": null,
"e": 27148,
"s": 26886,
"text": "Approach 1: Get the minimum and maximum number of n digits in variable min and max respectively. Then generate a random number using Math.random()(value lies between 0 and 1). Multiply the number by (max-min+1), get its floor value and then add min value to it."
},
{
"code": null,
"e": 28143,
"s": 27148,
"text": "Example: This example implements the above approach.<!DOCTYPE HTML><html><head> <title> Generate a n-digit number using JavaScript </title> <style> body { text-align: center; } h1 { color: green; } #geeks { color: green; font-size: 29px; font-weight: bold; } </style></head> <body> <h1> GeeksforGeeks </h1> <p> <!-- min and max are 5 digit so--> Click on the button to generate random 5 digit number </p> <button onclick=\"gfg();\"> click here </button> <p id=\"geeks\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('geeks'); function gfg() { var minm = 10000; var maxm = 99999; down.innerHTML = Math.floor(Math .random() * (maxm - minm + 1)) + minm; } </script></body> </html>"
},
{
"code": "<!DOCTYPE HTML><html><head> <title> Generate a n-digit number using JavaScript </title> <style> body { text-align: center; } h1 { color: green; } #geeks { color: green; font-size: 29px; font-weight: bold; } </style></head> <body> <h1> GeeksforGeeks </h1> <p> <!-- min and max are 5 digit so--> Click on the button to generate random 5 digit number </p> <button onclick=\"gfg();\"> click here </button> <p id=\"geeks\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('geeks'); function gfg() { var minm = 10000; var maxm = 99999; down.innerHTML = Math.floor(Math .random() * (maxm - minm + 1)) + minm; } </script></body> </html>",
"e": 29086,
"s": 28143,
"text": null
},
{
"code": null,
"e": 29094,
"s": 29086,
"text": "Output:"
},
{
"code": null,
"e": 29278,
"s": 29094,
"text": "Approach 2: Use Math.random() method to generate a random number between 0 and 1. Now we will use .substring() method to get a part of the random number after converting it to string."
},
{
"code": null,
"e": 30124,
"s": 29278,
"text": "Example: This example implements the above approach.<!DOCTYPE HTML><html> <head> <title> Generate a n-digit number using JavaScript </title> <style> body { text-align: center; } h1 { color: green; } #geeks { color: green; font-size: 29px; font-weight: bold; } </style></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p> Click on the button to generate random 6 digit number </p> <button onclick=\"gfg();\"> click here </button> <p id=\"geeks\"> </p> <script> var down = document.getElementById('geeks'); function gfg() { down.innerHTML = (\"\" + Math.random()).substring(2, 8); } </script></body> </html>"
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Generate a n-digit number using JavaScript </title> <style> body { text-align: center; } h1 { color: green; } #geeks { color: green; font-size: 29px; font-weight: bold; } </style></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p> Click on the button to generate random 6 digit number </p> <button onclick=\"gfg();\"> click here </button> <p id=\"geeks\"> </p> <script> var down = document.getElementById('geeks'); function gfg() { down.innerHTML = (\"\" + Math.random()).substring(2, 8); } </script></body> </html>",
"e": 30918,
"s": 30124,
"text": null
},
{
"code": null,
"e": 30926,
"s": 30918,
"text": "Output:"
},
{
"code": null,
"e": 30935,
"s": 30926,
"text": "CSS-Misc"
},
{
"code": null,
"e": 30945,
"s": 30935,
"text": "HTML-Misc"
},
{
"code": null,
"e": 30956,
"s": 30945,
"text": "JavaScript"
},
{
"code": null,
"e": 30973,
"s": 30956,
"text": "Web Technologies"
},
{
"code": null,
"e": 31000,
"s": 30973,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 31098,
"s": 31000,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31138,
"s": 31098,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31199,
"s": 31138,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 31240,
"s": 31199,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 31262,
"s": 31240,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 31316,
"s": 31262,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 31356,
"s": 31316,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31389,
"s": 31356,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31432,
"s": 31389,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 31482,
"s": 31432,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Max(), Min() and Mod() Function in MariaDB - GeeksforGeeks
|
13 Oct, 2020
1. Max() Function :In MariaDB, the Max() function is used to returns the maximum value of an expression. In this function, a query is passed and in the eligible records which value will be maximum, that will return a result. It works like maximum function in the processed query. An expression will be passed as a parameter and it will return the maximum value in the expression.
Syntax :
Max(expression)
Parameter : Required. An expression.expression : The input value.Returns : The maximum value in the expression.
Table β IPL
Example-1 :
SELECT Max(Score) AS MAX_Score
FROM IPL;
Output :
Example-2 :
SELECT Max(Score) AS MAX_Score
FROM IPL
WHERE Score < 190;
Output :
Example-3 :
SELECT Max(Score) AS MAX_Score
FROM IPL
WHERE Score < 160;
Output :
2. Min() Function :In MariaDB, the Min() function is used to returns the minimum value of an expression. In this function, a query is passed and in the eligible records which value will be minimum, that will return a result. It works like minimum function in the processed query. An expression will be passed as a parameter and it will return the minimum value in the expression.
Syntax :
Min(expression)
Parameter : Required. An expression.expression : The input value.Returns : The minimum value in the expression.
Example-1 :
SELECT Min(Score) AS Min_Score
FROM IPL;
Output :
Example-2 :
SELECT Min(Score) AS Min_Score
FROM IPL
WHERE Score > 150;
Output :
Example-3 :
SELECT Min(Score) AS Min_Score
FROM IPL
WHERE Score > 170;
Output :
3. Mod() Function :In MariaDB, the Mod() function used to return the remainder of n divided by m.In this function, two-parameter will be passed first is n (a value that will be divided by m) and the second will be m (a value that will be divided into n). The function uses the formula of n / m and returned what will be a remainder without any rounding.
Syntax :
MOD(n, m)
OR
n MOD m
OR
n % m
Parameters : Required. Two numeral values.
n : Divident (Value that will be divided).
m : Divisor (Value which the dividend is being divided by).
Returns : Remainder value (without any rounding) as the result of the division.
Example-1 :
SELECT MOD(20, 5);
Output :
0
Example-2 :
SELECT 21 MOD 4;
Output :
1
Example-3 :
SELECT 51 % 7;
Output :
2
DBMS-SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Subquery
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
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": "\n13 Oct, 2020"
},
{
"code": null,
"e": 25893,
"s": 25513,
"text": "1. Max() Function :In MariaDB, the Max() function is used to returns the maximum value of an expression. In this function, a query is passed and in the eligible records which value will be maximum, that will return a result. It works like maximum function in the processed query. An expression will be passed as a parameter and it will return the maximum value in the expression."
},
{
"code": null,
"e": 25902,
"s": 25893,
"text": "Syntax :"
},
{
"code": null,
"e": 25918,
"s": 25902,
"text": "Max(expression)"
},
{
"code": null,
"e": 26030,
"s": 25918,
"text": "Parameter : Required. An expression.expression : The input value.Returns : The maximum value in the expression."
},
{
"code": null,
"e": 26042,
"s": 26030,
"text": "Table β IPL"
},
{
"code": null,
"e": 26054,
"s": 26042,
"text": "Example-1 :"
},
{
"code": null,
"e": 26095,
"s": 26054,
"text": "SELECT Max(Score) AS MAX_Score\nFROM IPL;"
},
{
"code": null,
"e": 26104,
"s": 26095,
"text": "Output :"
},
{
"code": null,
"e": 26116,
"s": 26104,
"text": "Example-2 :"
},
{
"code": null,
"e": 26175,
"s": 26116,
"text": "SELECT Max(Score) AS MAX_Score\nFROM IPL\nWHERE Score < 190;"
},
{
"code": null,
"e": 26184,
"s": 26175,
"text": "Output :"
},
{
"code": null,
"e": 26196,
"s": 26184,
"text": "Example-3 :"
},
{
"code": null,
"e": 26255,
"s": 26196,
"text": "SELECT Max(Score) AS MAX_Score\nFROM IPL\nWHERE Score < 160;"
},
{
"code": null,
"e": 26264,
"s": 26255,
"text": "Output :"
},
{
"code": null,
"e": 26644,
"s": 26264,
"text": "2. Min() Function :In MariaDB, the Min() function is used to returns the minimum value of an expression. In this function, a query is passed and in the eligible records which value will be minimum, that will return a result. It works like minimum function in the processed query. An expression will be passed as a parameter and it will return the minimum value in the expression."
},
{
"code": null,
"e": 26653,
"s": 26644,
"text": "Syntax :"
},
{
"code": null,
"e": 26669,
"s": 26653,
"text": "Min(expression)"
},
{
"code": null,
"e": 26781,
"s": 26669,
"text": "Parameter : Required. An expression.expression : The input value.Returns : The minimum value in the expression."
},
{
"code": null,
"e": 26793,
"s": 26781,
"text": "Example-1 :"
},
{
"code": null,
"e": 26834,
"s": 26793,
"text": "SELECT Min(Score) AS Min_Score\nFROM IPL;"
},
{
"code": null,
"e": 26843,
"s": 26834,
"text": "Output :"
},
{
"code": null,
"e": 26855,
"s": 26843,
"text": "Example-2 :"
},
{
"code": null,
"e": 26914,
"s": 26855,
"text": "SELECT Min(Score) AS Min_Score\nFROM IPL\nWHERE Score > 150;"
},
{
"code": null,
"e": 26923,
"s": 26914,
"text": "Output :"
},
{
"code": null,
"e": 26935,
"s": 26923,
"text": "Example-3 :"
},
{
"code": null,
"e": 26995,
"s": 26935,
"text": "SELECT Min(Score) AS Min_Score\nFROM IPL\nWHERE Score > 170; "
},
{
"code": null,
"e": 27004,
"s": 26995,
"text": "Output :"
},
{
"code": null,
"e": 27358,
"s": 27004,
"text": "3. Mod() Function :In MariaDB, the Mod() function used to return the remainder of n divided by m.In this function, two-parameter will be passed first is n (a value that will be divided by m) and the second will be m (a value that will be divided into n). The function uses the formula of n / m and returned what will be a remainder without any rounding."
},
{
"code": null,
"e": 27367,
"s": 27358,
"text": "Syntax :"
},
{
"code": null,
"e": 27398,
"s": 27367,
"text": "MOD(n, m)\nOR\nn MOD m\nOR\nn % m "
},
{
"code": null,
"e": 27441,
"s": 27398,
"text": "Parameters : Required. Two numeral values."
},
{
"code": null,
"e": 27484,
"s": 27441,
"text": "n : Divident (Value that will be divided)."
},
{
"code": null,
"e": 27544,
"s": 27484,
"text": "m : Divisor (Value which the dividend is being divided by)."
},
{
"code": null,
"e": 27624,
"s": 27544,
"text": "Returns : Remainder value (without any rounding) as the result of the division."
},
{
"code": null,
"e": 27636,
"s": 27624,
"text": "Example-1 :"
},
{
"code": null,
"e": 27655,
"s": 27636,
"text": "SELECT MOD(20, 5);"
},
{
"code": null,
"e": 27664,
"s": 27655,
"text": "Output :"
},
{
"code": null,
"e": 27666,
"s": 27664,
"text": "0"
},
{
"code": null,
"e": 27678,
"s": 27666,
"text": "Example-2 :"
},
{
"code": null,
"e": 27695,
"s": 27678,
"text": "SELECT 21 MOD 4;"
},
{
"code": null,
"e": 27704,
"s": 27695,
"text": "Output :"
},
{
"code": null,
"e": 27706,
"s": 27704,
"text": "1"
},
{
"code": null,
"e": 27718,
"s": 27706,
"text": "Example-3 :"
},
{
"code": null,
"e": 27733,
"s": 27718,
"text": "SELECT 51 % 7;"
},
{
"code": null,
"e": 27742,
"s": 27733,
"text": "Output :"
},
{
"code": null,
"e": 27744,
"s": 27742,
"text": "2"
},
{
"code": null,
"e": 27753,
"s": 27744,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 27757,
"s": 27753,
"text": "SQL"
},
{
"code": null,
"e": 27761,
"s": 27757,
"text": "SQL"
},
{
"code": null,
"e": 27859,
"s": 27761,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27925,
"s": 27859,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 27940,
"s": 27925,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 27997,
"s": 27940,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 28029,
"s": 27997,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 28107,
"s": 28029,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 28143,
"s": 28107,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 28160,
"s": 28143,
"text": "SQL using Python"
},
{
"code": null,
"e": 28226,
"s": 28160,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
},
{
"code": null,
"e": 28288,
"s": 28226,
"text": "How to Select Data Between Two Dates and Times in SQL Server?"
}
] |
How to Count the Number of Rows in a MySQL Table in Python? - GeeksforGeeks
|
12 Nov, 2020
MySQL server is an open-source relational database management system which is a major support for web-based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. In order to access MySQL databases from a web server we use various modules in Python such as PyMySQL, mysql.connector, etc.
In this article, we are going to get the number of rows in a specific MySQL table in a Database. First, we are going to connect to a database having a MySQL table. The SQL query that is going to be used is:
SELECT * FROM table-name
And finally, display the number of rows in the table.
Below are some programs which depict how to count the number of rows from a MySQL table in a Database:
Example 1
Below is the table geeksdemo in database geek which is going to be accessed by a Python script:
Below is the program to get the number of rows in a MySQL table:
Python3
# import required modulesimport pymysqlpymysql.install_as_MySQLdb()import MySQLdb # connect python with mysql with your hostname, # username, password and databasedb= MySQLdb.connect("localhost", "root", "", "geek") # get cursor objectcursor= db.cursor() # get number of rows in a table and give your table# name in the querynumber_of_rows = cursor.execute("SELECT * FROM geeksdemo") # print the number of rowsprint(number_of_rows)
Output:
Example 2:
Here is another example to get the number of rows from a table in a given database, below is the table scheme and rows:
Below is the python script to get row count from the table TechCompanies:
Python3
# import required modulesimport pymysqlpymysql.install_as_MySQLdb()import MySQLdb # connect python with mysql with your hostname, # username, password and databasedb= MySQLdb.connect("localhost", "root", "", "techgeeks") # get cursor objectcursor= db.cursor() # get number of rows in a table and give your table# name in the querynumber_of_rows = cursor.execute("SELECT * FROM techcompanies") # print the number of rowsprint(number_of_rows)
Output:
Python-mySQL
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n12 Nov, 2020"
},
{
"code": null,
"e": 25921,
"s": 25537,
"text": "MySQL server is an open-source relational database management system which is a major support for web-based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. In order to access MySQL databases from a web server we use various modules in Python such as PyMySQL, mysql.connector, etc. "
},
{
"code": null,
"e": 26128,
"s": 25921,
"text": "In this article, we are going to get the number of rows in a specific MySQL table in a Database. First, we are going to connect to a database having a MySQL table. The SQL query that is going to be used is:"
},
{
"code": null,
"e": 26154,
"s": 26128,
"text": "SELECT * FROM table-name\n"
},
{
"code": null,
"e": 26209,
"s": 26154,
"text": " And finally, display the number of rows in the table."
},
{
"code": null,
"e": 26312,
"s": 26209,
"text": "Below are some programs which depict how to count the number of rows from a MySQL table in a Database:"
},
{
"code": null,
"e": 26322,
"s": 26312,
"text": "Example 1"
},
{
"code": null,
"e": 26418,
"s": 26322,
"text": "Below is the table geeksdemo in database geek which is going to be accessed by a Python script:"
},
{
"code": null,
"e": 26483,
"s": 26418,
"text": "Below is the program to get the number of rows in a MySQL table:"
},
{
"code": null,
"e": 26491,
"s": 26483,
"text": "Python3"
},
{
"code": "# import required modulesimport pymysqlpymysql.install_as_MySQLdb()import MySQLdb # connect python with mysql with your hostname, # username, password and databasedb= MySQLdb.connect(\"localhost\", \"root\", \"\", \"geek\") # get cursor objectcursor= db.cursor() # get number of rows in a table and give your table# name in the querynumber_of_rows = cursor.execute(\"SELECT * FROM geeksdemo\") # print the number of rowsprint(number_of_rows)",
"e": 26927,
"s": 26491,
"text": null
},
{
"code": null,
"e": 26935,
"s": 26927,
"text": "Output:"
},
{
"code": null,
"e": 26946,
"s": 26935,
"text": "Example 2:"
},
{
"code": null,
"e": 27066,
"s": 26946,
"text": "Here is another example to get the number of rows from a table in a given database, below is the table scheme and rows:"
},
{
"code": null,
"e": 27140,
"s": 27066,
"text": "Below is the python script to get row count from the table TechCompanies:"
},
{
"code": null,
"e": 27148,
"s": 27140,
"text": "Python3"
},
{
"code": "# import required modulesimport pymysqlpymysql.install_as_MySQLdb()import MySQLdb # connect python with mysql with your hostname, # username, password and databasedb= MySQLdb.connect(\"localhost\", \"root\", \"\", \"techgeeks\") # get cursor objectcursor= db.cursor() # get number of rows in a table and give your table# name in the querynumber_of_rows = cursor.execute(\"SELECT * FROM techcompanies\") # print the number of rowsprint(number_of_rows)",
"e": 27593,
"s": 27148,
"text": null
},
{
"code": null,
"e": 27601,
"s": 27593,
"text": "Output:"
},
{
"code": null,
"e": 27614,
"s": 27601,
"text": "Python-mySQL"
},
{
"code": null,
"e": 27621,
"s": 27614,
"text": "Python"
},
{
"code": null,
"e": 27719,
"s": 27621,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27751,
"s": 27719,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27793,
"s": 27751,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27835,
"s": 27793,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27891,
"s": 27835,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27918,
"s": 27891,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27949,
"s": 27918,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27988,
"s": 27949,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28017,
"s": 27988,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28039,
"s": 28017,
"text": "Defaultdict in Python"
}
] |
How to check two elements are same using jQuery/JavaScript ? - GeeksforGeeks
|
16 Oct, 2019
Given an HTML document containing two elements and the task is to check whether both elements are same or not with the help of JavaScript.
Approach 1: Use is() method to check both selected elements are same or not. It takes an element as argument and check if it is equal to the other element.
Example: This example implements the above approach.
<!DOCTYPE HTML> <html> <head> <title> How to check two elements are same using jQuery/JavaScript? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body style = "text-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 = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var id1 = "GFG_UP"; var id2 = "GFG_UP"; up.innerHTML = "Click on the button to check if " + "both elements are equal.<br>" + "id1 = " + id1 + "<br>id2 = " + id2; function GFG_Fun() { if ($('#GFG_UP').is($('#GFG_UP'))) { down.innerHTML = "Both elements are same"; } else { down.innerHTML = "Both elements are different"; } } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Approach 2: The == operator is used to compare two JavaScript elements. If both elements are equal then it returns True otherwise returns False.
Example: This example implaments the above approach.
<!DOCTYPE HTML> <html> <head> <title> How to check two elements are same using jQuery/JavaScript ? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body style = "text-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 = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var id1 = "GFG_UP"; var id2 = "GFG_DOWN"; up.innerHTML = "Click on the button to check if both" + " elements are equal.<br>" + "id1 = " + id1 + "<br>id2 = " + id2; function GFG_Fun() { if ($('#GFG_UP')[0] == $('#GFG_DOWN')[0]) { down.innerHTML = "Both elements are same"; } else { down.innerHTML = "Both elements are different"; } } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
javascript-basics
jQuery-Basics
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 26718,
"s": 26690,
"text": "\n16 Oct, 2019"
},
{
"code": null,
"e": 26857,
"s": 26718,
"text": "Given an HTML document containing two elements and the task is to check whether both elements are same or not with the help of JavaScript."
},
{
"code": null,
"e": 27013,
"s": 26857,
"text": "Approach 1: Use is() method to check both selected elements are same or not. It takes an element as argument and check if it is equal to the other element."
},
{
"code": null,
"e": 27066,
"s": 27013,
"text": "Example: This example implements the above approach."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> How to check two elements are same using jQuery/JavaScript? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body style = \"text-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 = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var id1 = \"GFG_UP\"; var id2 = \"GFG_UP\"; up.innerHTML = \"Click on the button to check if \" + \"both elements are equal.<br>\" + \"id1 = \" + id1 + \"<br>id2 = \" + id2; function GFG_Fun() { if ($('#GFG_UP').is($('#GFG_UP'))) { down.innerHTML = \"Both elements are same\"; } else { down.innerHTML = \"Both elements are different\"; } } </script> </body> </html>",
"e": 28309,
"s": 27066,
"text": null
},
{
"code": null,
"e": 28317,
"s": 28309,
"text": "Output:"
},
{
"code": null,
"e": 28348,
"s": 28317,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 28378,
"s": 28348,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 28523,
"s": 28378,
"text": "Approach 2: The == operator is used to compare two JavaScript elements. If both elements are equal then it returns True otherwise returns False."
},
{
"code": null,
"e": 28576,
"s": 28523,
"text": "Example: This example implaments the above approach."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> How to check two elements are same using jQuery/JavaScript ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body style = \"text-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 = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var id1 = \"GFG_UP\"; var id2 = \"GFG_DOWN\"; up.innerHTML = \"Click on the button to check if both\" + \" elements are equal.<br>\" + \"id1 = \" + id1 + \"<br>id2 = \" + id2; function GFG_Fun() { if ($('#GFG_UP')[0] == $('#GFG_DOWN')[0]) { down.innerHTML = \"Both elements are same\"; } else { down.innerHTML = \"Both elements are different\"; } } </script> </body> </html>",
"e": 29829,
"s": 28576,
"text": null
},
{
"code": null,
"e": 29837,
"s": 29829,
"text": "Output:"
},
{
"code": null,
"e": 29868,
"s": 29837,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 29898,
"s": 29868,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 29916,
"s": 29898,
"text": "javascript-basics"
},
{
"code": null,
"e": 29930,
"s": 29916,
"text": "jQuery-Basics"
},
{
"code": null,
"e": 29941,
"s": 29930,
"text": "JavaScript"
},
{
"code": null,
"e": 29958,
"s": 29941,
"text": "Web Technologies"
},
{
"code": null,
"e": 29985,
"s": 29958,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 30083,
"s": 29985,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30123,
"s": 30083,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30168,
"s": 30123,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30229,
"s": 30168,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30301,
"s": 30229,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 30353,
"s": 30301,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 30393,
"s": 30353,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30426,
"s": 30393,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30471,
"s": 30426,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30514,
"s": 30471,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
wxPython - Set tooltip for Button - GeeksforGeeks
|
24 Jun, 2020
In this article we will learn how we can assign a tooltip to a Button. In order to assign tooltip we use SetToolTip() function associated with wx.Button class of wxPython. SetToolTip() function takes a string argument that would be used as a tooltip.
Syntax: wx.Button.SetToolTip(self, string)
Parameters:
Code Example:
import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): self.locale = wx.Locale(wx.LANGUAGE_ENGLISH) # create parent panel self.pnl = wx.Panel(self) # create button at point (20, 20) self.btn = wx.Button(self.pnl, id = 1, label ="Button") # set tooltip for button self.btn.SetToolTip("Button ToolTip") self.SetSize((350, 250)) self.SetTitle('wx.Button') self.Centre() def main(): app = wx.App() ex = Example(None) ex.Show() app.MainLoop() if __name__ == '__main__': main()
Output Window
Python wxPython-Button
Python-gui
Python-wxPython
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
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n24 Jun, 2020"
},
{
"code": null,
"e": 25788,
"s": 25537,
"text": "In this article we will learn how we can assign a tooltip to a Button. In order to assign tooltip we use SetToolTip() function associated with wx.Button class of wxPython. SetToolTip() function takes a string argument that would be used as a tooltip."
},
{
"code": null,
"e": 25831,
"s": 25788,
"text": "Syntax: wx.Button.SetToolTip(self, string)"
},
{
"code": null,
"e": 25843,
"s": 25831,
"text": "Parameters:"
},
{
"code": null,
"e": 25857,
"s": 25843,
"text": "Code Example:"
},
{
"code": "import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): self.locale = wx.Locale(wx.LANGUAGE_ENGLISH) # create parent panel self.pnl = wx.Panel(self) # create button at point (20, 20) self.btn = wx.Button(self.pnl, id = 1, label =\"Button\") # set tooltip for button self.btn.SetToolTip(\"Button ToolTip\") self.SetSize((350, 250)) self.SetTitle('wx.Button') self.Centre() def main(): app = wx.App() ex = Example(None) ex.Show() app.MainLoop() if __name__ == '__main__': main()",
"e": 26555,
"s": 25857,
"text": null
},
{
"code": null,
"e": 26569,
"s": 26555,
"text": "Output Window"
},
{
"code": null,
"e": 26592,
"s": 26569,
"text": "Python wxPython-Button"
},
{
"code": null,
"e": 26603,
"s": 26592,
"text": "Python-gui"
},
{
"code": null,
"e": 26619,
"s": 26603,
"text": "Python-wxPython"
},
{
"code": null,
"e": 26626,
"s": 26619,
"text": "Python"
},
{
"code": null,
"e": 26724,
"s": 26626,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26756,
"s": 26724,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26798,
"s": 26756,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26840,
"s": 26798,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26867,
"s": 26840,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26923,
"s": 26867,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26962,
"s": 26923,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26984,
"s": 26962,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27015,
"s": 26984,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27044,
"s": 27015,
"text": "Create a directory in Python"
}
] |
Python NOT EQUAL operator - GeeksforGeeks
|
13 Sep, 2021
In this article, we are going to see != (Not equal) operators. In Python != is defined as not equal to operator. It returns True if operands on either side are not equal to each other, and returns False if they are equal.
Note: It is important to keep in mind that this comparison operator will return True if the the values are same but are of different data types.
Syntax: Value A != Value B
Python3
A = 1B = 2C = 2 print(A!=B)print(B!=C)
Output:
True
False
Python3
A = 1B = 1.0C = "1" print(A!=B)print(B!=C)print(A!=C)
Output:
False
True
True
The __ne__() gets called whenever the not equal operator is used. We can override this function to alter the nature of the not equal operator.
Python3
class Student: def __init__(self, name): self.student_name = name def __ne__(self, x): # return true for different types # of object if type(x) != type(self): return True # return True for different values if self.student_name != x.student_name: return True else: return False s1 = Student("Shyam")s2 = Student("Raju")s3 = Student("babu rao") print(s1 != s2)print(s2 != s3)
Output:
True
True
sweetyty
Blogathon-2021
Picked
Python-Operators
Blogathon
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create a Table With Multiple Foreign Keys in SQL?
How to Import JSON Data into SQL Server?
Stratified Sampling in Pandas
How to Install Tkinter in Windows?
Python program to convert XML to Dictionary
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": 26070,
"s": 26042,
"text": "\n13 Sep, 2021"
},
{
"code": null,
"e": 26293,
"s": 26070,
"text": "In this article, we are going to see != (Not equal) operators. In Python != is defined as not equal to operator. It returns True if operands on either side are not equal to each other, and returns False if they are equal. "
},
{
"code": null,
"e": 26438,
"s": 26293,
"text": "Note: It is important to keep in mind that this comparison operator will return True if the the values are same but are of different data types."
},
{
"code": null,
"e": 26465,
"s": 26438,
"text": "Syntax: Value A != Value B"
},
{
"code": null,
"e": 26473,
"s": 26465,
"text": "Python3"
},
{
"code": "A = 1B = 2C = 2 print(A!=B)print(B!=C)",
"e": 26512,
"s": 26473,
"text": null
},
{
"code": null,
"e": 26520,
"s": 26512,
"text": "Output:"
},
{
"code": null,
"e": 26531,
"s": 26520,
"text": "True\nFalse"
},
{
"code": null,
"e": 26539,
"s": 26531,
"text": "Python3"
},
{
"code": "A = 1B = 1.0C = \"1\" print(A!=B)print(B!=C)print(A!=C)",
"e": 26593,
"s": 26539,
"text": null
},
{
"code": null,
"e": 26601,
"s": 26593,
"text": "Output:"
},
{
"code": null,
"e": 26617,
"s": 26601,
"text": "False\nTrue\nTrue"
},
{
"code": null,
"e": 26760,
"s": 26617,
"text": "The __ne__() gets called whenever the not equal operator is used. We can override this function to alter the nature of the not equal operator."
},
{
"code": null,
"e": 26768,
"s": 26760,
"text": "Python3"
},
{
"code": "class Student: def __init__(self, name): self.student_name = name def __ne__(self, x): # return true for different types # of object if type(x) != type(self): return True # return True for different values if self.student_name != x.student_name: return True else: return False s1 = Student(\"Shyam\")s2 = Student(\"Raju\")s3 = Student(\"babu rao\") print(s1 != s2)print(s2 != s3)",
"e": 27243,
"s": 26768,
"text": null
},
{
"code": null,
"e": 27251,
"s": 27243,
"text": "Output:"
},
{
"code": null,
"e": 27261,
"s": 27251,
"text": "True\nTrue"
},
{
"code": null,
"e": 27270,
"s": 27261,
"text": "sweetyty"
},
{
"code": null,
"e": 27285,
"s": 27270,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 27292,
"s": 27285,
"text": "Picked"
},
{
"code": null,
"e": 27309,
"s": 27292,
"text": "Python-Operators"
},
{
"code": null,
"e": 27319,
"s": 27309,
"text": "Blogathon"
},
{
"code": null,
"e": 27326,
"s": 27319,
"text": "Python"
},
{
"code": null,
"e": 27424,
"s": 27326,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27481,
"s": 27424,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 27522,
"s": 27481,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 27552,
"s": 27522,
"text": "Stratified Sampling in Pandas"
},
{
"code": null,
"e": 27587,
"s": 27552,
"text": "How to Install Tkinter in Windows?"
},
{
"code": null,
"e": 27631,
"s": 27587,
"text": "Python program to convert XML to Dictionary"
},
{
"code": null,
"e": 27659,
"s": 27631,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 27709,
"s": 27659,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 27731,
"s": 27709,
"text": "Python map() function"
}
] |
Java Program to Implement CAS (Compare and Swap) Algorithm - GeeksforGeeks
|
22 Feb, 2021
Compare and swap is a technique used when designing concurrent algorithms. The approach is to compare the actual value of the variable to the expected value of the variable and if the actual value matches the expected value, then swap the actual value of the variable for the new value passed in.
For understanding the algorithm, one must have the basic knowledge of Concurrency and Multithread in Java.
Working of the Algorithm:
It is like we know that this variable should be 1, and we want to change it to 2. Since this is a multithreaded environment, we know that others might be working on the same variable. So we should first check if the value of the variable is 1 as we thought and if yes, then we change it to 2. If we see that the variable is 3 now, then that means someone else is working on it and so let us not touch it at this time.
Check then Act approach:-
The most common condition for concurrency problems is the βcheck then actβ approach. The βcheck then actβ occurs when the code first checks the value of a variable and then acts based on that value. Here is a simple example:
public boolean lock() {
if(!locked) {
lock = true;
return true;
}
return false;
}
Above, pseudocode Implies that, if it is already locked, you donβt need to lock again. So you first check and only if required, act.
The above code is not safe as If two or more threads might have access to lock() function and do the check at the same time , then above lock() function would not be guaranteed to work because all thread would lock the resource and use it as itβs own.
Letβs elaborate it :
There is Thread A and Thread B, thread B may check locked at any time between thread A has checked locked and seen it to be false then, both thread A and thread B may see locked as being false, and both will then act based on that information.
The above problem can be resolved by making the entire block of code as synchronized. Then only one thread (thread A or thread B) going to the check and act at one time, Only after the thread that got into the code completes its check, and itβs an act then another thread gets to try. Now there will be no misunderstanding between threads.
Example for synchronized code :
class GFG {
private boolean locked = false;
public synchronized boolean lock() {
if(!locked) {
locked = true;
return true;
}
return false;
}
}
Now the lock() method is synchronized so only one thread can execute it at a time on the same lock() function.
Atomic Operation
After Java 5, we donβt have to implement or write a synchronized block with the check and act code anymore, Java 5 offers this support via java.util.concurrent.atomic: a toolkit of classes used for lock-free, thread-safe programming on single variables.
AtomicBoolean makes sure that only one thread can read it at a time.
Here is an example showing how to implement the lock() method using AtomicBoolean :
public static class MyLock {
private AtomicBoolean locked = new AtomicBoolean(false);
public boolean lock() {
return locked.compareAndSet(false, true);
}
}
Notice how the locked variable is no longer a boolean but an AtomicBoolean. This class has a compareAndSet() function which will compare the value of the AtomicBoolean instance to an expected value, and if has the expected value, it swaps the value with a new value. In this case it compares the value of locked to false and if it is false it sets the new value of the AtomicBoolean to true.
The compareAndSet() method returns true if the value was swapped, and false if not.
So there is many other Atomic Variable like:
AtomicInteger: This variable lets you update an int value atomically.
AtomicLong: Long with thread-safe βCompare and Swapβ functionality.
AtomicReference: This variable provides an object reference variable which can be read and written atomically.
AtomicIntegerArray, AtomicLongArray, and AtomicReferenceArray
Example of Atomic Integer:
Java
// Java Program to demonstrates // the compareAndSet() function import java.util.concurrent.atomic.AtomicInteger; public class GFG { public static void main(String args[]) { // Initially value as 0 AtomicInteger val = new AtomicInteger(0); // Prints the updated value System.out.println("Previous value: " + val); // Checks if previous value was 0 // and then updates it boolean res = val.compareAndSet(0, 6); // Checks if the value was updated. if (res) System.out.println("The value was" + " updated and it is " + val); else System.out.println("The value was " + "not updated"); } }
Previous value: 0
The value was updated and it is 6
When multiple threads attempt to update the same variable simultaneously using CAS(Compare and Swap) algorithm, one wins and updates the variableβs value, and the rest lose. But the losers are not punished by suspension of thread. They are free to retry the operation or simply do nothing.
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Iterate through List in Java
|
[
{
"code": null,
"e": 25249,
"s": 25221,
"text": "\n22 Feb, 2021"
},
{
"code": null,
"e": 25549,
"s": 25249,
"text": "Compare and swap is a technique used when designing concurrent algorithms. The approach is to compare the actual value of the variable to the expected value of the variable and if the actual value matches the expected value, then swap the actual value of the variable for the new value passed in. "
},
{
"code": null,
"e": 25656,
"s": 25549,
"text": "For understanding the algorithm, one must have the basic knowledge of Concurrency and Multithread in Java."
},
{
"code": null,
"e": 25682,
"s": 25656,
"text": "Working of the Algorithm:"
},
{
"code": null,
"e": 26100,
"s": 25682,
"text": "It is like we know that this variable should be 1, and we want to change it to 2. Since this is a multithreaded environment, we know that others might be working on the same variable. So we should first check if the value of the variable is 1 as we thought and if yes, then we change it to 2. If we see that the variable is 3 now, then that means someone else is working on it and so let us not touch it at this time."
},
{
"code": null,
"e": 26126,
"s": 26100,
"text": "Check then Act approach:-"
},
{
"code": null,
"e": 26352,
"s": 26126,
"text": "The most common condition for concurrency problems is the βcheck then actβ approach. The βcheck then actβ occurs when the code first checks the value of a variable and then acts based on that value. Here is a simple example:"
},
{
"code": null,
"e": 26462,
"s": 26352,
"text": "public boolean lock() {\n if(!locked) {\n lock = true;\n return true;\n }\n return false;\n}"
},
{
"code": null,
"e": 26595,
"s": 26462,
"text": "Above, pseudocode Implies that, if it is already locked, you donβt need to lock again. So you first check and only if required, act."
},
{
"code": null,
"e": 26848,
"s": 26595,
"text": "The above code is not safe as If two or more threads might have access to lock() function and do the check at the same time , then above lock() function would not be guaranteed to work because all thread would lock the resource and use it as itβs own. "
},
{
"code": null,
"e": 26870,
"s": 26848,
"text": "Letβs elaborate it : "
},
{
"code": null,
"e": 27114,
"s": 26870,
"text": "There is Thread A and Thread B, thread B may check locked at any time between thread A has checked locked and seen it to be false then, both thread A and thread B may see locked as being false, and both will then act based on that information."
},
{
"code": null,
"e": 27454,
"s": 27114,
"text": "The above problem can be resolved by making the entire block of code as synchronized. Then only one thread (thread A or thread B) going to the check and act at one time, Only after the thread that got into the code completes its check, and itβs an act then another thread gets to try. Now there will be no misunderstanding between threads."
},
{
"code": null,
"e": 27486,
"s": 27454,
"text": "Example for synchronized code :"
},
{
"code": null,
"e": 27691,
"s": 27486,
"text": "class GFG {\n\n private boolean locked = false;\n\n public synchronized boolean lock() {\n if(!locked) {\n locked = true;\n return true;\n }\n return false;\n }\n}"
},
{
"code": null,
"e": 27803,
"s": 27691,
"text": "Now the lock() method is synchronized so only one thread can execute it at a time on the same lock() function. "
},
{
"code": null,
"e": 27820,
"s": 27803,
"text": "Atomic Operation"
},
{
"code": null,
"e": 28075,
"s": 27820,
"text": "After Java 5, we donβt have to implement or write a synchronized block with the check and act code anymore, Java 5 offers this support via java.util.concurrent.atomic: a toolkit of classes used for lock-free, thread-safe programming on single variables. "
},
{
"code": null,
"e": 28144,
"s": 28075,
"text": "AtomicBoolean makes sure that only one thread can read it at a time."
},
{
"code": null,
"e": 28228,
"s": 28144,
"text": "Here is an example showing how to implement the lock() method using AtomicBoolean :"
},
{
"code": null,
"e": 28406,
"s": 28228,
"text": "public static class MyLock {\n private AtomicBoolean locked = new AtomicBoolean(false);\n\n public boolean lock() {\n return locked.compareAndSet(false, true);\n }\n\n}"
},
{
"code": null,
"e": 28798,
"s": 28406,
"text": "Notice how the locked variable is no longer a boolean but an AtomicBoolean. This class has a compareAndSet() function which will compare the value of the AtomicBoolean instance to an expected value, and if has the expected value, it swaps the value with a new value. In this case it compares the value of locked to false and if it is false it sets the new value of the AtomicBoolean to true."
},
{
"code": null,
"e": 28882,
"s": 28798,
"text": "The compareAndSet() method returns true if the value was swapped, and false if not."
},
{
"code": null,
"e": 28927,
"s": 28882,
"text": "So there is many other Atomic Variable like:"
},
{
"code": null,
"e": 28997,
"s": 28927,
"text": "AtomicInteger: This variable lets you update an int value atomically."
},
{
"code": null,
"e": 29065,
"s": 28997,
"text": "AtomicLong: Long with thread-safe βCompare and Swapβ functionality."
},
{
"code": null,
"e": 29176,
"s": 29065,
"text": "AtomicReference: This variable provides an object reference variable which can be read and written atomically."
},
{
"code": null,
"e": 29238,
"s": 29176,
"text": "AtomicIntegerArray, AtomicLongArray, and AtomicReferenceArray"
},
{
"code": null,
"e": 29265,
"s": 29238,
"text": "Example of Atomic Integer:"
},
{
"code": null,
"e": 29270,
"s": 29265,
"text": "Java"
},
{
"code": "// Java Program to demonstrates // the compareAndSet() function import java.util.concurrent.atomic.AtomicInteger; public class GFG { public static void main(String args[]) { // Initially value as 0 AtomicInteger val = new AtomicInteger(0); // Prints the updated value System.out.println(\"Previous value: \" + val); // Checks if previous value was 0 // and then updates it boolean res = val.compareAndSet(0, 6); // Checks if the value was updated. if (res) System.out.println(\"The value was\" + \" updated and it is \" + val); else System.out.println(\"The value was \" + \"not updated\"); } }",
"e": 30108,
"s": 29270,
"text": null
},
{
"code": null,
"e": 30161,
"s": 30108,
"text": "Previous value: 0\nThe value was updated and it is 6\n"
},
{
"code": null,
"e": 30451,
"s": 30161,
"text": "When multiple threads attempt to update the same variable simultaneously using CAS(Compare and Swap) algorithm, one wins and updates the variableβs value, and the rest lose. But the losers are not punished by suspension of thread. They are free to retry the operation or simply do nothing."
},
{
"code": null,
"e": 30458,
"s": 30451,
"text": "Picked"
},
{
"code": null,
"e": 30463,
"s": 30458,
"text": "Java"
},
{
"code": null,
"e": 30477,
"s": 30463,
"text": "Java Programs"
},
{
"code": null,
"e": 30482,
"s": 30477,
"text": "Java"
},
{
"code": null,
"e": 30580,
"s": 30482,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30595,
"s": 30580,
"text": "Stream In Java"
},
{
"code": null,
"e": 30616,
"s": 30595,
"text": "Constructors in Java"
},
{
"code": null,
"e": 30635,
"s": 30616,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 30665,
"s": 30635,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 30711,
"s": 30665,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 30737,
"s": 30711,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 30771,
"s": 30737,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 30818,
"s": 30771,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 30850,
"s": 30818,
"text": "How to Iterate HashMap in Java?"
}
] |
Array product in C++ using STL - GeeksforGeeks
|
19 Apr, 2021
In C++, we can quickly find array product using accumulate() and multiplies<>().
The initialProduct specifies the initial value to be considered.
For multiplication, the initial value is 1.
Eg: array = [5, 10, 15],
So, Product = 1 x 5 x 10 x 15 = 750 (Notice that 1 is the initial value here)
CPP
// C++ program to find array product#include <iostream>#include <numeric>using namespace std; // User defined function that returns product of// arr[] using accumulate() library function.int arrayProduct(int a[], int n){ int initialProduct = 1; return accumulate(a, a + n, initialProduct, multiplies<int>());} int main(){ int a[] = { 5, 10, 15 }; int n = sizeof(a) / sizeof(a[0]); cout << arrayProduct(a, n); return 0;}
750
product of vector
CPP
// C++ program to find vector product#include <iostream>#include <numeric>#include <vector>using namespace std; // User defined function that returns product of// v using accumulate() library function.int arrayProduct(vector<int>& v){ int initialProduct = 1; return accumulate(v.begin(), v.end(), initialProduct, multiplies<int>());} int main(){ vector<int> v{ 5, 10, 15 }; cout << arrayProduct(v); return 0;}
750
We can also use a custom function in accumulate. Refer numeric header in C++ STL | Set 1 (accumulate() and partial_product()) for details.
puneethgr
cpp-vector
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Inline Functions in C++
Pair in C++ Standard Template Library (STL)
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Queue in C++ Standard Template Library (STL)
|
[
{
"code": null,
"e": 25343,
"s": 25315,
"text": "\n19 Apr, 2021"
},
{
"code": null,
"e": 25425,
"s": 25343,
"text": "In C++, we can quickly find array product using accumulate() and multiplies<>(). "
},
{
"code": null,
"e": 25490,
"s": 25425,
"text": "The initialProduct specifies the initial value to be considered."
},
{
"code": null,
"e": 25534,
"s": 25490,
"text": "For multiplication, the initial value is 1."
},
{
"code": null,
"e": 25560,
"s": 25534,
"text": "Eg: array = [5, 10, 15], "
},
{
"code": null,
"e": 25639,
"s": 25560,
"text": "So, Product = 1 x 5 x 10 x 15 = 750 (Notice that 1 is the initial value here)"
},
{
"code": null,
"e": 25643,
"s": 25639,
"text": "CPP"
},
{
"code": "// C++ program to find array product#include <iostream>#include <numeric>using namespace std; // User defined function that returns product of// arr[] using accumulate() library function.int arrayProduct(int a[], int n){ int initialProduct = 1; return accumulate(a, a + n, initialProduct, multiplies<int>());} int main(){ int a[] = { 5, 10, 15 }; int n = sizeof(a) / sizeof(a[0]); cout << arrayProduct(a, n); return 0;}",
"e": 26081,
"s": 25643,
"text": null
},
{
"code": null,
"e": 26085,
"s": 26081,
"text": "750"
},
{
"code": null,
"e": 26107,
"s": 26087,
"text": "product of vector "
},
{
"code": null,
"e": 26111,
"s": 26107,
"text": "CPP"
},
{
"code": "// C++ program to find vector product#include <iostream>#include <numeric>#include <vector>using namespace std; // User defined function that returns product of// v using accumulate() library function.int arrayProduct(vector<int>& v){ int initialProduct = 1; return accumulate(v.begin(), v.end(), initialProduct, multiplies<int>());} int main(){ vector<int> v{ 5, 10, 15 }; cout << arrayProduct(v); return 0;}",
"e": 26536,
"s": 26111,
"text": null
},
{
"code": null,
"e": 26540,
"s": 26536,
"text": "750"
},
{
"code": null,
"e": 26682,
"s": 26542,
"text": "We can also use a custom function in accumulate. Refer numeric header in C++ STL | Set 1 (accumulate() and partial_product()) for details. "
},
{
"code": null,
"e": 26692,
"s": 26682,
"text": "puneethgr"
},
{
"code": null,
"e": 26703,
"s": 26692,
"text": "cpp-vector"
},
{
"code": null,
"e": 26707,
"s": 26703,
"text": "STL"
},
{
"code": null,
"e": 26711,
"s": 26707,
"text": "C++"
},
{
"code": null,
"e": 26715,
"s": 26711,
"text": "STL"
},
{
"code": null,
"e": 26719,
"s": 26715,
"text": "CPP"
},
{
"code": null,
"e": 26817,
"s": 26719,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26845,
"s": 26817,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 26865,
"s": 26845,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 26898,
"s": 26865,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 26922,
"s": 26898,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 26947,
"s": 26922,
"text": "std::string class in C++"
},
{
"code": null,
"e": 26971,
"s": 26947,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 27015,
"s": 26971,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 27068,
"s": 27015,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 27104,
"s": 27068,
"text": "Convert string to char array in C++"
}
] |
LinkedHashSet add() method in Java with Examples - GeeksforGeeks
|
30 Sep, 2019
The add() method in Java LinkedHashSet is used to add a specific element into a LinkedHashSet. This method will add the element only if the specified element is not present in the LinkedHashSet else the function will return False if the element is already present in the LinkedHashSet.
Syntax:
Hash_Set.add(Object element)
Parameters: The parameter element is of the type LinkedHashSet and refers to the element to be added to the Set.
Return Value: The function returns True if the element is not present in the LinkedHashSet otherwise False if the element is already present in the LinkedHashSet.
Below program illustrate the Java.util.LinkedHashSet.add() method:
// Java code to illustrate add()import java.io.*;import java.util.LinkedHashSet; public class LinkedHashSetDemo { public static void main(String args[]) { // Creating an empty LinkedHashSet LinkedHashSet<String> set = new LinkedHashSet<String>(); // Use add() method to add elements into the Set set.add("Welcome"); set.add("To"); set.add("Geeks"); set.add("4"); set.add("Geeks"); // Displaying the LinkedHashSet System.out.println("LinkedHashSet: " + set); }}
LinkedHashSet: [Welcome, To, Geeks, 4]
Java-Functions
java-LinkedHashSet
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
|
[
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n30 Sep, 2019"
},
{
"code": null,
"e": 25511,
"s": 25225,
"text": "The add() method in Java LinkedHashSet is used to add a specific element into a LinkedHashSet. This method will add the element only if the specified element is not present in the LinkedHashSet else the function will return False if the element is already present in the LinkedHashSet."
},
{
"code": null,
"e": 25519,
"s": 25511,
"text": "Syntax:"
},
{
"code": null,
"e": 25548,
"s": 25519,
"text": "Hash_Set.add(Object element)"
},
{
"code": null,
"e": 25661,
"s": 25548,
"text": "Parameters: The parameter element is of the type LinkedHashSet and refers to the element to be added to the Set."
},
{
"code": null,
"e": 25824,
"s": 25661,
"text": "Return Value: The function returns True if the element is not present in the LinkedHashSet otherwise False if the element is already present in the LinkedHashSet."
},
{
"code": null,
"e": 25891,
"s": 25824,
"text": "Below program illustrate the Java.util.LinkedHashSet.add() method:"
},
{
"code": "// Java code to illustrate add()import java.io.*;import java.util.LinkedHashSet; public class LinkedHashSetDemo { public static void main(String args[]) { // Creating an empty LinkedHashSet LinkedHashSet<String> set = new LinkedHashSet<String>(); // Use add() method to add elements into the Set set.add(\"Welcome\"); set.add(\"To\"); set.add(\"Geeks\"); set.add(\"4\"); set.add(\"Geeks\"); // Displaying the LinkedHashSet System.out.println(\"LinkedHashSet: \" + set); }}",
"e": 26436,
"s": 25891,
"text": null
},
{
"code": null,
"e": 26476,
"s": 26436,
"text": "LinkedHashSet: [Welcome, To, Geeks, 4]\n"
},
{
"code": null,
"e": 26491,
"s": 26476,
"text": "Java-Functions"
},
{
"code": null,
"e": 26510,
"s": 26491,
"text": "java-LinkedHashSet"
},
{
"code": null,
"e": 26515,
"s": 26510,
"text": "Java"
},
{
"code": null,
"e": 26520,
"s": 26515,
"text": "Java"
},
{
"code": null,
"e": 26618,
"s": 26520,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26633,
"s": 26618,
"text": "Stream In Java"
},
{
"code": null,
"e": 26654,
"s": 26633,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26673,
"s": 26654,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26703,
"s": 26673,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 26749,
"s": 26703,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 26766,
"s": 26749,
"text": "Generics in Java"
},
{
"code": null,
"e": 26787,
"s": 26766,
"text": "Introduction to Java"
},
{
"code": null,
"e": 26830,
"s": 26787,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 26866,
"s": 26830,
"text": "Internal Working of HashMap in Java"
}
] |
Maximal independent set from a given Graph using Backtracking - GeeksforGeeks
|
25 Nov, 2021
Given an undirected graph with V vertices and E edges, the task is to print all the independent sets and also find the maximal independent set(s).
Independent set is a set of vertices such that any two vertices in the set do not have a direct edge between them.
Maximal independent set is an independent set having highest number of vertices.
Note: There can be more than one independent and maximal independent sets for a given graph.Examples:
Input: V = 3, E = 0 Graph:
Graph for example 1
Output: { }{ 1 }{ 1 2 }{ 1 2 3 }{ 1 3 }{ 2 }{ 2 3 }{ 3 } { 1 2 3 } Explanation: The first line represents all the possible independent sets for the given graph. The second line has the maximal independent sets possible for the given graph.Input: V = 4, E = 4 Graph:
Graph for example 2
Output: { }{ 1 }{ 1 3 }{ 2 }{ 2 4 }{ 3 }{ 4 } { 1 3 }{ 2 4 }
Approach: The idea is to use Backtracking to solve the problem. At every step, we need to check whether the current node has any direct edge with any of the nodes already present in our independent set. If not, we can add it to our independent set and recursively repeat the same process for all the nodes.
Illustration: Recursion tree for the first example:
Backtracking tree for all possible sets
In the above backtracking tree we will choose only those sets which are produced after adding a safe node to maintain the set as an independent set.
Below is the implementation of the above approach:
CPP
Python3
// C++ Program to print the// independent sets and// maximal independent sets// of the given graph #include <bits/stdc++.h>using namespace std; // To store all the independent// sets of the graphset<set<int> > independentSets; // To store all maximal independent// sets in the graphset<set<int> > maximalIndependentSets; map<pair<int, int>, int> edges;vector<int> vertices; // Function to print all independent setsvoid printAllIndependentSets(){ for (auto iter : independentSets) { cout << "{ "; for (auto iter2 : iter) { cout << iter2 << " "; } cout << "}"; } cout << endl;} // Function to extract all// maximal independent setsvoid printMaximalIndependentSets(){ int maxCount = 0; int localCount = 0; for (auto iter : independentSets) { localCount = 0; for (auto iter2 : iter) { localCount++; } if (localCount > maxCount) maxCount = localCount; } for (auto iter : independentSets) { localCount = 0; set<int> tempMaximalSet; for (auto iter2 : iter) { localCount++; tempMaximalSet.insert(iter2); } if (localCount == maxCount) maximalIndependentSets .insert(tempMaximalSet); } for (auto iter : maximalIndependentSets) { cout << "{ "; for (auto iter2 : iter) { cout << iter2 << " "; } cout << "}"; } cout << endl;} // Function to check if a// node is safe node.bool isSafeForIndependentSet( int vertex, set<int> tempSolutionSet){ for (auto iter : tempSolutionSet) { if (edges[make_pair(iter, vertex)]) { return false; } } return true;} // Recursive function to find// all independent setsvoid findAllIndependentSets( int currV, int setSize, set<int> tempSolutionSet){ for (int i = currV; i <= setSize; i++) { if (isSafeForIndependentSet( vertices[i - 1], tempSolutionSet)) { tempSolutionSet .insert(vertices[i - 1]); findAllIndependentSets( i + 1, setSize, tempSolutionSet); tempSolutionSet .erase(vertices[i - 1]); } } independentSets .insert(tempSolutionSet);} // Driver Programint main(){ int V = 3, E = 0; for (int i = 1; i <= V; i++) vertices.push_back(i); vector<pair<int, int> > inputEdges; pair<int, int> edge; int x, y; for (int i = 0; i < E; i++) { cout<<i<<endl; edge.first = inputEdges[i].first; edge.second = inputEdges[i].second; edges[edge] = 1; int t = edge.first; edge.first = edge.second; edge.second = t; edges[edge] = 1; } set<int> tempSolutionSet; findAllIndependentSets(1, V, tempSolutionSet); printAllIndependentSets(); printMaximalIndependentSets(); return 0;}
# Python3 Program to print the# independent sets and# maximal independent sets# of the given graph # To store all the independent# sets of the graphindependentSets=set() # To store all maximal independent# sets in the graphmaximalIndependentSets=set() edges=dict()vertices=[] # Function to print all independent setsdef printAllIndependentSets(): for itr in independentSets: print("{",end=" ") for itr2 in itr: print(itr2,end= " ") print("}",end='') print() # Function to extract all# maximal independent setsdef printMaximalIndependentSets(): maxCount = 0;localCount = 0 for itr in independentSets: localCount = 0 for itr2 in itr: localCount+=1 if (localCount > maxCount): maxCount = localCount for itr in independentSets: localCount = 0 tempMaximalSet=set() for itr2 in itr: localCount+=1 tempMaximalSet.add(itr2) if (localCount == maxCount): maximalIndependentSets.add(frozenset(tempMaximalSet)) for itr in maximalIndependentSets : print("{",end=" ") for itr2 in itr: print(itr2,end=" ") print("}",end="") print() # Function to check if a# node is safe node.def isSafeForIndependentSet(vertex, tempSolutionSet): for itr in tempSolutionSet: if (itr, vertex) in edges: return False return True # Recursive function to find# all independent setsdef findAllIndependentSets(currV, setSize, tempSolutionSet): for i in range(currV,setSize+1): if (isSafeForIndependentSet(vertices[i - 1], tempSolutionSet)) : tempSolutionSet.add(vertices[i - 1]) findAllIndependentSets(i + 1, setSize, tempSolutionSet) tempSolutionSet.remove(vertices[i - 1]) independentSets.add(frozenset(tempSolutionSet)) # Driver Programif __name__ == '__main__': V = 3; E = 0 for i in range(1,V+1): vertices.append(i) inputEdges=[] for i in range(E): edges[inputEdges[i]]=True edges[(inputEdges[i][1],inputEdges[i][0])]=True tempSolutionSet=set() findAllIndependentSets(1, V, tempSolutionSet) printAllIndependentSets() printMaximalIndependentSets()
{ }{ 1 }{ 1 2 }{ 1 2 3 }{ 1 3 }{ 2 }{ 2 3 }{ 3 }
{ 1 2 3 }
Time Complexity: O(2 ^ N)
Auxiliary Space: O(2 ^ N)
sooda367
pankajsharmagfg
ruhelaa48
amartyaghoshgfg
Algorithms
Backtracking
Competitive Programming
Data Structures
Graph
Data Structures
Graph
Backtracking
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
How to write a Pseudo Code?
Understanding Time Complexity with Simple Examples
Introduction to Algorithms
N Queen Problem | Backtracking-3
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Backtracking | Introduction
Rat in a Maze | Backtracking-2
|
[
{
"code": null,
"e": 26595,
"s": 26567,
"text": "\n25 Nov, 2021"
},
{
"code": null,
"e": 26744,
"s": 26595,
"text": "Given an undirected graph with V vertices and E edges, the task is to print all the independent sets and also find the maximal independent set(s). "
},
{
"code": null,
"e": 26859,
"s": 26744,
"text": "Independent set is a set of vertices such that any two vertices in the set do not have a direct edge between them."
},
{
"code": null,
"e": 26944,
"s": 26861,
"text": "Maximal independent set is an independent set having highest number of vertices. "
},
{
"code": null,
"e": 27047,
"s": 26944,
"text": "Note: There can be more than one independent and maximal independent sets for a given graph.Examples: "
},
{
"code": null,
"e": 27076,
"s": 27047,
"text": "Input: V = 3, E = 0 Graph: "
},
{
"code": null,
"e": 27096,
"s": 27076,
"text": "Graph for example 1"
},
{
"code": null,
"e": 27364,
"s": 27096,
"text": "Output: { }{ 1 }{ 1 2 }{ 1 2 3 }{ 1 3 }{ 2 }{ 2 3 }{ 3 } { 1 2 3 } Explanation: The first line represents all the possible independent sets for the given graph. The second line has the maximal independent sets possible for the given graph.Input: V = 4, E = 4 Graph: "
},
{
"code": null,
"e": 27384,
"s": 27364,
"text": "Graph for example 2"
},
{
"code": null,
"e": 27447,
"s": 27384,
"text": "Output: { }{ 1 }{ 1 3 }{ 2 }{ 2 4 }{ 3 }{ 4 } { 1 3 }{ 2 4 } "
},
{
"code": null,
"e": 27757,
"s": 27449,
"text": "Approach: The idea is to use Backtracking to solve the problem. At every step, we need to check whether the current node has any direct edge with any of the nodes already present in our independent set. If not, we can add it to our independent set and recursively repeat the same process for all the nodes. "
},
{
"code": null,
"e": 27811,
"s": 27757,
"text": "Illustration: Recursion tree for the first example: "
},
{
"code": null,
"e": 27851,
"s": 27811,
"text": "Backtracking tree for all possible sets"
},
{
"code": null,
"e": 28000,
"s": 27851,
"text": "In the above backtracking tree we will choose only those sets which are produced after adding a safe node to maintain the set as an independent set."
},
{
"code": null,
"e": 28052,
"s": 28000,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 28056,
"s": 28052,
"text": "CPP"
},
{
"code": null,
"e": 28064,
"s": 28056,
"text": "Python3"
},
{
"code": "// C++ Program to print the// independent sets and// maximal independent sets// of the given graph #include <bits/stdc++.h>using namespace std; // To store all the independent// sets of the graphset<set<int> > independentSets; // To store all maximal independent// sets in the graphset<set<int> > maximalIndependentSets; map<pair<int, int>, int> edges;vector<int> vertices; // Function to print all independent setsvoid printAllIndependentSets(){ for (auto iter : independentSets) { cout << \"{ \"; for (auto iter2 : iter) { cout << iter2 << \" \"; } cout << \"}\"; } cout << endl;} // Function to extract all// maximal independent setsvoid printMaximalIndependentSets(){ int maxCount = 0; int localCount = 0; for (auto iter : independentSets) { localCount = 0; for (auto iter2 : iter) { localCount++; } if (localCount > maxCount) maxCount = localCount; } for (auto iter : independentSets) { localCount = 0; set<int> tempMaximalSet; for (auto iter2 : iter) { localCount++; tempMaximalSet.insert(iter2); } if (localCount == maxCount) maximalIndependentSets .insert(tempMaximalSet); } for (auto iter : maximalIndependentSets) { cout << \"{ \"; for (auto iter2 : iter) { cout << iter2 << \" \"; } cout << \"}\"; } cout << endl;} // Function to check if a// node is safe node.bool isSafeForIndependentSet( int vertex, set<int> tempSolutionSet){ for (auto iter : tempSolutionSet) { if (edges[make_pair(iter, vertex)]) { return false; } } return true;} // Recursive function to find// all independent setsvoid findAllIndependentSets( int currV, int setSize, set<int> tempSolutionSet){ for (int i = currV; i <= setSize; i++) { if (isSafeForIndependentSet( vertices[i - 1], tempSolutionSet)) { tempSolutionSet .insert(vertices[i - 1]); findAllIndependentSets( i + 1, setSize, tempSolutionSet); tempSolutionSet .erase(vertices[i - 1]); } } independentSets .insert(tempSolutionSet);} // Driver Programint main(){ int V = 3, E = 0; for (int i = 1; i <= V; i++) vertices.push_back(i); vector<pair<int, int> > inputEdges; pair<int, int> edge; int x, y; for (int i = 0; i < E; i++) { cout<<i<<endl; edge.first = inputEdges[i].first; edge.second = inputEdges[i].second; edges[edge] = 1; int t = edge.first; edge.first = edge.second; edge.second = t; edges[edge] = 1; } set<int> tempSolutionSet; findAllIndependentSets(1, V, tempSolutionSet); printAllIndependentSets(); printMaximalIndependentSets(); return 0;}",
"e": 31076,
"s": 28064,
"text": null
},
{
"code": "# Python3 Program to print the# independent sets and# maximal independent sets# of the given graph # To store all the independent# sets of the graphindependentSets=set() # To store all maximal independent# sets in the graphmaximalIndependentSets=set() edges=dict()vertices=[] # Function to print all independent setsdef printAllIndependentSets(): for itr in independentSets: print(\"{\",end=\" \") for itr2 in itr: print(itr2,end= \" \") print(\"}\",end='') print() # Function to extract all# maximal independent setsdef printMaximalIndependentSets(): maxCount = 0;localCount = 0 for itr in independentSets: localCount = 0 for itr2 in itr: localCount+=1 if (localCount > maxCount): maxCount = localCount for itr in independentSets: localCount = 0 tempMaximalSet=set() for itr2 in itr: localCount+=1 tempMaximalSet.add(itr2) if (localCount == maxCount): maximalIndependentSets.add(frozenset(tempMaximalSet)) for itr in maximalIndependentSets : print(\"{\",end=\" \") for itr2 in itr: print(itr2,end=\" \") print(\"}\",end=\"\") print() # Function to check if a# node is safe node.def isSafeForIndependentSet(vertex, tempSolutionSet): for itr in tempSolutionSet: if (itr, vertex) in edges: return False return True # Recursive function to find# all independent setsdef findAllIndependentSets(currV, setSize, tempSolutionSet): for i in range(currV,setSize+1): if (isSafeForIndependentSet(vertices[i - 1], tempSolutionSet)) : tempSolutionSet.add(vertices[i - 1]) findAllIndependentSets(i + 1, setSize, tempSolutionSet) tempSolutionSet.remove(vertices[i - 1]) independentSets.add(frozenset(tempSolutionSet)) # Driver Programif __name__ == '__main__': V = 3; E = 0 for i in range(1,V+1): vertices.append(i) inputEdges=[] for i in range(E): edges[inputEdges[i]]=True edges[(inputEdges[i][1],inputEdges[i][0])]=True tempSolutionSet=set() findAllIndependentSets(1, V, tempSolutionSet) printAllIndependentSets() printMaximalIndependentSets()",
"e": 33378,
"s": 31076,
"text": null
},
{
"code": null,
"e": 33437,
"s": 33378,
"text": "{ }{ 1 }{ 1 2 }{ 1 2 3 }{ 1 3 }{ 2 }{ 2 3 }{ 3 }\n{ 1 2 3 }"
},
{
"code": null,
"e": 33465,
"s": 33439,
"text": "Time Complexity: O(2 ^ N)"
},
{
"code": null,
"e": 33491,
"s": 33465,
"text": "Auxiliary Space: O(2 ^ N)"
},
{
"code": null,
"e": 33500,
"s": 33491,
"text": "sooda367"
},
{
"code": null,
"e": 33516,
"s": 33500,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 33526,
"s": 33516,
"text": "ruhelaa48"
},
{
"code": null,
"e": 33542,
"s": 33526,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 33553,
"s": 33542,
"text": "Algorithms"
},
{
"code": null,
"e": 33566,
"s": 33553,
"text": "Backtracking"
},
{
"code": null,
"e": 33590,
"s": 33566,
"text": "Competitive Programming"
},
{
"code": null,
"e": 33606,
"s": 33590,
"text": "Data Structures"
},
{
"code": null,
"e": 33612,
"s": 33606,
"text": "Graph"
},
{
"code": null,
"e": 33628,
"s": 33612,
"text": "Data Structures"
},
{
"code": null,
"e": 33634,
"s": 33628,
"text": "Graph"
},
{
"code": null,
"e": 33647,
"s": 33634,
"text": "Backtracking"
},
{
"code": null,
"e": 33658,
"s": 33647,
"text": "Algorithms"
},
{
"code": null,
"e": 33756,
"s": 33658,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33805,
"s": 33756,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 33830,
"s": 33805,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 33858,
"s": 33830,
"text": "How to write a Pseudo Code?"
},
{
"code": null,
"e": 33909,
"s": 33858,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 33936,
"s": 33909,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 33969,
"s": 33936,
"text": "N Queen Problem | Backtracking-3"
},
{
"code": null,
"e": 34029,
"s": 33969,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 34114,
"s": 34029,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 34142,
"s": 34114,
"text": "Backtracking | Introduction"
}
] |
AWT MenuItem Class
|
The MenuBar class represents the actual item in a menu. All items in a menu should derive from class MenuItem, or one of its subclasses. By default, it embodies a simple labeled menu item.
Following is the declaration for java.awt.MenuItem class:
public class MenuItem
extends MenuComponent
implements Accessible
MenuItem()
Constructs a new MenuItem with an empty label and no keyboard shortcut.
MenuItem(String label)
Constructs a new MenuItem with the specified label and no keyboard shortcut.
MenuItem(String label, MenuShortcut s)
Create a menu item with an associated keyboard shortcut.
void addActionListener(ActionListener l)
Adds the specified action listener to receive action events from this menu item.
void addNotify()
Creates the menu item's peer.
void deleteShortcut()
Delete any MenuShortcut object associated with this menu item.
void disable()
Deprecated. As of JDK version 1.1, replaced by setEnabled(boolean).
protected void disableEvents(long eventsToDisable)
Disables event delivery to this menu item for events defined by the specified event mask parameter.
void enable()
Deprecated. As of JDK version 1.1, replaced by setEnabled(boolean).
void enable(boolean b)
Deprecated. As of JDK version 1.1, replaced by setEnabled(boolean).
protected void enableEvents(long eventsToEnable)
Enables event delivery to this menu item for events to be defined by the specified event mask parameter.
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this MenuItem.
String getActionCommand()
Gets the command name of the action event that is fired by this menu item.
ActionListener[] getActionListeners()
Returns an array of all the action listeners registered on this menu item.
String getLabel()
Gets the label for this menu item.
EventListener[] getListeners(Class listenerType)
Returns an array of all the objects currently registered as FooListeners upon this MenuItem.
MenuShortcut getShortcut()
Get the MenuShortcut object associated with this menu item.
boolean isEnabled()
Checks whether this menu item is enabled.
String paramString()
Returns a string representing the state of this MenuItem.
protected void processActionEvent(ActionEvent e)
Processes action events occurring on this menu item, by dispatching them to any registered ActionListener objects.
protected void processEvent(AWTEvent e)
Processes events on this menu item.
void removeActionListener(ActionListener l)
Removes the specified action listener so it no longer receives action events from this menu item.
void setActionCommand(String command)
Sets the command name of the action event that is fired by this menu item.
void setEnabled(boolean b)
Sets whether or not this menu item can be chosen.
void setLabel(String label)
Sets the label for this menu item to the specified label.
void setShortcut(MenuShortcut s)
Set the MenuShortcut object associated with this menu item.
This class inherits methods from the following classes:
java.awt.MenuComponent
java.awt.MenuComponent
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 AWTMenuDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AWTMenuDemo(){
prepareGUI();
}
public static void main(String[] args){
AWTMenuDemo awtMenuDemo = new AWTMenuDemo();
awtMenuDemo.showMenuDemo();
}
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);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showMenuDemo(){
//create a menu bar
final MenuBar menuBar = new MenuBar();
//create menus
Menu fileMenu = new Menu("File");
Menu editMenu = new Menu("Edit");
final Menu aboutMenu = new Menu("About");
//create menu items
MenuItem newMenuItem =
new MenuItem("New",new MenuShortcut(KeyEvent.VK_N));
newMenuItem.setActionCommand("New");
MenuItem openMenuItem = new MenuItem("Open");
openMenuItem.setActionCommand("Open");
MenuItem saveMenuItem = new MenuItem("Save");
saveMenuItem.setActionCommand("Save");
MenuItem exitMenuItem = new MenuItem("Exit");
exitMenuItem.setActionCommand("Exit");
MenuItem cutMenuItem = new MenuItem("Cut");
cutMenuItem.setActionCommand("Cut");
MenuItem copyMenuItem = new MenuItem("Copy");
copyMenuItem.setActionCommand("Copy");
MenuItem pasteMenuItem = new MenuItem("Paste");
pasteMenuItem.setActionCommand("Paste");
MenuItemListener menuItemListener = new MenuItemListener();
newMenuItem.addActionListener(menuItemListener);
openMenuItem.addActionListener(menuItemListener);
saveMenuItem.addActionListener(menuItemListener);
exitMenuItem.addActionListener(menuItemListener);
cutMenuItem.addActionListener(menuItemListener);
copyMenuItem.addActionListener(menuItemListener);
pasteMenuItem.addActionListener(menuItemListener);
final CheckboxMenuItem showWindowMenu =
new CheckboxMenuItem("Show About", true);
showWindowMenu.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if(showWindowMenu.getState()){
menuBar.add(aboutMenu);
}else{
menuBar.remove(aboutMenu);
}
}
});
//add menu items to menus
fileMenu.add(newMenuItem);
fileMenu.add(openMenuItem);
fileMenu.add(saveMenuItem);
fileMenu.addSeparator();
fileMenu.add(showWindowMenu);
fileMenu.addSeparator();
fileMenu.add(exitMenuItem);
editMenu.add(cutMenuItem);
editMenu.add(copyMenuItem);
editMenu.add(pasteMenuItem);
//add menu to menubar
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(aboutMenu);
//add menubar to the frame
mainFrame.setMenuBar(menuBar);
mainFrame.setVisible(true);
}
class MenuItemListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
statusLabel.setText(e.getActionCommand()
+ " MenuItem clicked.");
}
}
}
Compile the program using command prompt. Go to D:/ > AWT and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AWTMenuDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AWTMenuDemo
Verify the following output. (Click on File Menu. Select any menu item.)
13 Lectures
2 hours
EduOLC
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1936,
"s": 1747,
"text": "The MenuBar class represents the actual item in a menu. All items in a menu should derive from class MenuItem, or one of its subclasses. By default, it embodies a simple labeled menu item."
},
{
"code": null,
"e": 1994,
"s": 1936,
"text": "Following is the declaration for java.awt.MenuItem class:"
},
{
"code": null,
"e": 2069,
"s": 1994,
"text": "public class MenuItem\n extends MenuComponent\n implements Accessible"
},
{
"code": null,
"e": 2081,
"s": 2069,
"text": "MenuItem() "
},
{
"code": null,
"e": 2153,
"s": 2081,
"text": "Constructs a new MenuItem with an empty label and no keyboard shortcut."
},
{
"code": null,
"e": 2177,
"s": 2153,
"text": "MenuItem(String label) "
},
{
"code": null,
"e": 2254,
"s": 2177,
"text": "Constructs a new MenuItem with the specified label and no keyboard shortcut."
},
{
"code": null,
"e": 2294,
"s": 2254,
"text": "MenuItem(String label, MenuShortcut s) "
},
{
"code": null,
"e": 2351,
"s": 2294,
"text": "Create a menu item with an associated keyboard shortcut."
},
{
"code": null,
"e": 2393,
"s": 2351,
"text": "void addActionListener(ActionListener l) "
},
{
"code": null,
"e": 2474,
"s": 2393,
"text": "Adds the specified action listener to receive action events from this menu item."
},
{
"code": null,
"e": 2492,
"s": 2474,
"text": "void addNotify() "
},
{
"code": null,
"e": 2522,
"s": 2492,
"text": "Creates the menu item's peer."
},
{
"code": null,
"e": 2545,
"s": 2522,
"text": "void deleteShortcut() "
},
{
"code": null,
"e": 2608,
"s": 2545,
"text": "Delete any MenuShortcut object associated with this menu item."
},
{
"code": null,
"e": 2624,
"s": 2608,
"text": "void disable() "
},
{
"code": null,
"e": 2692,
"s": 2624,
"text": "Deprecated. As of JDK version 1.1, replaced by setEnabled(boolean)."
},
{
"code": null,
"e": 2745,
"s": 2692,
"text": "protected void disableEvents(long eventsToDisable) "
},
{
"code": null,
"e": 2845,
"s": 2745,
"text": "Disables event delivery to this menu item for events defined by the specified event mask parameter."
},
{
"code": null,
"e": 2860,
"s": 2845,
"text": "void enable() "
},
{
"code": null,
"e": 2928,
"s": 2860,
"text": "Deprecated. As of JDK version 1.1, replaced by setEnabled(boolean)."
},
{
"code": null,
"e": 2952,
"s": 2928,
"text": "void enable(boolean b) "
},
{
"code": null,
"e": 3020,
"s": 2952,
"text": "Deprecated. As of JDK version 1.1, replaced by setEnabled(boolean)."
},
{
"code": null,
"e": 3070,
"s": 3020,
"text": "protected void enableEvents(long eventsToEnable) "
},
{
"code": null,
"e": 3175,
"s": 3070,
"text": "Enables event delivery to this menu item for events to be defined by the specified event mask parameter."
},
{
"code": null,
"e": 3217,
"s": 3175,
"text": "AccessibleContext getAccessibleContext() "
},
{
"code": null,
"e": 3275,
"s": 3217,
"text": "Gets the AccessibleContext associated with this MenuItem."
},
{
"code": null,
"e": 3302,
"s": 3275,
"text": "String getActionCommand() "
},
{
"code": null,
"e": 3377,
"s": 3302,
"text": "Gets the command name of the action event that is fired by this menu item."
},
{
"code": null,
"e": 3416,
"s": 3377,
"text": "ActionListener[] getActionListeners() "
},
{
"code": null,
"e": 3491,
"s": 3416,
"text": "Returns an array of all the action listeners registered on this menu item."
},
{
"code": null,
"e": 3511,
"s": 3491,
"text": "String getLabel() \n"
},
{
"code": null,
"e": 3546,
"s": 3511,
"text": "Gets the label for this menu item."
},
{
"code": null,
"e": 3596,
"s": 3546,
"text": "EventListener[] getListeners(Class listenerType) "
},
{
"code": null,
"e": 3689,
"s": 3596,
"text": "Returns an array of all the objects currently registered as FooListeners upon this MenuItem."
},
{
"code": null,
"e": 3717,
"s": 3689,
"text": "MenuShortcut getShortcut() "
},
{
"code": null,
"e": 3777,
"s": 3717,
"text": "Get the MenuShortcut object associated with this menu item."
},
{
"code": null,
"e": 3798,
"s": 3777,
"text": "boolean\tisEnabled() "
},
{
"code": null,
"e": 3840,
"s": 3798,
"text": "Checks whether this menu item is enabled."
},
{
"code": null,
"e": 3862,
"s": 3840,
"text": "String paramString() "
},
{
"code": null,
"e": 3920,
"s": 3862,
"text": "Returns a string representing the state of this MenuItem."
},
{
"code": null,
"e": 3970,
"s": 3920,
"text": "protected void processActionEvent(ActionEvent e) "
},
{
"code": null,
"e": 4085,
"s": 3970,
"text": "Processes action events occurring on this menu item, by dispatching them to any registered ActionListener objects."
},
{
"code": null,
"e": 4126,
"s": 4085,
"text": "protected void processEvent(AWTEvent e) "
},
{
"code": null,
"e": 4162,
"s": 4126,
"text": "Processes events on this menu item."
},
{
"code": null,
"e": 4207,
"s": 4162,
"text": "void removeActionListener(ActionListener l) "
},
{
"code": null,
"e": 4305,
"s": 4207,
"text": "Removes the specified action listener so it no longer receives action events from this menu item."
},
{
"code": null,
"e": 4344,
"s": 4305,
"text": "void setActionCommand(String command) "
},
{
"code": null,
"e": 4419,
"s": 4344,
"text": "Sets the command name of the action event that is fired by this menu item."
},
{
"code": null,
"e": 4447,
"s": 4419,
"text": "void setEnabled(boolean b) "
},
{
"code": null,
"e": 4497,
"s": 4447,
"text": "Sets whether or not this menu item can be chosen."
},
{
"code": null,
"e": 4526,
"s": 4497,
"text": "void setLabel(String label) "
},
{
"code": null,
"e": 4584,
"s": 4526,
"text": "Sets the label for this menu item to the specified label."
},
{
"code": null,
"e": 4618,
"s": 4584,
"text": "void setShortcut(MenuShortcut s) "
},
{
"code": null,
"e": 4678,
"s": 4618,
"text": "Set the MenuShortcut object associated with this menu item."
},
{
"code": null,
"e": 4734,
"s": 4678,
"text": "This class inherits methods from the following classes:"
},
{
"code": null,
"e": 4757,
"s": 4734,
"text": "java.awt.MenuComponent"
},
{
"code": null,
"e": 4780,
"s": 4757,
"text": "java.awt.MenuComponent"
},
{
"code": null,
"e": 4797,
"s": 4780,
"text": "java.lang.Object"
},
{
"code": null,
"e": 4814,
"s": 4797,
"text": "java.lang.Object"
},
{
"code": null,
"e": 4928,
"s": 4814,
"text": "Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >"
},
{
"code": null,
"e": 8790,
"s": 4928,
"text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class AWTMenuDemo {\n private Frame mainFrame;\n private Label headerLabel;\n private Label statusLabel;\n private Panel controlPanel;\n\n public AWTMenuDemo(){\n prepareGUI();\n }\n\n public static void main(String[] args){\n AWTMenuDemo awtMenuDemo = new AWTMenuDemo(); \n awtMenuDemo.showMenuDemo();\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 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 showMenuDemo(){\n //create a menu bar\n final MenuBar menuBar = new MenuBar();\n\n //create menus\n Menu fileMenu = new Menu(\"File\");\n Menu editMenu = new Menu(\"Edit\"); \n final Menu aboutMenu = new Menu(\"About\");\n\n //create menu items\n MenuItem newMenuItem = \n new MenuItem(\"New\",new MenuShortcut(KeyEvent.VK_N));\n newMenuItem.setActionCommand(\"New\");\n\n MenuItem openMenuItem = new MenuItem(\"Open\");\n openMenuItem.setActionCommand(\"Open\");\n\n MenuItem saveMenuItem = new MenuItem(\"Save\");\n saveMenuItem.setActionCommand(\"Save\");\n\n MenuItem exitMenuItem = new MenuItem(\"Exit\");\n exitMenuItem.setActionCommand(\"Exit\");\n\n MenuItem cutMenuItem = new MenuItem(\"Cut\");\n cutMenuItem.setActionCommand(\"Cut\");\n\n MenuItem copyMenuItem = new MenuItem(\"Copy\");\n copyMenuItem.setActionCommand(\"Copy\");\n\n MenuItem pasteMenuItem = new MenuItem(\"Paste\");\n pasteMenuItem.setActionCommand(\"Paste\");\n \n MenuItemListener menuItemListener = new MenuItemListener();\n\n newMenuItem.addActionListener(menuItemListener);\n openMenuItem.addActionListener(menuItemListener);\n saveMenuItem.addActionListener(menuItemListener);\n exitMenuItem.addActionListener(menuItemListener);\n cutMenuItem.addActionListener(menuItemListener);\n copyMenuItem.addActionListener(menuItemListener);\n pasteMenuItem.addActionListener(menuItemListener);\n\n final CheckboxMenuItem showWindowMenu = \n new CheckboxMenuItem(\"Show About\", true);\n showWindowMenu.addItemListener(new ItemListener() {\n public void itemStateChanged(ItemEvent e) {\n if(showWindowMenu.getState()){\n menuBar.add(aboutMenu);\n }else{\n menuBar.remove(aboutMenu);\n }\n }\n });\n\n //add menu items to menus\n fileMenu.add(newMenuItem);\n fileMenu.add(openMenuItem);\n fileMenu.add(saveMenuItem);\n fileMenu.addSeparator();\n fileMenu.add(showWindowMenu);\n fileMenu.addSeparator();\n fileMenu.add(exitMenuItem);\n\n editMenu.add(cutMenuItem);\n editMenu.add(copyMenuItem);\n editMenu.add(pasteMenuItem);\n\n //add menu to menubar\n menuBar.add(fileMenu);\n menuBar.add(editMenu);\n menuBar.add(aboutMenu);\n\n //add menubar to the frame\n mainFrame.setMenuBar(menuBar);\n mainFrame.setVisible(true); \n}\n\n class MenuItemListener implements ActionListener {\n public void actionPerformed(ActionEvent e) { \n statusLabel.setText(e.getActionCommand() \n + \" MenuItem clicked.\");\n } \n }\n}"
},
{
"code": null,
"e": 8881,
"s": 8790,
"text": "Compile the program using command prompt. Go to D:/ > AWT and type the following command."
},
{
"code": null,
"e": 8934,
"s": 8881,
"text": "D:\\AWT>javac com\\tutorialspoint\\gui\\AWTMenuDemo.java"
},
{
"code": null,
"e": 9031,
"s": 8934,
"text": "If no error comes that means compilation is successful. Run the program using following command."
},
{
"code": null,
"e": 9078,
"s": 9031,
"text": "D:\\AWT>java com.tutorialspoint.gui.AWTMenuDemo"
},
{
"code": null,
"e": 9151,
"s": 9078,
"text": "Verify the following output. (Click on File Menu. Select any menu item.)"
},
{
"code": null,
"e": 9184,
"s": 9151,
"text": "\n 13 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 9192,
"s": 9184,
"text": " EduOLC"
},
{
"code": null,
"e": 9199,
"s": 9192,
"text": " Print"
},
{
"code": null,
"e": 9210,
"s": 9199,
"text": " Add Notes"
}
] |
Select all duplicate MySQL rows based on one or two columns?
|
For this, use subquery along with HAVING clause. Let us first create a table β
mysql> create table DemoTable
(
StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
StudentFirstName varchar(20),
StudentLastName varchar(20)
);
Query OK, 0 rows affected (0.27 sec)
Insert some records in the table using insert command β
mysql> insert into DemoTable(StudentFirstName,StudentLastName) values('John','Smith');
Query OK, 1 row affected (0.04 sec)
mysql> insert into DemoTable(StudentFirstName,StudentLastName) values('Carol','Taylor');
Query OK, 1 row affected (0.04 sec)
mysql> insert into DemoTable(StudentFirstName,StudentLastName) values('John','Doe');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(StudentFirstName,StudentLastName) values('John','Brown');
Query OK, 1 row affected (0.05 sec)
mysql> insert into DemoTable(StudentFirstName,StudentLastName) values('David','Miller');
Query OK, 1 row affected (0.06 sec)
Display all records from the table using select statement β
mysql> select *from DemoTable;
This will produce the following output β
+-----------+------------------+-----------------+
| StudentId | StudentFirstName | StudentLastName |
+-----------+------------------+-----------------+
| 1 | John | Smith |
| 2 | Carol | Taylor |
| 3 | John | Doe |
| 4 | John | Brown |
| 5 | David | Miller |
+-----------+------------------+-----------------+
5 rows in set (0.00 sec)
Following is the query to select all duplicate rows based on one or two columns. Here, we are counting the names appearing more than once i.e. duplicates β
mysql> select StudentId from DemoTable
where StudentFirstName=(select StudentFirstName from DemoTable having count(StudentFirstName) > 1);
This will produce the following output β
+-----------+
| StudentId |
+-----------+
| 1 |
| 3 |
| 4 |
+-----------+
3 rows in set (0.03 sec)
|
[
{
"code": null,
"e": 1141,
"s": 1062,
"text": "For this, use subquery along with HAVING clause. Let us first create a table β"
},
{
"code": null,
"e": 1337,
"s": 1141,
"text": "mysql> create table DemoTable\n (\n StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n StudentFirstName varchar(20),\n StudentLastName varchar(20)\n );\nQuery OK, 0 rows affected (0.27 sec)"
},
{
"code": null,
"e": 1393,
"s": 1337,
"text": "Insert some records in the table using insert command β"
},
{
"code": null,
"e": 2014,
"s": 1393,
"text": "mysql> insert into DemoTable(StudentFirstName,StudentLastName) values('John','Smith');\nQuery OK, 1 row affected (0.04 sec)\n\nmysql> insert into DemoTable(StudentFirstName,StudentLastName) values('Carol','Taylor');\nQuery OK, 1 row affected (0.04 sec)\n\nmysql> insert into DemoTable(StudentFirstName,StudentLastName) values('John','Doe');\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into DemoTable(StudentFirstName,StudentLastName) values('John','Brown');\nQuery OK, 1 row affected (0.05 sec)\n\nmysql> insert into DemoTable(StudentFirstName,StudentLastName) values('David','Miller');\nQuery OK, 1 row affected (0.06 sec)"
},
{
"code": null,
"e": 2074,
"s": 2014,
"text": "Display all records from the table using select statement β"
},
{
"code": null,
"e": 2105,
"s": 2074,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2146,
"s": 2105,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2630,
"s": 2146,
"text": "+-----------+------------------+-----------------+\n| StudentId | StudentFirstName | StudentLastName |\n+-----------+------------------+-----------------+\n| 1 | John | Smith |\n| 2 | Carol | Taylor |\n| 3 | John | Doe |\n| 4 | John | Brown |\n| 5 | David | Miller |\n+-----------+------------------+-----------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2786,
"s": 2630,
"text": "Following is the query to select all duplicate rows based on one or two columns. Here, we are counting the names appearing more than once i.e. duplicates β"
},
{
"code": null,
"e": 2928,
"s": 2786,
"text": "mysql> select StudentId from DemoTable\n where StudentFirstName=(select StudentFirstName from DemoTable having count(StudentFirstName) > 1);"
},
{
"code": null,
"e": 2969,
"s": 2928,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 3092,
"s": 2969,
"text": "+-----------+\n| StudentId |\n+-----------+\n| 1 |\n| 3 |\n| 4 |\n+-----------+\n3 rows in set (0.03 sec)"
}
] |
How to deserialize a Java object from Reader Stream using flexjson in Java?
|
The Flexjson is a lightweight library for serializing and deserializing Java objects into and from JSON format. We can deserialize a Java object from a Reader stream using the deserialize() method of JSONDeserializer class, it uses an instance of Reader class as JSON input.
public T deserialize(Reader input)
import java.io.*;
import flexjson.JSONDeserializer;
public class JSONDeserializeReaderTest {
public static void main(String[] args) {
JSONDeserializer<Student> deserializer = new JSONDeserializer<Student>();
String jsonStr =
"{" +
"\"firstName\": \"Adithya\"," +
"\"lastName\": \"Sai\"," +
"\"age\": 25," +
"\"address\": \"Hyderabad\"" +
"\"class\": \"Student\"" +
"}";
Student student = deserializer.deserialize(new StringReader(jsonStr));
System.out.println(student);
}
}
// Student class
class Student {
private String firstName;
private String lastName;
private int age;
private String address;
public Student() {}
public Student(String firstName, String lastName, int age, String address) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.address = address;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String toString() {
return "Student[ " +
"firstName = " + firstName +
", lastName = " + lastName +
", age = " + age +
", address = " + address +
" ]";
}
}
Student[ firstName = Adithya, lastName = Sai, age = 25, address = Hyderabad ]
|
[
{
"code": null,
"e": 1337,
"s": 1062,
"text": "The Flexjson is a lightweight library for serializing and deserializing Java objects into and from JSON format. We can deserialize a Java object from a Reader stream using the deserialize() method of JSONDeserializer class, it uses an instance of Reader class as JSON input."
},
{
"code": null,
"e": 1372,
"s": 1337,
"text": "public T deserialize(Reader input)"
},
{
"code": null,
"e": 3164,
"s": 1372,
"text": "import java.io.*;\nimport flexjson.JSONDeserializer;\npublic class JSONDeserializeReaderTest {\n public static void main(String[] args) {\n JSONDeserializer<Student> deserializer = new JSONDeserializer<Student>();\n String jsonStr =\n \"{\" +\n \"\\\"firstName\\\": \\\"Adithya\\\",\" +\n \"\\\"lastName\\\": \\\"Sai\\\",\" +\n \"\\\"age\\\": 25,\" +\n \"\\\"address\\\": \\\"Hyderabad\\\"\" +\n \"\\\"class\\\": \\\"Student\\\"\" +\n \"}\";\n Student student = deserializer.deserialize(new StringReader(jsonStr));\n System.out.println(student);\n }\n}\n// Student class\nclass Student {\n private String firstName;\n private String lastName;\n private int age;\n private String address;\n public Student() {}\n public Student(String firstName, String lastName, int age, String address) {\n super();\n this.firstName = firstName;\n this.lastName = lastName;\n this.age = age;\n this.address = address;\n }\n public String getFirstName() {\n return firstName;\n }\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n public String getLastName() {\n return lastName;\n }\n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n public int getAge() {\n return age;\n }\n public void setAge(int age) {\n this.age = age;\n }\n public String getAddress() {\n return address;\n }\n public void setAddress(String address) {\n this.address = address;\n }\n public String toString() {\n return \"Student[ \" +\n \"firstName = \" + firstName +\n \", lastName = \" + lastName +\n \", age = \" + age +\n \", address = \" + address +\n \" ]\";\n }\n}"
},
{
"code": null,
"e": 3242,
"s": 3164,
"text": "Student[ firstName = Adithya, lastName = Sai, age = 25, address = Hyderabad ]"
}
] |
Solve ERROR 1396 (HY000): Operation DROP USER failed for 'user'@'localhost' in MySql?
|
This error occurs when you drop a user with localhost while you have created a user with β%β.
Let us create a user with β%β and drop the user as a localhost. The syntax is as follows
CREATE USER 'yourUserName'@'%' IDENTIFIED BY 'yourPassword';
Let us create a user using the above syntax. The query to create a user is as follows
mysql> CREATE USER 'Jack'@'%' IDENTIFIED BY '1234';
Query OK, 0 rows affected (0.26 sec)
Check user is created successfully or not
mysql> select user,host from MySQL.user;
The following is the output
+------------------+-----------+
| user | host |
+------------------+-----------+
| Jack | % |
| Manish | % |
| User2 | % |
| mysql.infoschema | % |
| mysql.session | % |
| mysql.sys | % |
| root | % |
| Adam Smith | localhost |
| User1 | localhost |
| am | localhost |
+------------------+-----------+
10 rows in set (0.00 sec)
Look at the above sample output, we have a user with name βJackβ and host is β%β. Whenever you try to drop the user with localhost then you will get an error which is as follows
mysql> DROP USER 'Jack'@'localhost';
ERROR 1396 (HY000): Operation DROP USER failed for 'Jack'@'localhost'
Let us drop the above user with host β%β. The query is as follows
mysql> DROP USER 'Jack'@'%';
Query OK, 0 rows affected (0.19 sec)
Check the user has been dropped or not from MySQL.user table. The query is as follows
mysql> select user,host from MySQL.user;
The following is the output displaying that the user Jack is removed successfully
+------------------+-----------+
| user | host |
+------------------+-----------+
| Manish | % |
| User2 | % |
| mysql.infoschema | % |
| mysql.session | % |
| mysql.sys | % |
| root | % |
| Adam Smith | localhost |
| User1 | localhost |
| am | localhost |
+------------------+-----------+
9 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1156,
"s": 1062,
"text": "This error occurs when you drop a user with localhost while you have created a user with β%β."
},
{
"code": null,
"e": 1245,
"s": 1156,
"text": "Let us create a user with β%β and drop the user as a localhost. The syntax is as follows"
},
{
"code": null,
"e": 1306,
"s": 1245,
"text": "CREATE USER 'yourUserName'@'%' IDENTIFIED BY 'yourPassword';"
},
{
"code": null,
"e": 1392,
"s": 1306,
"text": "Let us create a user using the above syntax. The query to create a user is as follows"
},
{
"code": null,
"e": 1481,
"s": 1392,
"text": "mysql> CREATE USER 'Jack'@'%' IDENTIFIED BY '1234';\nQuery OK, 0 rows affected (0.26 sec)"
},
{
"code": null,
"e": 1523,
"s": 1481,
"text": "Check user is created successfully or not"
},
{
"code": null,
"e": 1564,
"s": 1523,
"text": "mysql> select user,host from MySQL.user;"
},
{
"code": null,
"e": 1592,
"s": 1564,
"text": "The following is the output"
},
{
"code": null,
"e": 2080,
"s": 1592,
"text": "+------------------+-----------+\n| user | host |\n+------------------+-----------+\n| Jack | % |\n| Manish | % |\n| User2 | % |\n| mysql.infoschema | % |\n| mysql.session | % |\n| mysql.sys | % |\n| root | % |\n| Adam Smith | localhost |\n| User1 | localhost |\n| am | localhost |\n+------------------+-----------+\n10 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2258,
"s": 2080,
"text": "Look at the above sample output, we have a user with name βJackβ and host is β%β. Whenever you try to drop the user with localhost then you will get an error which is as follows"
},
{
"code": null,
"e": 2365,
"s": 2258,
"text": "mysql> DROP USER 'Jack'@'localhost';\nERROR 1396 (HY000): Operation DROP USER failed for 'Jack'@'localhost'"
},
{
"code": null,
"e": 2431,
"s": 2365,
"text": "Let us drop the above user with host β%β. The query is as follows"
},
{
"code": null,
"e": 2497,
"s": 2431,
"text": "mysql> DROP USER 'Jack'@'%';\nQuery OK, 0 rows affected (0.19 sec)"
},
{
"code": null,
"e": 2583,
"s": 2497,
"text": "Check the user has been dropped or not from MySQL.user table. The query is as follows"
},
{
"code": null,
"e": 2624,
"s": 2583,
"text": "mysql> select user,host from MySQL.user;"
},
{
"code": null,
"e": 2706,
"s": 2624,
"text": "The following is the output displaying that the user Jack is removed successfully"
},
{
"code": null,
"e": 3160,
"s": 2706,
"text": "+------------------+-----------+\n| user | host |\n+------------------+-----------+\n| Manish | % |\n| User2 | % |\n| mysql.infoschema | % |\n| mysql.session | % |\n| mysql.sys | % |\n| root | % |\n| Adam Smith | localhost |\n| User1 | localhost |\n| am | localhost |\n+------------------+-----------+\n9 rows in set (0.00 sec)"
}
] |
MS SQL Server - Restoring Databases
|
Restoring is the process of copying data from a backup and applying logged transactions to the data. Restore is what you do with backups. Take the backup file and turn it back into a database.
The Restore database option can be done using either of the following two methods.
Restore database <Your database name> from disk = '<Backup file location + file name>'
The following command is used to restore database called 'TestDB' with backup file name 'TestDB_Full.bak' which is available in 'D:\' location if you are overwriting the existed database.
Restore database TestDB from disk = ' D:\TestDB_Full.bak' with replace
If you are creating a new database with this restore command and there is no similar path of data, log files in target server, then use move option like the following command.
Make sure the D:\Data path exists as used in the following command for data and log files.
RESTORE DATABASE TestDB FROM DISK = 'D:\ TestDB_Full.bak' WITH MOVE 'TestDB' TO
'D:\Data\TestDB.mdf', MOVE 'TestDB_Log' TO 'D:\Data\TestDB_Log.ldf'
Step 1 β Connect to database instance named 'TESTINSTANCE' and right-click on databases folder. Click Restore database as shown in the following snapshot.
Step 2 β Select device radio button and click on ellipse to select the backup file as shown in the following snapshot.
Step 3 β Click OK and the following screen pops up.
Step 4 β Select Files option which is on the top left corner as shown in the following snapshot.
Step 5 β Select Options which is on the top left corner and click OK to restore 'TestDB' database as shown in the following snapshot.
32 Lectures
2.5 hours
Pavan Lalwani
18 Lectures
1.5 hours
Dr. Saatya Prasad
102 Lectures
10 hours
Pavan Lalwani
52 Lectures
4 hours
Pavan Lalwani
239 Lectures
33 hours
Gowthami Swarna
53 Lectures
5 hours
Akshay Magre
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2428,
"s": 2235,
"text": "Restoring is the process of copying data from a backup and applying logged transactions to the data. Restore is what you do with backups. Take the backup file and turn it back into a database."
},
{
"code": null,
"e": 2511,
"s": 2428,
"text": "The Restore database option can be done using either of the following two methods."
},
{
"code": null,
"e": 2599,
"s": 2511,
"text": "Restore database <Your database name> from disk = '<Backup file location + file name>'\n"
},
{
"code": null,
"e": 2787,
"s": 2599,
"text": "The following command is used to restore database called 'TestDB' with backup file name 'TestDB_Full.bak' which is available in 'D:\\' location if you are overwriting the existed database."
},
{
"code": null,
"e": 2859,
"s": 2787,
"text": "Restore database TestDB from disk = ' D:\\TestDB_Full.bak' with replace\n"
},
{
"code": null,
"e": 3035,
"s": 2859,
"text": "If you are creating a new database with this restore command and there is no similar path of data, log files in target server, then use move option like the following command."
},
{
"code": null,
"e": 3126,
"s": 3035,
"text": "Make sure the D:\\Data path exists as used in the following command for data and log files."
},
{
"code": null,
"e": 3279,
"s": 3126,
"text": "RESTORE DATABASE TestDB FROM DISK = 'D:\\ TestDB_Full.bak' WITH MOVE 'TestDB' TO \n 'D:\\Data\\TestDB.mdf', MOVE 'TestDB_Log' TO 'D:\\Data\\TestDB_Log.ldf'\n"
},
{
"code": null,
"e": 3434,
"s": 3279,
"text": "Step 1 β Connect to database instance named 'TESTINSTANCE' and right-click on databases folder. Click Restore database as shown in the following snapshot."
},
{
"code": null,
"e": 3553,
"s": 3434,
"text": "Step 2 β Select device radio button and click on ellipse to select the backup file as shown in the following snapshot."
},
{
"code": null,
"e": 3605,
"s": 3553,
"text": "Step 3 β Click OK and the following screen pops up."
},
{
"code": null,
"e": 3702,
"s": 3605,
"text": "Step 4 β Select Files option which is on the top left corner as shown in the following snapshot."
},
{
"code": null,
"e": 3836,
"s": 3702,
"text": "Step 5 β Select Options which is on the top left corner and click OK to restore 'TestDB' database as shown in the following snapshot."
},
{
"code": null,
"e": 3871,
"s": 3836,
"text": "\n 32 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3886,
"s": 3871,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 3921,
"s": 3886,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3940,
"s": 3921,
"text": " Dr. Saatya Prasad"
},
{
"code": null,
"e": 3975,
"s": 3940,
"text": "\n 102 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3990,
"s": 3975,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 4023,
"s": 3990,
"text": "\n 52 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4038,
"s": 4023,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 4073,
"s": 4038,
"text": "\n 239 Lectures \n 33 hours \n"
},
{
"code": null,
"e": 4090,
"s": 4073,
"text": " Gowthami Swarna"
},
{
"code": null,
"e": 4123,
"s": 4090,
"text": "\n 53 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4137,
"s": 4123,
"text": " Akshay Magre"
},
{
"code": null,
"e": 4144,
"s": 4137,
"text": " Print"
},
{
"code": null,
"e": 4155,
"s": 4144,
"text": " Add Notes"
}
] |
MySQL query to multiply values of two rows and add the result
|
For this, use aggregate function SUM(). Within this method, multiply the row values. Let us first create a table β
mysql> create table DemoTable(
ProductQuantity int,
ProductPrice int
);
Query OK, 0 rows affected (0.48 sec)
Insert some records in the table using insert command β
mysql> insert into DemoTable values(10,9);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(6,20);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(7,100);
Query OK, 1 row affected (0.08 sec)
Display all records from the table using select statement β
mysql> select *from DemoTable;
This will produce the following output β
+-----------------+--------------+
| ProductQuantity | ProductPrice |
+-----------------+--------------+
| 10 | 9 |
| 6 | 20 |
| 7 | 100 |
+-----------------+--------------+
3 rows in set (0.00 sec)
Following is the query to multiply values of two rows and add the result β
mysql> select SUM(ProductQuantity*ProductPrice) AS Total_Value from DemoTable;
This will produce the following output β
+-------------+
| Total_Value |
+-------------+
| 910 |
+-------------+
1 row in set (0.00 sec)
|
[
{
"code": null,
"e": 1177,
"s": 1062,
"text": "For this, use aggregate function SUM(). Within this method, multiply the row values. Let us first create a table β"
},
{
"code": null,
"e": 1292,
"s": 1177,
"text": "mysql> create table DemoTable(\n ProductQuantity int,\n ProductPrice int\n);\nQuery OK, 0 rows affected (0.48 sec)"
},
{
"code": null,
"e": 1348,
"s": 1292,
"text": "Insert some records in the table using insert command β"
},
{
"code": null,
"e": 1586,
"s": 1348,
"text": "mysql> insert into DemoTable values(10,9);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values(6,20);\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable values(7,100);\nQuery OK, 1 row affected (0.08 sec)"
},
{
"code": null,
"e": 1646,
"s": 1586,
"text": "Display all records from the table using select statement β"
},
{
"code": null,
"e": 1677,
"s": 1646,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1718,
"s": 1677,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 1988,
"s": 1718,
"text": "+-----------------+--------------+\n| ProductQuantity | ProductPrice |\n+-----------------+--------------+\n| 10 | 9 |\n| 6 | 20 |\n| 7 | 100 |\n+-----------------+--------------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2063,
"s": 1988,
"text": "Following is the query to multiply values of two rows and add the result β"
},
{
"code": null,
"e": 2142,
"s": 2063,
"text": "mysql> select SUM(ProductQuantity*ProductPrice) AS Total_Value from DemoTable;"
},
{
"code": null,
"e": 2183,
"s": 2142,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2287,
"s": 2183,
"text": "+-------------+\n| Total_Value |\n+-------------+\n| 910 |\n+-------------+\n1 row in set (0.00 sec)"
}
] |
How to override class methods in Python?
|
Overriding is the property of a class to change the implementation of a method provided by one of its base classes.
Overriding is a very important part of OOP since it makes inheritance utilize its full power. By using method overriding a class may "copy" another class, avoiding duplicated code, and at the same time enhance or customize part of it. Method overriding is thus a part of the inheritance mechanism.
In Python method overriding occurs by simply defining in the child class a method with the same name of a method in the parent class. When you define a method in the object you make this latter able to satisfy that method call, so the implementations of its ancestors do not come in play.
class Parent(object):
def __init__(self):
self.value = 4
def get_value(self):
return self.value
class Child(Parent):
def get_value(self):
return self.value + 1
Now Child objects behave differently
>>> c = Child()
>>> c.get_value()
5
|
[
{
"code": null,
"e": 1178,
"s": 1062,
"text": "Overriding is the property of a class to change the implementation of a method provided by one of its base classes."
},
{
"code": null,
"e": 1476,
"s": 1178,
"text": "Overriding is a very important part of OOP since it makes inheritance utilize its full power. By using method overriding a class may \"copy\" another class, avoiding duplicated code, and at the same time enhance or customize part of it. Method overriding is thus a part of the inheritance mechanism."
},
{
"code": null,
"e": 1769,
"s": 1476,
"text": "In Python method overriding occurs by simply defining in the child class a method with the same name of a method in the parent class. When you define a method in the object you make this latter able to satisfy that method call, so the implementations of its ancestors do not come in play."
},
{
"code": null,
"e": 1975,
"s": 1769,
"text": "class Parent(object):\n def __init__(self):\n self.value = 4\n def get_value(self):\n return self.value\n \nclass Child(Parent):\n def get_value(self):\n return self.value + 1\n "
},
{
"code": null,
"e": 2012,
"s": 1975,
"text": "Now Child objects behave differently"
},
{
"code": null,
"e": 2048,
"s": 2012,
"text": ">>> c = Child()\n>>> c.get_value()\n5"
}
] |
Print a number 100 times without using loop, recursion and macro expansion in C
|
In this section we will see how to print a number 100 times in C. There are some constraints. We cannot use loops, recursions or macro expansions.
To solve this problem we will use the setjump and longjump in C. The setjump() and longjump() is located at setjmp.h library. The syntax of these two functions are like below.
#include <stdio.h>
#include <setjmp.h>
jmp_buf buf;
main() {
int x = 1;
setjmp(buf); //set the jump position using buf
printf("5"); // Prints a number
x++;
if (x <= 100)
longjmp(buf, 1); // Jump to the point located by setjmp
}
5555555555555555555555555555555555555555555555555555555555555555555555555555
555555555555555555555555
|
[
{
"code": null,
"e": 1209,
"s": 1062,
"text": "In this section we will see how to print a number 100 times in C. There are some constraints. We cannot use loops, recursions or macro expansions."
},
{
"code": null,
"e": 1385,
"s": 1209,
"text": "To solve this problem we will use the setjump and longjump in C. The setjump() and longjump() is located at setjmp.h library. The syntax of these two functions are like below."
},
{
"code": null,
"e": 1634,
"s": 1385,
"text": "#include <stdio.h>\n#include <setjmp.h>\njmp_buf buf;\nmain() {\n int x = 1;\n setjmp(buf); //set the jump position using buf\n printf(\"5\"); // Prints a number\n x++;\n if (x <= 100)\n longjmp(buf, 1); // Jump to the point located by setjmp\n}"
},
{
"code": null,
"e": 1736,
"s": 1634,
"text": "5555555555555555555555555555555555555555555555555555555555555555555555555555\n555555555555555555555555"
}
] |
D3.js stack.keys() Method - GeeksforGeeks
|
07 Sep, 2020
The stack.keys() method makes an array of strings as an argument and returns the stack generator.
Syntax:
stack.keys([keys])
Parameters: This method accepts a single parameter as mentioned above and described below.
domain: This parameter holds an array of strings as key arguments.
Return Value: This method returns the stack generator.
Example:
HTML
<!DOCTYPE html><html><head> <meta charset="utf-8"> <script src= "https://d3js.org/d3.v5.min.js"> </script></head> <body> <h1 style="text-align: center; color: green;"> GeeksforGeeks </h1> <center> <canvas id="gfg" width="200" height="200"> </canvas> </center> <script> var data = [ {a: 3840, b: 1920, c: 960, d: 400}, {a: 1600, b: 1440, c: 960, d: 400}, {a: 640, b: 960, c: 640, d: 400}, {a: 320, b: 480, c: 640, d: 400} ]; var stackGen = d3.stack() // Defining keys .keys(["a", "b", "c", "d"]) var stack = stackGen(data); console.log(stack); for (i = 0; i < 4; i++) { // Displaying keys console.log(stack[i].key); } </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 filter object array based on attributes?
How to get selected value in dropdown list using JavaScript ?
How to remove duplicate elements from JavaScript Array ?
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": "\n07 Sep, 2020"
},
{
"code": null,
"e": 25318,
"s": 25220,
"text": "The stack.keys() method makes an array of strings as an argument and returns the stack generator."
},
{
"code": null,
"e": 25326,
"s": 25318,
"text": "Syntax:"
},
{
"code": null,
"e": 25347,
"s": 25326,
"text": " stack.keys([keys])\n"
},
{
"code": null,
"e": 25438,
"s": 25347,
"text": "Parameters: This method accepts a single parameter as mentioned above and described below."
},
{
"code": null,
"e": 25505,
"s": 25438,
"text": "domain: This parameter holds an array of strings as key arguments."
},
{
"code": null,
"e": 25560,
"s": 25505,
"text": "Return Value: This method returns the stack generator."
},
{
"code": null,
"e": 25569,
"s": 25560,
"text": "Example:"
},
{
"code": null,
"e": 25574,
"s": 25569,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <meta charset=\"utf-8\"> <script src= \"https://d3js.org/d3.v5.min.js\"> </script></head> <body> <h1 style=\"text-align: center; color: green;\"> GeeksforGeeks </h1> <center> <canvas id=\"gfg\" width=\"200\" height=\"200\"> </canvas> </center> <script> var data = [ {a: 3840, b: 1920, c: 960, d: 400}, {a: 1600, b: 1440, c: 960, d: 400}, {a: 640, b: 960, c: 640, d: 400}, {a: 320, b: 480, c: 640, d: 400} ]; var stackGen = d3.stack() // Defining keys .keys([\"a\", \"b\", \"c\", \"d\"]) var stack = stackGen(data); console.log(stack); for (i = 0; i < 4; i++) { // Displaying keys console.log(stack[i].key); } </script></body></html>",
"e": 26447,
"s": 25574,
"text": null
},
{
"code": null,
"e": 26455,
"s": 26447,
"text": "Output:"
},
{
"code": null,
"e": 26461,
"s": 26455,
"text": "D3.js"
},
{
"code": null,
"e": 26472,
"s": 26461,
"text": "JavaScript"
},
{
"code": null,
"e": 26489,
"s": 26472,
"text": "Web Technologies"
},
{
"code": null,
"e": 26587,
"s": 26489,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26596,
"s": 26587,
"text": "Comments"
},
{
"code": null,
"e": 26609,
"s": 26596,
"text": "Old Comments"
},
{
"code": null,
"e": 26670,
"s": 26609,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26711,
"s": 26670,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 26759,
"s": 26711,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 26821,
"s": 26759,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 26878,
"s": 26821,
"text": "How to remove duplicate elements from JavaScript Array ?"
},
{
"code": null,
"e": 26920,
"s": 26878,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26953,
"s": 26920,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27015,
"s": 26953,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27058,
"s": 27015,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Select and filter the records on month basis in a MySQL table?
|
You can use aggregate function SUM() with GROUP BY clause to achieve this.
Let us create a table. The query to create a table is as follows β
mysql> create table SelectPerMonthDemo
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> Price int,
-> PurchaseDate datetime
-> );
Query OK, 0 rows affected (2.34 sec)
Insert some records in the table using insert command with one of them would be the date of purchase. The query is as follows β
mysql> insert into SelectPerMonthDemo(Price,PurchaseDate) values(600,date_add(now(),
interval -1 month));
Query OK, 1 row affected (0.42 sec)
mysql> insert into SelectPerMonthDemo(Price,PurchaseDate) values(600,date_add(now(),
interval 2 month));
Query OK, 1 row affected (0.34 sec)
mysql> insert into SelectPerMonthDemo(Price,PurchaseDate) values(400,now());
Query OK, 1 row affected (0.20 sec)
mysql> insert into SelectPerMonthDemo(Price,PurchaseDate) values(800,date_add(now(),
interval 3 month));
Query OK, 1 row affected (0.13 sec)
mysql> insert into SelectPerMonthDemo(Price,PurchaseDate) values(900,date_add(now(),
interval 4 month));
Query OK, 1 row affected (0.10 sec)
mysql> insert into SelectPerMonthDemo(Price,PurchaseDate) values(100,date_add(now(),
interval 4 month));
Query OK, 1 row affected (0.22 sec)
mysql> insert into SelectPerMonthDemo(Price,PurchaseDate) values(1200,date_add(now(),
interval -1 month));
Query OK, 1 row affected (0.09 sec)
Display all records from the table using a select statement. The query is as follows β
mysql> select *from SelectPerMonthDemo;
The following is the output displaying the price and purchase date of the products β
+----+-------+---------------------+
| Id | Price | PurchaseDate |
+----+-------+---------------------+
| 1 | 600 | 2019-01-10 22:39:30 |
| 2 | 600 | 2019-04-10 22:39:47 |
| 3 | 400 | 2019-02-10 22:40:03 |
| 4 | 800 | 2019-05-10 22:40:18 |
| 5 | 900 | 2019-06-10 22:40:29 |
| 6 | 100 | 2019-06-10 22:40:41 |
| 7 | 1200 | 2019-01-10 22:40:50 |
+----+-------+---------------------+
7 rows in set (0.00 sec)
Here is the query to get the records according to individual months based on the Purchase Date β
mysql> select monthname(PurchaseDate) as MONTHNAME,sum(Price) from
SelectPerMonthDemo
-> group by monthname(PurchaseDate);
+-----------+------------+
| MONTHNAME | sum(Price) |
+-----------+------------+
| January | 1800 |
| April | 600 |
| February | 400 |
| May | 800 |
| June | 1000 |
+-----------+------------+
5 rows in set (0.07 sec)
If you do not want the month name (only the month number), then use the following query β
mysql> select month(PurchaseDate),sum(Price) from SelectPerMonthDemo
-> group by month(PurchaseDate);
+---------------------+------------+
| month(PurchaseDate) | sum(Price) |
+---------------------+------------+
| 1 | 1800 |
| 4 | 600 |
| 2 | 400 |
| 5 | 800 |
| 6 | 1000 |
+---------------------+------------+
5 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1137,
"s": 1062,
"text": "You can use aggregate function SUM() with GROUP BY clause to achieve this."
},
{
"code": null,
"e": 1204,
"s": 1137,
"text": "Let us create a table. The query to create a table is as follows β"
},
{
"code": null,
"e": 1392,
"s": 1204,
"text": "mysql> create table SelectPerMonthDemo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> Price int,\n -> PurchaseDate datetime\n -> );\nQuery OK, 0 rows affected (2.34 sec)"
},
{
"code": null,
"e": 1520,
"s": 1392,
"text": "Insert some records in the table using insert command with one of them would be the date of purchase. The query is as follows β"
},
{
"code": null,
"e": 2482,
"s": 1520,
"text": "mysql> insert into SelectPerMonthDemo(Price,PurchaseDate) values(600,date_add(now(),\ninterval -1 month));\nQuery OK, 1 row affected (0.42 sec)\nmysql> insert into SelectPerMonthDemo(Price,PurchaseDate) values(600,date_add(now(),\ninterval 2 month));\nQuery OK, 1 row affected (0.34 sec)\nmysql> insert into SelectPerMonthDemo(Price,PurchaseDate) values(400,now());\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into SelectPerMonthDemo(Price,PurchaseDate) values(800,date_add(now(),\ninterval 3 month));\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into SelectPerMonthDemo(Price,PurchaseDate) values(900,date_add(now(),\ninterval 4 month));\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into SelectPerMonthDemo(Price,PurchaseDate) values(100,date_add(now(),\ninterval 4 month));\nQuery OK, 1 row affected (0.22 sec)\nmysql> insert into SelectPerMonthDemo(Price,PurchaseDate) values(1200,date_add(now(),\ninterval -1 month));\nQuery OK, 1 row affected (0.09 sec)"
},
{
"code": null,
"e": 2569,
"s": 2482,
"text": "Display all records from the table using a select statement. The query is as follows β"
},
{
"code": null,
"e": 2609,
"s": 2569,
"text": "mysql> select *from SelectPerMonthDemo;"
},
{
"code": null,
"e": 2694,
"s": 2609,
"text": "The following is the output displaying the price and purchase date of the products β"
},
{
"code": null,
"e": 3119,
"s": 2694,
"text": "+----+-------+---------------------+\n| Id | Price | PurchaseDate |\n+----+-------+---------------------+\n| 1 | 600 | 2019-01-10 22:39:30 |\n| 2 | 600 | 2019-04-10 22:39:47 |\n| 3 | 400 | 2019-02-10 22:40:03 |\n| 4 | 800 | 2019-05-10 22:40:18 |\n| 5 | 900 | 2019-06-10 22:40:29 |\n| 6 | 100 | 2019-06-10 22:40:41 |\n| 7 | 1200 | 2019-01-10 22:40:50 |\n+----+-------+---------------------+\n7 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3216,
"s": 3119,
"text": "Here is the query to get the records according to individual months based on the Purchase Date β"
},
{
"code": null,
"e": 3339,
"s": 3216,
"text": "mysql> select monthname(PurchaseDate) as MONTHNAME,sum(Price) from\nSelectPerMonthDemo\n-> group by monthname(PurchaseDate);"
},
{
"code": null,
"e": 3556,
"s": 3339,
"text": "+-----------+------------+\n| MONTHNAME | sum(Price) |\n+-----------+------------+\n| January | 1800 |\n| April | 600 |\n| February | 400 |\n| May | 800 |\n| June | 1000 |\n+-----------+------------+\n5 rows in set (0.07 sec)"
},
{
"code": null,
"e": 3646,
"s": 3556,
"text": "If you do not want the month name (only the month number), then use the following query β"
},
{
"code": null,
"e": 3748,
"s": 3646,
"text": "mysql> select month(PurchaseDate),sum(Price) from SelectPerMonthDemo\n-> group by month(PurchaseDate);"
},
{
"code": null,
"e": 3983,
"s": 3748,
"text": "+---------------------+------------+\n| month(PurchaseDate) | sum(Price) |\n+---------------------+------------+\n| 1 | 1800 |\n| 4 | 600 |\n| 2 | 400 |\n| 5 | 800 |\n| 6 | 1000 |\n+---------------------+------------+\n5 rows in set (0.00 sec)"
}
] |
Letβs Make a Deal. Three approaches to solving the Monty... | by Alex Muhr | Towards Data Science
|
Your heart is pumping heavily. Youβre excited and nervous, not quite sure what to expect next. Youβve never been on TV before, but you know the game well. Led by the wily and charismatic Monty Hall, βLetβs Make a Dealβ is one of the most popular shows on TV these days. Youβve been a regular viewer since 1965 and seen Monty barter with contestants countless times. Once you watched a woman accept $50 in exchange for an envelope which held $1,000. Another time you watched a man turn down $800 to instead keep a box that was revealed to contain only paper towels! Now itβs your turn.
Monty Hall turns to you. Quickly, like a play by play announcer, βBehind one of these three doors, labeled 1,2, and 3, lies a new Corvette; the other two conceal worthless goats. Thatβs right, absolutely worthless goats. Now there, which door will you have?β
You hear a muted βBAAAAAβ, but youβre not sure where itβs coming from.
βIβll have door 1,β you say with conviction.
βExcellent choice! As you can see, behind door 3 is a worthless goat.β Door 3 is opened to reveal a black and white spotted billy goat. Itβs almost cute, though it is in fact absolutely worthless. The idea of a goat in your city apartment is comical, and itβs not like you would know how to sell a goat either.
Monty continues, βIs door 1 your final choice? You may switch to door 2 but thereβs no going back. Iβd hate to see make the wrong decision here.β
You ponder the situation. Your initial choice had a 1β3 probability of being correct, but youβve been granted new information and door 3 is now out of the running. The car must be behind either door 1 or 2, but which one? You consider how bummed you would feel if you were to switch from door 1 to door 2, only to find the car behind door 1 all along. Perhaps itβs best to stick to the original choice ... or is it?
The Monty Hall problem is a classic brain teaser that tests oneβs ability to reason with conditional probabilities. In addition, the premise of the problem adds a psychological edge; many choose to stay with the original door only to avoid the disappointment of switching away from the car. In this article, I will demonstrate 3 methods to determine the optimal strategy, stay or switch.
Itβs relatively easy to simulate the Monty Hall game many times over and record how many times the game is won vs lost. To be statistically rigorous, one can treat each attempt at the game as a Bernoulli trial (a random experiment with binary outcome) with probability of success is P. By the law of large numbers, a win rate of 100*P percent is expected if the number of experiments, N, is very large. By recording the outcome of many trials for both the stay and switch strategies, a z-test can be used to determine whether there is a statistically significant difference in win rates.
The python code below defines a function monty_hall that simulates the game. The keyword argument switch controls whether a stay or switch strategy is employed. Further, setting the keyword argument verbose = True allows one to play the game in an interactive manner and choose on the spot whether to stay or switch.
import numpy as npdef monty_hall(chosen_door, switch = False, verbose = False): ''' Parameters ---------- chosen_door : Initial choice of door, must be either 1, 2, or 3. switch : False --> stay strategy True --> switch strategy. verbose: False --> no input required True --> player is asked if they'd like to switch doors. overrides switch input. Returns ------ 1 : if the game is won 0 : if the game is lost ''' # Correct indexing for chosen door chosen_door += -1 # Randomly initialize array to represent the 3 doors # Array contains two 0s for goats and a single 1 for the car doors = [0, 0, 0] doors[np.random.randint(0,3)] = 1 # Reveal a door concealing a Goat revealed_door = np.random.choice([i for i, x in enumerate(doors) if x == 0 and i != chosen_door]) switch_door = list({0, 1, 2} - {chosen_door, revealed_door})[0] # If verbose == True ask the player if they'd like to switch. input_string = f"You've chosen door {chosen_door + 1}, an excellent choice! As you can see behind door {revealed_door + 1} is a worthless goat. Is door {chosen_door + 1} your final choice? You may switch to door {switch_door + 1} but there's no going back. Enter y if you'd like to switch." if verbose == True: choice = input(input_string) if choice == 'y': switch == True else: switch == False # Return the result of the game if switch == False: result = doors[chosen_door] else: result = doors[switch_door] if verbose == True: if result == 0: print("How unfortunate, you've chosen a worthless goat!") if result == 1: print("Congratulations, you've just won a new Corvette!") return result
Letβs use this function to play the game 100,000 times for both the stay and switch strategies. The results will be saved in the stay and switch lists and the win rate for each strategy will be printed.
i = 0stay = []switch = []while i < 100000: stay.append(monty_hall(np.random.randint(1, 4))) switch.append(monty_hall(np.random.randint(1, 4), switch = True)) i += 1 print(f"Stay win rate: {round(100 * np.sum(stay) / 100000, 1)}%")print(f"Switch win rate: {round(100 * np.sum(switch) / 100000, 1)}%")
Stay win rate: 33.3%
Switch win rate: 66.6%
Clearly there is a very large difference between the two strategies. Although a statistical test isnβt really needed to detect a difference here, letβs apply a two-tailed z-test to our data anyway.
from statsmodels.stats.weightstats import ztesttest_statistic, p_value = ztest(stay, switch)print(f"Test Statistic: {round(test_statistic, 1)}")print(f"P-Value: {round(p_value, 5)}")
Test Statistic: -157.5
P-Value: 0.0
The z-test has returned a test statistic of -157.5 and a p-value of 0 (really an infinitesimally small number that our computer has rounded to 0). Therefore the null hypothesis, that the win rate of stay and switch strategies are the same, can be rejected with complete certainty. Switching has been revealed to be the obviously superior strategy!
But why is switching so much better? To bet a better sense letβs look at the problem from a Bayesian point of view.
Bayesian statistics, as compared to frequentist statistics, offers an alternative perspective on cause and effect. Frequentist statistics seek to answer the question, βgiven my hypothesis, how probable is my data?β On the other hand, Bayesian statistics seek to answer the question, βgiven my data, how probable is my hypothesis?β The difference is subtle yet powerful.
The cornerstone of Bayesian statistics is Bayesβ Rule, a simple identity that informs how to properly update belief in a hypothesis given new data.
P(H|D) = P(D|H)*P(H) / P(D)
H = The hypothesis, D = New observed data
P(H|D) is the probability of our hypothesis given the new observed data. P(D|H) is the probability of observing the data given that the hypothesis is correct. P(H) is our assessment of the probability of the hypothesis being correct before observing the new data, also known as a βBayesian priorβ. P(D) is the probability of observing the data under any circumstances whether or not the hypothesis is true.
For the Monty Hall problem there are two possible hypotheses: H1) the car is behind the initially chosen door, and H2) the car is not behind the initially chosen door and switching will result in a win. For now letβs consider H1 and see how Bayeβs rule can be used to determine the probability of this hypothesis.
First, consider the prior probability of the hypothesis P(H1). Remember that the initial choice is made from 3 options that are all equally likely to be correct. P(H1), the probability of making an initial correct choice, is simply 1/3.
Next, consider the probability of observing the new data given that H1 is correct. If the car is in fact behind the originally chosen door, then the probability of a goat being revealed at either of the other doors is 1/2, as Monty will choose randomly between his two options. P(D|H1) = 1/2.
Finally, consider the probability of observing the new data under any circumstances. Because there are only two mutually exclusive hypotheses possible, P(D) can be determined using the following equation, P(D) = P(D|H1)P(H1) + P(D|H2)P(H2). We already know that P(D|H1) = 1/2 and P(H1) = 1/3. P(H2) = 2/3 and is simply the probability of making an initially incorrect choice. Lastly, P(D|H2) = 1/2, since if our initial door conceals a goat the remaining two doors both have equal probabilities of concealing the second goat. In summation P(D) = 1/2 * 1/3 + 1/2 * 2/3 = 1/2.
Altogether we have: P(H1) = 1/3, P(H2) = 2/3, P(D|H1) = 1/2, P(D|H2) = 1/2, and P(D) = 1/2
These values can now be inserted into Bayesβ rule to determine the probability that the car is behind our initially chosen door.
P(H1|D) = P(D|H1) * P(H1) / P(D) = (1/2 * 1/3) / (1/2) = 1/3
It would appear that the new information has not increased the probability of the initial choice being correct at all!
While weβre at it, letβs also use Bayesβ rule to determine the probability of H2, that the car is not behind our initial choice and that a switch will result in a win.
P(H2|D) = P(D|H2)*P(H2) / P(D) = (1/2 * 2/3) / (1/2) = 2/3
Weβve now used Bayesian reasoning to confirm the results of our Frequentist experiment. Further, the Bayesian probabilities determined for H1 and H2 correspond exactly to the win rates observed! By now itβs becoming clearer as to why switching is so much better than staying, but letβs look at the problem in one last way to really drive the point home.
The Monty Hall problem is certainly deceptive, but itβs not especially complex. By thinking through all the possible outcomes one can conclude that switching is the superior strategy rather quickly.
Consider the circumstances under which the switching strategy will either win or lose. Switching will lose when the initial door conceals the car. When the initial door conceals a goat, Monty will be forced to reveal the second goat, the remaining door will conceal the car, and switching will always win. As the initial choice will only conceal the car in 1 of 3 games, the switching strategy will lose approximately 1 in 3 games and win the other 2. Conversely, staying will only win the 1 in 3 games where the initial choice happens to be correct.
Monty shoots an impatient look, βAny day now buddy. Iβm beginning to think I should give that new Corvette to the goats!β
βBAAAAAβ the black and white billy goat seems to agree with Montyβs sentiment.
βIβll ask one last time, would you like to switch to door number 2?β
In a rush of epiphany you recall an article you read on this exact topic. Though you canβt be certain, you understand the odds associated with your choices. Resisting the temptation to stick to your guns, and accepting the possible embarrassment of self inflicted misfortune, you calmly announce βIβll switch to door 2.β
For an even deeper dive into the Monty Hall problem, its history, psychology, and many variations, check out The Monty Hall Problem by Jason Rosenhouse.
|
[
{
"code": null,
"e": 756,
"s": 171,
"text": "Your heart is pumping heavily. Youβre excited and nervous, not quite sure what to expect next. Youβve never been on TV before, but you know the game well. Led by the wily and charismatic Monty Hall, βLetβs Make a Dealβ is one of the most popular shows on TV these days. Youβve been a regular viewer since 1965 and seen Monty barter with contestants countless times. Once you watched a woman accept $50 in exchange for an envelope which held $1,000. Another time you watched a man turn down $800 to instead keep a box that was revealed to contain only paper towels! Now itβs your turn."
},
{
"code": null,
"e": 1015,
"s": 756,
"text": "Monty Hall turns to you. Quickly, like a play by play announcer, βBehind one of these three doors, labeled 1,2, and 3, lies a new Corvette; the other two conceal worthless goats. Thatβs right, absolutely worthless goats. Now there, which door will you have?β"
},
{
"code": null,
"e": 1086,
"s": 1015,
"text": "You hear a muted βBAAAAAβ, but youβre not sure where itβs coming from."
},
{
"code": null,
"e": 1131,
"s": 1086,
"text": "βIβll have door 1,β you say with conviction."
},
{
"code": null,
"e": 1442,
"s": 1131,
"text": "βExcellent choice! As you can see, behind door 3 is a worthless goat.β Door 3 is opened to reveal a black and white spotted billy goat. Itβs almost cute, though it is in fact absolutely worthless. The idea of a goat in your city apartment is comical, and itβs not like you would know how to sell a goat either."
},
{
"code": null,
"e": 1588,
"s": 1442,
"text": "Monty continues, βIs door 1 your final choice? You may switch to door 2 but thereβs no going back. Iβd hate to see make the wrong decision here.β"
},
{
"code": null,
"e": 2004,
"s": 1588,
"text": "You ponder the situation. Your initial choice had a 1β3 probability of being correct, but youβve been granted new information and door 3 is now out of the running. The car must be behind either door 1 or 2, but which one? You consider how bummed you would feel if you were to switch from door 1 to door 2, only to find the car behind door 1 all along. Perhaps itβs best to stick to the original choice ... or is it?"
},
{
"code": null,
"e": 2392,
"s": 2004,
"text": "The Monty Hall problem is a classic brain teaser that tests oneβs ability to reason with conditional probabilities. In addition, the premise of the problem adds a psychological edge; many choose to stay with the original door only to avoid the disappointment of switching away from the car. In this article, I will demonstrate 3 methods to determine the optimal strategy, stay or switch."
},
{
"code": null,
"e": 2980,
"s": 2392,
"text": "Itβs relatively easy to simulate the Monty Hall game many times over and record how many times the game is won vs lost. To be statistically rigorous, one can treat each attempt at the game as a Bernoulli trial (a random experiment with binary outcome) with probability of success is P. By the law of large numbers, a win rate of 100*P percent is expected if the number of experiments, N, is very large. By recording the outcome of many trials for both the stay and switch strategies, a z-test can be used to determine whether there is a statistically significant difference in win rates."
},
{
"code": null,
"e": 3297,
"s": 2980,
"text": "The python code below defines a function monty_hall that simulates the game. The keyword argument switch controls whether a stay or switch strategy is employed. Further, setting the keyword argument verbose = True allows one to play the game in an interactive manner and choose on the spot whether to stay or switch."
},
{
"code": null,
"e": 5174,
"s": 3297,
"text": "import numpy as npdef monty_hall(chosen_door, switch = False, verbose = False): ''' Parameters ---------- chosen_door : Initial choice of door, must be either 1, 2, or 3. switch : False --> stay strategy True --> switch strategy. verbose: False --> no input required True --> player is asked if they'd like to switch doors. overrides switch input. Returns ------ 1 : if the game is won 0 : if the game is lost ''' # Correct indexing for chosen door chosen_door += -1 # Randomly initialize array to represent the 3 doors # Array contains two 0s for goats and a single 1 for the car doors = [0, 0, 0] doors[np.random.randint(0,3)] = 1 # Reveal a door concealing a Goat revealed_door = np.random.choice([i for i, x in enumerate(doors) if x == 0 and i != chosen_door]) switch_door = list({0, 1, 2} - {chosen_door, revealed_door})[0] # If verbose == True ask the player if they'd like to switch. input_string = f\"You've chosen door {chosen_door + 1}, an excellent choice! As you can see behind door {revealed_door + 1} is a worthless goat. Is door {chosen_door + 1} your final choice? You may switch to door {switch_door + 1} but there's no going back. Enter y if you'd like to switch.\" if verbose == True: choice = input(input_string) if choice == 'y': switch == True else: switch == False # Return the result of the game if switch == False: result = doors[chosen_door] else: result = doors[switch_door] if verbose == True: if result == 0: print(\"How unfortunate, you've chosen a worthless goat!\") if result == 1: print(\"Congratulations, you've just won a new Corvette!\") return result"
},
{
"code": null,
"e": 5377,
"s": 5174,
"text": "Letβs use this function to play the game 100,000 times for both the stay and switch strategies. The results will be saved in the stay and switch lists and the win rate for each strategy will be printed."
},
{
"code": null,
"e": 5689,
"s": 5377,
"text": "i = 0stay = []switch = []while i < 100000: stay.append(monty_hall(np.random.randint(1, 4))) switch.append(monty_hall(np.random.randint(1, 4), switch = True)) i += 1 print(f\"Stay win rate: {round(100 * np.sum(stay) / 100000, 1)}%\")print(f\"Switch win rate: {round(100 * np.sum(switch) / 100000, 1)}%\")"
},
{
"code": null,
"e": 5710,
"s": 5689,
"text": "Stay win rate: 33.3%"
},
{
"code": null,
"e": 5733,
"s": 5710,
"text": "Switch win rate: 66.6%"
},
{
"code": null,
"e": 5931,
"s": 5733,
"text": "Clearly there is a very large difference between the two strategies. Although a statistical test isnβt really needed to detect a difference here, letβs apply a two-tailed z-test to our data anyway."
},
{
"code": null,
"e": 6114,
"s": 5931,
"text": "from statsmodels.stats.weightstats import ztesttest_statistic, p_value = ztest(stay, switch)print(f\"Test Statistic: {round(test_statistic, 1)}\")print(f\"P-Value: {round(p_value, 5)}\")"
},
{
"code": null,
"e": 6137,
"s": 6114,
"text": "Test Statistic: -157.5"
},
{
"code": null,
"e": 6150,
"s": 6137,
"text": "P-Value: 0.0"
},
{
"code": null,
"e": 6498,
"s": 6150,
"text": "The z-test has returned a test statistic of -157.5 and a p-value of 0 (really an infinitesimally small number that our computer has rounded to 0). Therefore the null hypothesis, that the win rate of stay and switch strategies are the same, can be rejected with complete certainty. Switching has been revealed to be the obviously superior strategy!"
},
{
"code": null,
"e": 6614,
"s": 6498,
"text": "But why is switching so much better? To bet a better sense letβs look at the problem from a Bayesian point of view."
},
{
"code": null,
"e": 6984,
"s": 6614,
"text": "Bayesian statistics, as compared to frequentist statistics, offers an alternative perspective on cause and effect. Frequentist statistics seek to answer the question, βgiven my hypothesis, how probable is my data?β On the other hand, Bayesian statistics seek to answer the question, βgiven my data, how probable is my hypothesis?β The difference is subtle yet powerful."
},
{
"code": null,
"e": 7132,
"s": 6984,
"text": "The cornerstone of Bayesian statistics is Bayesβ Rule, a simple identity that informs how to properly update belief in a hypothesis given new data."
},
{
"code": null,
"e": 7160,
"s": 7132,
"text": "P(H|D) = P(D|H)*P(H) / P(D)"
},
{
"code": null,
"e": 7202,
"s": 7160,
"text": "H = The hypothesis, D = New observed data"
},
{
"code": null,
"e": 7609,
"s": 7202,
"text": "P(H|D) is the probability of our hypothesis given the new observed data. P(D|H) is the probability of observing the data given that the hypothesis is correct. P(H) is our assessment of the probability of the hypothesis being correct before observing the new data, also known as a βBayesian priorβ. P(D) is the probability of observing the data under any circumstances whether or not the hypothesis is true."
},
{
"code": null,
"e": 7923,
"s": 7609,
"text": "For the Monty Hall problem there are two possible hypotheses: H1) the car is behind the initially chosen door, and H2) the car is not behind the initially chosen door and switching will result in a win. For now letβs consider H1 and see how Bayeβs rule can be used to determine the probability of this hypothesis."
},
{
"code": null,
"e": 8160,
"s": 7923,
"text": "First, consider the prior probability of the hypothesis P(H1). Remember that the initial choice is made from 3 options that are all equally likely to be correct. P(H1), the probability of making an initial correct choice, is simply 1/3."
},
{
"code": null,
"e": 8453,
"s": 8160,
"text": "Next, consider the probability of observing the new data given that H1 is correct. If the car is in fact behind the originally chosen door, then the probability of a goat being revealed at either of the other doors is 1/2, as Monty will choose randomly between his two options. P(D|H1) = 1/2."
},
{
"code": null,
"e": 9028,
"s": 8453,
"text": "Finally, consider the probability of observing the new data under any circumstances. Because there are only two mutually exclusive hypotheses possible, P(D) can be determined using the following equation, P(D) = P(D|H1)P(H1) + P(D|H2)P(H2). We already know that P(D|H1) = 1/2 and P(H1) = 1/3. P(H2) = 2/3 and is simply the probability of making an initially incorrect choice. Lastly, P(D|H2) = 1/2, since if our initial door conceals a goat the remaining two doors both have equal probabilities of concealing the second goat. In summation P(D) = 1/2 * 1/3 + 1/2 * 2/3 = 1/2."
},
{
"code": null,
"e": 9119,
"s": 9028,
"text": "Altogether we have: P(H1) = 1/3, P(H2) = 2/3, P(D|H1) = 1/2, P(D|H2) = 1/2, and P(D) = 1/2"
},
{
"code": null,
"e": 9248,
"s": 9119,
"text": "These values can now be inserted into Bayesβ rule to determine the probability that the car is behind our initially chosen door."
},
{
"code": null,
"e": 9309,
"s": 9248,
"text": "P(H1|D) = P(D|H1) * P(H1) / P(D) = (1/2 * 1/3) / (1/2) = 1/3"
},
{
"code": null,
"e": 9428,
"s": 9309,
"text": "It would appear that the new information has not increased the probability of the initial choice being correct at all!"
},
{
"code": null,
"e": 9596,
"s": 9428,
"text": "While weβre at it, letβs also use Bayesβ rule to determine the probability of H2, that the car is not behind our initial choice and that a switch will result in a win."
},
{
"code": null,
"e": 9655,
"s": 9596,
"text": "P(H2|D) = P(D|H2)*P(H2) / P(D) = (1/2 * 2/3) / (1/2) = 2/3"
},
{
"code": null,
"e": 10009,
"s": 9655,
"text": "Weβve now used Bayesian reasoning to confirm the results of our Frequentist experiment. Further, the Bayesian probabilities determined for H1 and H2 correspond exactly to the win rates observed! By now itβs becoming clearer as to why switching is so much better than staying, but letβs look at the problem in one last way to really drive the point home."
},
{
"code": null,
"e": 10208,
"s": 10009,
"text": "The Monty Hall problem is certainly deceptive, but itβs not especially complex. By thinking through all the possible outcomes one can conclude that switching is the superior strategy rather quickly."
},
{
"code": null,
"e": 10759,
"s": 10208,
"text": "Consider the circumstances under which the switching strategy will either win or lose. Switching will lose when the initial door conceals the car. When the initial door conceals a goat, Monty will be forced to reveal the second goat, the remaining door will conceal the car, and switching will always win. As the initial choice will only conceal the car in 1 of 3 games, the switching strategy will lose approximately 1 in 3 games and win the other 2. Conversely, staying will only win the 1 in 3 games where the initial choice happens to be correct."
},
{
"code": null,
"e": 10881,
"s": 10759,
"text": "Monty shoots an impatient look, βAny day now buddy. Iβm beginning to think I should give that new Corvette to the goats!β"
},
{
"code": null,
"e": 10960,
"s": 10881,
"text": "βBAAAAAβ the black and white billy goat seems to agree with Montyβs sentiment."
},
{
"code": null,
"e": 11029,
"s": 10960,
"text": "βIβll ask one last time, would you like to switch to door number 2?β"
},
{
"code": null,
"e": 11350,
"s": 11029,
"text": "In a rush of epiphany you recall an article you read on this exact topic. Though you canβt be certain, you understand the odds associated with your choices. Resisting the temptation to stick to your guns, and accepting the possible embarrassment of self inflicted misfortune, you calmly announce βIβll switch to door 2.β"
}
] |
JPA - Entity Managers
|
This chapter takes you through simple example with JPA. Let us consider employee management as example. It means the employee management is creating, updating, finding, and deleting an employee. As mentioned above we are using MySQL database for database operations.
The main modules for this example are as follows:
Model or POJO
Employee.java
Model or POJO
Employee.java
Persistence
Persistence.xml
Persistence
Persistence.xml
Service
CreatingEmployee.java
UpdatingEmployee.java
FindingEmployee.java
DeletingEmployee.java
Service
CreatingEmployee.java
UpdatingEmployee.java
FindingEmployee.java
DeletingEmployee.java
Let us take the package hierarchy which we have used in the JPA installation with Eclipselink. Follow the hierarchy for this example as below:
Entities are nothing but beans or Models, in this example we will use Employee as entity. eid, ename, salary, and deg are the attributes of this entity. It contains default constructor, setter and getter methods of those attributes.
In the above shown hierarchy, create a package named βcom.tutorialspoint.eclipselink.entityβ, under βsrcβ (Source) package. Create a class named Employee.java under given package as follows:
package com.tutorialspoint.eclipselink.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int eid;
private String ename;
private double salary;
private String deg;
public Employee(int eid, String ename, double salary, String deg) {
super( );
this.eid = eid;
this.ename = ename;
this.salary = salary;
this.deg = deg;
}
public Employee( ) {
super();
}
public int getEid( ) {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public String getEname( ) {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public double getSalary( ) {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getDeg( ) {
return deg;
}
public void setDeg(String deg) {
this.deg = deg;
}
@Override
public String toString() {
return "Employee [eid=" + eid + ", ename=" + ename + ", salary=" + salary + ", deg=" + deg + "]";
}
}
In the above code, we have used @Entity annotation to make this POJO class as entity.
Before going to next module we need to create database for relational entity, which will register the database in persistence.xml file. Open MySQL workbench and type query as follows:
create database jpadb
use jpadb
This module plays a crucial role in the concept of JPA. In this xml file we will register the database and specify the entity class.
In the above shown package hierarchy, persistence.xml under JPA Content package is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="Eclipselink_JPA" transaction-type="RESOURCE_LOCAL">
<class>com.tutorialspoint.eclipselink.entity.Employee</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpadb"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="eclipselink.logging.level" value="FINE"/>
<property name="eclipselink.ddl-generation" value="create-tables"/>
</properties>
</persistence-unit>
</persistence>
In the above xml, <persistence-unit> tag is defined with specific name for JPA persistence. The <class> tag defines entity class with package name. The <properties> tag defines all the properties, and <property> tag defines each property such as database registration, URL specification, username, and password. These are the Eclipselink properties. This file will configure the database.
Persistence operations are used against database and they are load and store operations. In a business component all the persistence operations fall under service classes.
In the above shown package hierarchy, create a package named βcom.tutorialspoint.eclipselink.serviceβ, under βsrcβ (source) package. All the service classes named as CreateEmloyee.java, UpdateEmployee.java, FindEmployee.java, and DeleteEmployee.java. comes under the given package as follows:
Creating an Employee class named as CreateEmployee.java as follows:
package com.tutorialspoint.eclipselink.service;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import com.tutorialspoint.eclipselink.entity.Employee;
public class CreateEmployee {
public static void main( String[ ] args ) {
EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
EntityManager entitymanager = emfactory.createEntityManager( );
entitymanager.getTransaction( ).begin( );
Employee employee = new Employee( );
employee.setEid( 1201 );
employee.setEname( "Gopal" );
employee.setSalary( 40000 );
employee.setDeg( "Technical Manager" );
entitymanager.persist( employee );
entitymanager.getTransaction( ).commit( );
entitymanager.close( );
emfactory.close( );
}
}
In the above code the createEntityManagerFactory () creates a persistence unit by providing the same unique name which we provide for persistence-unit in persistent.xml file. The entitymanagerfactory object will create the entitymanger instance by using createEntityManager () method. The entitymanager object creates entitytransaction instance for transaction management. By using entitymanager object, we can persist entities into database.
After compilation and execution of the above program you will get notifications from eclipselink library on the console panel of eclipse IDE.
For result, open the MySQL workbench and type the following queries.
use jpadb
select * from employee
The effected database table named employee will be shown in a tabular format as follows:
To Update an employee, we need to get record form database, make changes, and finally committ it. The class named UpdateEmployee.java is shown as follows:
package com.tutorialspoint.eclipselink.service;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import com.tutorialspoint.eclipselink.entity.Employee;
public class UpdateEmployee {
public static void main( String[ ] args ) {
EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
EntityManager entitymanager = emfactory.createEntityManager( );
entitymanager.getTransaction( ).begin( );
Employee employee = entitymanager.find( Employee.class, 1201 );
//before update
System.out.println( employee );
employee.setSalary( 46000 );
entitymanager.getTransaction( ).commit( );
//after update
System.out.println( employee );
entitymanager.close();
emfactory.close();
}
}
After compilation and execution of the above program you will get notifications from Eclipselink library on the console panel of eclipse IDE.
For result, open the MySQL workbench and type the following queries.
use jpadb
select * from employee
The effected database table named employee will be shown in a tabular format as follows:
The salary of employee, 1201 is updated to 46000.
To Find an employee we will get record from database and display it. In this operation, EntityTransaction is not involved any transaction is not applied while retrieving a record.
The class named FindEmployee.java as follows.
package com.tutorialspoint.eclipselink.service;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import com.tutorialspoint.eclipselink.entity.Employee;
public class FindEmployee {
public static void main( String[ ] args ) {
EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
EntityManager entitymanager = emfactory.createEntityManager();
Employee employee = entitymanager.find( Employee.class, 1201 );
System.out.println("employee ID = " + employee.getEid( ));
System.out.println("employee NAME = " + employee.getEname( ));
System.out.println("employee SALARY = " + employee.getSalary( ));
System.out.println("employee DESIGNATION = " + employee.getDeg( ));
}
}
After compilation and execution of the above program you will get output from Eclipselink library on the console panel of eclipse IDE as follows:
employee ID = 1201
employee NAME = Gopal
employee SALARY = 46000.0
employee DESIGNATION = Technical Manager
To Delete an Employee, first we will find the record and then delete it. Here EntityTransaction plays an important role.
The class named DeleteEmployee.java as follows:
package com.tutorialspoint.eclipselink.service;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import com.tutorialspoint.eclipselink.entity.Employee;
public class DeleteEmployee {
public static void main( String[ ] args ) {
EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
EntityManager entitymanager = emfactory.createEntityManager( );
entitymanager.getTransaction( ).begin( );
Employee employee = entitymanager.find( Employee.class, 1201 );
entitymanager.remove( employee );
entitymanager.getTransaction( ).commit( );
entitymanager.close( );
emfactory.close( );
}
}
After compilation and execution of the above program you will get notifications from Eclipselink library on the console panel of eclipse IDE.
For result, open the MySQL workbench and type the following queries.
use jpadb
select * from employee
The effected database named employee will have null records.
After completion of all the modules in this example, the package and file hierarchy is shown as follows:
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2006,
"s": 1739,
"text": "This chapter takes you through simple example with JPA. Let us consider employee management as example. It means the employee management is creating, updating, finding, and deleting an employee. As mentioned above we are using MySQL database for database operations."
},
{
"code": null,
"e": 2056,
"s": 2006,
"text": "The main modules for this example are as follows:"
},
{
"code": null,
"e": 2084,
"s": 2056,
"text": "Model or POJO\nEmployee.java"
},
{
"code": null,
"e": 2098,
"s": 2084,
"text": "Model or POJO"
},
{
"code": null,
"e": 2112,
"s": 2098,
"text": "Employee.java"
},
{
"code": null,
"e": 2140,
"s": 2112,
"text": "Persistence\nPersistence.xml"
},
{
"code": null,
"e": 2152,
"s": 2140,
"text": "Persistence"
},
{
"code": null,
"e": 2168,
"s": 2152,
"text": "Persistence.xml"
},
{
"code": null,
"e": 2264,
"s": 2168,
"text": "Service\nCreatingEmployee.java\nUpdatingEmployee.java\nFindingEmployee.java\nDeletingEmployee.java\n"
},
{
"code": null,
"e": 2272,
"s": 2264,
"text": "Service"
},
{
"code": null,
"e": 2294,
"s": 2272,
"text": "CreatingEmployee.java"
},
{
"code": null,
"e": 2316,
"s": 2294,
"text": "UpdatingEmployee.java"
},
{
"code": null,
"e": 2337,
"s": 2316,
"text": "FindingEmployee.java"
},
{
"code": null,
"e": 2359,
"s": 2337,
"text": "DeletingEmployee.java"
},
{
"code": null,
"e": 2502,
"s": 2359,
"text": "Let us take the package hierarchy which we have used in the JPA installation with Eclipselink. Follow the hierarchy for this example as below:"
},
{
"code": null,
"e": 2735,
"s": 2502,
"text": "Entities are nothing but beans or Models, in this example we will use Employee as entity. eid, ename, salary, and deg are the attributes of this entity. It contains default constructor, setter and getter methods of those attributes."
},
{
"code": null,
"e": 2926,
"s": 2735,
"text": "In the above shown hierarchy, create a package named βcom.tutorialspoint.eclipselink.entityβ, under βsrcβ (Source) package. Create a class named Employee.java under given package as follows:"
},
{
"code": null,
"e": 4253,
"s": 2926,
"text": "package com.tutorialspoint.eclipselink.entity;\n\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table\npublic class Employee {\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO) \t\n \n private int eid;\n private String ename;\n private double salary;\n private String deg;\n \n public Employee(int eid, String ename, double salary, String deg) {\n super( );\n this.eid = eid;\n this.ename = ename;\n this.salary = salary;\n this.deg = deg;\n }\n\n public Employee( ) {\n super();\n }\n\n public int getEid( ) {\n return eid;\n }\n \n public void setEid(int eid) {\n this.eid = eid;\n }\n \n public String getEname( ) {\n return ename;\n }\n \n public void setEname(String ename) {\n this.ename = ename;\n }\n\n public double getSalary( ) {\n return salary;\n }\n \n public void setSalary(double salary) {\n this.salary = salary;\n }\n\n public String getDeg( ) {\n return deg;\n }\n \n public void setDeg(String deg) {\n this.deg = deg;\n }\n \n @Override\n public String toString() {\n return \"Employee [eid=\" + eid + \", ename=\" + ename + \", salary=\" + salary + \", deg=\" + deg + \"]\";\n }\n}"
},
{
"code": null,
"e": 4339,
"s": 4253,
"text": "In the above code, we have used @Entity annotation to make this POJO class as entity."
},
{
"code": null,
"e": 4523,
"s": 4339,
"text": "Before going to next module we need to create database for relational entity, which will register the database in persistence.xml file. Open MySQL workbench and type query as follows:"
},
{
"code": null,
"e": 4556,
"s": 4523,
"text": "create database jpadb\nuse jpadb\n"
},
{
"code": null,
"e": 4689,
"s": 4556,
"text": "This module plays a crucial role in the concept of JPA. In this xml file we will register the database and specify the entity class."
},
{
"code": null,
"e": 4784,
"s": 4689,
"text": "In the above shown package hierarchy, persistence.xml under JPA Content package is as follows:"
},
{
"code": null,
"e": 5794,
"s": 4784,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<persistence version=\"2.0\" xmlns=\"http://java.sun.com/xml/ns/persistence\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence \n http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\">\n \n <persistence-unit name=\"Eclipselink_JPA\" transaction-type=\"RESOURCE_LOCAL\">\n \n <class>com.tutorialspoint.eclipselink.entity.Employee</class>\n\n <properties>\n <property name=\"javax.persistence.jdbc.url\" value=\"jdbc:mysql://localhost:3306/jpadb\"/>\n <property name=\"javax.persistence.jdbc.user\" value=\"root\"/>\n <property name=\"javax.persistence.jdbc.password\" value=\"root\"/>\n <property name=\"javax.persistence.jdbc.driver\" value=\"com.mysql.jdbc.Driver\"/>\n <property name=\"eclipselink.logging.level\" value=\"FINE\"/>\n <property name=\"eclipselink.ddl-generation\" value=\"create-tables\"/>\n </properties>\n \n </persistence-unit>\n</persistence>"
},
{
"code": null,
"e": 6183,
"s": 5794,
"text": "In the above xml, <persistence-unit> tag is defined with specific name for JPA persistence. The <class> tag defines entity class with package name. The <properties> tag defines all the properties, and <property> tag defines each property such as database registration, URL specification, username, and password. These are the Eclipselink properties. This file will configure the database."
},
{
"code": null,
"e": 6355,
"s": 6183,
"text": "Persistence operations are used against database and they are load and store operations. In a business component all the persistence operations fall under service classes."
},
{
"code": null,
"e": 6649,
"s": 6355,
"text": "In the above shown package hierarchy, create a package named βcom.tutorialspoint.eclipselink.serviceβ, under βsrcβ (source) package. All the service classes named as CreateEmloyee.java, UpdateEmployee.java, FindEmployee.java, and DeleteEmployee.java. comes under the given package as follows:"
},
{
"code": null,
"e": 6717,
"s": 6649,
"text": "Creating an Employee class named as CreateEmployee.java as follows:"
},
{
"code": null,
"e": 7608,
"s": 6717,
"text": "package com.tutorialspoint.eclipselink.service;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport com.tutorialspoint.eclipselink.entity.Employee;\n\npublic class CreateEmployee {\n\n public static void main( String[ ] args ) {\n \n EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( \"Eclipselink_JPA\" );\n \n EntityManager entitymanager = emfactory.createEntityManager( );\n entitymanager.getTransaction( ).begin( );\n\n Employee employee = new Employee( ); \n employee.setEid( 1201 );\n employee.setEname( \"Gopal\" );\n employee.setSalary( 40000 );\n employee.setDeg( \"Technical Manager\" );\n \n entitymanager.persist( employee );\n entitymanager.getTransaction( ).commit( );\n\n entitymanager.close( );\n emfactory.close( );\n }\n}"
},
{
"code": null,
"e": 8052,
"s": 7608,
"text": "In the above code the createEntityManagerFactory () creates a persistence unit by providing the same unique name which we provide for persistence-unit in persistent.xml file. The entitymanagerfactory object will create the entitymanger instance by using createEntityManager () method. The entitymanager object creates entitytransaction instance for transaction management. By using entitymanager object, we can persist entities into database."
},
{
"code": null,
"e": 8194,
"s": 8052,
"text": "After compilation and execution of the above program you will get notifications from eclipselink library on the console panel of eclipse IDE."
},
{
"code": null,
"e": 8263,
"s": 8194,
"text": "For result, open the MySQL workbench and type the following queries."
},
{
"code": null,
"e": 8297,
"s": 8263,
"text": "use jpadb\nselect * from employee\n"
},
{
"code": null,
"e": 8386,
"s": 8297,
"text": "The effected database table named employee will be shown in a tabular format as follows:"
},
{
"code": null,
"e": 8541,
"s": 8386,
"text": "To Update an employee, we need to get record form database, make changes, and finally committ it. The class named UpdateEmployee.java is shown as follows:"
},
{
"code": null,
"e": 9421,
"s": 8541,
"text": "package com.tutorialspoint.eclipselink.service;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport com.tutorialspoint.eclipselink.entity.Employee;\n\npublic class UpdateEmployee {\n public static void main( String[ ] args ) {\n EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( \"Eclipselink_JPA\" );\n \n EntityManager entitymanager = emfactory.createEntityManager( );\n entitymanager.getTransaction( ).begin( );\n Employee employee = entitymanager.find( Employee.class, 1201 );\n \n //before update\n System.out.println( employee );\n employee.setSalary( 46000 );\n entitymanager.getTransaction( ).commit( );\n \n //after update\n System.out.println( employee );\n entitymanager.close();\n emfactory.close();\n }\n}"
},
{
"code": null,
"e": 9563,
"s": 9421,
"text": "After compilation and execution of the above program you will get notifications from Eclipselink library on the console panel of eclipse IDE."
},
{
"code": null,
"e": 9632,
"s": 9563,
"text": "For result, open the MySQL workbench and type the following queries."
},
{
"code": null,
"e": 9666,
"s": 9632,
"text": "use jpadb\nselect * from employee\n"
},
{
"code": null,
"e": 9755,
"s": 9666,
"text": "The effected database table named employee will be shown in a tabular format as follows:"
},
{
"code": null,
"e": 9805,
"s": 9755,
"text": "The salary of employee, 1201 is updated to 46000."
},
{
"code": null,
"e": 9986,
"s": 9805,
"text": "To Find an employee we will get record from database and display it. In this operation, EntityTransaction is not involved any transaction is not applied while retrieving a record."
},
{
"code": null,
"e": 10032,
"s": 9986,
"text": "The class named FindEmployee.java as follows."
},
{
"code": null,
"e": 10868,
"s": 10032,
"text": "package com.tutorialspoint.eclipselink.service;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport com.tutorialspoint.eclipselink.entity.Employee;\n\npublic class FindEmployee {\n public static void main( String[ ] args ) {\n \n EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( \"Eclipselink_JPA\" );\n EntityManager entitymanager = emfactory.createEntityManager();\n Employee employee = entitymanager.find( Employee.class, 1201 );\n\n System.out.println(\"employee ID = \" + employee.getEid( ));\n System.out.println(\"employee NAME = \" + employee.getEname( ));\n System.out.println(\"employee SALARY = \" + employee.getSalary( ));\n System.out.println(\"employee DESIGNATION = \" + employee.getDeg( ));\n }\n}"
},
{
"code": null,
"e": 11014,
"s": 10868,
"text": "After compilation and execution of the above program you will get output from Eclipselink library on the console panel of eclipse IDE as follows:"
},
{
"code": null,
"e": 11123,
"s": 11014,
"text": "employee ID = 1201\nemployee NAME = Gopal\nemployee SALARY = 46000.0\nemployee DESIGNATION = Technical Manager\n"
},
{
"code": null,
"e": 11244,
"s": 11123,
"text": "To Delete an Employee, first we will find the record and then delete it. Here EntityTransaction plays an important role."
},
{
"code": null,
"e": 11292,
"s": 11244,
"text": "The class named DeleteEmployee.java as follows:"
},
{
"code": null,
"e": 12050,
"s": 11292,
"text": "package com.tutorialspoint.eclipselink.service;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport com.tutorialspoint.eclipselink.entity.Employee;\n\npublic class DeleteEmployee {\n public static void main( String[ ] args ) {\n \n EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( \"Eclipselink_JPA\" );\n EntityManager entitymanager = emfactory.createEntityManager( );\n entitymanager.getTransaction( ).begin( );\n \n Employee employee = entitymanager.find( Employee.class, 1201 );\n entitymanager.remove( employee );\n entitymanager.getTransaction( ).commit( );\n entitymanager.close( );\n emfactory.close( );\n }\n}"
},
{
"code": null,
"e": 12192,
"s": 12050,
"text": "After compilation and execution of the above program you will get notifications from Eclipselink library on the console panel of eclipse IDE."
},
{
"code": null,
"e": 12261,
"s": 12192,
"text": "For result, open the MySQL workbench and type the following queries."
},
{
"code": null,
"e": 12295,
"s": 12261,
"text": "use jpadb\nselect * from employee\n"
},
{
"code": null,
"e": 12356,
"s": 12295,
"text": "The effected database named employee will have null records."
},
{
"code": null,
"e": 12461,
"s": 12356,
"text": "After completion of all the modules in this example, the package and file hierarchy is shown as follows:"
},
{
"code": null,
"e": 12468,
"s": 12461,
"text": " Print"
},
{
"code": null,
"e": 12479,
"s": 12468,
"text": " Add Notes"
}
] |
Euler Circuit in a Directed Graph - GeeksforGeeks
|
28 Jul, 2021
Eulerian Path is a path in graph that visits every edge exactly once. Eulerian Circuit is an Eulerian Path which starts and ends on the same vertex.
A graph is said to be eulerian if it has a eulerian cycle. We have discussed eulerian circuit for an undirected graph. In this post, the same is discussed for a directed graph.
For example, the following graph has eulerian cycle as {1, 0, 3, 4, 0, 2, 1}
How to check if a directed graph is eulerian? A directed graph has an eulerian cycle if following conditions are true (Source: Wiki) 1) All vertices with nonzero degree belong to a single strongly connected component. 2) In degree is equal to the out degree for every vertex.
We can detect singly connected component using Kosarajuβs DFS based simple algorithm.
To compare in degree and out-degree, we need to store in degree and out-degree of every vertex. Out degree can be obtained by the size of an adjacency list. In degree can be stored by creating an array of size equal to the number of vertices.
Following implementations of above approach.
C++
Java
Python3
C#
Javascript
// A C++ program to check if a given directed graph is Eulerian or not#include<iostream>#include <list>#define CHARS 26using namespace std; // A class that represents an undirected graphclass Graph{ int V; // No. of vertices list<int> *adj; // A dynamic array of adjacency lists int *in;public: // Constructor and destructor Graph(int V); ~Graph() { delete [] adj; delete [] in; } // function to add an edge to graph void addEdge(int v, int w) { adj[v].push_back(w); (in[w])++; } // Method to check if this graph is Eulerian or not bool isEulerianCycle(); // Method to check if all non-zero degree vertices are connected bool isSC(); // Function to do DFS starting from v. Used in isConnected(); void DFSUtil(int v, bool visited[]); Graph getTranspose();}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V]; in = new int[V]; for (int i = 0; i < V; i++) in[i] = 0;} /* This function returns true if the directed graph has a eulerian cycle, otherwise returns false */bool Graph::isEulerianCycle(){ // Check if all non-zero degree vertices are connected if (isSC() == false) return false; // Check if in degree and out degree of every vertex is same for (int i = 0; i < V; i++) if (adj[i].size() != in[i]) return false; return true;} // A recursive function to do DFS starting from vvoid Graph::DFSUtil(int v, bool visited[]){ // Mark the current node as visited and print it visited[v] = true; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i, visited);} // Function that returns reverse (or transpose) of this graph// This function is needed in isSC()Graph Graph::getTranspose(){ Graph g(V); for (int v = 0; v < V; v++) { // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for(i = adj[v].begin(); i != adj[v].end(); ++i) { g.adj[*i].push_back(v); (g.in[v])++; } } return g;} // This function returns true if all non-zero degree vertices of// graph are strongly connected (Please refer// https://www.geeksforgeeks.org/connectivity-in-a-directed-graph/ )bool Graph::isSC(){ // Mark all the vertices as not visited (For first DFS) bool visited[V]; for (int i = 0; i < V; i++) visited[i] = false; // Find the first vertex with non-zero degree int n; for (n = 0; n < V; n++) if (adj[n].size() > 0) break; // Do DFS traversal starting from first non zero degrees vertex. DFSUtil(n, visited); // If DFS traversal doesn't visit all vertices, then return false. for (int i = 0; i < V; i++) if (adj[i].size() > 0 && visited[i] == false) return false; // Create a reversed graph Graph gr = getTranspose(); // Mark all the vertices as not visited (For second DFS) for (int i = 0; i < V; i++) visited[i] = false; // Do DFS for reversed graph starting from first vertex. // Starting Vertex must be same starting point of first DFS gr.DFSUtil(n, visited); // If all vertices are not visited in second DFS, then // return false for (int i = 0; i < V; i++) if (adj[i].size() > 0 && visited[i] == false) return false; return true;} // Driver program to test above functionsint main(){ // Create a graph given in the above diagram Graph g(5); g.addEdge(1, 0); g.addEdge(0, 2); g.addEdge(2, 1); g.addEdge(0, 3); g.addEdge(3, 4); g.addEdge(4, 0); if (g.isEulerianCycle()) cout << "Given directed graph is eulerian n"; else cout << "Given directed graph is NOT eulerian n"; return 0;}
// A Java program to check if a given directed graph is Eulerian or not // A class that represents an undirected graphimport java.io.*;import java.util.*;import java.util.LinkedList; // This class represents a directed graph using adjacency listclass Graph{ private int V; // No. of vertices private LinkedList<Integer> adj[];//Adjacency List private int in[]; //maintaining in degree //Constructor Graph(int v) { V = v; adj = new LinkedList[v]; in = new int[V]; for (int i=0; i<v; ++i) { adj[i] = new LinkedList(); in[i] = 0; } } //Function to add an edge into the graph void addEdge(int v,int w) { adj[v].add(w); in[w]++; } // A recursive function to print DFS starting from v void DFSUtil(int v,Boolean visited[]) { // Mark the current node as visited visited[v] = true; int n; // Recur for all the vertices adjacent to this vertex Iterator<Integer> i =adj[v].iterator(); while (i.hasNext()) { n = i.next(); if (!visited[n]) DFSUtil(n,visited); } } // Function that returns reverse (or transpose) of this graph Graph getTranspose() { Graph g = new Graph(V); for (int v = 0; v < V; v++) { // Recur for all the vertices adjacent to this vertex Iterator<Integer> i = adj[v].listIterator(); while (i.hasNext()) { g.adj[i.next()].add(v); (g.in[v])++; } } return g; } // The main function that returns true if graph is strongly // connected Boolean isSC() { // Step 1: Mark all the vertices as not visited (For // first DFS) Boolean visited[] = new Boolean[V]; for (int i = 0; i < V; i++) visited[i] = false; // Step 2: Do DFS traversal starting from the first vertex. DFSUtil(0, visited); // If DFS traversal doesn't visit all vertices, then return false. for (int i = 0; i < V; i++) if (visited[i] == false) return false; // Step 3: Create a reversed graph Graph gr = getTranspose(); // Step 4: Mark all the vertices as not visited (For second DFS) for (int i = 0; i < V; i++) visited[i] = false; // Step 5: Do DFS for reversed graph starting from first vertex. // Starting Vertex must be same starting point of first DFS gr.DFSUtil(0, visited); // If all vertices are not visited in second DFS, then // return false for (int i = 0; i < V; i++) if (visited[i] == false) return false; return true; } /* This function returns true if the directed graph has a eulerian cycle, otherwise returns false */ Boolean isEulerianCycle() { // Check if all non-zero degree vertices are connected if (isSC() == false) return false; // Check if in degree and out degree of every vertex is same for (int i = 0; i < V; i++) if (adj[i].size() != in[i]) return false; return true; } public static void main (String[] args) throws java.lang.Exception { Graph g = new Graph(5); g.addEdge(1, 0); g.addEdge(0, 2); g.addEdge(2, 1); g.addEdge(0, 3); g.addEdge(3, 4); g.addEdge(4, 0); if (g.isEulerianCycle()) System.out.println("Given directed graph is eulerian "); else System.out.println("Given directed graph is NOT eulerian "); }}//This code is contributed by Aakash Hasija
# A Python3 program to check if a given# directed graph is Eulerian or not from collections import defaultdict class Graph(): def __init__(self, vertices): self.V = vertices self.graph = defaultdict(list) self.IN = [0] * vertices def addEdge(self, v, u): self.graph[v].append(u) self.IN[u] += 1 def DFSUtil(self, v, visited): visited[v] = True for node in self.graph[v]: if visited[node] == False: self.DFSUtil(node, visited) def getTranspose(self): gr = Graph(self.V) for node in range(self.V): for child in self.graph[node]: gr.addEdge(child, node) return gr def isSC(self): visited = [False] * self.V v = 0 for v in range(self.V): if len(self.graph[v]) > 0: break self.DFSUtil(v, visited) # If DFS traversal doesn't visit all # vertices, then return false. for i in range(self.V): if visited[i] == False: return False gr = self.getTranspose() visited = [False] * self.V gr.DFSUtil(v, visited) for i in range(self.V): if visited[i] == False: return False return True def isEulerianCycle(self): # Check if all non-zero degree vertices # are connected if self.isSC() == False: return False # Check if in degree and out degree of # every vertex is same for v in range(self.V): if len(self.graph[v]) != self.IN[v]: return False return True g = Graph(5);g.addEdge(1, 0);g.addEdge(0, 2);g.addEdge(2, 1);g.addEdge(0, 3);g.addEdge(3, 4);g.addEdge(4, 0);if g.isEulerianCycle(): print( "Given directed graph is eulerian");else: print( "Given directed graph is NOT eulerian"); # This code is contributed by Divyanshu Mehta
// A C# program to check if a given// directed graph is Eulerian or not // A class that represents an// undirected graphusing System;using System.Collections.Generic; // This class represents a directed// graph using adjacency listclass Graph{ // No. of verticespublic int V; // Adjacency Listpublic List<int> []adj; // Maintaining in degreepublic int []init; // ConstructorGraph(int v){ V = v; adj = new List<int>[v]; init = new int[V]; for(int i = 0; i < v; ++i) { adj[i] = new List<int>(); init[i] = 0; }} // Function to add an edge into the graphvoid addEdge(int v, int w){ adj[v].Add(w); init[w]++;} // A recursive function to print DFS// starting from vvoid DFSUtil(int v, Boolean []visited){ // Mark the current node as visited visited[v] = true; // Recur for all the vertices // adjacent to this vertex foreach(int i in adj[v]) { if (!visited[i]) DFSUtil(i, visited); }} // Function that returns reverse// (or transpose) of this graphGraph getTranspose(){ Graph g = new Graph(V); for(int v = 0; v < V; v++) { // Recur for all the vertices // adjacent to this vertex foreach(int i in adj[v]) { g.adj[i].Add(v); (g.init[v])++; } } return g;} // The main function that returns// true if graph is strongly connectedBoolean isSC(){ // Step 1: Mark all the vertices // as not visited (For first DFS) Boolean []visited = new Boolean[V]; for(int i = 0; i < V; i++) visited[i] = false; // Step 2: Do DFS traversal starting // from the first vertex. DFSUtil(0, visited); // If DFS traversal doesn't visit // all vertices, then return false. for(int i = 0; i < V; i++) if (visited[i] == false) return false; // Step 3: Create a reversed graph Graph gr = getTranspose(); // Step 4: Mark all the vertices as // not visited (For second DFS) for(int i = 0; i < V; i++) visited[i] = false; // Step 5: Do DFS for reversed graph // starting from first vertex. // Staring Vertex must be same // starting point of first DFS gr.DFSUtil(0, visited); // If all vertices are not visited // in second DFS, then return false for(int i = 0; i < V; i++) if (visited[i] == false) return false; return true;} // This function returns true if the// directed graph has a eulerian// cycle, otherwise returns false Boolean isEulerianCycle(){ // Check if all non-zero degree // vertices are connected if (isSC() == false) return false; // Check if in degree and out // degree of every vertex is same for(int i = 0; i < V; i++) if (adj[i].Count != init[i]) return false; return true;} // Driver codepublic static void Main(String[] args){ Graph g = new Graph(5); g.addEdge(1, 0); g.addEdge(0, 2); g.addEdge(2, 1); g.addEdge(0, 3); g.addEdge(3, 4); g.addEdge(4, 0); if (g.isEulerianCycle()) Console.WriteLine("Given directed " + "graph is eulerian "); else Console.WriteLine("Given directed " + "graph is NOT eulerian ");}} // This code is contributed by Princi Singh
<script>// A Javascript program to check if a given directed graph is Eulerian or not // This class represents a directed graph using adjacency// list representationclass Graph{ // Constructor constructor(v) { this.V = v; this.adj = new Array(v); this.in=new Array(v); for (let i=0; i<v; ++i) { this.adj[i] = []; this.in[i]=0; } } //Function to add an edge into the graph addEdge(v,w) { this.adj[v].push(w); this.in[w]++; } // A recursive function to print DFS starting from v DFSUtil(v,visited) { // Mark the current node as visited visited[v] = true; let n; // Recur for all the vertices adjacent to this vertex for(let i of this.adj[v]) { n = i; if (!visited[n]) this.DFSUtil(n,visited); } } // Function that returns reverse (or transpose) of this graph getTranspose() { let g = new Graph(this.V); for (let v = 0; v < this.V; v++) { // Recur for all the vertices adjacent to this vertex for(let i of this.adj[v]) { g.adj[i].push(v); (g.in[v])++; } } return g; } // The main function that returns true if graph is strongly // connected isSC() { // Step 1: Mark all the vertices as not visited (For // first DFS) let visited = new Array(this.V); for (let i = 0; i < this.V; i++) visited[i] = false; // Step 2: Do DFS traversal starting from the first vertex. this.DFSUtil(0, visited); // If DFS traversal doesn't visit all vertices, then return false. for (let i = 0; i < this.V; i++) if (visited[i] == false) return false; // Step 3: Create a reversed graph let gr = this.getTranspose(); // Step 4: Mark all the vertices as not visited (For second DFS) for (let i = 0; i < this.V; i++) visited[i] = false; // Step 5: Do DFS for reversed graph starting from first vertex. // Starting Vertex must be same starting point of first DFS gr.DFSUtil(0, visited); // If all vertices are not visited in second DFS, then // return false for (let i = 0; i < this.V; i++) if (visited[i] == false) return false; return true; } /* This function returns true if the directed graph has a eulerian cycle, otherwise returns false */ isEulerianCycle() { // Check if all non-zero degree vertices are connected if (this.isSC() == false) return false; // Check if in degree and out degree of every vertex is same for (let i = 0; i < this.V; i++) if (this.adj[i].length != this.in[i]) return false; return true; }} let g = new Graph(5);g.addEdge(1, 0);g.addEdge(0, 2);g.addEdge(2, 1);g.addEdge(0, 3);g.addEdge(3, 4);g.addEdge(4, 0); if (g.isEulerianCycle()) document.write("Given directed graph is eulerian ");else document.write("Given directed graph is NOT eulerian "); // This code is contributed by avanitrachhadiya2155</script>
Output:
Given directed graph is eulerian
Time complexity of the above implementation is O(V + E) as Kosarajuβs algorithm takes O(V + E) time. After running Kosarajuβs algorithm we traverse all vertices and compare in degree with out degree which takes O(V) time.
See following as an application of this. Find if the given array of strings can be chained to form a circle.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
UtkarshVerma12
princi singh
khushboogoyal499
avanitrachhadiya2155
DFS
Euler-Circuit
graph-connectivity
graph-cycle
Graph
DFS
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Topological Sorting
Detect Cycle in a Directed Graph
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Ford-Fulkerson Algorithm for Maximum Flow Problem
Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
Traveling Salesman Problem (TSP) Implementation
Detect cycle in an undirected graph
Hamiltonian Cycle | Backtracking-6
m Coloring Problem | Backtracking-5
Find the number of islands | Set 1 (Using DFS)
|
[
{
"code": null,
"e": 26471,
"s": 26443,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 26621,
"s": 26471,
"text": "Eulerian Path is a path in graph that visits every edge exactly once. Eulerian Circuit is an Eulerian Path which starts and ends on the same vertex. "
},
{
"code": null,
"e": 26798,
"s": 26621,
"text": "A graph is said to be eulerian if it has a eulerian cycle. We have discussed eulerian circuit for an undirected graph. In this post, the same is discussed for a directed graph."
},
{
"code": null,
"e": 26876,
"s": 26798,
"text": "For example, the following graph has eulerian cycle as {1, 0, 3, 4, 0, 2, 1} "
},
{
"code": null,
"e": 27152,
"s": 26876,
"text": "How to check if a directed graph is eulerian? A directed graph has an eulerian cycle if following conditions are true (Source: Wiki) 1) All vertices with nonzero degree belong to a single strongly connected component. 2) In degree is equal to the out degree for every vertex."
},
{
"code": null,
"e": 27239,
"s": 27152,
"text": "We can detect singly connected component using Kosarajuβs DFS based simple algorithm. "
},
{
"code": null,
"e": 27483,
"s": 27239,
"text": "To compare in degree and out-degree, we need to store in degree and out-degree of every vertex. Out degree can be obtained by the size of an adjacency list. In degree can be stored by creating an array of size equal to the number of vertices. "
},
{
"code": null,
"e": 27529,
"s": 27483,
"text": "Following implementations of above approach. "
},
{
"code": null,
"e": 27533,
"s": 27529,
"text": "C++"
},
{
"code": null,
"e": 27538,
"s": 27533,
"text": "Java"
},
{
"code": null,
"e": 27546,
"s": 27538,
"text": "Python3"
},
{
"code": null,
"e": 27549,
"s": 27546,
"text": "C#"
},
{
"code": null,
"e": 27560,
"s": 27549,
"text": "Javascript"
},
{
"code": "// A C++ program to check if a given directed graph is Eulerian or not#include<iostream>#include <list>#define CHARS 26using namespace std; // A class that represents an undirected graphclass Graph{ int V; // No. of vertices list<int> *adj; // A dynamic array of adjacency lists int *in;public: // Constructor and destructor Graph(int V); ~Graph() { delete [] adj; delete [] in; } // function to add an edge to graph void addEdge(int v, int w) { adj[v].push_back(w); (in[w])++; } // Method to check if this graph is Eulerian or not bool isEulerianCycle(); // Method to check if all non-zero degree vertices are connected bool isSC(); // Function to do DFS starting from v. Used in isConnected(); void DFSUtil(int v, bool visited[]); Graph getTranspose();}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V]; in = new int[V]; for (int i = 0; i < V; i++) in[i] = 0;} /* This function returns true if the directed graph has a eulerian cycle, otherwise returns false */bool Graph::isEulerianCycle(){ // Check if all non-zero degree vertices are connected if (isSC() == false) return false; // Check if in degree and out degree of every vertex is same for (int i = 0; i < V; i++) if (adj[i].size() != in[i]) return false; return true;} // A recursive function to do DFS starting from vvoid Graph::DFSUtil(int v, bool visited[]){ // Mark the current node as visited and print it visited[v] = true; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i, visited);} // Function that returns reverse (or transpose) of this graph// This function is needed in isSC()Graph Graph::getTranspose(){ Graph g(V); for (int v = 0; v < V; v++) { // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for(i = adj[v].begin(); i != adj[v].end(); ++i) { g.adj[*i].push_back(v); (g.in[v])++; } } return g;} // This function returns true if all non-zero degree vertices of// graph are strongly connected (Please refer// https://www.geeksforgeeks.org/connectivity-in-a-directed-graph/ )bool Graph::isSC(){ // Mark all the vertices as not visited (For first DFS) bool visited[V]; for (int i = 0; i < V; i++) visited[i] = false; // Find the first vertex with non-zero degree int n; for (n = 0; n < V; n++) if (adj[n].size() > 0) break; // Do DFS traversal starting from first non zero degrees vertex. DFSUtil(n, visited); // If DFS traversal doesn't visit all vertices, then return false. for (int i = 0; i < V; i++) if (adj[i].size() > 0 && visited[i] == false) return false; // Create a reversed graph Graph gr = getTranspose(); // Mark all the vertices as not visited (For second DFS) for (int i = 0; i < V; i++) visited[i] = false; // Do DFS for reversed graph starting from first vertex. // Starting Vertex must be same starting point of first DFS gr.DFSUtil(n, visited); // If all vertices are not visited in second DFS, then // return false for (int i = 0; i < V; i++) if (adj[i].size() > 0 && visited[i] == false) return false; return true;} // Driver program to test above functionsint main(){ // Create a graph given in the above diagram Graph g(5); g.addEdge(1, 0); g.addEdge(0, 2); g.addEdge(2, 1); g.addEdge(0, 3); g.addEdge(3, 4); g.addEdge(4, 0); if (g.isEulerianCycle()) cout << \"Given directed graph is eulerian n\"; else cout << \"Given directed graph is NOT eulerian n\"; return 0;}",
"e": 31376,
"s": 27560,
"text": null
},
{
"code": "// A Java program to check if a given directed graph is Eulerian or not // A class that represents an undirected graphimport java.io.*;import java.util.*;import java.util.LinkedList; // This class represents a directed graph using adjacency listclass Graph{ private int V; // No. of vertices private LinkedList<Integer> adj[];//Adjacency List private int in[]; //maintaining in degree //Constructor Graph(int v) { V = v; adj = new LinkedList[v]; in = new int[V]; for (int i=0; i<v; ++i) { adj[i] = new LinkedList(); in[i] = 0; } } //Function to add an edge into the graph void addEdge(int v,int w) { adj[v].add(w); in[w]++; } // A recursive function to print DFS starting from v void DFSUtil(int v,Boolean visited[]) { // Mark the current node as visited visited[v] = true; int n; // Recur for all the vertices adjacent to this vertex Iterator<Integer> i =adj[v].iterator(); while (i.hasNext()) { n = i.next(); if (!visited[n]) DFSUtil(n,visited); } } // Function that returns reverse (or transpose) of this graph Graph getTranspose() { Graph g = new Graph(V); for (int v = 0; v < V; v++) { // Recur for all the vertices adjacent to this vertex Iterator<Integer> i = adj[v].listIterator(); while (i.hasNext()) { g.adj[i.next()].add(v); (g.in[v])++; } } return g; } // The main function that returns true if graph is strongly // connected Boolean isSC() { // Step 1: Mark all the vertices as not visited (For // first DFS) Boolean visited[] = new Boolean[V]; for (int i = 0; i < V; i++) visited[i] = false; // Step 2: Do DFS traversal starting from the first vertex. DFSUtil(0, visited); // If DFS traversal doesn't visit all vertices, then return false. for (int i = 0; i < V; i++) if (visited[i] == false) return false; // Step 3: Create a reversed graph Graph gr = getTranspose(); // Step 4: Mark all the vertices as not visited (For second DFS) for (int i = 0; i < V; i++) visited[i] = false; // Step 5: Do DFS for reversed graph starting from first vertex. // Starting Vertex must be same starting point of first DFS gr.DFSUtil(0, visited); // If all vertices are not visited in second DFS, then // return false for (int i = 0; i < V; i++) if (visited[i] == false) return false; return true; } /* This function returns true if the directed graph has a eulerian cycle, otherwise returns false */ Boolean isEulerianCycle() { // Check if all non-zero degree vertices are connected if (isSC() == false) return false; // Check if in degree and out degree of every vertex is same for (int i = 0; i < V; i++) if (adj[i].size() != in[i]) return false; return true; } public static void main (String[] args) throws java.lang.Exception { Graph g = new Graph(5); g.addEdge(1, 0); g.addEdge(0, 2); g.addEdge(2, 1); g.addEdge(0, 3); g.addEdge(3, 4); g.addEdge(4, 0); if (g.isEulerianCycle()) System.out.println(\"Given directed graph is eulerian \"); else System.out.println(\"Given directed graph is NOT eulerian \"); }}//This code is contributed by Aakash Hasija",
"e": 35116,
"s": 31376,
"text": null
},
{
"code": "# A Python3 program to check if a given# directed graph is Eulerian or not from collections import defaultdict class Graph(): def __init__(self, vertices): self.V = vertices self.graph = defaultdict(list) self.IN = [0] * vertices def addEdge(self, v, u): self.graph[v].append(u) self.IN[u] += 1 def DFSUtil(self, v, visited): visited[v] = True for node in self.graph[v]: if visited[node] == False: self.DFSUtil(node, visited) def getTranspose(self): gr = Graph(self.V) for node in range(self.V): for child in self.graph[node]: gr.addEdge(child, node) return gr def isSC(self): visited = [False] * self.V v = 0 for v in range(self.V): if len(self.graph[v]) > 0: break self.DFSUtil(v, visited) # If DFS traversal doesn't visit all # vertices, then return false. for i in range(self.V): if visited[i] == False: return False gr = self.getTranspose() visited = [False] * self.V gr.DFSUtil(v, visited) for i in range(self.V): if visited[i] == False: return False return True def isEulerianCycle(self): # Check if all non-zero degree vertices # are connected if self.isSC() == False: return False # Check if in degree and out degree of # every vertex is same for v in range(self.V): if len(self.graph[v]) != self.IN[v]: return False return True g = Graph(5);g.addEdge(1, 0);g.addEdge(0, 2);g.addEdge(2, 1);g.addEdge(0, 3);g.addEdge(3, 4);g.addEdge(4, 0);if g.isEulerianCycle(): print( \"Given directed graph is eulerian\");else: print( \"Given directed graph is NOT eulerian\"); # This code is contributed by Divyanshu Mehta",
"e": 37042,
"s": 35116,
"text": null
},
{
"code": "// A C# program to check if a given// directed graph is Eulerian or not // A class that represents an// undirected graphusing System;using System.Collections.Generic; // This class represents a directed// graph using adjacency listclass Graph{ // No. of verticespublic int V; // Adjacency Listpublic List<int> []adj; // Maintaining in degreepublic int []init; // ConstructorGraph(int v){ V = v; adj = new List<int>[v]; init = new int[V]; for(int i = 0; i < v; ++i) { adj[i] = new List<int>(); init[i] = 0; }} // Function to add an edge into the graphvoid addEdge(int v, int w){ adj[v].Add(w); init[w]++;} // A recursive function to print DFS// starting from vvoid DFSUtil(int v, Boolean []visited){ // Mark the current node as visited visited[v] = true; // Recur for all the vertices // adjacent to this vertex foreach(int i in adj[v]) { if (!visited[i]) DFSUtil(i, visited); }} // Function that returns reverse// (or transpose) of this graphGraph getTranspose(){ Graph g = new Graph(V); for(int v = 0; v < V; v++) { // Recur for all the vertices // adjacent to this vertex foreach(int i in adj[v]) { g.adj[i].Add(v); (g.init[v])++; } } return g;} // The main function that returns// true if graph is strongly connectedBoolean isSC(){ // Step 1: Mark all the vertices // as not visited (For first DFS) Boolean []visited = new Boolean[V]; for(int i = 0; i < V; i++) visited[i] = false; // Step 2: Do DFS traversal starting // from the first vertex. DFSUtil(0, visited); // If DFS traversal doesn't visit // all vertices, then return false. for(int i = 0; i < V; i++) if (visited[i] == false) return false; // Step 3: Create a reversed graph Graph gr = getTranspose(); // Step 4: Mark all the vertices as // not visited (For second DFS) for(int i = 0; i < V; i++) visited[i] = false; // Step 5: Do DFS for reversed graph // starting from first vertex. // Staring Vertex must be same // starting point of first DFS gr.DFSUtil(0, visited); // If all vertices are not visited // in second DFS, then return false for(int i = 0; i < V; i++) if (visited[i] == false) return false; return true;} // This function returns true if the// directed graph has a eulerian// cycle, otherwise returns false Boolean isEulerianCycle(){ // Check if all non-zero degree // vertices are connected if (isSC() == false) return false; // Check if in degree and out // degree of every vertex is same for(int i = 0; i < V; i++) if (adj[i].Count != init[i]) return false; return true;} // Driver codepublic static void Main(String[] args){ Graph g = new Graph(5); g.addEdge(1, 0); g.addEdge(0, 2); g.addEdge(2, 1); g.addEdge(0, 3); g.addEdge(3, 4); g.addEdge(4, 0); if (g.isEulerianCycle()) Console.WriteLine(\"Given directed \" + \"graph is eulerian \"); else Console.WriteLine(\"Given directed \" + \"graph is NOT eulerian \");}} // This code is contributed by Princi Singh",
"e": 40359,
"s": 37042,
"text": null
},
{
"code": "<script>// A Javascript program to check if a given directed graph is Eulerian or not // This class represents a directed graph using adjacency// list representationclass Graph{ // Constructor constructor(v) { this.V = v; this.adj = new Array(v); this.in=new Array(v); for (let i=0; i<v; ++i) { this.adj[i] = []; this.in[i]=0; } } //Function to add an edge into the graph addEdge(v,w) { this.adj[v].push(w); this.in[w]++; } // A recursive function to print DFS starting from v DFSUtil(v,visited) { // Mark the current node as visited visited[v] = true; let n; // Recur for all the vertices adjacent to this vertex for(let i of this.adj[v]) { n = i; if (!visited[n]) this.DFSUtil(n,visited); } } // Function that returns reverse (or transpose) of this graph getTranspose() { let g = new Graph(this.V); for (let v = 0; v < this.V; v++) { // Recur for all the vertices adjacent to this vertex for(let i of this.adj[v]) { g.adj[i].push(v); (g.in[v])++; } } return g; } // The main function that returns true if graph is strongly // connected isSC() { // Step 1: Mark all the vertices as not visited (For // first DFS) let visited = new Array(this.V); for (let i = 0; i < this.V; i++) visited[i] = false; // Step 2: Do DFS traversal starting from the first vertex. this.DFSUtil(0, visited); // If DFS traversal doesn't visit all vertices, then return false. for (let i = 0; i < this.V; i++) if (visited[i] == false) return false; // Step 3: Create a reversed graph let gr = this.getTranspose(); // Step 4: Mark all the vertices as not visited (For second DFS) for (let i = 0; i < this.V; i++) visited[i] = false; // Step 5: Do DFS for reversed graph starting from first vertex. // Starting Vertex must be same starting point of first DFS gr.DFSUtil(0, visited); // If all vertices are not visited in second DFS, then // return false for (let i = 0; i < this.V; i++) if (visited[i] == false) return false; return true; } /* This function returns true if the directed graph has a eulerian cycle, otherwise returns false */ isEulerianCycle() { // Check if all non-zero degree vertices are connected if (this.isSC() == false) return false; // Check if in degree and out degree of every vertex is same for (let i = 0; i < this.V; i++) if (this.adj[i].length != this.in[i]) return false; return true; }} let g = new Graph(5);g.addEdge(1, 0);g.addEdge(0, 2);g.addEdge(2, 1);g.addEdge(0, 3);g.addEdge(3, 4);g.addEdge(4, 0); if (g.isEulerianCycle()) document.write(\"Given directed graph is eulerian \");else document.write(\"Given directed graph is NOT eulerian \"); // This code is contributed by avanitrachhadiya2155</script>",
"e": 43702,
"s": 40359,
"text": null
},
{
"code": null,
"e": 43711,
"s": 43702,
"text": "Output: "
},
{
"code": null,
"e": 43745,
"s": 43711,
"text": "Given directed graph is eulerian "
},
{
"code": null,
"e": 43969,
"s": 43745,
"text": " Time complexity of the above implementation is O(V + E) as Kosarajuβs algorithm takes O(V + E) time. After running Kosarajuβs algorithm we traverse all vertices and compare in degree with out degree which takes O(V) time. "
},
{
"code": null,
"e": 44078,
"s": 43969,
"text": "See following as an application of this. Find if the given array of strings can be chained to form a circle."
},
{
"code": null,
"e": 44204,
"s": 44078,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 44221,
"s": 44206,
"text": "UtkarshVerma12"
},
{
"code": null,
"e": 44234,
"s": 44221,
"text": "princi singh"
},
{
"code": null,
"e": 44251,
"s": 44234,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 44272,
"s": 44251,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 44276,
"s": 44272,
"text": "DFS"
},
{
"code": null,
"e": 44290,
"s": 44276,
"text": "Euler-Circuit"
},
{
"code": null,
"e": 44309,
"s": 44290,
"text": "graph-connectivity"
},
{
"code": null,
"e": 44321,
"s": 44309,
"text": "graph-cycle"
},
{
"code": null,
"e": 44327,
"s": 44321,
"text": "Graph"
},
{
"code": null,
"e": 44331,
"s": 44327,
"text": "DFS"
},
{
"code": null,
"e": 44337,
"s": 44331,
"text": "Graph"
},
{
"code": null,
"e": 44435,
"s": 44337,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44455,
"s": 44435,
"text": "Topological Sorting"
},
{
"code": null,
"e": 44488,
"s": 44455,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 44556,
"s": 44488,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 44606,
"s": 44556,
"text": "Ford-Fulkerson Algorithm for Maximum Flow Problem"
},
{
"code": null,
"e": 44681,
"s": 44606,
"text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)"
},
{
"code": null,
"e": 44729,
"s": 44681,
"text": "Traveling Salesman Problem (TSP) Implementation"
},
{
"code": null,
"e": 44765,
"s": 44729,
"text": "Detect cycle in an undirected graph"
},
{
"code": null,
"e": 44800,
"s": 44765,
"text": "Hamiltonian Cycle | Backtracking-6"
},
{
"code": null,
"e": 44836,
"s": 44800,
"text": "m Coloring Problem | Backtracking-5"
}
] |
Removing the default underlines from links using CSS
|
By default, all links in HTML are decorated with an underline. We can remove this underline using CSS text-decoration property.
The syntax of CSS text-decoration property is as follows β
Selector {
text-decoration: /*value*/
}
The following examples illustrate CSS text-decoration property.
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
p {
padding: 5px;
box-shadow: inset 0 0 5px violet;
}
a {
font-style: italic;
text-decoration: none;
}
</style>
</head>
<body>
<a href="#">Demo</a>
<p>
<a href="https://example.com/">Example domain</a>
</p>
</body>
</html>
This gives the following output β
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
div {
margin: auto;
width: 50%;
text-align: right;
color: green;
border: thin dashed red;
}
a {
text-decoration: none;
}
a:last-child {
color: inherit;
background-color: moccasin;
}
</style>
</head>
<body>
<div>
<a href="#">Link Demo</a>
<p>
Watch this: <a href="https://example.com/">Example site</a>
</p>
</div>
</body>
</html>
This gives the following output β
|
[
{
"code": null,
"e": 1190,
"s": 1062,
"text": "By default, all links in HTML are decorated with an underline. We can remove this underline using CSS text-decoration property."
},
{
"code": null,
"e": 1249,
"s": 1190,
"text": "The syntax of CSS text-decoration property is as follows β"
},
{
"code": null,
"e": 1292,
"s": 1249,
"text": "Selector {\n text-decoration: /*value*/\n}"
},
{
"code": null,
"e": 1356,
"s": 1292,
"text": "The following examples illustrate CSS text-decoration property."
},
{
"code": null,
"e": 1367,
"s": 1356,
"text": " Live Demo"
},
{
"code": null,
"e": 1640,
"s": 1367,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\np {\n padding: 5px;\n box-shadow: inset 0 0 5px violet;\n}\na {\n font-style: italic;\n text-decoration: none;\n}\n</style>\n</head>\n<body>\n<a href=\"#\">Demo</a>\n<p>\n<a href=\"https://example.com/\">Example domain</a>\n</p>\n</body>\n</html>"
},
{
"code": null,
"e": 1674,
"s": 1640,
"text": "This gives the following output β"
},
{
"code": null,
"e": 1685,
"s": 1674,
"text": " Live Demo"
},
{
"code": null,
"e": 2077,
"s": 1685,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\ndiv {\n margin: auto;\n width: 50%;\n text-align: right;\n color: green;\n border: thin dashed red;\n}\na {\n text-decoration: none;\n}\na:last-child {\n color: inherit;\n background-color: moccasin;\n}\n</style>\n</head>\n<body>\n<div>\n<a href=\"#\">Link Demo</a>\n<p>\nWatch this: <a href=\"https://example.com/\">Example site</a>\n</p>\n</div>\n</body>\n</html>"
},
{
"code": null,
"e": 2111,
"s": 2077,
"text": "This gives the following output β"
}
] |
StringBuilder setCharAt() in Java with Examples
|
19 Aug, 2019
The setCharAt(int index, char ch) method of StringBuilder class is used to set the character at the position index passed as ch. This method changes the old sequence to represents a new sequence which is identical to old sequence only difference is a new character ch is present at position index. The index argument must be greater than or equal to 0, and less than the length of the String contained by StringBUilder object.Syntax:
public void setCharAt(int index, char ch)
Parameters:This method accepts two parameters:
index β Integer type value which refers to the index of character you want to set.ch β Character type value which refers to the new char.
index β Integer type value which refers to the index of character you want to set.
ch β Character type value which refers to the new char.
Returns:This method returns nothing.Exception:If the index is negative, greater than length() then IndexOutOfBoundsException.
Below programs illustrate the java.lang.StringBuilder.setCharAt() method:Example 1:
// Java program to demonstrate// the setCharAt() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder("WelcomeGeeks"); // print string System.out.println("String = " + str.toString()); // set char at index 2 to 'L' str.setCharAt(2, 'L'); // print string System.out.println("After setCharAt() String = " + str.toString()); }}
Output:
String = WelcomeGeeks
After setCharAt() String = WeLcomeGeeks
Example 2:
// Java program to demonstrate// the setCharAt() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder("Tony Stark will die"); // print string System.out.println("String = " + str.toString()); // set char at index 9 to '1' str.setCharAt(9, '1'); // print string System.out.println("After setCharAt() String = " + str.toString()); }}
Output:
String = Tony Stark will die
After setCharAt() String = Tony Star1 will die
Example 3: When negative index is passed:
// Java program to demonstrate// Exception thrown by the setCharAt() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder("Tony Stark"); try { // pass index -15 str.setCharAt(-15, 'A'); } catch (Exception e) { e.printStackTrace(); } }}
Output:
java.lang.StringIndexOutOfBoundsException: String index out of range: -15
at java.lang.AbstractStringBuilder.setCharAt(AbstractStringBuilder.java:407)
at java.lang.StringBuilder.setCharAt(StringBuilder.java:76)
at GFG.main(File.java:16)
References:https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#setCharAt(int, char)
Akanksha_Rai
Java-Functions
Java-StringBuilder
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Aug, 2019"
},
{
"code": null,
"e": 486,
"s": 52,
"text": "The setCharAt(int index, char ch) method of StringBuilder class is used to set the character at the position index passed as ch. This method changes the old sequence to represents a new sequence which is identical to old sequence only difference is a new character ch is present at position index. The index argument must be greater than or equal to 0, and less than the length of the String contained by StringBUilder object.Syntax:"
},
{
"code": null,
"e": 528,
"s": 486,
"text": "public void setCharAt(int index, char ch)"
},
{
"code": null,
"e": 575,
"s": 528,
"text": "Parameters:This method accepts two parameters:"
},
{
"code": null,
"e": 713,
"s": 575,
"text": "index β Integer type value which refers to the index of character you want to set.ch β Character type value which refers to the new char."
},
{
"code": null,
"e": 796,
"s": 713,
"text": "index β Integer type value which refers to the index of character you want to set."
},
{
"code": null,
"e": 852,
"s": 796,
"text": "ch β Character type value which refers to the new char."
},
{
"code": null,
"e": 978,
"s": 852,
"text": "Returns:This method returns nothing.Exception:If the index is negative, greater than length() then IndexOutOfBoundsException."
},
{
"code": null,
"e": 1062,
"s": 978,
"text": "Below programs illustrate the java.lang.StringBuilder.setCharAt() method:Example 1:"
},
{
"code": "// Java program to demonstrate// the setCharAt() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder(\"WelcomeGeeks\"); // print string System.out.println(\"String = \" + str.toString()); // set char at index 2 to 'L' str.setCharAt(2, 'L'); // print string System.out.println(\"After setCharAt() String = \" + str.toString()); }}",
"e": 1645,
"s": 1062,
"text": null
},
{
"code": null,
"e": 1653,
"s": 1645,
"text": "Output:"
},
{
"code": null,
"e": 1716,
"s": 1653,
"text": "String = WelcomeGeeks\nAfter setCharAt() String = WeLcomeGeeks\n"
},
{
"code": null,
"e": 1727,
"s": 1716,
"text": "Example 2:"
},
{
"code": "// Java program to demonstrate// the setCharAt() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder(\"Tony Stark will die\"); // print string System.out.println(\"String = \" + str.toString()); // set char at index 9 to '1' str.setCharAt(9, '1'); // print string System.out.println(\"After setCharAt() String = \" + str.toString()); }}",
"e": 2317,
"s": 1727,
"text": null
},
{
"code": null,
"e": 2325,
"s": 2317,
"text": "Output:"
},
{
"code": null,
"e": 2402,
"s": 2325,
"text": "String = Tony Stark will die\nAfter setCharAt() String = Tony Star1 will die\n"
},
{
"code": null,
"e": 2444,
"s": 2402,
"text": "Example 3: When negative index is passed:"
},
{
"code": "// Java program to demonstrate// Exception thrown by the setCharAt() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder(\"Tony Stark\"); try { // pass index -15 str.setCharAt(-15, 'A'); } catch (Exception e) { e.printStackTrace(); } }}",
"e": 2904,
"s": 2444,
"text": null
},
{
"code": null,
"e": 2912,
"s": 2904,
"text": "Output:"
},
{
"code": null,
"e": 3162,
"s": 2912,
"text": "java.lang.StringIndexOutOfBoundsException: String index out of range: -15\n at java.lang.AbstractStringBuilder.setCharAt(AbstractStringBuilder.java:407)\n at java.lang.StringBuilder.setCharAt(StringBuilder.java:76)\n at GFG.main(File.java:16)\n"
},
{
"code": null,
"e": 3266,
"s": 3162,
"text": "References:https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#setCharAt(int, char)"
},
{
"code": null,
"e": 3279,
"s": 3266,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 3294,
"s": 3279,
"text": "Java-Functions"
},
{
"code": null,
"e": 3313,
"s": 3294,
"text": "Java-StringBuilder"
},
{
"code": null,
"e": 3318,
"s": 3313,
"text": "Java"
},
{
"code": null,
"e": 3323,
"s": 3318,
"text": "Java"
},
{
"code": null,
"e": 3421,
"s": 3323,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3472,
"s": 3421,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 3503,
"s": 3472,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 3522,
"s": 3503,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3552,
"s": 3522,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 3570,
"s": 3552,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3585,
"s": 3570,
"text": "Stream In Java"
},
{
"code": null,
"e": 3605,
"s": 3585,
"text": "Collections in Java"
},
{
"code": null,
"e": 3637,
"s": 3605,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 3661,
"s": 3637,
"text": "Singleton Class in Java"
}
] |
How to find the sum of all elements of a given array in JavaScript ?
|
08 Oct, 2021
In this article, we will learn how we can find the sum of all elements/numbers of the given array. There are many approaches to solve the problems that are described below through examples.
Example 1: In this example, we are simply going to iterate over all the elements of the array using a for loop to find the sum.
Filename: gfg.js
Javascript
<script> // Creating array var arr = [4, 8, 7, 13, 12] // Creating variable to store the sum var sum = 0; // Running the for loop for (let i = 0; i < arr.length; i++) { sum += arr[i]; } document.write("Sum is " + sum) // Prints: 44</script>
Output:
Sum is 44
Example 2: In this example, we are going to use forEach method of the array to calculate the sum.
Filename: gfg.js
Javascript
<script> // Creating array var arr = [4, 8, 7, 13, 12] // Creating variable to store the sum var sum = 0; // Calculation the sum using forEach arr.forEach(x => { sum += x; }); // Prints: 44 document.write("Sum is " + sum);</script>
Output:
Sum is 44
Example 3: In this example, we are going to use reduce() method to find the sum of the array.
Filename: gfg.js
Javascript
<script> // Creating array var arr = [4, 8, 7, 13, 12] // Using reduce function to find the sum var sum = arr.reduce(function (x, y) { return x + y; }, 0); // Prints: 44 document.write("Sum using Reduce method: " + sum); </script>
Output:
Sum using Reduce method: 44
javascript-array
JavaScript-Methods
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 244,
"s": 54,
"text": "In this article, we will learn how we can find the sum of all elements/numbers of the given array. There are many approaches to solve the problems that are described below through examples."
},
{
"code": null,
"e": 372,
"s": 244,
"text": "Example 1: In this example, we are simply going to iterate over all the elements of the array using a for loop to find the sum."
},
{
"code": null,
"e": 389,
"s": 372,
"text": "Filename: gfg.js"
},
{
"code": null,
"e": 400,
"s": 389,
"text": "Javascript"
},
{
"code": "<script> // Creating array var arr = [4, 8, 7, 13, 12] // Creating variable to store the sum var sum = 0; // Running the for loop for (let i = 0; i < arr.length; i++) { sum += arr[i]; } document.write(\"Sum is \" + sum) // Prints: 44</script>",
"e": 678,
"s": 400,
"text": null
},
{
"code": null,
"e": 686,
"s": 678,
"text": "Output:"
},
{
"code": null,
"e": 696,
"s": 686,
"text": "Sum is 44"
},
{
"code": null,
"e": 794,
"s": 696,
"text": "Example 2: In this example, we are going to use forEach method of the array to calculate the sum."
},
{
"code": null,
"e": 811,
"s": 794,
"text": "Filename: gfg.js"
},
{
"code": null,
"e": 822,
"s": 811,
"text": "Javascript"
},
{
"code": "<script> // Creating array var arr = [4, 8, 7, 13, 12] // Creating variable to store the sum var sum = 0; // Calculation the sum using forEach arr.forEach(x => { sum += x; }); // Prints: 44 document.write(\"Sum is \" + sum);</script>",
"e": 1100,
"s": 822,
"text": null
},
{
"code": null,
"e": 1108,
"s": 1100,
"text": "Output:"
},
{
"code": null,
"e": 1118,
"s": 1108,
"text": "Sum is 44"
},
{
"code": null,
"e": 1212,
"s": 1118,
"text": "Example 3: In this example, we are going to use reduce() method to find the sum of the array."
},
{
"code": null,
"e": 1229,
"s": 1212,
"text": "Filename: gfg.js"
},
{
"code": null,
"e": 1240,
"s": 1229,
"text": "Javascript"
},
{
"code": "<script> // Creating array var arr = [4, 8, 7, 13, 12] // Using reduce function to find the sum var sum = arr.reduce(function (x, y) { return x + y; }, 0); // Prints: 44 document.write(\"Sum using Reduce method: \" + sum); </script>",
"e": 1506,
"s": 1240,
"text": null
},
{
"code": null,
"e": 1514,
"s": 1506,
"text": "Output:"
},
{
"code": null,
"e": 1542,
"s": 1514,
"text": "Sum using Reduce method: 44"
},
{
"code": null,
"e": 1559,
"s": 1542,
"text": "javascript-array"
},
{
"code": null,
"e": 1578,
"s": 1559,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 1599,
"s": 1578,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 1606,
"s": 1599,
"text": "Picked"
},
{
"code": null,
"e": 1617,
"s": 1606,
"text": "JavaScript"
},
{
"code": null,
"e": 1634,
"s": 1617,
"text": "Web Technologies"
},
{
"code": null,
"e": 1732,
"s": 1634,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1793,
"s": 1732,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1833,
"s": 1793,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1874,
"s": 1833,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 1916,
"s": 1874,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 1938,
"s": 1916,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 2000,
"s": 1938,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2033,
"s": 2000,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2094,
"s": 2033,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2144,
"s": 2094,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to Exclude Records With Certain Values in SQL Select?
|
08 Oct, 2021
In this article, we will understand how to exclude some records having certain values from a table. For the purpose of demonstration, we will be creating a Participant table in a database called βGeeksForGeeksDatabaseβ.
Use the below SQL statement to create a database called GeeksForGeeksDatabase.
Query:
CREATE DATABASE GeeksForGeeksDatabase;
Use the below SQL statement to switch the database context to GeeksForGeeksDatabase.
Query:
USE GeeksForGeeksDatabase;
Query:
CREATE TABLE Geeks(
GeekID INTEGER PRIMARY KEY,
GeekName VARCHAR(255) NOT NULL,
GeekRank INTEGER NOT NULL,
GeekSchool VARCHAR(255) NOT NULL
);
Query:
INSERT INTO Geeks VALUES (101, 'Nix',2 ,'Code Valley School');
INSERT INTO Geeks VALUES (102, 'Rutz',4 ,'Blue Chip School');
INSERT INTO Geeks VALUES (103, 'Shrey',1 ,'GCOEA School');
INSERT INTO Geeks VALUES (104, 'Ankx',3 ,'Round Robin Play School');
INSERT INTO Geeks VALUES (105, 'Ridz',7 ,'Dream School');
INSERT INTO Geeks VALUES (106, 'Mayo',6 ,'Silver Shining School');
INSERT INTO Geeks VALUES (107, 'Bugs',5 ,'Twinkle Star Convent');
You can use the below statement to see the contents of the created table:
Query:
SELECT * FROM Geeks;
Now letβs see how to exclude some records from the table according to certain conditions.
There are many ways to do so, lets see the examples one by one:
Query:
Query to exclude a student from a particular school i.e. Blue Chip School. NOT shows those records where the condition is NOT TRUE.
Note: If we havenβt use NOT here then the result would be the opposite.
SELECT * FROM Geeks WHERE NOT GeekSchool = 'Blue Chip School';
This query will output all students except the students with a given school:
We can also exclude some more records by providing where conditions are separated by AND OR operator.
Note: We can also do the same using != operator
Query:
SELECT * FROM Geeks WHERE NOT GeekID > 104;
Now see the difference in how NOT is working. Here in the example, we provided the condition, which when true follows the NOT means the query will select all the rows for which the provided condition is not true.
In the above output, the condition GeekID > 104 is satisfied and due to NOT all the rows are selected which are less than 104.
Note: We can also do the same using != operator
Query:
SELECT * FROM Geeks WHERE GeekID NOT IN (104,101,102,107);
In this query, we are excluding those records (rows) where GeekID does not lie in the provided list (i.e. GeekID should not be 104,101,102,107)
So the resultant data will contain the records excluding the provided Geek ids.
Thus we can apply any condition to any column of the table and exclude those using NOT operator.
Query:
We can also provide subquery in IN operator and can also include one or many conditions using WHERE clause :
SELECT * FROM Geeks WHERE GeekRank NOT IN (SELECT GeekRank FROM Geeks WHERE GeekRank >= 4);
The resultant table selects all the rows which not satisfies the condition GeekRank >=4, So all the geeks with ranks above 4 are selected. We can also combine many conditions together and get different results accordingly.
Picked
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 272,
"s": 52,
"text": "In this article, we will understand how to exclude some records having certain values from a table. For the purpose of demonstration, we will be creating a Participant table in a database called βGeeksForGeeksDatabaseβ."
},
{
"code": null,
"e": 351,
"s": 272,
"text": "Use the below SQL statement to create a database called GeeksForGeeksDatabase."
},
{
"code": null,
"e": 358,
"s": 351,
"text": "Query:"
},
{
"code": null,
"e": 397,
"s": 358,
"text": "CREATE DATABASE GeeksForGeeksDatabase;"
},
{
"code": null,
"e": 482,
"s": 397,
"text": "Use the below SQL statement to switch the database context to GeeksForGeeksDatabase."
},
{
"code": null,
"e": 489,
"s": 482,
"text": "Query:"
},
{
"code": null,
"e": 516,
"s": 489,
"text": "USE GeeksForGeeksDatabase;"
},
{
"code": null,
"e": 523,
"s": 516,
"text": "Query:"
},
{
"code": null,
"e": 666,
"s": 523,
"text": "CREATE TABLE Geeks(\nGeekID INTEGER PRIMARY KEY,\nGeekName VARCHAR(255) NOT NULL,\nGeekRank INTEGER NOT NULL,\nGeekSchool VARCHAR(255) NOT NULL\n);"
},
{
"code": null,
"e": 673,
"s": 666,
"text": "Query:"
},
{
"code": null,
"e": 1117,
"s": 673,
"text": "INSERT INTO Geeks VALUES (101, 'Nix',2 ,'Code Valley School');\nINSERT INTO Geeks VALUES (102, 'Rutz',4 ,'Blue Chip School');\nINSERT INTO Geeks VALUES (103, 'Shrey',1 ,'GCOEA School');\nINSERT INTO Geeks VALUES (104, 'Ankx',3 ,'Round Robin Play School');\nINSERT INTO Geeks VALUES (105, 'Ridz',7 ,'Dream School');\nINSERT INTO Geeks VALUES (106, 'Mayo',6 ,'Silver Shining School');\nINSERT INTO Geeks VALUES (107, 'Bugs',5 ,'Twinkle Star Convent');"
},
{
"code": null,
"e": 1191,
"s": 1117,
"text": "You can use the below statement to see the contents of the created table:"
},
{
"code": null,
"e": 1198,
"s": 1191,
"text": "Query:"
},
{
"code": null,
"e": 1219,
"s": 1198,
"text": "SELECT * FROM Geeks;"
},
{
"code": null,
"e": 1309,
"s": 1219,
"text": "Now letβs see how to exclude some records from the table according to certain conditions."
},
{
"code": null,
"e": 1373,
"s": 1309,
"text": "There are many ways to do so, lets see the examples one by one:"
},
{
"code": null,
"e": 1380,
"s": 1373,
"text": "Query:"
},
{
"code": null,
"e": 1512,
"s": 1380,
"text": "Query to exclude a student from a particular school i.e. Blue Chip School. NOT shows those records where the condition is NOT TRUE."
},
{
"code": null,
"e": 1584,
"s": 1512,
"text": "Note: If we havenβt use NOT here then the result would be the opposite."
},
{
"code": null,
"e": 1647,
"s": 1584,
"text": "SELECT * FROM Geeks WHERE NOT GeekSchool = 'Blue Chip School';"
},
{
"code": null,
"e": 1724,
"s": 1647,
"text": "This query will output all students except the students with a given school:"
},
{
"code": null,
"e": 1826,
"s": 1724,
"text": "We can also exclude some more records by providing where conditions are separated by AND OR operator."
},
{
"code": null,
"e": 1874,
"s": 1826,
"text": "Note: We can also do the same using != operator"
},
{
"code": null,
"e": 1881,
"s": 1874,
"text": "Query:"
},
{
"code": null,
"e": 1925,
"s": 1881,
"text": "SELECT * FROM Geeks WHERE NOT GeekID > 104;"
},
{
"code": null,
"e": 2138,
"s": 1925,
"text": "Now see the difference in how NOT is working. Here in the example, we provided the condition, which when true follows the NOT means the query will select all the rows for which the provided condition is not true."
},
{
"code": null,
"e": 2265,
"s": 2138,
"text": "In the above output, the condition GeekID > 104 is satisfied and due to NOT all the rows are selected which are less than 104."
},
{
"code": null,
"e": 2313,
"s": 2265,
"text": "Note: We can also do the same using != operator"
},
{
"code": null,
"e": 2320,
"s": 2313,
"text": "Query:"
},
{
"code": null,
"e": 2379,
"s": 2320,
"text": "SELECT * FROM Geeks WHERE GeekID NOT IN (104,101,102,107);"
},
{
"code": null,
"e": 2523,
"s": 2379,
"text": "In this query, we are excluding those records (rows) where GeekID does not lie in the provided list (i.e. GeekID should not be 104,101,102,107)"
},
{
"code": null,
"e": 2603,
"s": 2523,
"text": "So the resultant data will contain the records excluding the provided Geek ids."
},
{
"code": null,
"e": 2700,
"s": 2603,
"text": "Thus we can apply any condition to any column of the table and exclude those using NOT operator."
},
{
"code": null,
"e": 2707,
"s": 2700,
"text": "Query:"
},
{
"code": null,
"e": 2816,
"s": 2707,
"text": "We can also provide subquery in IN operator and can also include one or many conditions using WHERE clause :"
},
{
"code": null,
"e": 2908,
"s": 2816,
"text": "SELECT * FROM Geeks WHERE GeekRank NOT IN (SELECT GeekRank FROM Geeks WHERE GeekRank >= 4);"
},
{
"code": null,
"e": 3131,
"s": 2908,
"text": "The resultant table selects all the rows which not satisfies the condition GeekRank >=4, So all the geeks with ranks above 4 are selected. We can also combine many conditions together and get different results accordingly."
},
{
"code": null,
"e": 3138,
"s": 3131,
"text": "Picked"
},
{
"code": null,
"e": 3149,
"s": 3138,
"text": "SQL-Server"
},
{
"code": null,
"e": 3153,
"s": 3149,
"text": "SQL"
},
{
"code": null,
"e": 3157,
"s": 3153,
"text": "SQL"
}
] |
Strong Password Suggester Program
|
26 Jul, 2021
Given a password entered by the user, check its strength and suggest some password if it is not strong.
Criteria for strong password is as follows : A password is strong if it has : 1. At least 8 characters 2. At least one special char 3. At least one number 4. At least one upper and one lower case char.
Examples :
Input : keshav123
Output : Suggested Password
k(eshav12G3
keshav1@A23
kesh!Aav123
ke(shav12V3
keGshav1$23
kesXhav@123
keAshav12$3
kesKhav@123
kes$hav12N3
$kesRhav123
Input :rakesh@1995kumar
Output : Your Password is Strong
Approach : Check the input password for its strength if it fulfills all the criteria, then it is strong password else check for the absent characters in it, and return the randomly generated password to the user.
C++
Java
Python3
C#
PHP
// CPP code to suggest strong password#include <bits/stdc++.h> using namespace std; // adding more characters to suggest strong passwordstring add_more_char(string str, int need){ int pos = 0; // all 26 letters string low_case = "abcdefghijklmnopqrstuvwxyz"; for (int i = 0; i < need; i++) { pos = rand() % str.length(); str.insert(pos, 1, low_case[rand() % 26]); } return str;} // make powerful stringstring suggester(int l, int u, int d, int s, string str){ // all digits string num = "0123456789"; // all lower case, uppercase and special characters string low_case = "abcdefghijklmnopqrstuvwxyz"; string up_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; string spl_char = "@#$_()!"; // position at which place a character int pos = 0; // if there is no lowercase char in input string, add it if (l == 0) { // generate random integer under string length pos = rand() % str.length(); // generate random integer under 26 for indexing of a to z str.insert(pos, 1, low_case[rand() % 26]); } // if there is no upper case char in input string, add it if (u == 0) { pos = rand() % str.length(); str.insert(pos, 1, up_case[rand() % 26]); } // if there is no digit in input string, add it if (d == 0) { pos = rand() % str.length(); str.insert(pos, 1, num[rand() % 10]); } // if there is no special character in input string, add it if (s == 0) { pos = rand() % str.length(); str.insert(pos, 1, spl_char[rand() % 7]); } return str;} /* make_password function :This function is used to checkstrongness and if input string is not strong, it will suggest*/void generate_password(int n, string p){ // flag for lower case, upper case, special // characters and need of more characters int l = 0, u = 0, d = 0, s = 0, need = 0; // password suggestions. string suggest; for (int i = 0; i < n; i++) { // password suggestions. if (p[i] >= 97 && p[i] <= 122) l = 1; else if (p[i] >= 65 && p[i] <= 90) u = 1; else if (p[i] >= 48 && p[i] <= 57) d = 1; else s = 1; } // Check if input string is strong that // means all flag are active. if ((l + u + d + s) == 4) { cout << "Your Password is Strong" << endl; return; } else cout << "Suggested password " << endl; /*suggest 10 strong strings */ for (int i = 0; i < 10; i++) { suggest = suggester(l, u, d, s, p); need = 8 - suggest.length(); if (need > 0) suggest = add_more_char(suggest, need); cout << suggest << endl; }} // Driver codeint main(){ string input_string = "geek@2018"; srand(time(NULL)); // srand function set Seed for rand(). generate_password(input_string.length(), input_string); return 0;}
// Java code to suggest strong passwordimport java.io.*;import java.util.*;import java.util.Random; public class GFG { // adding more characters to suggest // strong password static StringBuilder add_more_char( StringBuilder str, int need) { int pos = 0; Random randm = new Random(); // all 26 letters String low_case = "abcdefghijklmnopqrstuvwxyz"; for (int i = 0; i < need; i++) { pos = randm.nextInt(1000) % str.length(); str.setCharAt(pos,low_case.charAt( randm.nextInt(1000) % 26)); } return str; } // make powerful String static StringBuilder suggester(int l, int u, int d, int s, StringBuilder str) { Random randm = new Random(); // all digits String num = "0123456789"; // all lower case, uppercase and special // characters String low_case = "abcdefghijklmnopqrstuvwxyz"; String up_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String spl_char = "@#$_()!"; // position at which place a character int pos = 0; // if there is no lowercase char in input // String, add it if (l == 0) { // generate random integer under // String length() pos = randm.nextInt(1000) % str.length(); // generate random integer under 26 for // indexing of a to z str.setCharAt(pos,low_case.charAt(randm.nextInt(1000) % 26)); } // if there is no upper case char in input // String, add it if (u == 0) { pos = randm.nextInt(1000) % str.length(); str.setCharAt(pos,low_case.charAt(randm.nextInt(1000) % 26)); } // if there is no digit in input String, add it if (d == 0) { pos = randm.nextInt(1000) % str.length(); str.setCharAt(pos,low_case.charAt(randm.nextInt(1000) % 10)); } // if there is no special character in input // String, add it if (s == 0) { pos = randm.nextInt(1000) % str.length(); str.setCharAt(pos,low_case.charAt(randm.nextInt(1000) % 7)); } return str; } /* make_password function :This function is used to check strongness and if input String is not strong, it will suggest*/ static void generate_password(int n, StringBuilder p) { // flag for lower case, upper case, special // characters and need of more characters int l = 0, u = 0, d = 0, s = 0, need = 0; // password suggestions. StringBuilder suggest; for (int i = 0; i < n; i++) { // password suggestions. if (p.charAt(i) >= 97 && p.charAt(i) <= 122) l = 1; else if (p.charAt(i) >= 65 && p.charAt(i) <= 90) u = 1; else if (p.charAt(i) >= 48 && p.charAt(i) <= 57) d = 1; else s = 1; } // Check if input String is strong that // means all flag are active. if ((l + u + d + s) == 4) { System.out.println("Your Password is Strong"); return; } else System.out.println("Suggested password "); /*suggest 10 strong Strings */ for (int i = 0; i < 10; i++) { suggest = suggester(l, u, d, s, p); need = 8 - suggest.length(); if (need > 0) suggest = add_more_char(suggest, need); System.out.println(suggest);; } } // Driver code public static void main(String[] args) { StringBuilder input_String = new StringBuilder("geek@2018"); generate_password(input_String.length(), input_String); }} // This code is contributed by Manish Shaw (manishshaw1)
# Python code to suggest strong password import random # Function to insert character in a string# Because string is immutable in pythondef insert(s, pos, ch): return(s[:pos] + ch + s[pos:]) # adding more characters to# suggest strong passworddef add_more_char(s, need): pos = 0 # add 26 letters low_case = "abcdefghijklmnopqrstuvwxyz" for i in range(need): pos = random.randint(0, len(s)-1) s = insert(s, pos, low_case[random.randint(0,25)]) return(s) # Make powerful stringdef suggester(l, u, d, s, st): # all digits num = '0123456789' # all lower case, upper case and special characters low_case = "abcdefghijklmnopqrstuvwxyz" up_case = low_case.upper() spl_char = '@#$_()!' # Position at which place a character pos = 0 # If there is no lowercase char # in input string, add it if( l == 0 ): # Generate random integer under string length pos = random.randint(0,len(st)-1) # Generate random integer under 26 for indexing of a to z st = insert(st, pos, low_case[random.randint(0,25)]) # If there is no upper case char in input string, add it if( u == 0 ): # Generate random integer under string length pos = random.randint(0,len(st)-1) # Generate random integer under 26 for indexing of A to Z st = insert(st, pos, up_case[random.randint(0,25)]) # If there is no digit in input string, add it if( d == 0 ): # Generate random integer under string length pos = random.randint(0,len(st)-1) # Generate random integer under 10 for indexing of 0 to 9 st = insert(st, pos, num[random.randint(0,9)]) # If there is no special character # in input string, add it if( s == 0 ): # Generate random integer under string length pos = random.randint(0,len(st)-1) # Generate random integer under 7 for # indexing of special characters st = insert(st, pos, low_case[random.randint(0,6)]) return st # generate_password function : This function is used to check# strength and if input string is not strong, It will suggestdef generate_password(n, p): # flag for lower case, upper case, special # characters and need of more characters l = 0; u = 0; d = 0; s = 0; need = 0 # Password suggestions suggest = '' for i in range(n): # Password suggestion if( p[i].islower() ): l = 1 elif( p[i].isupper() ): u = 1 elif( p[i].isdigit() ): d = 1 else: s = 1 # Check if input string is strong that # means all flags are active if( (l + u + d + s) == 4): print("Your Password is Strong") return else: print("Suggested Passwords") # Suggest 10 strong strings for i in range(10): suggest = suggester(l, u, d, s, p) need = 8 - len(suggest) if(need > 0): suggest = add_more_char(suggest, need) print(suggest) # Driver Codeinput_string = 'geek@2018' generate_password( len(input_string), input_string) # This code is contributed by Arjun Saini
// C# code to suggest strong passwordusing System;using System.Collections.Generic; class GFG { // adding more characters to suggest // strong password static string add_more_char(string str, int need) { int pos = 0; Random randm = new Random(); // all 26 letters string low_case = "abcdefghijklmnopqrstuvwxyz"; for (int i = 0; i < need; i++) { pos = randm.Next(1,1000) % str.Length; str = str.Insert(pos,low_case[randm.Next(1000) % 26].ToString()); } return str; } // make powerful string static string suggester(int l, int u, int d, int s, string str) { Random randm = new Random(); // all digits string num = "0123456789"; // all lower case, uppercase and special // characters string low_case = "abcdefghijklmnopqrstuvwxyz"; string up_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; string spl_char = "@#$_()!"; // position at which place a character int pos = 0; // if there is no lowercase char in input // string, add it if (l == 0) { // generate random integer under // string length pos = randm.Next(1,1000) % str.Length; // generate random integer under 26 for // indexing of a to z str = str.Insert(pos,low_case[randm.Next(1, 1000) % 26].ToString()); } // if there is no upper case char in input // string, add it if (u == 0) { pos = randm.Next(1,1000) % str.Length; str = str.Insert(pos,up_case[randm.Next( 1,1000) % 26].ToString()); } // if there is no digit in input string, add it if (d == 0) { pos = randm.Next(1,1000) % str.Length; str = str.Insert(pos,num[randm.Next(1,1000) % 10].ToString()); } // if there is no special character in input // string, add it if (s == 0) { pos = randm.Next(1,1000) % str.Length; str = str.Insert(pos,spl_char[randm.Next( 1,1000) % 7].ToString()); } return str; } /* make_password function :This function is used to check strongness and if input string is not strong, it will suggest*/ static void generate_password(int n, string p) { // flag for lower case, upper case, special // characters and need of more characters int l = 0, u = 0, d = 0, s = 0, need = 0; // password suggestions. string suggest; for (int i = 0; i < n; i++) { // password suggestions. if (p[i] >= 97 && p[i] <= 122) l = 1; else if (p[i] >= 65 && p[i] <= 90) u = 1; else if (p[i] >= 48 && p[i] <= 57) d = 1; else s = 1; } // Check if input string is strong that // means all flag are active. if ((l + u + d + s) == 4) { Console.WriteLine("Your Password is Strong\n"); return; } else Console.WriteLine("Suggested password\n "); /*suggest 10 strong strings */ for (int i = 0; i < 10; i++) { suggest = suggester(l, u, d, s, p); need = 8 - suggest.Length; if (need > 0) suggest = add_more_char(suggest, need); Console.WriteLine(suggest + "\n");; } } // Driver code public static void Main() { string input_string = "geek@2018"; generate_password(input_string.Length, input_string); }} // This code is contributed by Manish Shaw (manishshaw1)
<?php// php code to suggest// strong password // adding more characters to// suggest strong passwordfunction add_more_char( $str, $need){ $pos = 0; // all 26 letters $low_case = "abcdefghijklmnopqrstuvwxyz"; for ($i = 0; $i < $need; $i++) { $pos = rand() % strlen($str); $str[$pos]=$low_case[rand() % 26]; } return $str;} // make powerful stringfunction suggester($l, $u, $d, $s, $str){ // all digits $num = "0123456789"; // all lower case, uppercase and // special characters $low_case = "abcdefghijklmnopqrstuvwxyz"; $up_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // $spl_char1 = "@#$_()!"; // position at which place // a character $pos = 0; // if there is no lowercase char // in input string, add it if ($l == 0) { // generate random integer // under string length $pos = rand() % strlen($str); // generate random integer under // 26 for indexing of a to z $str[$pos]=$low_case[rand() % 26]; } // if there is no upper case // char in input string, add it if ($u == 0) { $pos = rand() % strlen($str); $str[$pos]=$up_case[rand() % 26]; } // if there is no digit // in input string, add it if ($d == 0) { $pos = rand() % strlen($str); $str[$pos]=$num[rand() % 10]; } // if there is no special character // in input string, add it if ($s == 0) { $pos = rand() % strlen($str); $str[$pos]=$spl_char1[rand() % 7]; } return $str;} // Make_password function : This// function is used to check// strongness and if input string// is not strong, it will suggestfunction generate_password($n, $p){ // flag for lower case, upper case, // special characters and need // of more characters $l = 0; $u = 0; $d = 0; $s = 0; $need = 0; // password suggestions. $suggest; for ($i = 0; $i < $n; $i++) { // password suggestions. if ($p[$i] >= 97 && $p[$i] <= 122) $l = 1; else if ($p[$i] >= 65 && $p[$i] <= 90) $u = 1; else if ($p[$i] >= 48 && $p[$i] <= 57) $d = 1; else $s = 1; } // Check if input string is strong // that means all flag are active. if (($l + $u + $d + $s) == 4) { echo "Your Password is Strong.\n"; return; } else echo "Suggested password"; // suggest 10 strong strings for ($i = 0; $i < 10; $i++) { $suggest = suggester($l, $u, $d, $s, $p); $need = 8 - strlen($suggest); if ($need > 0) $suggest = add_more_char($suggest, $need); echo "\n".$suggest; }} // Driver code $input_string = "geek@2018"; srand(mktime(NULL)); // srand function set Seed for rand(). generate_password(strlen($input_string), $input_string); // This code is contributed by mits?>
Suggested password
geek@201K8
geek@201S8
gOeek@2018
geek@201N8
geek@2P018
geek@D2018
geUek@2018
geek@2Q018
geek@2F018
geekZ@2018
Time complexity : O(n).
Mithun Kumar
manishshaw1
arjunsaini9081
simranarora5sos
singghakshay
C++ Programs
Randomized
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++
K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)
Shuffle a given array using FisherβYates shuffle Algorithm
Shuffle or Randomize a list in Java
Generating Random String Using PHP
Estimating the value of Pi using Monte Carlo
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n26 Jul, 2021"
},
{
"code": null,
"e": 158,
"s": 54,
"text": "Given a password entered by the user, check its strength and suggest some password if it is not strong."
},
{
"code": null,
"e": 361,
"s": 158,
"text": "Criteria for strong password is as follows : A password is strong if it has : 1. At least 8 characters 2. At least one special char 3. At least one number 4. At least one upper and one lower case char. "
},
{
"code": null,
"e": 373,
"s": 361,
"text": "Examples : "
},
{
"code": null,
"e": 597,
"s": 373,
"text": "Input : keshav123\nOutput : Suggested Password\nk(eshav12G3\nkeshav1@A23\nkesh!Aav123\nke(shav12V3\nkeGshav1$23\nkesXhav@123\nkeAshav12$3\nkesKhav@123\nkes$hav12N3\n$kesRhav123\n\nInput :rakesh@1995kumar\nOutput : Your Password is Strong"
},
{
"code": null,
"e": 812,
"s": 597,
"text": "Approach : Check the input password for its strength if it fulfills all the criteria, then it is strong password else check for the absent characters in it, and return the randomly generated password to the user. "
},
{
"code": null,
"e": 816,
"s": 812,
"text": "C++"
},
{
"code": null,
"e": 821,
"s": 816,
"text": "Java"
},
{
"code": null,
"e": 829,
"s": 821,
"text": "Python3"
},
{
"code": null,
"e": 832,
"s": 829,
"text": "C#"
},
{
"code": null,
"e": 836,
"s": 832,
"text": "PHP"
},
{
"code": "// CPP code to suggest strong password#include <bits/stdc++.h> using namespace std; // adding more characters to suggest strong passwordstring add_more_char(string str, int need){ int pos = 0; // all 26 letters string low_case = \"abcdefghijklmnopqrstuvwxyz\"; for (int i = 0; i < need; i++) { pos = rand() % str.length(); str.insert(pos, 1, low_case[rand() % 26]); } return str;} // make powerful stringstring suggester(int l, int u, int d, int s, string str){ // all digits string num = \"0123456789\"; // all lower case, uppercase and special characters string low_case = \"abcdefghijklmnopqrstuvwxyz\"; string up_case = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"; string spl_char = \"@#$_()!\"; // position at which place a character int pos = 0; // if there is no lowercase char in input string, add it if (l == 0) { // generate random integer under string length pos = rand() % str.length(); // generate random integer under 26 for indexing of a to z str.insert(pos, 1, low_case[rand() % 26]); } // if there is no upper case char in input string, add it if (u == 0) { pos = rand() % str.length(); str.insert(pos, 1, up_case[rand() % 26]); } // if there is no digit in input string, add it if (d == 0) { pos = rand() % str.length(); str.insert(pos, 1, num[rand() % 10]); } // if there is no special character in input string, add it if (s == 0) { pos = rand() % str.length(); str.insert(pos, 1, spl_char[rand() % 7]); } return str;} /* make_password function :This function is used to checkstrongness and if input string is not strong, it will suggest*/void generate_password(int n, string p){ // flag for lower case, upper case, special // characters and need of more characters int l = 0, u = 0, d = 0, s = 0, need = 0; // password suggestions. string suggest; for (int i = 0; i < n; i++) { // password suggestions. if (p[i] >= 97 && p[i] <= 122) l = 1; else if (p[i] >= 65 && p[i] <= 90) u = 1; else if (p[i] >= 48 && p[i] <= 57) d = 1; else s = 1; } // Check if input string is strong that // means all flag are active. if ((l + u + d + s) == 4) { cout << \"Your Password is Strong\" << endl; return; } else cout << \"Suggested password \" << endl; /*suggest 10 strong strings */ for (int i = 0; i < 10; i++) { suggest = suggester(l, u, d, s, p); need = 8 - suggest.length(); if (need > 0) suggest = add_more_char(suggest, need); cout << suggest << endl; }} // Driver codeint main(){ string input_string = \"geek@2018\"; srand(time(NULL)); // srand function set Seed for rand(). generate_password(input_string.length(), input_string); return 0;}",
"e": 3743,
"s": 836,
"text": null
},
{
"code": "// Java code to suggest strong passwordimport java.io.*;import java.util.*;import java.util.Random; public class GFG { // adding more characters to suggest // strong password static StringBuilder add_more_char( StringBuilder str, int need) { int pos = 0; Random randm = new Random(); // all 26 letters String low_case = \"abcdefghijklmnopqrstuvwxyz\"; for (int i = 0; i < need; i++) { pos = randm.nextInt(1000) % str.length(); str.setCharAt(pos,low_case.charAt( randm.nextInt(1000) % 26)); } return str; } // make powerful String static StringBuilder suggester(int l, int u, int d, int s, StringBuilder str) { Random randm = new Random(); // all digits String num = \"0123456789\"; // all lower case, uppercase and special // characters String low_case = \"abcdefghijklmnopqrstuvwxyz\"; String up_case = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"; String spl_char = \"@#$_()!\"; // position at which place a character int pos = 0; // if there is no lowercase char in input // String, add it if (l == 0) { // generate random integer under // String length() pos = randm.nextInt(1000) % str.length(); // generate random integer under 26 for // indexing of a to z str.setCharAt(pos,low_case.charAt(randm.nextInt(1000) % 26)); } // if there is no upper case char in input // String, add it if (u == 0) { pos = randm.nextInt(1000) % str.length(); str.setCharAt(pos,low_case.charAt(randm.nextInt(1000) % 26)); } // if there is no digit in input String, add it if (d == 0) { pos = randm.nextInt(1000) % str.length(); str.setCharAt(pos,low_case.charAt(randm.nextInt(1000) % 10)); } // if there is no special character in input // String, add it if (s == 0) { pos = randm.nextInt(1000) % str.length(); str.setCharAt(pos,low_case.charAt(randm.nextInt(1000) % 7)); } return str; } /* make_password function :This function is used to check strongness and if input String is not strong, it will suggest*/ static void generate_password(int n, StringBuilder p) { // flag for lower case, upper case, special // characters and need of more characters int l = 0, u = 0, d = 0, s = 0, need = 0; // password suggestions. StringBuilder suggest; for (int i = 0; i < n; i++) { // password suggestions. if (p.charAt(i) >= 97 && p.charAt(i) <= 122) l = 1; else if (p.charAt(i) >= 65 && p.charAt(i) <= 90) u = 1; else if (p.charAt(i) >= 48 && p.charAt(i) <= 57) d = 1; else s = 1; } // Check if input String is strong that // means all flag are active. if ((l + u + d + s) == 4) { System.out.println(\"Your Password is Strong\"); return; } else System.out.println(\"Suggested password \"); /*suggest 10 strong Strings */ for (int i = 0; i < 10; i++) { suggest = suggester(l, u, d, s, p); need = 8 - suggest.length(); if (need > 0) suggest = add_more_char(suggest, need); System.out.println(suggest);; } } // Driver code public static void main(String[] args) { StringBuilder input_String = new StringBuilder(\"geek@2018\"); generate_password(input_String.length(), input_String); }} // This code is contributed by Manish Shaw (manishshaw1)",
"e": 7802,
"s": 3743,
"text": null
},
{
"code": "# Python code to suggest strong password import random # Function to insert character in a string# Because string is immutable in pythondef insert(s, pos, ch): return(s[:pos] + ch + s[pos:]) # adding more characters to# suggest strong passworddef add_more_char(s, need): pos = 0 # add 26 letters low_case = \"abcdefghijklmnopqrstuvwxyz\" for i in range(need): pos = random.randint(0, len(s)-1) s = insert(s, pos, low_case[random.randint(0,25)]) return(s) # Make powerful stringdef suggester(l, u, d, s, st): # all digits num = '0123456789' # all lower case, upper case and special characters low_case = \"abcdefghijklmnopqrstuvwxyz\" up_case = low_case.upper() spl_char = '@#$_()!' # Position at which place a character pos = 0 # If there is no lowercase char # in input string, add it if( l == 0 ): # Generate random integer under string length pos = random.randint(0,len(st)-1) # Generate random integer under 26 for indexing of a to z st = insert(st, pos, low_case[random.randint(0,25)]) # If there is no upper case char in input string, add it if( u == 0 ): # Generate random integer under string length pos = random.randint(0,len(st)-1) # Generate random integer under 26 for indexing of A to Z st = insert(st, pos, up_case[random.randint(0,25)]) # If there is no digit in input string, add it if( d == 0 ): # Generate random integer under string length pos = random.randint(0,len(st)-1) # Generate random integer under 10 for indexing of 0 to 9 st = insert(st, pos, num[random.randint(0,9)]) # If there is no special character # in input string, add it if( s == 0 ): # Generate random integer under string length pos = random.randint(0,len(st)-1) # Generate random integer under 7 for # indexing of special characters st = insert(st, pos, low_case[random.randint(0,6)]) return st # generate_password function : This function is used to check# strength and if input string is not strong, It will suggestdef generate_password(n, p): # flag for lower case, upper case, special # characters and need of more characters l = 0; u = 0; d = 0; s = 0; need = 0 # Password suggestions suggest = '' for i in range(n): # Password suggestion if( p[i].islower() ): l = 1 elif( p[i].isupper() ): u = 1 elif( p[i].isdigit() ): d = 1 else: s = 1 # Check if input string is strong that # means all flags are active if( (l + u + d + s) == 4): print(\"Your Password is Strong\") return else: print(\"Suggested Passwords\") # Suggest 10 strong strings for i in range(10): suggest = suggester(l, u, d, s, p) need = 8 - len(suggest) if(need > 0): suggest = add_more_char(suggest, need) print(suggest) # Driver Codeinput_string = 'geek@2018' generate_password( len(input_string), input_string) # This code is contributed by Arjun Saini",
"e": 11439,
"s": 7802,
"text": null
},
{
"code": "// C# code to suggest strong passwordusing System;using System.Collections.Generic; class GFG { // adding more characters to suggest // strong password static string add_more_char(string str, int need) { int pos = 0; Random randm = new Random(); // all 26 letters string low_case = \"abcdefghijklmnopqrstuvwxyz\"; for (int i = 0; i < need; i++) { pos = randm.Next(1,1000) % str.Length; str = str.Insert(pos,low_case[randm.Next(1000) % 26].ToString()); } return str; } // make powerful string static string suggester(int l, int u, int d, int s, string str) { Random randm = new Random(); // all digits string num = \"0123456789\"; // all lower case, uppercase and special // characters string low_case = \"abcdefghijklmnopqrstuvwxyz\"; string up_case = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"; string spl_char = \"@#$_()!\"; // position at which place a character int pos = 0; // if there is no lowercase char in input // string, add it if (l == 0) { // generate random integer under // string length pos = randm.Next(1,1000) % str.Length; // generate random integer under 26 for // indexing of a to z str = str.Insert(pos,low_case[randm.Next(1, 1000) % 26].ToString()); } // if there is no upper case char in input // string, add it if (u == 0) { pos = randm.Next(1,1000) % str.Length; str = str.Insert(pos,up_case[randm.Next( 1,1000) % 26].ToString()); } // if there is no digit in input string, add it if (d == 0) { pos = randm.Next(1,1000) % str.Length; str = str.Insert(pos,num[randm.Next(1,1000) % 10].ToString()); } // if there is no special character in input // string, add it if (s == 0) { pos = randm.Next(1,1000) % str.Length; str = str.Insert(pos,spl_char[randm.Next( 1,1000) % 7].ToString()); } return str; } /* make_password function :This function is used to check strongness and if input string is not strong, it will suggest*/ static void generate_password(int n, string p) { // flag for lower case, upper case, special // characters and need of more characters int l = 0, u = 0, d = 0, s = 0, need = 0; // password suggestions. string suggest; for (int i = 0; i < n; i++) { // password suggestions. if (p[i] >= 97 && p[i] <= 122) l = 1; else if (p[i] >= 65 && p[i] <= 90) u = 1; else if (p[i] >= 48 && p[i] <= 57) d = 1; else s = 1; } // Check if input string is strong that // means all flag are active. if ((l + u + d + s) == 4) { Console.WriteLine(\"Your Password is Strong\\n\"); return; } else Console.WriteLine(\"Suggested password\\n \"); /*suggest 10 strong strings */ for (int i = 0; i < 10; i++) { suggest = suggester(l, u, d, s, p); need = 8 - suggest.Length; if (need > 0) suggest = add_more_char(suggest, need); Console.WriteLine(suggest + \"\\n\");; } } // Driver code public static void Main() { string input_string = \"geek@2018\"; generate_password(input_string.Length, input_string); }} // This code is contributed by Manish Shaw (manishshaw1)",
"e": 15337,
"s": 11439,
"text": null
},
{
"code": "<?php// php code to suggest// strong password // adding more characters to// suggest strong passwordfunction add_more_char( $str, $need){ $pos = 0; // all 26 letters $low_case = \"abcdefghijklmnopqrstuvwxyz\"; for ($i = 0; $i < $need; $i++) { $pos = rand() % strlen($str); $str[$pos]=$low_case[rand() % 26]; } return $str;} // make powerful stringfunction suggester($l, $u, $d, $s, $str){ // all digits $num = \"0123456789\"; // all lower case, uppercase and // special characters $low_case = \"abcdefghijklmnopqrstuvwxyz\"; $up_case = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"; // $spl_char1 = \"@#$_()!\"; // position at which place // a character $pos = 0; // if there is no lowercase char // in input string, add it if ($l == 0) { // generate random integer // under string length $pos = rand() % strlen($str); // generate random integer under // 26 for indexing of a to z $str[$pos]=$low_case[rand() % 26]; } // if there is no upper case // char in input string, add it if ($u == 0) { $pos = rand() % strlen($str); $str[$pos]=$up_case[rand() % 26]; } // if there is no digit // in input string, add it if ($d == 0) { $pos = rand() % strlen($str); $str[$pos]=$num[rand() % 10]; } // if there is no special character // in input string, add it if ($s == 0) { $pos = rand() % strlen($str); $str[$pos]=$spl_char1[rand() % 7]; } return $str;} // Make_password function : This// function is used to check// strongness and if input string// is not strong, it will suggestfunction generate_password($n, $p){ // flag for lower case, upper case, // special characters and need // of more characters $l = 0; $u = 0; $d = 0; $s = 0; $need = 0; // password suggestions. $suggest; for ($i = 0; $i < $n; $i++) { // password suggestions. if ($p[$i] >= 97 && $p[$i] <= 122) $l = 1; else if ($p[$i] >= 65 && $p[$i] <= 90) $u = 1; else if ($p[$i] >= 48 && $p[$i] <= 57) $d = 1; else $s = 1; } // Check if input string is strong // that means all flag are active. if (($l + $u + $d + $s) == 4) { echo \"Your Password is Strong.\\n\"; return; } else echo \"Suggested password\"; // suggest 10 strong strings for ($i = 0; $i < 10; $i++) { $suggest = suggester($l, $u, $d, $s, $p); $need = 8 - strlen($suggest); if ($need > 0) $suggest = add_more_char($suggest, $need); echo \"\\n\".$suggest; }} // Driver code $input_string = \"geek@2018\"; srand(mktime(NULL)); // srand function set Seed for rand(). generate_password(strlen($input_string), $input_string); // This code is contributed by mits?>",
"e": 18277,
"s": 15337,
"text": null
},
{
"code": null,
"e": 18407,
"s": 18277,
"text": "Suggested password \ngeek@201K8\ngeek@201S8\ngOeek@2018\ngeek@201N8\ngeek@2P018\ngeek@D2018\ngeUek@2018\ngeek@2Q018\ngeek@2F018\ngeekZ@2018"
},
{
"code": null,
"e": 18435,
"s": 18409,
"text": "Time complexity : O(n). "
},
{
"code": null,
"e": 18448,
"s": 18435,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 18460,
"s": 18448,
"text": "manishshaw1"
},
{
"code": null,
"e": 18475,
"s": 18460,
"text": "arjunsaini9081"
},
{
"code": null,
"e": 18491,
"s": 18475,
"text": "simranarora5sos"
},
{
"code": null,
"e": 18504,
"s": 18491,
"text": "singghakshay"
},
{
"code": null,
"e": 18517,
"s": 18504,
"text": "C++ Programs"
},
{
"code": null,
"e": 18528,
"s": 18517,
"text": "Randomized"
},
{
"code": null,
"e": 18536,
"s": 18528,
"text": "Strings"
},
{
"code": null,
"e": 18544,
"s": 18536,
"text": "Strings"
},
{
"code": null,
"e": 18642,
"s": 18544,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 18677,
"s": 18642,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 18711,
"s": 18677,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 18755,
"s": 18711,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 18814,
"s": 18755,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 18848,
"s": 18814,
"text": "Shallow Copy and Deep Copy in C++"
},
{
"code": null,
"e": 18927,
"s": 18848,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)"
},
{
"code": null,
"e": 18986,
"s": 18927,
"text": "Shuffle a given array using FisherβYates shuffle Algorithm"
},
{
"code": null,
"e": 19022,
"s": 18986,
"text": "Shuffle or Randomize a list in Java"
},
{
"code": null,
"e": 19057,
"s": 19022,
"text": "Generating Random String Using PHP"
}
] |
How to create a basic application in Java Spring Boot
|
28 Jan, 2022
Spring MVC is a widely used module of spring which is used to create scalable web applications. But the main disadvantage of spring projects is that configuration is really time-consuming and can be a bit overwhelming for the new developers. Making the application production-ready takes some time if you are new to the spring. The solution to this is Spring Boot. Spring Boot is built on the top of the spring and contains all the features of spring. In this article, we will see how to create a basic spring boot application.Spring Initializr is a web-based tool using which we can easily generate the structure of the Spring Boot project. It also provides various different features for the projects expressed in a metadata model. This model allows us to configure the list of dependencies which are supported by JVM. Here, we will create the structure of an application using spring initializr and then use an IDE to create a sample GET route. Therefore, to do this, the following steps are followed:
Go to Spring InitializrFill in the details as per the requirements. For this application:
Go to Spring Initializr
Fill in the details as per the requirements. For this application:
Project: Maven Language: Java Spring Boot: 2.2.8 Packaging: JAR Java: 8 Dependencies: Spring Web
Click on Generate which will download the starter project.
Click on Generate which will download the starter project.
Extract the zip file. Now open a suitable IDE and then go to File->New->Project from existing sources->Spring-boot-app and select pom.xml. Click on import changes on prompt and wait for the project to sync.
Extract the zip file. Now open a suitable IDE and then go to File->New->Project from existing sources->Spring-boot-app and select pom.xml. Click on import changes on prompt and wait for the project to sync.
Note: In the Import Project for Maven window, make sure you choose the same version of JDK which you selected while creating the project.Go to src->main->java->com.gfg.Spring.boot.app, create a java class with name as Controller and add the annotation @RestController. Now create a GET API as shown below:
Note: In the Import Project for Maven window, make sure you choose the same version of JDK which you selected while creating the project.
Go to src->main->java->com.gfg.Spring.boot.app, create a java class with name as Controller and add the annotation @RestController. Now create a GET API as shown below:
Java
@RestControllerpublic class Controller { // One syntax to implement a // GET method @GetMapping("/") public String home() { String str = "<html><body><font color=\"green\">" + "<h1>WELCOME To GeeksForGeeks</h1>" + "</font></body></html>"; return str; } // Another syntax to implement a // GET method @RequestMapping( method = { RequestMethod.GET }, value = { "/gfg" }) public String info() { String str2 = "<html><body><font color=\"green\">" + "<h2>GeeksForGeeks is a Computer" + " Science portal for Geeks. " + "This portal has been " + "created to provide well written, " + "well thought and well explained " + "solutions for selected questions." + "</h2></font></body></html>"; return str2; }}
This application is now ready to run. Run the SpringBootAppApplication class and wait for the Tomcat server to start.
This application is now ready to run. Run the SpringBootAppApplication class and wait for the Tomcat server to start.
Note: The default port of the Tomcat server is 8080 and can be changed in the application.properties file.Now go to the browser and enter the URL localhost:8080. Observe the output and now do the same for localhost:8080/gfg
Note: The default port of the Tomcat server is 8080 and can be changed in the application.properties file.
Now go to the browser and enter the URL localhost:8080. Observe the output and now do the same for localhost:8080/gfg
Output: On running the above application, the following output is generated:
Conclusion: By following the above steps, we have created a simple RESTful route with some message in it. In order to make a more complex application, more RESTful routes are added to perform the CRUD operations on the server.
AakashYadav4
germanshephered48
java-advanced
Java-Spring
Web-Programs
Java Programs
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate Over the Characters of a String in Java
How to Convert Char to String in Java?
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
How to Write Data into Excel Sheet using Java?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jan, 2022"
},
{
"code": null,
"e": 1035,
"s": 28,
"text": "Spring MVC is a widely used module of spring which is used to create scalable web applications. But the main disadvantage of spring projects is that configuration is really time-consuming and can be a bit overwhelming for the new developers. Making the application production-ready takes some time if you are new to the spring. The solution to this is Spring Boot. Spring Boot is built on the top of the spring and contains all the features of spring. In this article, we will see how to create a basic spring boot application.Spring Initializr is a web-based tool using which we can easily generate the structure of the Spring Boot project. It also provides various different features for the projects expressed in a metadata model. This model allows us to configure the list of dependencies which are supported by JVM. Here, we will create the structure of an application using spring initializr and then use an IDE to create a sample GET route. Therefore, to do this, the following steps are followed: "
},
{
"code": null,
"e": 1127,
"s": 1035,
"text": "Go to Spring InitializrFill in the details as per the requirements. For this application: "
},
{
"code": null,
"e": 1151,
"s": 1127,
"text": "Go to Spring Initializr"
},
{
"code": null,
"e": 1220,
"s": 1151,
"text": "Fill in the details as per the requirements. For this application: "
},
{
"code": null,
"e": 1319,
"s": 1220,
"text": "Project: Maven Language: Java Spring Boot: 2.2.8 Packaging: JAR Java: 8 Dependencies: Spring Web "
},
{
"code": null,
"e": 1380,
"s": 1319,
"text": "Click on Generate which will download the starter project. "
},
{
"code": null,
"e": 1441,
"s": 1380,
"text": "Click on Generate which will download the starter project. "
},
{
"code": null,
"e": 1650,
"s": 1441,
"text": "Extract the zip file. Now open a suitable IDE and then go to File->New->Project from existing sources->Spring-boot-app and select pom.xml. Click on import changes on prompt and wait for the project to sync. "
},
{
"code": null,
"e": 1859,
"s": 1650,
"text": "Extract the zip file. Now open a suitable IDE and then go to File->New->Project from existing sources->Spring-boot-app and select pom.xml. Click on import changes on prompt and wait for the project to sync. "
},
{
"code": null,
"e": 2166,
"s": 1859,
"text": "Note: In the Import Project for Maven window, make sure you choose the same version of JDK which you selected while creating the project.Go to src->main->java->com.gfg.Spring.boot.app, create a java class with name as Controller and add the annotation @RestController. Now create a GET API as shown below: "
},
{
"code": null,
"e": 2304,
"s": 2166,
"text": "Note: In the Import Project for Maven window, make sure you choose the same version of JDK which you selected while creating the project."
},
{
"code": null,
"e": 2474,
"s": 2304,
"text": "Go to src->main->java->com.gfg.Spring.boot.app, create a java class with name as Controller and add the annotation @RestController. Now create a GET API as shown below: "
},
{
"code": null,
"e": 2479,
"s": 2474,
"text": "Java"
},
{
"code": "@RestControllerpublic class Controller { // One syntax to implement a // GET method @GetMapping(\"/\") public String home() { String str = \"<html><body><font color=\\\"green\\\">\" + \"<h1>WELCOME To GeeksForGeeks</h1>\" + \"</font></body></html>\"; return str; } // Another syntax to implement a // GET method @RequestMapping( method = { RequestMethod.GET }, value = { \"/gfg\" }) public String info() { String str2 = \"<html><body><font color=\\\"green\\\">\" + \"<h2>GeeksForGeeks is a Computer\" + \" Science portal for Geeks. \" + \"This portal has been \" + \"created to provide well written, \" + \"well thought and well explained \" + \"solutions for selected questions.\" + \"</h2></font></body></html>\"; return str2; }}",
"e": 3397,
"s": 2479,
"text": null
},
{
"code": null,
"e": 3516,
"s": 3397,
"text": "This application is now ready to run. Run the SpringBootAppApplication class and wait for the Tomcat server to start. "
},
{
"code": null,
"e": 3635,
"s": 3516,
"text": "This application is now ready to run. Run the SpringBootAppApplication class and wait for the Tomcat server to start. "
},
{
"code": null,
"e": 3859,
"s": 3635,
"text": "Note: The default port of the Tomcat server is 8080 and can be changed in the application.properties file.Now go to the browser and enter the URL localhost:8080. Observe the output and now do the same for localhost:8080/gfg"
},
{
"code": null,
"e": 3966,
"s": 3859,
"text": "Note: The default port of the Tomcat server is 8080 and can be changed in the application.properties file."
},
{
"code": null,
"e": 4084,
"s": 3966,
"text": "Now go to the browser and enter the URL localhost:8080. Observe the output and now do the same for localhost:8080/gfg"
},
{
"code": null,
"e": 4162,
"s": 4084,
"text": "Output: On running the above application, the following output is generated: "
},
{
"code": null,
"e": 4389,
"s": 4162,
"text": "Conclusion: By following the above steps, we have created a simple RESTful route with some message in it. In order to make a more complex application, more RESTful routes are added to perform the CRUD operations on the server."
},
{
"code": null,
"e": 4402,
"s": 4389,
"text": "AakashYadav4"
},
{
"code": null,
"e": 4420,
"s": 4402,
"text": "germanshephered48"
},
{
"code": null,
"e": 4434,
"s": 4420,
"text": "java-advanced"
},
{
"code": null,
"e": 4446,
"s": 4434,
"text": "Java-Spring"
},
{
"code": null,
"e": 4459,
"s": 4446,
"text": "Web-Programs"
},
{
"code": null,
"e": 4473,
"s": 4459,
"text": "Java Programs"
},
{
"code": null,
"e": 4490,
"s": 4473,
"text": "Web Technologies"
},
{
"code": null,
"e": 4588,
"s": 4490,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4636,
"s": 4588,
"text": "Iterate Over the Characters of a String in Java"
},
{
"code": null,
"e": 4675,
"s": 4636,
"text": "How to Convert Char to String in Java?"
},
{
"code": null,
"e": 4726,
"s": 4675,
"text": "How to Get Elements By Index from HashSet in Java?"
},
{
"code": null,
"e": 4760,
"s": 4726,
"text": "Java Program to Write into a File"
},
{
"code": null,
"e": 4807,
"s": 4760,
"text": "How to Write Data into Excel Sheet using Java?"
},
{
"code": null,
"e": 4869,
"s": 4807,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4902,
"s": 4869,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4963,
"s": 4902,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5013,
"s": 4963,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Puzzle 5 | (Finding the Injection for Anesthesia)
|
24 Feb, 2022
In a Medical Laboratory, you have 240 Injections, one of which is for Anesthesia for a rat. If Anesthesia injection is injected in a rat, it will faint in within 24 hours. You have 5 rats available to determine which one injection contains the Anesthesia. How do you achieve this in 48 hours ?
Solution: Let us number the each injection with unique 5 digit numbers consisting of only 0, 1 and 2. Let us number the Rats as 1, 10, 100, 1000, 10000.
The action corresponding to the digit in the unit place will be executed by rat numbered 1. The action corresponding to the digit in the tenth place will be executed by rat numbered 10. The action corresponding to the digit in the 100th place will be executed by rat numbered 100. The action corresponding to the digit in the 1000th place will be executed by rat numbered 1000. The action corresponding to the digit in the 10000th place will be executed by rat numbered 10000.
Number 0 on an Injection represents that the injection will not be injected to rat. Number 1 on an Injection represents that the injection will be injected to rat on 1st day. Number 2 on an Injection represents that the injection will be injected to rat on 2nd day (after 24 hours).
Example: Let us say the Injection is numbered 11201. The Injections is injected on the first day to rat numbered 10000, 1000 and 1. It is injected on the second day to rat numbered 100. And it is not injected to rat numbered 10.
So if the rats numbered 10000, 1000 and 1 faint within first 24 hours, rat numbered 100 faints in the next 24 hours and the rat numbered 10 does not faint, then the Anesthesia Injection has to be 11201.
Total number of injections that can be tested in this way will be:
= 3 * 3 * 3 * 3 * 3 = 3^5 = 243 Injections
So with the help of 5 rats and within 48 hours we will be able to find a Anesthesia Injection among 243 Injections.
Note β The language of this puzzle has been changed: rats from slaves, Anesthesia injection from poison, faint from death, etc.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=NRSk7hUblos" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
SHREYAS6652
Chandan
akshi2
trilokeshtarala18
Puzzles
Puzzles
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Top 20 Puzzles Commonly Asked During SDE Interviews
Puzzle 21 | (3 Ants and Triangle)
Puzzle 24 | (10 Coins Puzzle)
Container with Most Water
Puzzle | Set 35 (2 Eggs and 100 Floors)
Puzzle 31 | (Minimum cut Puzzle)
Puzzle | Heaven and Hell
Puzzle | 3 cuts to cut round cake into 8 equal pieces
Puzzle 27 | (Hourglasses Puzzle)
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Feb, 2022"
},
{
"code": null,
"e": 347,
"s": 52,
"text": "In a Medical Laboratory, you have 240 Injections, one of which is for Anesthesia for a rat. If Anesthesia injection is injected in a rat, it will faint in within 24 hours. You have 5 rats available to determine which one injection contains the Anesthesia. How do you achieve this in 48 hours ? "
},
{
"code": null,
"e": 502,
"s": 347,
"text": "Solution: Let us number the each injection with unique 5 digit numbers consisting of only 0, 1 and 2. Let us number the Rats as 1, 10, 100, 1000, 10000. "
},
{
"code": null,
"e": 979,
"s": 502,
"text": "The action corresponding to the digit in the unit place will be executed by rat numbered 1. The action corresponding to the digit in the tenth place will be executed by rat numbered 10. The action corresponding to the digit in the 100th place will be executed by rat numbered 100. The action corresponding to the digit in the 1000th place will be executed by rat numbered 1000. The action corresponding to the digit in the 10000th place will be executed by rat numbered 10000."
},
{
"code": null,
"e": 1263,
"s": 979,
"text": "Number 0 on an Injection represents that the injection will not be injected to rat. Number 1 on an Injection represents that the injection will be injected to rat on 1st day. Number 2 on an Injection represents that the injection will be injected to rat on 2nd day (after 24 hours). "
},
{
"code": null,
"e": 1493,
"s": 1263,
"text": "Example: Let us say the Injection is numbered 11201. The Injections is injected on the first day to rat numbered 10000, 1000 and 1. It is injected on the second day to rat numbered 100. And it is not injected to rat numbered 10. "
},
{
"code": null,
"e": 1697,
"s": 1493,
"text": "So if the rats numbered 10000, 1000 and 1 faint within first 24 hours, rat numbered 100 faints in the next 24 hours and the rat numbered 10 does not faint, then the Anesthesia Injection has to be 11201. "
},
{
"code": null,
"e": 1764,
"s": 1697,
"text": "Total number of injections that can be tested in this way will be:"
},
{
"code": null,
"e": 1808,
"s": 1764,
"text": "= 3 * 3 * 3 * 3 * 3 = 3^5 = 243 Injections "
},
{
"code": null,
"e": 1926,
"s": 1808,
"text": "So with the help of 5 rats and within 48 hours we will be able to find a Anesthesia Injection among 243 Injections. "
},
{
"code": null,
"e": 2055,
"s": 1926,
"text": "Note β The language of this puzzle has been changed: rats from slaves, Anesthesia injection from poison, faint from death, etc. "
},
{
"code": null,
"e": 2181,
"s": 2055,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 2473,
"s": 2181,
"text": "YouTube<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=NRSk7hUblos\" 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": 2485,
"s": 2473,
"text": "SHREYAS6652"
},
{
"code": null,
"e": 2493,
"s": 2485,
"text": "Chandan"
},
{
"code": null,
"e": 2500,
"s": 2493,
"text": "akshi2"
},
{
"code": null,
"e": 2518,
"s": 2500,
"text": "trilokeshtarala18"
},
{
"code": null,
"e": 2526,
"s": 2518,
"text": "Puzzles"
},
{
"code": null,
"e": 2534,
"s": 2526,
"text": "Puzzles"
},
{
"code": null,
"e": 2632,
"s": 2534,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2664,
"s": 2632,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 2716,
"s": 2664,
"text": "Top 20 Puzzles Commonly Asked During SDE Interviews"
},
{
"code": null,
"e": 2750,
"s": 2716,
"text": "Puzzle 21 | (3 Ants and Triangle)"
},
{
"code": null,
"e": 2780,
"s": 2750,
"text": "Puzzle 24 | (10 Coins Puzzle)"
},
{
"code": null,
"e": 2806,
"s": 2780,
"text": "Container with Most Water"
},
{
"code": null,
"e": 2846,
"s": 2806,
"text": "Puzzle | Set 35 (2 Eggs and 100 Floors)"
},
{
"code": null,
"e": 2879,
"s": 2846,
"text": "Puzzle 31 | (Minimum cut Puzzle)"
},
{
"code": null,
"e": 2904,
"s": 2879,
"text": "Puzzle | Heaven and Hell"
},
{
"code": null,
"e": 2958,
"s": 2904,
"text": "Puzzle | 3 cuts to cut round cake into 8 equal pieces"
}
] |
Node.js Event Loop
|
11 Oct, 2021
Node.js is a single-threaded event-driven platform that is capable of running non-blocking, asynchronously programming. These functionalities of Node.js make it memory efficient. The event loop allows Node.js to perform non-blocking I/O operations despite the fact that JavaScript is single-threaded. It is done by assigning operations to the operating system whenever and wherever possible.
Most operating systems are multi-threaded and hence can handle multiple operations executing in the background. When one of these operations is completed, the kernel tells Node.js and the respective callback assigned to that operation is added to the event queue which will eventually be executed. This will be explained further in detail later in this topic.
Features of Event Loop:
Event loop is an endless loop, which waits for tasks, executes them and then sleeps until it receives more tasks.
The event loop executes tasks from the event queue only when the call stack is empty i.e. there is no ongoing task.
The event loop allows us to use callbacks and promises.
The event loop executes the tasks starting from the oldest first.
Example:
console.log("This is the first statement"); setTimeout(function(){ console.log("This is the second statement");}, 1000); console.log("This is the third statement");
Output:
This is the first statement
This is the third statement
This is the second statement
Explanation: In the above example, the first console log statement is pushed to the call stack and βThis is the first statementβ is logged on the console and the task is popped from the stack. Next, the setTimeout is pushed to the queue and the task is sent to the Operating system and the timer is set for the task. This task is then popped from the stack. Next, the third console log statement is pushed to the call stack and βThis is the third statementβ is logged on the console and the task is popped from the stack.
When the timer set by setTimeout function (in this case 1000 ms) runs out, the callback is sent to the event queue. The event loop on finding the call stack empty takes the task at the top of the event queue and sends it to the call stack. The callback function for setTimeout function runs the instruction and βThis is the second statementβ is logged on the console and the task is popped from the stack.
Note: In the above case, if the timeout was set to 0ms then also the statements will be displayed in the same order. This is because although the callback with be immediately sent to the event queue, the event loop wonβt send it to the call stack unless the call stack is empty i.e. until the provided input script comes to an end.
Working of the Event loop: When Node.js starts, it initializes the event loop, processes the provided input script which may make async API calls, schedule timers, then begins processing the event loop. In the previous example, the initial input script consisted of console.log() statements and a setTimeout() function which schedules a timer.
When using Node.js, a special library module called libuv is used to perform async operations. This library is also used, together with the back logic of Node, to manage a special thread pool called the libuv thread pool.This thread pool is composed of four threads used to delegate operations that are too heavy for the event loop. I/O operations, Opening and closing connections, setTimeouts are the example of such operations.
When the thread pool completes a task, a callback function is called which handles the error(if any) or does some other operation. This callback function is sent to the event queue. When the call stack is empty, the event goes through the event queue and sends the callback to the call stack.
The following diagram is a proper representation of the event loop in a Node.js server:
Phases of the Event loop: The following diagram shows a simplified overview of the event loop order of operations:
Timers: Callbacks scheduled by setTimeout() or setInterval() are executed in this phase.
Pending Callbacks: I/O callbacks deferred to the next loop iteration are executed here.
Idle, Prepare: Used internally only.
Poll: Retrieves new I/O events.
Check: It invokes setIntermediate() callbacks.
Close Callbacks: It handles some close callbacks. Eg: socket.on(βcloseβ, ...)
Node.js-Basics
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 444,
"s": 52,
"text": "Node.js is a single-threaded event-driven platform that is capable of running non-blocking, asynchronously programming. These functionalities of Node.js make it memory efficient. The event loop allows Node.js to perform non-blocking I/O operations despite the fact that JavaScript is single-threaded. It is done by assigning operations to the operating system whenever and wherever possible."
},
{
"code": null,
"e": 804,
"s": 444,
"text": "Most operating systems are multi-threaded and hence can handle multiple operations executing in the background. When one of these operations is completed, the kernel tells Node.js and the respective callback assigned to that operation is added to the event queue which will eventually be executed. This will be explained further in detail later in this topic."
},
{
"code": null,
"e": 828,
"s": 804,
"text": "Features of Event Loop:"
},
{
"code": null,
"e": 942,
"s": 828,
"text": "Event loop is an endless loop, which waits for tasks, executes them and then sleeps until it receives more tasks."
},
{
"code": null,
"e": 1058,
"s": 942,
"text": "The event loop executes tasks from the event queue only when the call stack is empty i.e. there is no ongoing task."
},
{
"code": null,
"e": 1114,
"s": 1058,
"text": "The event loop allows us to use callbacks and promises."
},
{
"code": null,
"e": 1180,
"s": 1114,
"text": "The event loop executes the tasks starting from the oldest first."
},
{
"code": null,
"e": 1189,
"s": 1180,
"text": "Example:"
},
{
"code": "console.log(\"This is the first statement\"); setTimeout(function(){ console.log(\"This is the second statement\");}, 1000); console.log(\"This is the third statement\"); ",
"e": 1362,
"s": 1189,
"text": null
},
{
"code": null,
"e": 1370,
"s": 1362,
"text": "Output:"
},
{
"code": null,
"e": 1455,
"s": 1370,
"text": "This is the first statement\nThis is the third statement\nThis is the second statement"
},
{
"code": null,
"e": 1977,
"s": 1455,
"text": "Explanation: In the above example, the first console log statement is pushed to the call stack and βThis is the first statementβ is logged on the console and the task is popped from the stack. Next, the setTimeout is pushed to the queue and the task is sent to the Operating system and the timer is set for the task. This task is then popped from the stack. Next, the third console log statement is pushed to the call stack and βThis is the third statementβ is logged on the console and the task is popped from the stack."
},
{
"code": null,
"e": 2383,
"s": 1977,
"text": "When the timer set by setTimeout function (in this case 1000 ms) runs out, the callback is sent to the event queue. The event loop on finding the call stack empty takes the task at the top of the event queue and sends it to the call stack. The callback function for setTimeout function runs the instruction and βThis is the second statementβ is logged on the console and the task is popped from the stack."
},
{
"code": null,
"e": 2715,
"s": 2383,
"text": "Note: In the above case, if the timeout was set to 0ms then also the statements will be displayed in the same order. This is because although the callback with be immediately sent to the event queue, the event loop wonβt send it to the call stack unless the call stack is empty i.e. until the provided input script comes to an end."
},
{
"code": null,
"e": 3059,
"s": 2715,
"text": "Working of the Event loop: When Node.js starts, it initializes the event loop, processes the provided input script which may make async API calls, schedule timers, then begins processing the event loop. In the previous example, the initial input script consisted of console.log() statements and a setTimeout() function which schedules a timer."
},
{
"code": null,
"e": 3489,
"s": 3059,
"text": "When using Node.js, a special library module called libuv is used to perform async operations. This library is also used, together with the back logic of Node, to manage a special thread pool called the libuv thread pool.This thread pool is composed of four threads used to delegate operations that are too heavy for the event loop. I/O operations, Opening and closing connections, setTimeouts are the example of such operations."
},
{
"code": null,
"e": 3782,
"s": 3489,
"text": "When the thread pool completes a task, a callback function is called which handles the error(if any) or does some other operation. This callback function is sent to the event queue. When the call stack is empty, the event goes through the event queue and sends the callback to the call stack."
},
{
"code": null,
"e": 3870,
"s": 3782,
"text": "The following diagram is a proper representation of the event loop in a Node.js server:"
},
{
"code": null,
"e": 3985,
"s": 3870,
"text": "Phases of the Event loop: The following diagram shows a simplified overview of the event loop order of operations:"
},
{
"code": null,
"e": 4074,
"s": 3985,
"text": "Timers: Callbacks scheduled by setTimeout() or setInterval() are executed in this phase."
},
{
"code": null,
"e": 4162,
"s": 4074,
"text": "Pending Callbacks: I/O callbacks deferred to the next loop iteration are executed here."
},
{
"code": null,
"e": 4199,
"s": 4162,
"text": "Idle, Prepare: Used internally only."
},
{
"code": null,
"e": 4231,
"s": 4199,
"text": "Poll: Retrieves new I/O events."
},
{
"code": null,
"e": 4278,
"s": 4231,
"text": "Check: It invokes setIntermediate() callbacks."
},
{
"code": null,
"e": 4356,
"s": 4278,
"text": "Close Callbacks: It handles some close callbacks. Eg: socket.on(βcloseβ, ...)"
},
{
"code": null,
"e": 4371,
"s": 4356,
"text": "Node.js-Basics"
},
{
"code": null,
"e": 4378,
"s": 4371,
"text": "Picked"
},
{
"code": null,
"e": 4386,
"s": 4378,
"text": "Node.js"
},
{
"code": null,
"e": 4403,
"s": 4386,
"text": "Web Technologies"
}
] |
Major Google Algorithms
|
28 Jul, 2020
Google Algorithms are used to give the best possible outcome or result whenever someone searches something on Google. Not only one but it uses several algorithms to perform this task and it also checks for the rank of the web pages which is delivered after the task. Google is making a vast change in its algorithm at a very frequent period.
Some of Google updates are as follows:
Panda update
Payday Loan Algorithm
Penguin Update
Hummingbird update
Mobile Update
Rank Brain Possum
Update Fred Pigeon
Page Layout Algorithm
Exact Match Domain
The focus of these updates was to improve the quality of sites and content that is going to show up on Google.
1. Panda Update: It is one of Googleβs official algorithm update. This update was done to reduce the low-quality data because in 2009 after the caffeine update the low-quality data also became part of the search results. To reduce that google make a new update and named its Panda. In panda, the pages were given a quality parameter based on the rating given by humans to the pages. So panda eliminates the low-quality content and promotes high quality and user-friendly pages.
2. Payday Loan Algorithm: This algorithm was released in 2013, cause at that time the spam in Google was increasing. So to reduce Spam websites from Google search results this algorithm was introduced. This was one of the important updates by Google, which targeted Spam queries which were related to super high-interest loans and other heavily spammed queries.
3. Penguin Update: It was launched in 2012, the same as panda this algorithm also used to promote high-quality data in search results and also to not show the spammy content or low-quality data. This algorithm is an extension of the panda which works on reducing the effectiveness of black hat techniques, that were used to promote the low-quality pages in the search results of Google. The main task of the penguin algorithm was to show the relevant, real, and genuine result websites, and the spam my websites were downgraded.
4. Hummingbird Update: This update was launched on 22 August 2013, its main work is to show the query that query on the internet which may not have the same word. It mainly focuses on the intention of the searcher. So hummingbird algorithm is important because sometimes grammatical mistakes occur during typing and results did not show up so this was corrected by using this algorithm.
5. Mobile Update: As the name suggests this algorithm is for mobile search, its task is to show the Mobile-friendly pages on the top when searched from a mobile. This was launched on 21 st April 2015. The top results will be mobile optimized, and those who are not optimized will be downgraded.
6. Rank Brain: It is a machine learning algorithm. It is kind of similar to a hummingbird, its a machine learning from which Google understand and shows the best result. It is one of the important algorithms of Google and was launched on 26 October 2015.
7. Possum Update: This algorithm is mainly based on the location, it will show the local result according to the location. The nearer you are to the business address, the more chances that you will see it in your search result, and the result may vary on different locations for local addresses. This was launched on 1 September 2016.
8. Fred: One of the latest updates in Google and was launched on 8 March 2017. Its main focus is to target websites that have less content and more ads or you can say the websites having focus is on generating revenue with low-class content. Small websites and blogs are focused on this update.
9. Pigeon: This update was launched by Google on 24th July 2014 in the US and 22 DEC 2014 in UK, Canada, Australia. This update mainly links with those searches on Google in which the location of the user is mainly focused. SEO is used to show local results in an area. So to rank after the pigeon update focus time and efforts on the on-page and off-page SEO.
10. Page Layout Algorithm: This update was introduced by Google on 19 January 2012. After the release, this algorithm was updated on 9 October 2012 and the last update till now was on 1 November 2016. This algorithm is linked with the user experience. This algorithm affects those sites which have so many extra ads. So here in this algorithm, those sites in which ads force the user to see content, and approximately 1% of sites were affected.
11. Exact Match Domain: This algorithm was introduced in 2012. As the name suggests it works on the exact name and targets exactly what the name suggests. This update was to focus on the exact match of domain despite thin content and the quality of the site. The major weakness of EDM was that the websites SEOs would buy domains with exact match keyword phrases, build a site out, but have extremely thin content with little to no value on them. And it was so easy to do. The result of this update occurred in a way that, non-dot-com domains experienced a more severe punishment than .com counterparts.
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jul, 2020"
},
{
"code": null,
"e": 371,
"s": 28,
"text": "Google Algorithms are used to give the best possible outcome or result whenever someone searches something on Google. Not only one but it uses several algorithms to perform this task and it also checks for the rank of the web pages which is delivered after the task. Google is making a vast change in its algorithm at a very frequent period. "
},
{
"code": null,
"e": 410,
"s": 371,
"text": "Some of Google updates are as follows:"
},
{
"code": null,
"e": 423,
"s": 410,
"text": "Panda update"
},
{
"code": null,
"e": 445,
"s": 423,
"text": "Payday Loan Algorithm"
},
{
"code": null,
"e": 460,
"s": 445,
"text": "Penguin Update"
},
{
"code": null,
"e": 479,
"s": 460,
"text": "Hummingbird update"
},
{
"code": null,
"e": 493,
"s": 479,
"text": "Mobile Update"
},
{
"code": null,
"e": 511,
"s": 493,
"text": "Rank Brain Possum"
},
{
"code": null,
"e": 530,
"s": 511,
"text": "Update Fred Pigeon"
},
{
"code": null,
"e": 552,
"s": 530,
"text": "Page Layout Algorithm"
},
{
"code": null,
"e": 571,
"s": 552,
"text": "Exact Match Domain"
},
{
"code": null,
"e": 683,
"s": 571,
"text": "The focus of these updates was to improve the quality of sites and content that is going to show up on Google. "
},
{
"code": null,
"e": 1162,
"s": 683,
"text": "1. Panda Update: It is one of Googleβs official algorithm update. This update was done to reduce the low-quality data because in 2009 after the caffeine update the low-quality data also became part of the search results. To reduce that google make a new update and named its Panda. In panda, the pages were given a quality parameter based on the rating given by humans to the pages. So panda eliminates the low-quality content and promotes high quality and user-friendly pages. "
},
{
"code": null,
"e": 1525,
"s": 1162,
"text": "2. Payday Loan Algorithm: This algorithm was released in 2013, cause at that time the spam in Google was increasing. So to reduce Spam websites from Google search results this algorithm was introduced. This was one of the important updates by Google, which targeted Spam queries which were related to super high-interest loans and other heavily spammed queries. "
},
{
"code": null,
"e": 2055,
"s": 1525,
"text": "3. Penguin Update: It was launched in 2012, the same as panda this algorithm also used to promote high-quality data in search results and also to not show the spammy content or low-quality data. This algorithm is an extension of the panda which works on reducing the effectiveness of black hat techniques, that were used to promote the low-quality pages in the search results of Google. The main task of the penguin algorithm was to show the relevant, real, and genuine result websites, and the spam my websites were downgraded. "
},
{
"code": null,
"e": 2443,
"s": 2055,
"text": "4. Hummingbird Update: This update was launched on 22 August 2013, its main work is to show the query that query on the internet which may not have the same word. It mainly focuses on the intention of the searcher. So hummingbird algorithm is important because sometimes grammatical mistakes occur during typing and results did not show up so this was corrected by using this algorithm. "
},
{
"code": null,
"e": 2739,
"s": 2443,
"text": "5. Mobile Update: As the name suggests this algorithm is for mobile search, its task is to show the Mobile-friendly pages on the top when searched from a mobile. This was launched on 21 st April 2015. The top results will be mobile optimized, and those who are not optimized will be downgraded. "
},
{
"code": null,
"e": 2995,
"s": 2739,
"text": "6. Rank Brain: It is a machine learning algorithm. It is kind of similar to a hummingbird, its a machine learning from which Google understand and shows the best result. It is one of the important algorithms of Google and was launched on 26 October 2015. "
},
{
"code": null,
"e": 3331,
"s": 2995,
"text": "7. Possum Update: This algorithm is mainly based on the location, it will show the local result according to the location. The nearer you are to the business address, the more chances that you will see it in your search result, and the result may vary on different locations for local addresses. This was launched on 1 September 2016. "
},
{
"code": null,
"e": 3627,
"s": 3331,
"text": "8. Fred: One of the latest updates in Google and was launched on 8 March 2017. Its main focus is to target websites that have less content and more ads or you can say the websites having focus is on generating revenue with low-class content. Small websites and blogs are focused on this update. "
},
{
"code": null,
"e": 3989,
"s": 3627,
"text": "9. Pigeon: This update was launched by Google on 24th July 2014 in the US and 22 DEC 2014 in UK, Canada, Australia. This update mainly links with those searches on Google in which the location of the user is mainly focused. SEO is used to show local results in an area. So to rank after the pigeon update focus time and efforts on the on-page and off-page SEO. "
},
{
"code": null,
"e": 4434,
"s": 3989,
"text": "10. Page Layout Algorithm: This update was introduced by Google on 19 January 2012. After the release, this algorithm was updated on 9 October 2012 and the last update till now was on 1 November 2016. This algorithm is linked with the user experience. This algorithm affects those sites which have so many extra ads. So here in this algorithm, those sites in which ads force the user to see content, and approximately 1% of sites were affected."
},
{
"code": null,
"e": 5039,
"s": 4434,
"text": "11. Exact Match Domain: This algorithm was introduced in 2012. As the name suggests it works on the exact name and targets exactly what the name suggests. This update was to focus on the exact match of domain despite thin content and the quality of the site. The major weakness of EDM was that the websites SEOs would buy domains with exact match keyword phrases, build a site out, but have extremely thin content with little to no value on them. And it was so easy to do. The result of this update occurred in a way that, non-dot-com domains experienced a more severe punishment than .com counterparts. "
},
{
"code": null,
"e": 5045,
"s": 5039,
"text": "GBlog"
}
] |
How we can perform sort on ObjectId column in MongoDB?
|
To perform sort on ObjectId column, use sort(). Let us create a collection with document.
> db.demo403.insertOne({"Name":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e6f89b0fac4d418a017858e")
}
> db.demo403.insertOne({"Name":"David"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e6f89b2fac4d418a017858f")
}
> db.demo403.insertOne({"Name":"Bob"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e6f89b5fac4d418a0178590")
}
> db.demo403.insertOne({"Name":"Adam"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e6f89b8fac4d418a0178591")
}
Display all documents from a collection with the help of find() method β
> db.demo403.find();
This will produce the following output β
{ "_id" : ObjectId("5e6f89b0fac4d418a017858e"), "Name" : "Chris" }
{ "_id" : ObjectId("5e6f89b2fac4d418a017858f"), "Name" : "David" }
{ "_id" : ObjectId("5e6f89b5fac4d418a0178590"), "Name" : "Bob" }
{ "_id" : ObjectId("5e6f89b8fac4d418a0178591"), "Name" : "Adam" }
Following is the query to perform sort on ObjectId column in MongoDB β
> db.demo403.find().sort({_id:-1});
This will produce the following output β
{ "_id" : ObjectId("5e6f89b8fac4d418a0178591"), "Name" : "Adam" }
{ "_id" : ObjectId("5e6f89b5fac4d418a0178590"), "Name" : "Bob" }
{ "_id" : ObjectId("5e6f89b2fac4d418a017858f"), "Name" : "David" }
{ "_id" : ObjectId("5e6f89b0fac4d418a017858e"), "Name" : "Chris" }
|
[
{
"code": null,
"e": 1277,
"s": 1187,
"text": "To perform sort on ObjectId column, use sort(). Let us create a collection with document."
},
{
"code": null,
"e": 1782,
"s": 1277,
"text": "> db.demo403.insertOne({\"Name\":\"Chris\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e6f89b0fac4d418a017858e\")\n}\n> db.demo403.insertOne({\"Name\":\"David\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e6f89b2fac4d418a017858f\")\n}\n> db.demo403.insertOne({\"Name\":\"Bob\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e6f89b5fac4d418a0178590\")\n}\n> db.demo403.insertOne({\"Name\":\"Adam\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e6f89b8fac4d418a0178591\")\n}"
},
{
"code": null,
"e": 1855,
"s": 1782,
"text": "Display all documents from a collection with the help of find() method β"
},
{
"code": null,
"e": 1876,
"s": 1855,
"text": "> db.demo403.find();"
},
{
"code": null,
"e": 1917,
"s": 1876,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2182,
"s": 1917,
"text": "{ \"_id\" : ObjectId(\"5e6f89b0fac4d418a017858e\"), \"Name\" : \"Chris\" }\n{ \"_id\" : ObjectId(\"5e6f89b2fac4d418a017858f\"), \"Name\" : \"David\" }\n{ \"_id\" : ObjectId(\"5e6f89b5fac4d418a0178590\"), \"Name\" : \"Bob\" }\n{ \"_id\" : ObjectId(\"5e6f89b8fac4d418a0178591\"), \"Name\" : \"Adam\" }"
},
{
"code": null,
"e": 2253,
"s": 2182,
"text": "Following is the query to perform sort on ObjectId column in MongoDB β"
},
{
"code": null,
"e": 2289,
"s": 2253,
"text": "> db.demo403.find().sort({_id:-1});"
},
{
"code": null,
"e": 2330,
"s": 2289,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2595,
"s": 2330,
"text": "{ \"_id\" : ObjectId(\"5e6f89b8fac4d418a0178591\"), \"Name\" : \"Adam\" }\n{ \"_id\" : ObjectId(\"5e6f89b5fac4d418a0178590\"), \"Name\" : \"Bob\" }\n{ \"_id\" : ObjectId(\"5e6f89b2fac4d418a017858f\"), \"Name\" : \"David\" }\n{ \"_id\" : ObjectId(\"5e6f89b0fac4d418a017858e\"), \"Name\" : \"Chris\" }"
}
] |
DoubleStream of() in Java
|
06 Dec, 2018
DoubleStream of(double t) returns a sequential DoubleStream containing a single element.Syntax :
static DoubleStream of(double t)
Parameters :
DoubleStream : A sequence of primitive double-valued elements.t : Represents the single element in the DoubleStream.
DoubleStream : A sequence of primitive double-valued elements.
t : Represents the single element in the DoubleStream.
Return Value : DoubleStream of(double t) returns a sequential DoubleStream containing the single specified element.
Example :
// Java code for DoubleStream of(double t)// to get a sequential DoubleStream// containing a single element.import java.util.*;import java.util.stream.DoubleStream; class GFG { // Driver code public static void main(String[] args) { // Creating a DoubleStream having single // element only DoubleStream stream = DoubleStream.of(8.2); // Displaying the DoubleStream having // single element stream.forEach(System.out::println); }}
Output :
8.2
DoubleStream of(double... values) returns a sequential ordered stream whose elements are the specified values.Syntax :
static DoubleStream of(double... values)
Parameters :
DoubleStream : A sequence of primitive double-valued elements.values : Represents the elements of the new stream.
DoubleStream : A sequence of primitive double-valued elements.
values : Represents the elements of the new stream.
Return Value : DoubleStream of(double... values) returns a sequential ordered stream whose elements are the specified values.
Example 1 :
// Java code for DoubleStream of(double... values)// to get a sequential ordered stream whose// elements are the specified values.import java.util.*;import java.util.stream.DoubleStream; class GFG { // Driver code public static void main(String[] args) { // Creating an DoubleStream DoubleStream stream = DoubleStream.of(8.2, 5.6, 4.1); // Displaying the sequential ordered stream stream.forEach(System.out::println); }}
Output :
8.2
5.6
4.1
Example 2 :
// Java code for DoubleStream of(double... values)// to get a sequential ordered stream whose// elements are the specified values.import java.util.*;import java.util.stream.DoubleStream; class GFG { // Driver code public static void main(String[] args) { // Creating an DoubleStream DoubleStream stream = DoubleStream.of(5.2, 4.2, 6.3); // Storing the count of elements in DoubleStream long total = stream.count(); // Displaying the count of elements System.out.println(total); }}
Output :
3
Java - util package
java-DoubleStream
Java-Functions
java-stream
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
Stack Class in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Dec, 2018"
},
{
"code": null,
"e": 125,
"s": 28,
"text": "DoubleStream of(double t) returns a sequential DoubleStream containing a single element.Syntax :"
},
{
"code": null,
"e": 159,
"s": 125,
"text": "static DoubleStream of(double t)\n"
},
{
"code": null,
"e": 172,
"s": 159,
"text": "Parameters :"
},
{
"code": null,
"e": 289,
"s": 172,
"text": "DoubleStream : A sequence of primitive double-valued elements.t : Represents the single element in the DoubleStream."
},
{
"code": null,
"e": 352,
"s": 289,
"text": "DoubleStream : A sequence of primitive double-valued elements."
},
{
"code": null,
"e": 407,
"s": 352,
"text": "t : Represents the single element in the DoubleStream."
},
{
"code": null,
"e": 523,
"s": 407,
"text": "Return Value : DoubleStream of(double t) returns a sequential DoubleStream containing the single specified element."
},
{
"code": null,
"e": 533,
"s": 523,
"text": "Example :"
},
{
"code": "// Java code for DoubleStream of(double t)// to get a sequential DoubleStream// containing a single element.import java.util.*;import java.util.stream.DoubleStream; class GFG { // Driver code public static void main(String[] args) { // Creating a DoubleStream having single // element only DoubleStream stream = DoubleStream.of(8.2); // Displaying the DoubleStream having // single element stream.forEach(System.out::println); }}",
"e": 1023,
"s": 533,
"text": null
},
{
"code": null,
"e": 1032,
"s": 1023,
"text": "Output :"
},
{
"code": null,
"e": 1037,
"s": 1032,
"text": "8.2\n"
},
{
"code": null,
"e": 1156,
"s": 1037,
"text": "DoubleStream of(double... values) returns a sequential ordered stream whose elements are the specified values.Syntax :"
},
{
"code": null,
"e": 1198,
"s": 1156,
"text": "static DoubleStream of(double... values)\n"
},
{
"code": null,
"e": 1211,
"s": 1198,
"text": "Parameters :"
},
{
"code": null,
"e": 1325,
"s": 1211,
"text": "DoubleStream : A sequence of primitive double-valued elements.values : Represents the elements of the new stream."
},
{
"code": null,
"e": 1388,
"s": 1325,
"text": "DoubleStream : A sequence of primitive double-valued elements."
},
{
"code": null,
"e": 1440,
"s": 1388,
"text": "values : Represents the elements of the new stream."
},
{
"code": null,
"e": 1566,
"s": 1440,
"text": "Return Value : DoubleStream of(double... values) returns a sequential ordered stream whose elements are the specified values."
},
{
"code": null,
"e": 1578,
"s": 1566,
"text": "Example 1 :"
},
{
"code": "// Java code for DoubleStream of(double... values)// to get a sequential ordered stream whose// elements are the specified values.import java.util.*;import java.util.stream.DoubleStream; class GFG { // Driver code public static void main(String[] args) { // Creating an DoubleStream DoubleStream stream = DoubleStream.of(8.2, 5.6, 4.1); // Displaying the sequential ordered stream stream.forEach(System.out::println); }}",
"e": 2044,
"s": 1578,
"text": null
},
{
"code": null,
"e": 2053,
"s": 2044,
"text": "Output :"
},
{
"code": null,
"e": 2066,
"s": 2053,
"text": "8.2\n5.6\n4.1\n"
},
{
"code": null,
"e": 2078,
"s": 2066,
"text": "Example 2 :"
},
{
"code": "// Java code for DoubleStream of(double... values)// to get a sequential ordered stream whose// elements are the specified values.import java.util.*;import java.util.stream.DoubleStream; class GFG { // Driver code public static void main(String[] args) { // Creating an DoubleStream DoubleStream stream = DoubleStream.of(5.2, 4.2, 6.3); // Storing the count of elements in DoubleStream long total = stream.count(); // Displaying the count of elements System.out.println(total); }}",
"e": 2620,
"s": 2078,
"text": null
},
{
"code": null,
"e": 2629,
"s": 2620,
"text": "Output :"
},
{
"code": null,
"e": 2632,
"s": 2629,
"text": "3\n"
},
{
"code": null,
"e": 2652,
"s": 2632,
"text": "Java - util package"
},
{
"code": null,
"e": 2670,
"s": 2652,
"text": "java-DoubleStream"
},
{
"code": null,
"e": 2685,
"s": 2670,
"text": "Java-Functions"
},
{
"code": null,
"e": 2697,
"s": 2685,
"text": "java-stream"
},
{
"code": null,
"e": 2702,
"s": 2697,
"text": "Java"
},
{
"code": null,
"e": 2707,
"s": 2702,
"text": "Java"
},
{
"code": null,
"e": 2805,
"s": 2707,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2856,
"s": 2805,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 2887,
"s": 2856,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 2906,
"s": 2887,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 2936,
"s": 2906,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 2954,
"s": 2936,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 2974,
"s": 2954,
"text": "Collections in Java"
},
{
"code": null,
"e": 3006,
"s": 2974,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 3030,
"s": 3006,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 3042,
"s": 3030,
"text": "Set in Java"
}
] |
How to calculate strike rate of a batsman
|
31 Mar, 2021
Given two integers A and B representing the run scored and ball faced by a batsman in a Cricket match. The task is to calculate the Strike rate of the batsman.
Batting strike rate is a measure of how quickly a batsman achieves the primary goal of batting. It is mathematically equal to: Strike Rate = (Runs Scored / Balls faced) * 100
Examples:
Input: A = 264, B = 173 Output: 152.601 Explanation: Srike rate of batsman is equal to (264 / 173) * 100 = 162.601
Input: A = 0, B = 10 Output: 0.00
Approach:
Use the formula for the strike rate to calculate the strike rate. Strike Rate = (Runs Scored / Balls faced) * 100Return the strike rate in float data type format.
Use the formula for the strike rate to calculate the strike rate. Strike Rate = (Runs Scored / Balls faced) * 100
Return the strike rate in float data type format.
Here is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to calculate strike// rate of a batsman #include <bits/stdc++.h>using namespace std; // function to calculate strike// rate of a batsmanfloat strikerate(int bowls, int runs){ float z; z = (float(runs) / bowls) * 100; return z;} // Driver Codeint main(){ int A, B; A = 264; B = 173; cout << strikerate(B, A) << endl; return 0;}
// Java program to calculate strike// rate of a batsmanclass GFG{ // function to calculate strike// rate of a batsmanstatic float strikerate(float bowls, float runs){ float z; z = (runs / bowls) * 100; return z;} // Driver Codepublic static void main(String[] args){ int A, B; A = 264; B = 173; System.out.println(strikerate(B, A));}} // This code is contributed by rock_cool
# Python3 program to calculate strike# rate of a batsman # function to calculate strike# rate of a batsmandef strikerate(bowls, runs): z = (float(runs) / bowls) * 100; return z; # Driver CodeA = 264;B = 173;print(strikerate(B, A)); # This code is contributed by Code_Mech
// C# program to calculate strike// rate of a batsmanusing System;class GFG{ // function to calculate strike// rate of a batsmanstatic float strikerate(float bowls, float runs){ float z; z = (runs / bowls) * 100; return z;} // Driver Codepublic static void Main(){ int A, B; A = 264; B = 173; Console.Write(strikerate(B, A));}} // This code is contributed by Code_Mech
<script> // Javascript program to calculate strike// rate of a batsman // function to calculate strike// rate of a batsmanfunction strikerate(bowls, runs){ let z; z = (runs / bowls) * 100; return z.toFixed(3);} // Driver code let A, B;A = 264;B = 173; document.write(strikerate(B, A)); // This code is contributed by divyesh072019 </script>
152.601
Time Complexity: O (1) Auxiliary Space: O (1)
Akanksha_Rai
rock_cool
Code_Mech
divyesh072019
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Mar, 2021"
},
{
"code": null,
"e": 189,
"s": 28,
"text": "Given two integers A and B representing the run scored and ball faced by a batsman in a Cricket match. The task is to calculate the Strike rate of the batsman. "
},
{
"code": null,
"e": 366,
"s": 189,
"text": "Batting strike rate is a measure of how quickly a batsman achieves the primary goal of batting. It is mathematically equal to: Strike Rate = (Runs Scored / Balls faced) * 100 "
},
{
"code": null,
"e": 378,
"s": 366,
"text": "Examples: "
},
{
"code": null,
"e": 493,
"s": 378,
"text": "Input: A = 264, B = 173 Output: 152.601 Explanation: Srike rate of batsman is equal to (264 / 173) * 100 = 162.601"
},
{
"code": null,
"e": 528,
"s": 493,
"text": "Input: A = 0, B = 10 Output: 0.00 "
},
{
"code": null,
"e": 538,
"s": 528,
"text": "Approach:"
},
{
"code": null,
"e": 701,
"s": 538,
"text": "Use the formula for the strike rate to calculate the strike rate. Strike Rate = (Runs Scored / Balls faced) * 100Return the strike rate in float data type format."
},
{
"code": null,
"e": 815,
"s": 701,
"text": "Use the formula for the strike rate to calculate the strike rate. Strike Rate = (Runs Scored / Balls faced) * 100"
},
{
"code": null,
"e": 865,
"s": 815,
"text": "Return the strike rate in float data type format."
},
{
"code": null,
"e": 917,
"s": 865,
"text": "Here is the implementation of the above approach: "
},
{
"code": null,
"e": 921,
"s": 917,
"text": "C++"
},
{
"code": null,
"e": 926,
"s": 921,
"text": "Java"
},
{
"code": null,
"e": 934,
"s": 926,
"text": "Python3"
},
{
"code": null,
"e": 937,
"s": 934,
"text": "C#"
},
{
"code": null,
"e": 948,
"s": 937,
"text": "Javascript"
},
{
"code": "// C++ program to calculate strike// rate of a batsman #include <bits/stdc++.h>using namespace std; // function to calculate strike// rate of a batsmanfloat strikerate(int bowls, int runs){ float z; z = (float(runs) / bowls) * 100; return z;} // Driver Codeint main(){ int A, B; A = 264; B = 173; cout << strikerate(B, A) << endl; return 0;}",
"e": 1323,
"s": 948,
"text": null
},
{
"code": "// Java program to calculate strike// rate of a batsmanclass GFG{ // function to calculate strike// rate of a batsmanstatic float strikerate(float bowls, float runs){ float z; z = (runs / bowls) * 100; return z;} // Driver Codepublic static void main(String[] args){ int A, B; A = 264; B = 173; System.out.println(strikerate(B, A));}} // This code is contributed by rock_cool",
"e": 1725,
"s": 1323,
"text": null
},
{
"code": "# Python3 program to calculate strike# rate of a batsman # function to calculate strike# rate of a batsmandef strikerate(bowls, runs): z = (float(runs) / bowls) * 100; return z; # Driver CodeA = 264;B = 173;print(strikerate(B, A)); # This code is contributed by Code_Mech",
"e": 2004,
"s": 1725,
"text": null
},
{
"code": "// C# program to calculate strike// rate of a batsmanusing System;class GFG{ // function to calculate strike// rate of a batsmanstatic float strikerate(float bowls, float runs){ float z; z = (runs / bowls) * 100; return z;} // Driver Codepublic static void Main(){ int A, B; A = 264; B = 173; Console.Write(strikerate(B, A));}} // This code is contributed by Code_Mech",
"e": 2422,
"s": 2004,
"text": null
},
{
"code": "<script> // Javascript program to calculate strike// rate of a batsman // function to calculate strike// rate of a batsmanfunction strikerate(bowls, runs){ let z; z = (runs / bowls) * 100; return z.toFixed(3);} // Driver code let A, B;A = 264;B = 173; document.write(strikerate(B, A)); // This code is contributed by divyesh072019 </script>",
"e": 2774,
"s": 2422,
"text": null
},
{
"code": null,
"e": 2782,
"s": 2774,
"text": "152.601"
},
{
"code": null,
"e": 2831,
"s": 2784,
"text": "Time Complexity: O (1) Auxiliary Space: O (1) "
},
{
"code": null,
"e": 2844,
"s": 2831,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 2854,
"s": 2844,
"text": "rock_cool"
},
{
"code": null,
"e": 2864,
"s": 2854,
"text": "Code_Mech"
},
{
"code": null,
"e": 2878,
"s": 2864,
"text": "divyesh072019"
},
{
"code": null,
"e": 2891,
"s": 2878,
"text": "Mathematical"
},
{
"code": null,
"e": 2910,
"s": 2891,
"text": "School Programming"
},
{
"code": null,
"e": 2923,
"s": 2910,
"text": "Mathematical"
}
] |
Program to convert given Matrix to a Diagonal Matrix
|
13 May, 2022
Given a N*N matrix. The task is to convert the matrix to a diagonal matrix. That is to change the values of the non-diagonal elements of a matrix to 0.Diagonal-Matrix: A matrix is called a Diagonal Matrix if all the non-diagonal elements of the matrix are zero.Examples:
Input : mat[][] = {{ 2, 1, 7 },
{ 3, 7, 2 },
{ 5, 4, 9 }}
Output : {{2, 0, 7},
{0, 7, 0},
{5, 0, 9}}
Input : mat[][] = {{1, 3, 5, 6, 7},
{3, 5, 3, 2, 1},
{1, 2, 3, 4, 5},
{7, 9, 2, 1, 6},
{9, 1, 5, 3, 2}}
Output : {{1, 0, 0, 0, 7},
{0, 5, 0, 2, 0},
{0, 0, 3, 0, 0},
{0, 9, 0, 1, 0},
{9, 0, 0, 0, 2}}
Traverse all the non-diagonal elements of the matrix using two nested loops as shown in the below code and make them zero.Below is the program to make all non-diagonal elements of a matrix zero:
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to change the value of// non-diagonal elements of a matrix to 0 #include <iostream>using namespace std; const int MAX = 100; // Function to print the resultant matrixvoid print(int mat[][MAX], int n, int m){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cout << mat[i][j] << " "; } cout << endl; }} // Function to change the values of all// non-diagonal elements to 0void makenondiagonalzero(int mat[][MAX], int n, int m){ // Traverse all non-diagonal elements for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (i != j && i + j + 1 != n) // Change all non-diagonal // elements to zero mat[i][j] = 0; } } // print resultant matrix print(mat, n, m);} // Driver Codeint main(){ int mat[][MAX] = { { 2, 1, 7 }, { 3, 7, 2 }, { 5, 4, 9 } }; makenondiagonalzero(mat, 3, 3); return 0;}
// C program to change the value of// non-diagonal elements of a matrix to 0#include <stdio.h>#define M 100#define N 100 // Function to print the resultant matrixvoid print(int mat[M][N], int n, int m){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { printf("%d ",mat[i][j]); } printf("\n"); }} // Function to change the values of all// non-diagonal elements to 0void makenondiagonalzero(int mat[M][N], int n, int m){ // Traverse all non-diagonal elements for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (i != j && i + j + 1 != n) // Change all non-diagonal // elements to zero mat[i][j] = 0; } } // print resultant matrix print(mat, n, m);} // Driver Codeint main(){ int mat[][100] = { { 2, 1, 7 }, { 3, 7, 2 }, { 5, 4, 9 } }; makenondiagonalzero(mat, 3, 3); return 0;} // This code is contributed by kothvvsaakash.
// Java program to change the value of// non-diagonal elements of a matrix to 0import java.io.*; class GFG{static int MAX = 100; // Function to print the resultant matrixstatic void print(int mat[][], int n, int m){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { System.out.print( mat[i][j] + " "); } System.out.println(); }} // Function to change the values of all// non-diagonal elements to 0static void makenondiagonalzero(int mat[][], int n, int m){ // Traverse all non-diagonal elements for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (i != j && i + j + 1 != n) // Change all non-diagonal // elements to zero mat[i][j] = 0; } } // print resultant matrix print(mat, n, m);} // Driver Codepublic static void main (String[] args){ int mat[][] = { { 2, 1, 7 }, { 3, 7, 2 }, { 5, 4, 9 } }; makenondiagonalzero(mat, 3, 3);}} // This code is contributed by inder_verma
# Python 3 program to change the value of# non-diagonal elements of a matrix to 0 # Function to print the resultant matrixdef printmatrix(mat, n, m) : for i in range(n) : for j in range(m) : print(mat[i][j], end = " ") print() # Function to change the values# of all non-diagonal elements to 0def makenondiagonalzero(mat, n, m) : # Traverse all non-diagonal elements for i in range(n) : for j in range(m) : if i != j and i + j + 1 != n : # Change all non-diagonal # elements to zero mat[i][j] = 0 # print resultant matrix printmatrix(mat, n, m) # Driver codeif __name__ == "__main__" : mat = [ [2, 1, 7], [3, 7, 2], [5, 4, 9] ] makenondiagonalzero(mat, 3, 3) # This code is contributed by Ryuga
// C# program to change the value// of non-diagonal elements of a// matrix to 0using System; class GFG{ // static int MAX = 100; // Function to print the resultant// matrixstatic void print(int [,]mat, int n, int m){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { Console.Write(mat[i, j] + " "); } Console.WriteLine(); }} // Function to change the values of all// non-diagonal elements to 0static void makenondiagonalzero(int [,]mat, int n, int m){ // Traverse all non-diagonal elements for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (i != j && i + j + 1 != n) // Change all non-diagonal // elements to zero mat[i, j] = 0; } } // print resultant matrix print(mat, n, m);} // Driver Codepublic static void Main (){ int [,]mat = { { 2, 1, 7 }, { 3, 7, 2 }, { 5, 4, 9 } }; makenondiagonalzero(mat, 3, 3);}} // This code is contributed by anuj_67..
<?php// PHP program to change the value of// non-diagonal elements of a matrix to 0 // Function to print the resultant matrixfunction print1($mat, $n, $m){ for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $m; $j++) { echo $mat[$i][$j] . " "; } echo "\n"; }} // Function to change the values of// all non-diagonal elements to 0function makenondiagonalzero($mat, $n, $m){ // Traverse all non-diagonal elements for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $m; $j++) { if ($i != $j && $i + $j + 1 != $n) // Change all non-diagonal // elements to zero $mat[$i][$j] = 0; } } // print resultant matrix print1($mat, $n, $m);} // Driver Code$mat = array( array( 2, 1, 7 ), array( 3, 7, 2 ), array( 5, 4, 9 ) ); makenondiagonalzero($mat, 3, 3); // This code is contributed// by Arnab Kundu?>
<script>// Java Script program to change the value of// non-diagonal elements of a matrix to 0let MAX = 100; // Function to print the resultant matrixfunction print(mat,n,m){ for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) { document.write( mat[i][j] + " "); } document.write("<br>"); }} // Function to change the values of all// non-diagonal elements to 0function makenondiagonalzero(mat,n,m){ // Traverse all non-diagonal elements for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) { if (i != j && i + j + 1 != n) // Change all non-diagonal // elements to zero mat[i][j] = 0; } } // print resultant matrix print(mat, n, m);} // Driver Code let mat = [[ 2, 1, 7 ], [ 3, 7, 2 ], [ 5, 4, 9 ]]; makenondiagonalzero(mat, 3, 3); // This code is contributed by sravan kumar G</script>
2 0 7
0 7 0
5 0 9
Time complexity : O(n*m)
inderDuMCA
vt_m
andrew1234
ankthon
VishalBachchas
sravankumar8128
kothavvsaakash
Technical Scripter 2018
Matrix
School Programming
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 May, 2022"
},
{
"code": null,
"e": 301,
"s": 28,
"text": "Given a N*N matrix. The task is to convert the matrix to a diagonal matrix. That is to change the values of the non-diagonal elements of a matrix to 0.Diagonal-Matrix: A matrix is called a Diagonal Matrix if all the non-diagonal elements of the matrix are zero.Examples: "
},
{
"code": null,
"e": 781,
"s": 301,
"text": "Input : mat[][] = {{ 2, 1, 7 },\n { 3, 7, 2 },\n { 5, 4, 9 }}\nOutput : {{2, 0, 7},\n {0, 7, 0},\n {5, 0, 9}}\n\nInput : mat[][] = {{1, 3, 5, 6, 7},\n {3, 5, 3, 2, 1},\n {1, 2, 3, 4, 5},\n {7, 9, 2, 1, 6},\n {9, 1, 5, 3, 2}}\nOutput : {{1, 0, 0, 0, 7},\n {0, 5, 0, 2, 0},\n {0, 0, 3, 0, 0},\n {0, 9, 0, 1, 0},\n {9, 0, 0, 0, 2}}"
},
{
"code": null,
"e": 980,
"s": 783,
"text": "Traverse all the non-diagonal elements of the matrix using two nested loops as shown in the below code and make them zero.Below is the program to make all non-diagonal elements of a matrix zero: "
},
{
"code": null,
"e": 984,
"s": 980,
"text": "C++"
},
{
"code": null,
"e": 986,
"s": 984,
"text": "C"
},
{
"code": null,
"e": 991,
"s": 986,
"text": "Java"
},
{
"code": null,
"e": 999,
"s": 991,
"text": "Python3"
},
{
"code": null,
"e": 1002,
"s": 999,
"text": "C#"
},
{
"code": null,
"e": 1006,
"s": 1002,
"text": "PHP"
},
{
"code": null,
"e": 1017,
"s": 1006,
"text": "Javascript"
},
{
"code": "// C++ program to change the value of// non-diagonal elements of a matrix to 0 #include <iostream>using namespace std; const int MAX = 100; // Function to print the resultant matrixvoid print(int mat[][MAX], int n, int m){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cout << mat[i][j] << \" \"; } cout << endl; }} // Function to change the values of all// non-diagonal elements to 0void makenondiagonalzero(int mat[][MAX], int n, int m){ // Traverse all non-diagonal elements for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (i != j && i + j + 1 != n) // Change all non-diagonal // elements to zero mat[i][j] = 0; } } // print resultant matrix print(mat, n, m);} // Driver Codeint main(){ int mat[][MAX] = { { 2, 1, 7 }, { 3, 7, 2 }, { 5, 4, 9 } }; makenondiagonalzero(mat, 3, 3); return 0;}",
"e": 2017,
"s": 1017,
"text": null
},
{
"code": "// C program to change the value of// non-diagonal elements of a matrix to 0#include <stdio.h>#define M 100#define N 100 // Function to print the resultant matrixvoid print(int mat[M][N], int n, int m){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { printf(\"%d \",mat[i][j]); } printf(\"\\n\"); }} // Function to change the values of all// non-diagonal elements to 0void makenondiagonalzero(int mat[M][N], int n, int m){ // Traverse all non-diagonal elements for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (i != j && i + j + 1 != n) // Change all non-diagonal // elements to zero mat[i][j] = 0; } } // print resultant matrix print(mat, n, m);} // Driver Codeint main(){ int mat[][100] = { { 2, 1, 7 }, { 3, 7, 2 }, { 5, 4, 9 } }; makenondiagonalzero(mat, 3, 3); return 0;} // This code is contributed by kothvvsaakash.",
"e": 3041,
"s": 2017,
"text": null
},
{
"code": "// Java program to change the value of// non-diagonal elements of a matrix to 0import java.io.*; class GFG{static int MAX = 100; // Function to print the resultant matrixstatic void print(int mat[][], int n, int m){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { System.out.print( mat[i][j] + \" \"); } System.out.println(); }} // Function to change the values of all// non-diagonal elements to 0static void makenondiagonalzero(int mat[][], int n, int m){ // Traverse all non-diagonal elements for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (i != j && i + j + 1 != n) // Change all non-diagonal // elements to zero mat[i][j] = 0; } } // print resultant matrix print(mat, n, m);} // Driver Codepublic static void main (String[] args){ int mat[][] = { { 2, 1, 7 }, { 3, 7, 2 }, { 5, 4, 9 } }; makenondiagonalzero(mat, 3, 3);}} // This code is contributed by inder_verma",
"e": 4157,
"s": 3041,
"text": null
},
{
"code": "# Python 3 program to change the value of# non-diagonal elements of a matrix to 0 # Function to print the resultant matrixdef printmatrix(mat, n, m) : for i in range(n) : for j in range(m) : print(mat[i][j], end = \" \") print() # Function to change the values# of all non-diagonal elements to 0def makenondiagonalzero(mat, n, m) : # Traverse all non-diagonal elements for i in range(n) : for j in range(m) : if i != j and i + j + 1 != n : # Change all non-diagonal # elements to zero mat[i][j] = 0 # print resultant matrix printmatrix(mat, n, m) # Driver codeif __name__ == \"__main__\" : mat = [ [2, 1, 7], [3, 7, 2], [5, 4, 9] ] makenondiagonalzero(mat, 3, 3) # This code is contributed by Ryuga",
"e": 5058,
"s": 4157,
"text": null
},
{
"code": "// C# program to change the value// of non-diagonal elements of a// matrix to 0using System; class GFG{ // static int MAX = 100; // Function to print the resultant// matrixstatic void print(int [,]mat, int n, int m){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { Console.Write(mat[i, j] + \" \"); } Console.WriteLine(); }} // Function to change the values of all// non-diagonal elements to 0static void makenondiagonalzero(int [,]mat, int n, int m){ // Traverse all non-diagonal elements for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (i != j && i + j + 1 != n) // Change all non-diagonal // elements to zero mat[i, j] = 0; } } // print resultant matrix print(mat, n, m);} // Driver Codepublic static void Main (){ int [,]mat = { { 2, 1, 7 }, { 3, 7, 2 }, { 5, 4, 9 } }; makenondiagonalzero(mat, 3, 3);}} // This code is contributed by anuj_67..",
"e": 6172,
"s": 5058,
"text": null
},
{
"code": "<?php// PHP program to change the value of// non-diagonal elements of a matrix to 0 // Function to print the resultant matrixfunction print1($mat, $n, $m){ for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $m; $j++) { echo $mat[$i][$j] . \" \"; } echo \"\\n\"; }} // Function to change the values of// all non-diagonal elements to 0function makenondiagonalzero($mat, $n, $m){ // Traverse all non-diagonal elements for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $m; $j++) { if ($i != $j && $i + $j + 1 != $n) // Change all non-diagonal // elements to zero $mat[$i][$j] = 0; } } // print resultant matrix print1($mat, $n, $m);} // Driver Code$mat = array( array( 2, 1, 7 ), array( 3, 7, 2 ), array( 5, 4, 9 ) ); makenondiagonalzero($mat, 3, 3); // This code is contributed// by Arnab Kundu?>",
"e": 7127,
"s": 6172,
"text": null
},
{
"code": "<script>// Java Script program to change the value of// non-diagonal elements of a matrix to 0let MAX = 100; // Function to print the resultant matrixfunction print(mat,n,m){ for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) { document.write( mat[i][j] + \" \"); } document.write(\"<br>\"); }} // Function to change the values of all// non-diagonal elements to 0function makenondiagonalzero(mat,n,m){ // Traverse all non-diagonal elements for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) { if (i != j && i + j + 1 != n) // Change all non-diagonal // elements to zero mat[i][j] = 0; } } // print resultant matrix print(mat, n, m);} // Driver Code let mat = [[ 2, 1, 7 ], [ 3, 7, 2 ], [ 5, 4, 9 ]]; makenondiagonalzero(mat, 3, 3); // This code is contributed by sravan kumar G</script>",
"e": 8115,
"s": 7127,
"text": null
},
{
"code": null,
"e": 8135,
"s": 8115,
"text": "2 0 7 \n0 7 0 \n5 0 9"
},
{
"code": null,
"e": 8163,
"s": 8137,
"text": "Time complexity : O(n*m) "
},
{
"code": null,
"e": 8174,
"s": 8163,
"text": "inderDuMCA"
},
{
"code": null,
"e": 8179,
"s": 8174,
"text": "vt_m"
},
{
"code": null,
"e": 8190,
"s": 8179,
"text": "andrew1234"
},
{
"code": null,
"e": 8198,
"s": 8190,
"text": "ankthon"
},
{
"code": null,
"e": 8213,
"s": 8198,
"text": "VishalBachchas"
},
{
"code": null,
"e": 8229,
"s": 8213,
"text": "sravankumar8128"
},
{
"code": null,
"e": 8244,
"s": 8229,
"text": "kothavvsaakash"
},
{
"code": null,
"e": 8268,
"s": 8244,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 8275,
"s": 8268,
"text": "Matrix"
},
{
"code": null,
"e": 8294,
"s": 8275,
"text": "School Programming"
},
{
"code": null,
"e": 8301,
"s": 8294,
"text": "Matrix"
}
] |
How to make div width expand with its content using CSS ?
|
30 Jul, 2020
Given an HTML document and the task is to make div width expand with its content using CSS. To do this, the width property is used to set the width of an element excluding padding, margin and border of element. The width property values are listed below:
Syntax:
width: length|percentage|auto|initial|inherit;
Property Values:
width: auto; It is used to set width property to its default value. If the width property set to auto then the browser calculates the width of element.
width: length; It is used to set the width of element in form of px, cm etc. The length can not be negative.
width: initial; It is used to set width property to its default value.
width: inherit; It is used to set width property from its parent element.
Example 1: This example use width: auto; property to display the content.
HTML
<!DOCTYPE html><html> <head> <title> How to make div width expand with its content using CSS ? </title> <style> .geek2 { background-color: #6ba832; height: 120px; width: 49%; float: left; color: white; } .geek3 { background-color: green; height: 7.5em; width: 49%; float: right; color: white; } h1 { color: Green; } .geek1 { background-color: #35cc27; width: auto; color: white; float: right; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h3> How to make div width expand with its content using CSS ? </h3> <div class="geek2"> <p> Javascript is the most common programming language used in many startups and large enterprises for software development. It is used as a client-side development tool in 95% of the websites. </p> </div> <div class="geek3"> <p>Python is a dynamic, high level, open-source programming language. It is relatively a newer language in the world of programming languages and in AWS environment as well. This is the simplest language and beginners friendly. </p> </div> <div class="geek1"> <p>Java is an object-oriented language with fewer dependencies. It is a secure and dynamic language designed to have high performance. Java is one of the earliest languages used in business-critical ideas. </p> </div> </center></body> </html>
Output:
Output after changing the screen size:
Example 2: This example uses width: inherit property to display the content.
HTML
<!DOCTYPE html><html> <head> <title> How to make div width expand with its content using CSS ? </title> <style> .geek2 { width: auto; background-color: green; width: 75%; } .geek3 { width: inherit; background-color: #28cc23; color: white; } .geek1 { width: 25%; } h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h3> How to make div width expand with its content using CSS ? </h3> <div class="geek2"> <p> Javascript is the most common programming language used in many startups and large enterprises for software development. </p> <div class="geek3"> <p> Python is a dynamic, high level, open-source programming language. It is relatively a newer language in the world of programming languages and in AWS environment as well. </p> </div> <div class="geek1"> <p> Java is an object-oriented language with fewer dependencies. It is a secure and dynamic language designed to have high performance. </p> </div> </div> </center></body> </html>
Output:
Output after changing the screen size:
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jul, 2020"
},
{
"code": null,
"e": 283,
"s": 28,
"text": "Given an HTML document and the task is to make div width expand with its content using CSS. To do this, the width property is used to set the width of an element excluding padding, margin and border of element. The width property values are listed below:"
},
{
"code": null,
"e": 291,
"s": 283,
"text": "Syntax:"
},
{
"code": null,
"e": 339,
"s": 291,
"text": "width: length|percentage|auto|initial|inherit;\n"
},
{
"code": null,
"e": 356,
"s": 339,
"text": "Property Values:"
},
{
"code": null,
"e": 508,
"s": 356,
"text": "width: auto; It is used to set width property to its default value. If the width property set to auto then the browser calculates the width of element."
},
{
"code": null,
"e": 617,
"s": 508,
"text": "width: length; It is used to set the width of element in form of px, cm etc. The length can not be negative."
},
{
"code": null,
"e": 688,
"s": 617,
"text": "width: initial; It is used to set width property to its default value."
},
{
"code": null,
"e": 762,
"s": 688,
"text": "width: inherit; It is used to set width property from its parent element."
},
{
"code": null,
"e": 836,
"s": 762,
"text": "Example 1: This example use width: auto; property to display the content."
},
{
"code": null,
"e": 841,
"s": 836,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to make div width expand with its content using CSS ? </title> <style> .geek2 { background-color: #6ba832; height: 120px; width: 49%; float: left; color: white; } .geek3 { background-color: green; height: 7.5em; width: 49%; float: right; color: white; } h1 { color: Green; } .geek1 { background-color: #35cc27; width: auto; color: white; float: right; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h3> How to make div width expand with its content using CSS ? </h3> <div class=\"geek2\"> <p> Javascript is the most common programming language used in many startups and large enterprises for software development. It is used as a client-side development tool in 95% of the websites. </p> </div> <div class=\"geek3\"> <p>Python is a dynamic, high level, open-source programming language. It is relatively a newer language in the world of programming languages and in AWS environment as well. This is the simplest language and beginners friendly. </p> </div> <div class=\"geek1\"> <p>Java is an object-oriented language with fewer dependencies. It is a secure and dynamic language designed to have high performance. Java is one of the earliest languages used in business-critical ideas. </p> </div> </center></body> </html>",
"e": 2805,
"s": 841,
"text": null
},
{
"code": null,
"e": 2813,
"s": 2805,
"text": "Output:"
},
{
"code": null,
"e": 2852,
"s": 2813,
"text": "Output after changing the screen size:"
},
{
"code": null,
"e": 2929,
"s": 2852,
"text": "Example 2: This example uses width: inherit property to display the content."
},
{
"code": null,
"e": 2934,
"s": 2929,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to make div width expand with its content using CSS ? </title> <style> .geek2 { width: auto; background-color: green; width: 75%; } .geek3 { width: inherit; background-color: #28cc23; color: white; } .geek1 { width: 25%; } h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h3> How to make div width expand with its content using CSS ? </h3> <div class=\"geek2\"> <p> Javascript is the most common programming language used in many startups and large enterprises for software development. </p> <div class=\"geek3\"> <p> Python is a dynamic, high level, open-source programming language. It is relatively a newer language in the world of programming languages and in AWS environment as well. </p> </div> <div class=\"geek1\"> <p> Java is an object-oriented language with fewer dependencies. It is a secure and dynamic language designed to have high performance. </p> </div> </div> </center></body> </html>",
"e": 4578,
"s": 2934,
"text": null
},
{
"code": null,
"e": 4586,
"s": 4578,
"text": "Output:"
},
{
"code": null,
"e": 4625,
"s": 4586,
"text": "Output after changing the screen size:"
},
{
"code": null,
"e": 4634,
"s": 4625,
"text": "CSS-Misc"
},
{
"code": null,
"e": 4644,
"s": 4634,
"text": "HTML-Misc"
},
{
"code": null,
"e": 4648,
"s": 4644,
"text": "CSS"
},
{
"code": null,
"e": 4653,
"s": 4648,
"text": "HTML"
},
{
"code": null,
"e": 4670,
"s": 4653,
"text": "Web Technologies"
},
{
"code": null,
"e": 4697,
"s": 4670,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 4702,
"s": 4697,
"text": "HTML"
}
] |
LinkedList listIterator() Method in Java
|
10 Dec, 2018
The Java.util.LinkedList.listIterator() method is used to return a list-iterator containing the same elements as that of the LinkedList in proper and same sequence starting from a specific position or index number which is passed as a parameter to this method.
Syntax:
ListIterator new_list = LinkedList.listIterator(int index);
Parameters: The parameter index is an integer type value that specifies the position of the element from where ListIterator starts operating and returning values.
Return Value: The method returns the list created using ListIterator, starting from the specified index.
Below program illustrate the Java.util.LinkedList.listIterator() method:
// Java code to illustrate listIterator()import java.io.*;import java.util.LinkedList;import java.util.ListIterator; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList LinkedList<String> list = new LinkedList<String>(); // Use add() method to add elements in the list list.add("Geeks"); list.add("for"); list.add("Geeks"); list.add("10"); list.add("20"); // Displaying the linkedlist System.out.println("LinkedList:" + list); // Setting the ListIterator at a specified position ListIterator list_Iter = list.listIterator(2); // Iterating through the created list from the position System.out.println("The list is as follows:"); while(list_Iter.hasNext()){ System.out.println(list_Iter.next()); } }}
LinkedList:[Geeks, for, Geeks, 10, 20]
The list is as follows:
Geeks
10
20
Java - util package
Java-Collections
Java-Functions
java-LinkedList
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 Dec, 2018"
},
{
"code": null,
"e": 313,
"s": 52,
"text": "The Java.util.LinkedList.listIterator() method is used to return a list-iterator containing the same elements as that of the LinkedList in proper and same sequence starting from a specific position or index number which is passed as a parameter to this method."
},
{
"code": null,
"e": 321,
"s": 313,
"text": "Syntax:"
},
{
"code": null,
"e": 382,
"s": 321,
"text": "ListIterator new_list = LinkedList.listIterator(int index);\n"
},
{
"code": null,
"e": 545,
"s": 382,
"text": "Parameters: The parameter index is an integer type value that specifies the position of the element from where ListIterator starts operating and returning values."
},
{
"code": null,
"e": 650,
"s": 545,
"text": "Return Value: The method returns the list created using ListIterator, starting from the specified index."
},
{
"code": null,
"e": 723,
"s": 650,
"text": "Below program illustrate the Java.util.LinkedList.listIterator() method:"
},
{
"code": "// Java code to illustrate listIterator()import java.io.*;import java.util.LinkedList;import java.util.ListIterator; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList LinkedList<String> list = new LinkedList<String>(); // Use add() method to add elements in the list list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); list.add(\"10\"); list.add(\"20\"); // Displaying the linkedlist System.out.println(\"LinkedList:\" + list); // Setting the ListIterator at a specified position ListIterator list_Iter = list.listIterator(2); // Iterating through the created list from the position System.out.println(\"The list is as follows:\"); while(list_Iter.hasNext()){ System.out.println(list_Iter.next()); } }}",
"e": 1622,
"s": 723,
"text": null
},
{
"code": null,
"e": 1698,
"s": 1622,
"text": "LinkedList:[Geeks, for, Geeks, 10, 20]\nThe list is as follows:\nGeeks\n10\n20\n"
},
{
"code": null,
"e": 1718,
"s": 1698,
"text": "Java - util package"
},
{
"code": null,
"e": 1735,
"s": 1718,
"text": "Java-Collections"
},
{
"code": null,
"e": 1750,
"s": 1735,
"text": "Java-Functions"
},
{
"code": null,
"e": 1766,
"s": 1750,
"text": "java-LinkedList"
},
{
"code": null,
"e": 1771,
"s": 1766,
"text": "Java"
},
{
"code": null,
"e": 1776,
"s": 1771,
"text": "Java"
},
{
"code": null,
"e": 1793,
"s": 1776,
"text": "Java-Collections"
},
{
"code": null,
"e": 1891,
"s": 1793,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1906,
"s": 1891,
"text": "Stream In Java"
},
{
"code": null,
"e": 1927,
"s": 1906,
"text": "Introduction to Java"
},
{
"code": null,
"e": 1948,
"s": 1927,
"text": "Constructors in Java"
},
{
"code": null,
"e": 1967,
"s": 1948,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 1984,
"s": 1967,
"text": "Generics in Java"
},
{
"code": null,
"e": 2014,
"s": 1984,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 2040,
"s": 2014,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 2056,
"s": 2040,
"text": "Strings in Java"
},
{
"code": null,
"e": 2093,
"s": 2056,
"text": "Differences between JDK, JRE and JVM"
}
] |
N-bonacci Numbers
|
Difficulty Level :
Easy
You are given two integers N and M, and print all the terms of the series up to M-terms of the N-bonacci Numbers. For example, when N = 2, the sequence becomes Fibonacci, when n = 3, sequence becomes Tribonacci.
In general, in N-bonacci sequence, we use sum of preceding N numbers from the next term. For example, a 3-bonacci sequence is the following: 0, 0, 1, 1, 2, 4, 7, 13, 24, 44, 81
The Fibonacci sequence is a set of numbers that starts with one or zero, followed by a one, and proceeds based on the rule that each number is equal to the sum of preceding two numbers 0, 1, 1, 2, 3, 5, 8.....
Examples :
Input : N = 3, M = 8
Output : 0, 0, 1, 1, 2, 4, 7, 13
We need to print first M terms.
First three terms are 0, 0 and 1.
Fourth term is 0 + 0 + 1 = 1
Fifth term is 0 + 1 + 1 = 2
Sixth terms is 1 + 1 + 2 = 4
Seventh term is 7 (1 + 2 + 4) and eighth
term is 13 (7 + 4 + 2).
Input : N = 4, M = 10
Output : 0 0 0 1 1 2 4 8 15 29
Method 1 (Simple)
Initialize first N-1 terms as 0 and N-th term as 1. Now to find terms from (N+1)-th to M-th, we simply compute sum of previous N terms.
Example : N = 4, M = 9
First three terms are 0, 0, 0
Fourth term is 1.
Remaining terms are computed by adding
previous 4 terms. 0 0 0 1 0 0 0 1 1 0 0 0 1 1 2 0 0 0 1 1 2 4 0 0 0 1 1 2 4 80 0 0 1 1 2 4 8 150 0 0 1 1 2 4 8 15 29
C++
Java
Python3
C#
PHP
Javascript
// CPP program print first M terms of// N-bonacci series.#include <bits/stdc++.h>using namespace std; // Function to print bonacci seriesvoid bonacciseries(long n, int m){ // Assuming m >= n. int a[m] = { 0 }; a[n - 1] = 1; // Computing every term as sum of previous // n terms. for (int i = n; i < m; i++) for (int j = i - n; j < i; j++) a[i] += a[j]; for (int i = 0; i < m; i++) cout << a[i] << " ";} // Driver's Codeint main(){ int N = 5, M = 15; bonacciseries(N, M); return 0;}
// Java program print first M // terms of N-bonacci series.import java.io.*; class GFG{ // Function to print // bonacci series static void bonacciseries(int n, int m) { // Assuming m >= n. int []a = new int[m]; a[n - 1] = 1; // Computing every term as // sum of previous n terms. for (int i = n; i < m; i++) for (int j = i - n; j < i; j++) a[i] += a[j]; for (int i = 0; i < m; i++) System.out.print(a[i] + " "); } // Driver Code public static void main(String args[]) { int N = 5, M = 15; bonacciseries(N, M); }} // This code is contributed by // Manish Shaw(manishshaw1)
# Python program print first M # terms of N-bonacci series. # Function to print bonacci seriesdef bonacciseries(n, m) : # Assuming m >= n. a = [0] * m a[n - 1] = 1 # Computing every term as # sum of previous n terms. for i in range(n, m) : for j in range(i - n, i) : a[i] = a[i] + a[j] for i in range(0, m) : print (a[i], end = " ") # Driver CodeN = 5M = 15bonacciseries(N, M) # This code is contributed # by Manish Shaw(manishshaw1)
// C# program print first M // terms of N-bonacci series.using System; class GFG{ // Function to print // bonacci series static void bonacciseries(int n, int m) { // Assuming m >= n. int []a = new int[m]; Array.Clear(a, 0, a.Length); a[n - 1] = 1; // Computing every term as // sum of previous n terms. for (int i = n; i < m; i++) for (int j = i - n; j < i; j++) a[i] += a[j]; for (int i = 0; i < m; i++) Console.Write(a[i] + " "); } // Driver Code static void Main() { int N = 5, M = 15; bonacciseries(N, M); }} // This code is contributed by // Manish Shaw(manishshaw1)
<?php// PHP program print first M // terms of N-bonacci series. // Function to print bonacci seriesfunction bonacciseries($n, $m){ // Assuming m >= n. $a = array_fill(0, $m, 0); $a[$n - 1] = 1; // Computing every term as // sum of previous n terms. for ($i = $n; $i < $m; $i++) for ($j = $i - $n; $j < $i; $j++) $a[$i] += $a[$j]; for ($i = 0; $i < $m; $i++) echo ($a[$i]." ");} // Driver Code$N = 5; $M = 15;bonacciseries($N, $M); // This code is contributed // by Manish Shaw(manishshaw1)?>
<script> // Javascript program print first M // terms of N-bonacci series. // Function to print // bonacci series function bonacciseries(n , m) { // Assuming m >= n. var a = Array(m).fill(0); a[n - 1] = 1; // Computing every term as // sum of previous n terms. for (i = n; i < m; i++) for (j = i - n; j < i; j++) a[i] += a[j]; for (i = 0; i < m; i++) document.write(a[i] + " "); } // Driver Code var N = 5, M = 15; bonacciseries(N, M); // This code contributed by Rajput-Ji </script>
0 0 0 0 1 1 2 4 8 16 31 61 120 236 464
Time Complexity : O(M * N)
Auxiliary Space : O(M)
Method 2 (Optimized)
We can optimize for large values of N. The idea is based on sliding window. The current term a[i] can be computed as a[i-1] + a[i-1] β a[i-n-1]
C++
Java
Python3
C#
PHP
Javascript
// CPP program print first M terms of// N-bonacci series.#include <bits/stdc++.h>using namespace std; // Function to print bonacci seriesvoid bonacciseries(long n, int m){ // Assuming m > n. int a[m] = { 0 }; a[n - 1] = 1; a[n] = 1; // Uses sliding window for (int i = n + 1; i < m; i++) a[i] = 2 * a[i - 1] - a[i - n - 1]; // Printing result for (int i = 0; i < m; i++) cout << a[i] << " ";} // Driver's Codeint main(){ int N = 5, M = 15; bonacciseries(N, M); return 0;}
// Java program print first M terms of// N-bonacci series.class GFG { // Function to print bonacci series static void bonacciseries(int n, int m) { // Assuming m > n. int a[] = new int[m]; for(int i = 0; i < m; i++) a[i] = 0; a[n - 1] = 1; a[n] = 1; // Uses sliding window for (int i = n + 1; i < m; i++) a[i] = 2 * a[i - 1] - a[i - n - 1]; // Printing result for (int i = 0; i < m; i++) System.out.print(a[i] + " "); } // Driver's Code public static void main(String args[]) { int N = 5, M = 15; bonacciseries(N, M); }} // This code is contributed by JaideepPyne.
# Python3 program print first M terms of# N-bonacci series. # Function to print bonacci seriesdef bonacciseries(n, m): # Assuming m > n. a = [0 for i in range(m)] a[n - 1] = 1 a[n] = 1 # Uses sliding window for i in range(n + 1, m): a[i] = 2 * a[i - 1] - a[i - n - 1] # Printing result for i in range(0, m): print(a[i], end=" ") # Driver's Codeif __name__=='__main__': N, M = 5, 15 bonacciseries(N, M) # This code is contributed by# Sanjit_Prasad
// Java program print // first M terms of// N-bonacci series.using System; class GFG { // Function to print // bonacci series static void bonacciseries(int n, int m) { // Assuming m > n. int []a = new int[m]; for(int i = 0; i < m; i++) a[i] = 0; a[n - 1] = 1; a[n] = 1; // Uses sliding window for (int i = n + 1; i < m; i++) a[i] = 2 * a[i - 1] - a[i - n - 1]; // Printing result for (int i = 0; i < m; i++) Console.Write(a[i] + " "); } // Driver Code static void Main() { int N = 5, M = 15; bonacciseries(N, M); }} // This code is contributed by// Manish Shaw(manishshaw1)
<?php// PHP program print // first M terms of// N-bonacci series. // Function to print // N-bonacci seriesfunction bonacciseries($n, $m){ // Assuming m > n. $a = array(); for ($i = 0; $i < $m; $i++) $a[$i] = 0; $a[$n - 1] = 1; $a[$n] = 1; // Uses sliding window for ($i = $n + 1; $i < $m; $i++) $a[$i] = 2 * $a[$i - 1] - $a[$i - $n - 1]; // Printing result for ($i = 0; $i < $m; $i++) echo ($a[$i] . " ");} // Driver Code$N = 5; $M = 15;bonacciseries($N, $M); // This code is contributed by // Manish Shaw(manishshaw1)?>
<script> // Javascript program print first M terms of// N-bonacci series. // Function to print bonacci series function bonacciseries(n , m) { // Assuming m > n. var a = Array(m).fill(0); for (i = 0; i < m; i++) a[i] = 0; a[n - 1] = 1; a[n] = 1; // Uses sliding window for (i = n + 1; i < m; i++) a[i] = 2 * a[i - 1] - a[i - n - 1]; // Printing result for (i = 0; i < m; i++) document.write(a[i] + " "); } // Driver's Code var N = 5, M = 15; bonacciseries(N, M); // This code contributed by Rajput-Ji </script>
0 0 0 0 1 1 2 4 8 16 31 61 120 236 464
Time Complexity: O(M)
Auxiliary Space: O(M)
jaideeppyne1997
manishshaw1
Sanjit_Prasad
Akanksha_Rai
Rajput-Ji
kingrishabdugar
simranarora5sos
Fibonacci
series
sliding-window
Mathematical
sliding-window
Mathematical
series
Fibonacci
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
Coin Change | DP-7
Operators in C / C++
Prime Numbers
Program to find GCD or HCF of two numbers
Minimum number of jumps to reach end
|
[
{
"code": null,
"e": 24,
"s": 0,
"text": "Difficulty Level :\nEasy"
},
{
"code": null,
"e": 236,
"s": 24,
"text": "You are given two integers N and M, and print all the terms of the series up to M-terms of the N-bonacci Numbers. For example, when N = 2, the sequence becomes Fibonacci, when n = 3, sequence becomes Tribonacci."
},
{
"code": null,
"e": 413,
"s": 236,
"text": "In general, in N-bonacci sequence, we use sum of preceding N numbers from the next term. For example, a 3-bonacci sequence is the following: 0, 0, 1, 1, 2, 4, 7, 13, 24, 44, 81"
},
{
"code": null,
"e": 623,
"s": 413,
"text": "The Fibonacci sequence is a set of numbers that starts with one or zero, followed by a one, and proceeds based on the rule that each number is equal to the sum of preceding two numbers 0, 1, 1, 2, 3, 5, 8....."
},
{
"code": null,
"e": 636,
"s": 623,
"text": "Examples : "
},
{
"code": null,
"e": 962,
"s": 636,
"text": "Input : N = 3, M = 8\nOutput : 0, 0, 1, 1, 2, 4, 7, 13\nWe need to print first M terms.\nFirst three terms are 0, 0 and 1.\nFourth term is 0 + 0 + 1 = 1\nFifth term is 0 + 1 + 1 = 2\nSixth terms is 1 + 1 + 2 = 4\nSeventh term is 7 (1 + 2 + 4) and eighth\nterm is 13 (7 + 4 + 2).\n\nInput : N = 4, M = 10\nOutput : 0 0 0 1 1 2 4 8 15 29 "
},
{
"code": null,
"e": 981,
"s": 962,
"text": "Method 1 (Simple) "
},
{
"code": null,
"e": 1118,
"s": 981,
"text": "Initialize first N-1 terms as 0 and N-th term as 1. Now to find terms from (N+1)-th to M-th, we simply compute sum of previous N terms. "
},
{
"code": null,
"e": 1141,
"s": 1118,
"text": "Example : N = 4, M = 9"
},
{
"code": null,
"e": 1172,
"s": 1141,
"text": "First three terms are 0, 0, 0 "
},
{
"code": null,
"e": 1191,
"s": 1172,
"text": "Fourth term is 1. "
},
{
"code": null,
"e": 1231,
"s": 1191,
"text": "Remaining terms are computed by adding "
},
{
"code": null,
"e": 1348,
"s": 1231,
"text": "previous 4 terms. 0 0 0 1 0 0 0 1 1 0 0 0 1 1 2 0 0 0 1 1 2 4 0 0 0 1 1 2 4 80 0 0 1 1 2 4 8 150 0 0 1 1 2 4 8 15 29"
},
{
"code": null,
"e": 1352,
"s": 1348,
"text": "C++"
},
{
"code": null,
"e": 1357,
"s": 1352,
"text": "Java"
},
{
"code": null,
"e": 1365,
"s": 1357,
"text": "Python3"
},
{
"code": null,
"e": 1368,
"s": 1365,
"text": "C#"
},
{
"code": null,
"e": 1372,
"s": 1368,
"text": "PHP"
},
{
"code": null,
"e": 1383,
"s": 1372,
"text": "Javascript"
},
{
"code": "// CPP program print first M terms of// N-bonacci series.#include <bits/stdc++.h>using namespace std; // Function to print bonacci seriesvoid bonacciseries(long n, int m){ // Assuming m >= n. int a[m] = { 0 }; a[n - 1] = 1; // Computing every term as sum of previous // n terms. for (int i = n; i < m; i++) for (int j = i - n; j < i; j++) a[i] += a[j]; for (int i = 0; i < m; i++) cout << a[i] << \" \";} // Driver's Codeint main(){ int N = 5, M = 15; bonacciseries(N, M); return 0;}",
"e": 1927,
"s": 1383,
"text": null
},
{
"code": "// Java program print first M // terms of N-bonacci series.import java.io.*; class GFG{ // Function to print // bonacci series static void bonacciseries(int n, int m) { // Assuming m >= n. int []a = new int[m]; a[n - 1] = 1; // Computing every term as // sum of previous n terms. for (int i = n; i < m; i++) for (int j = i - n; j < i; j++) a[i] += a[j]; for (int i = 0; i < m; i++) System.out.print(a[i] + \" \"); } // Driver Code public static void main(String args[]) { int N = 5, M = 15; bonacciseries(N, M); }} // This code is contributed by // Manish Shaw(manishshaw1)",
"e": 2681,
"s": 1927,
"text": null
},
{
"code": "# Python program print first M # terms of N-bonacci series. # Function to print bonacci seriesdef bonacciseries(n, m) : # Assuming m >= n. a = [0] * m a[n - 1] = 1 # Computing every term as # sum of previous n terms. for i in range(n, m) : for j in range(i - n, i) : a[i] = a[i] + a[j] for i in range(0, m) : print (a[i], end = \" \") # Driver CodeN = 5M = 15bonacciseries(N, M) # This code is contributed # by Manish Shaw(manishshaw1)",
"e": 3171,
"s": 2681,
"text": null
},
{
"code": "// C# program print first M // terms of N-bonacci series.using System; class GFG{ // Function to print // bonacci series static void bonacciseries(int n, int m) { // Assuming m >= n. int []a = new int[m]; Array.Clear(a, 0, a.Length); a[n - 1] = 1; // Computing every term as // sum of previous n terms. for (int i = n; i < m; i++) for (int j = i - n; j < i; j++) a[i] += a[j]; for (int i = 0; i < m; i++) Console.Write(a[i] + \" \"); } // Driver Code static void Main() { int N = 5, M = 15; bonacciseries(N, M); }} // This code is contributed by // Manish Shaw(manishshaw1)",
"e": 3928,
"s": 3171,
"text": null
},
{
"code": "<?php// PHP program print first M // terms of N-bonacci series. // Function to print bonacci seriesfunction bonacciseries($n, $m){ // Assuming m >= n. $a = array_fill(0, $m, 0); $a[$n - 1] = 1; // Computing every term as // sum of previous n terms. for ($i = $n; $i < $m; $i++) for ($j = $i - $n; $j < $i; $j++) $a[$i] += $a[$j]; for ($i = 0; $i < $m; $i++) echo ($a[$i].\" \");} // Driver Code$N = 5; $M = 15;bonacciseries($N, $M); // This code is contributed // by Manish Shaw(manishshaw1)?>",
"e": 4487,
"s": 3928,
"text": null
},
{
"code": "<script> // Javascript program print first M // terms of N-bonacci series. // Function to print // bonacci series function bonacciseries(n , m) { // Assuming m >= n. var a = Array(m).fill(0); a[n - 1] = 1; // Computing every term as // sum of previous n terms. for (i = n; i < m; i++) for (j = i - n; j < i; j++) a[i] += a[j]; for (i = 0; i < m; i++) document.write(a[i] + \" \"); } // Driver Code var N = 5, M = 15; bonacciseries(N, M); // This code contributed by Rajput-Ji </script>",
"e": 5108,
"s": 4487,
"text": null
},
{
"code": null,
"e": 5161,
"s": 5108,
"text": "0 0 0 0 1 1 2 4 8 16 31 61 120 236 464"
},
{
"code": null,
"e": 5189,
"s": 5161,
"text": "Time Complexity : O(M * N) "
},
{
"code": null,
"e": 5212,
"s": 5189,
"text": "Auxiliary Space : O(M)"
},
{
"code": null,
"e": 5234,
"s": 5212,
"text": "Method 2 (Optimized) "
},
{
"code": null,
"e": 5379,
"s": 5234,
"text": "We can optimize for large values of N. The idea is based on sliding window. The current term a[i] can be computed as a[i-1] + a[i-1] β a[i-n-1] "
},
{
"code": null,
"e": 5383,
"s": 5379,
"text": "C++"
},
{
"code": null,
"e": 5388,
"s": 5383,
"text": "Java"
},
{
"code": null,
"e": 5396,
"s": 5388,
"text": "Python3"
},
{
"code": null,
"e": 5399,
"s": 5396,
"text": "C#"
},
{
"code": null,
"e": 5403,
"s": 5399,
"text": "PHP"
},
{
"code": null,
"e": 5414,
"s": 5403,
"text": "Javascript"
},
{
"code": "// CPP program print first M terms of// N-bonacci series.#include <bits/stdc++.h>using namespace std; // Function to print bonacci seriesvoid bonacciseries(long n, int m){ // Assuming m > n. int a[m] = { 0 }; a[n - 1] = 1; a[n] = 1; // Uses sliding window for (int i = n + 1; i < m; i++) a[i] = 2 * a[i - 1] - a[i - n - 1]; // Printing result for (int i = 0; i < m; i++) cout << a[i] << \" \";} // Driver's Codeint main(){ int N = 5, M = 15; bonacciseries(N, M); return 0;}",
"e": 5941,
"s": 5414,
"text": null
},
{
"code": "// Java program print first M terms of// N-bonacci series.class GFG { // Function to print bonacci series static void bonacciseries(int n, int m) { // Assuming m > n. int a[] = new int[m]; for(int i = 0; i < m; i++) a[i] = 0; a[n - 1] = 1; a[n] = 1; // Uses sliding window for (int i = n + 1; i < m; i++) a[i] = 2 * a[i - 1] - a[i - n - 1]; // Printing result for (int i = 0; i < m; i++) System.out.print(a[i] + \" \"); } // Driver's Code public static void main(String args[]) { int N = 5, M = 15; bonacciseries(N, M); }} // This code is contributed by JaideepPyne.",
"e": 6685,
"s": 5941,
"text": null
},
{
"code": "# Python3 program print first M terms of# N-bonacci series. # Function to print bonacci seriesdef bonacciseries(n, m): # Assuming m > n. a = [0 for i in range(m)] a[n - 1] = 1 a[n] = 1 # Uses sliding window for i in range(n + 1, m): a[i] = 2 * a[i - 1] - a[i - n - 1] # Printing result for i in range(0, m): print(a[i], end=\" \") # Driver's Codeif __name__=='__main__': N, M = 5, 15 bonacciseries(N, M) # This code is contributed by# Sanjit_Prasad",
"e": 7187,
"s": 6685,
"text": null
},
{
"code": "// Java program print // first M terms of// N-bonacci series.using System; class GFG { // Function to print // bonacci series static void bonacciseries(int n, int m) { // Assuming m > n. int []a = new int[m]; for(int i = 0; i < m; i++) a[i] = 0; a[n - 1] = 1; a[n] = 1; // Uses sliding window for (int i = n + 1; i < m; i++) a[i] = 2 * a[i - 1] - a[i - n - 1]; // Printing result for (int i = 0; i < m; i++) Console.Write(a[i] + \" \"); } // Driver Code static void Main() { int N = 5, M = 15; bonacciseries(N, M); }} // This code is contributed by// Manish Shaw(manishshaw1)",
"e": 7997,
"s": 7187,
"text": null
},
{
"code": "<?php// PHP program print // first M terms of// N-bonacci series. // Function to print // N-bonacci seriesfunction bonacciseries($n, $m){ // Assuming m > n. $a = array(); for ($i = 0; $i < $m; $i++) $a[$i] = 0; $a[$n - 1] = 1; $a[$n] = 1; // Uses sliding window for ($i = $n + 1; $i < $m; $i++) $a[$i] = 2 * $a[$i - 1] - $a[$i - $n - 1]; // Printing result for ($i = 0; $i < $m; $i++) echo ($a[$i] . \" \");} // Driver Code$N = 5; $M = 15;bonacciseries($N, $M); // This code is contributed by // Manish Shaw(manishshaw1)?>",
"e": 8595,
"s": 7997,
"text": null
},
{
"code": "<script> // Javascript program print first M terms of// N-bonacci series. // Function to print bonacci series function bonacciseries(n , m) { // Assuming m > n. var a = Array(m).fill(0); for (i = 0; i < m; i++) a[i] = 0; a[n - 1] = 1; a[n] = 1; // Uses sliding window for (i = n + 1; i < m; i++) a[i] = 2 * a[i - 1] - a[i - n - 1]; // Printing result for (i = 0; i < m; i++) document.write(a[i] + \" \"); } // Driver's Code var N = 5, M = 15; bonacciseries(N, M); // This code contributed by Rajput-Ji </script>",
"e": 9249,
"s": 8595,
"text": null
},
{
"code": null,
"e": 9288,
"s": 9249,
"text": "0 0 0 0 1 1 2 4 8 16 31 61 120 236 464"
},
{
"code": null,
"e": 9311,
"s": 9288,
"text": "Time Complexity: O(M) "
},
{
"code": null,
"e": 9334,
"s": 9311,
"text": "Auxiliary Space: O(M) "
},
{
"code": null,
"e": 9350,
"s": 9334,
"text": "jaideeppyne1997"
},
{
"code": null,
"e": 9362,
"s": 9350,
"text": "manishshaw1"
},
{
"code": null,
"e": 9376,
"s": 9362,
"text": "Sanjit_Prasad"
},
{
"code": null,
"e": 9389,
"s": 9376,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 9399,
"s": 9389,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 9415,
"s": 9399,
"text": "kingrishabdugar"
},
{
"code": null,
"e": 9431,
"s": 9415,
"text": "simranarora5sos"
},
{
"code": null,
"e": 9441,
"s": 9431,
"text": "Fibonacci"
},
{
"code": null,
"e": 9448,
"s": 9441,
"text": "series"
},
{
"code": null,
"e": 9463,
"s": 9448,
"text": "sliding-window"
},
{
"code": null,
"e": 9476,
"s": 9463,
"text": "Mathematical"
},
{
"code": null,
"e": 9491,
"s": 9476,
"text": "sliding-window"
},
{
"code": null,
"e": 9504,
"s": 9491,
"text": "Mathematical"
},
{
"code": null,
"e": 9511,
"s": 9504,
"text": "series"
},
{
"code": null,
"e": 9521,
"s": 9511,
"text": "Fibonacci"
},
{
"code": null,
"e": 9619,
"s": 9521,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9649,
"s": 9619,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 9692,
"s": 9649,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 9752,
"s": 9692,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 9767,
"s": 9752,
"text": "C++ Data Types"
},
{
"code": null,
"e": 9791,
"s": 9767,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 9810,
"s": 9791,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 9831,
"s": 9810,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 9845,
"s": 9831,
"text": "Prime Numbers"
},
{
"code": null,
"e": 9887,
"s": 9845,
"text": "Program to find GCD or HCF of two numbers"
}
] |
response.links β Python requests
|
01 Mar, 2020
response.links returns the header links. To know more about Http Headers, visit β Http Headers. Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.links out of a response object.
To illustrate use of response.links, letβs ping api.github.com. To run this script, you need to have Python and requests installed on your PC.
Download and Install Python 3 Latest Version
How to install requests in Python β For windows, linux, mac
response.links
# import requests moduleimport requests # Making a get requestresponse = requests.get('https://api.github.com/') # print responseprint(response) # print linksprint(response.links)
Save above file as request.py and run using
Python request.py
Check that {} at the start of the output, it shows the header links JSON.
There are many libraries to make an HTTP request in Python, which are httplib, urllib, httplib2, treq, etc., but requests is the one of the best with cool features. If any attribute of requests shows NULL, check the status code using below attribute.
requests.status_code
If status_code doesnβt lie in range of 200-29. You probably need to check method begin used for making a request + the url you are requesting for resources.
Python-requests
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Mar, 2020"
},
{
"code": null,
"e": 489,
"s": 28,
"text": "response.links returns the header links. To know more about Http Headers, visit β Http Headers. Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.links out of a response object."
},
{
"code": null,
"e": 632,
"s": 489,
"text": "To illustrate use of response.links, letβs ping api.github.com. To run this script, you need to have Python and requests installed on your PC."
},
{
"code": null,
"e": 677,
"s": 632,
"text": "Download and Install Python 3 Latest Version"
},
{
"code": null,
"e": 737,
"s": 677,
"text": "How to install requests in Python β For windows, linux, mac"
},
{
"code": null,
"e": 752,
"s": 737,
"text": "response.links"
},
{
"code": "# import requests moduleimport requests # Making a get requestresponse = requests.get('https://api.github.com/') # print responseprint(response) # print linksprint(response.links)",
"e": 935,
"s": 752,
"text": null
},
{
"code": null,
"e": 979,
"s": 935,
"text": "Save above file as request.py and run using"
},
{
"code": null,
"e": 998,
"s": 979,
"text": "Python request.py\n"
},
{
"code": null,
"e": 1072,
"s": 998,
"text": "Check that {} at the start of the output, it shows the header links JSON."
},
{
"code": null,
"e": 1323,
"s": 1072,
"text": "There are many libraries to make an HTTP request in Python, which are httplib, urllib, httplib2, treq, etc., but requests is the one of the best with cool features. If any attribute of requests shows NULL, check the status code using below attribute."
},
{
"code": null,
"e": 1344,
"s": 1323,
"text": "requests.status_code"
},
{
"code": null,
"e": 1501,
"s": 1344,
"text": "If status_code doesnβt lie in range of 200-29. You probably need to check method begin used for making a request + the url you are requesting for resources."
},
{
"code": null,
"e": 1517,
"s": 1501,
"text": "Python-requests"
},
{
"code": null,
"e": 1524,
"s": 1517,
"text": "Python"
},
{
"code": null,
"e": 1622,
"s": 1524,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1654,
"s": 1622,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1681,
"s": 1654,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1702,
"s": 1681,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1725,
"s": 1702,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1781,
"s": 1725,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1812,
"s": 1781,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1854,
"s": 1812,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1896,
"s": 1854,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1935,
"s": 1896,
"text": "Python | Get unique values from a list"
}
] |
What is Nikto and itβs usages ?
|
19 Nov, 2021
Nikto is an Open Source software written in Perl language that is used to scan a web-server for the vulnerability that can be exploited and can compromise the server. It can also check for outdated version details of 1200 server and can detect problems with specific version details of over 200 servers. It can also fingerprint server using favicon.ico files present in the server. It is not designed to be a particularly a stealth tool rather than it is designed to be fast and time-efficient to achieve the task in very little time. Because of this, a web admin can easily detect that its server is being scanned by looking into the log files. It can also show some items that do not have security problem but are info only which shows how to take full use of it to secure the web-server more properly.
Features:
Full support for SSL
Finds sub-domain
Supports full HTTP Proxy
Outdated component report
Result saved in multiple format (xml, csv etc)
Username guessing
Gives details of installed software
Takes Nmap file as input to scan port in a web-server.
Able to perform dictionary attack.
Updated easily
How to install Nikto in Linux:
Step 1: root@kali:~# git clone https://github.com/sullo/nikto.git
Step 2: root@kali:~# cd nikto/program
Step 3: root@kali:~/nikto/program# perl nikto.pl
Usages:-
Help menu: root@kali:~/nikto/program# perl nikto.pl -H
Scan a website: root@kali:~/nikto/program# perl nikto.pl -host https://www.webscantest.com/
rajeev0719singh
Software Testing
GBlog
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!
Geek Streak - 24 Days POTD Challenge
What is Hashing | A Complete Tutorial
How to Learn Data Science in 10 weeks?
GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n19 Nov, 2021"
},
{
"code": null,
"e": 859,
"s": 53,
"text": "Nikto is an Open Source software written in Perl language that is used to scan a web-server for the vulnerability that can be exploited and can compromise the server. It can also check for outdated version details of 1200 server and can detect problems with specific version details of over 200 servers. It can also fingerprint server using favicon.ico files present in the server. It is not designed to be a particularly a stealth tool rather than it is designed to be fast and time-efficient to achieve the task in very little time. Because of this, a web admin can easily detect that its server is being scanned by looking into the log files. It can also show some items that do not have security problem but are info only which shows how to take full use of it to secure the web-server more properly. "
},
{
"code": null,
"e": 871,
"s": 859,
"text": "Features: "
},
{
"code": null,
"e": 892,
"s": 871,
"text": "Full support for SSL"
},
{
"code": null,
"e": 909,
"s": 892,
"text": "Finds sub-domain"
},
{
"code": null,
"e": 934,
"s": 909,
"text": "Supports full HTTP Proxy"
},
{
"code": null,
"e": 960,
"s": 934,
"text": "Outdated component report"
},
{
"code": null,
"e": 1007,
"s": 960,
"text": "Result saved in multiple format (xml, csv etc)"
},
{
"code": null,
"e": 1025,
"s": 1007,
"text": "Username guessing"
},
{
"code": null,
"e": 1061,
"s": 1025,
"text": "Gives details of installed software"
},
{
"code": null,
"e": 1116,
"s": 1061,
"text": "Takes Nmap file as input to scan port in a web-server."
},
{
"code": null,
"e": 1151,
"s": 1116,
"text": "Able to perform dictionary attack."
},
{
"code": null,
"e": 1166,
"s": 1151,
"text": "Updated easily"
},
{
"code": null,
"e": 1199,
"s": 1166,
"text": "How to install Nikto in Linux: "
},
{
"code": null,
"e": 1353,
"s": 1199,
"text": "Step 1: root@kali:~# git clone https://github.com/sullo/nikto.git\nStep 2: root@kali:~# cd nikto/program\nStep 3: root@kali:~/nikto/program# perl nikto.pl "
},
{
"code": null,
"e": 1364,
"s": 1353,
"text": "Usages:- "
},
{
"code": null,
"e": 1421,
"s": 1364,
"text": "Help menu: root@kali:~/nikto/program# perl nikto.pl -H "
},
{
"code": null,
"e": 1515,
"s": 1421,
"text": "Scan a website: root@kali:~/nikto/program# perl nikto.pl -host https://www.webscantest.com/ "
},
{
"code": null,
"e": 1533,
"s": 1517,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 1550,
"s": 1533,
"text": "Software Testing"
},
{
"code": null,
"e": 1556,
"s": 1550,
"text": "GBlog"
},
{
"code": null,
"e": 1573,
"s": 1556,
"text": "Web Technologies"
},
{
"code": null,
"e": 1600,
"s": 1573,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 1698,
"s": 1600,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1753,
"s": 1698,
"text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!"
},
{
"code": null,
"e": 1790,
"s": 1753,
"text": "Geek Streak - 24 Days POTD Challenge"
},
{
"code": null,
"e": 1828,
"s": 1790,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 1867,
"s": 1828,
"text": "How to Learn Data Science in 10 weeks?"
},
{
"code": null,
"e": 1933,
"s": 1867,
"text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?"
},
{
"code": null,
"e": 1966,
"s": 1933,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2027,
"s": 1966,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2077,
"s": 2027,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 2120,
"s": 2077,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Overriding in Java
|
07 Mar, 2022
In any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, same parameters or signature, and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class.
Method overriding is one of the way by which java achieve Run Time Polymorphism.The version of a method that is executed will be determined by the object that is used to invoke it. If an object of a parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the subclass is used to invoke the method, then the version in the child class will be executed. In other words, it is the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed.
// A Simple Java program to demonstrate// method overriding in java // Base Classclass Parent { void show() { System.out.println("Parent's show()"); }} // Inherited classclass Child extends Parent { // This method overrides show() of Parent @Override void show() { System.out.println("Child's show()"); }} // Driver classclass Main { public static void main(String[] args) { // If a Parent type reference refers // to a Parent object, then Parent's // show is called Parent obj1 = new Parent(); obj1.show(); // If a Parent type reference refers // to a Child object Child's show() // is called. This is called RUN TIME // POLYMORPHISM. Parent obj2 = new Child(); obj2.show(); }}
Parent's show()
Child's show()
Rules for method overriding:
Overriding and Access-Modifiers : The access modifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the super-class can be made public, but not private, in the subclass. Doing so, will generate compile-time error.// A Simple Java program to demonstrate// Overriding and Access-Modifiers class Parent { // private methods are not overridden private void m1() { System.out.println("From parent m1()"); } protected void m2() { System.out.println("From parent m2()"); }} class Child extends Parent { // new m1() method // unique to Child class private void m1() { System.out.println("From child m1()"); } // overriding method // with more accessibility @Override public void m2() { System.out.println("From child m2()"); }} // Driver classclass Main { public static void main(String[] args) { Parent obj1 = new Parent(); obj1.m2(); Parent obj2 = new Child(); obj2.m2(); }}Output:From parent m2()
From child m2()
Final methods can not be overridden : If we donβt want a method to be overridden, we declare it as final. Please see Using final with Inheritance .// A Java program to demonstrate that// final methods cannot be overridden class Parent { // Can't be overridden final void show() {}} class Child extends Parent { // This would produce error void show() {}}Output:13: error: show() in Child cannot override show() in Parent
void show() { }
^
overridden method is final
Static methods can not be overridden(Method Overriding vs Method Hiding) : When you define a static method with same signature as a static method in base class, it is known as method hiding.The following table summarizes what happens when you define a method with the same signature as a method in a super-class. Superclass Instance MethodSuperclass Static MethodSubclass Instance MethodOverridesGenerates a compile-time errorSubclass Static MethodGenerates a compile-time errorHides// Java program to show that// if the static method is redefined by// a derived class, then it is not// overriding, it is hiding class Parent { // Static method in base class // which will be hidden in subclass static void m1() { System.out.println("From parent " + "static m1()"); } // Non-static method which will // be overridden in derived class void m2() { System.out.println("From parent " + "non-static(instance) m2()"); }} class Child extends Parent { // This method hides m1() in Parent static void m1() { System.out.println("From child static m1()"); } // This method overrides m2() in Parent @Override public void m2() { System.out.println("From child " + "non-static(instance) m2()"); }} // Driver classclass Main { public static void main(String[] args) { Parent obj1 = new Child(); // As per overriding rules this // should call to class Child static // overridden method. Since static // method can not be overridden, it // calls Parent's m1() obj1.m1(); // Here overriding works // and Child's m2() is called obj1.m2(); }}Output:From parent static m1()
From child non-static(instance) m2()
Private methods can not be overridden : Private methods cannot be overridden as they are bonded during compile time. Therefore we canβt even override private methods in a subclass.(See this for details). The overriding method must have same return type (or subtype) : From Java 5.0 onwards it is possible to have different return type for a overriding method in child class, but childβs return type should be sub-type of parentβs return type. This phenomena is known as covariant return type. Invoking overridden method from sub-class : We can call parent class method in overriding method using super keyword.// A Java program to demonstrate that overridden// method can be called from sub-class // Base Classclass Parent { void show() { System.out.println("Parent's show()"); }} // Inherited classclass Child extends Parent { // This method overrides show() of Parent @Override void show() { super.show(); System.out.println("Child's show()"); }} // Driver classclass Main { public static void main(String[] args) { Parent obj = new Child(); obj.show(); }}Output:Parent's show()
Child's show()
Overriding and constructor : We can not override constructor as parent and child class can never have constructor with same name(Constructor name must always be same as Class name).Overriding and Exception-Handling : Below are two rules to note when overriding methods related to exception-handling.Rule#1 : If the super-class overridden method does not throw an exception, subclass overriding method can only throws the unchecked exception, throwing checked exception will lead to compile-time error./* Java program to demonstrate overriding when superclass method does not declare an exception*/ class Parent { void m1() { System.out.println("From parent m1()"); } void m2() { System.out.println("From parent m2()"); }} class Child extends Parent { @Override // no issue while throwing unchecked exception void m1() throws ArithmeticException { System.out.println("From child m1()"); } @Override // compile-time error // issue while throwing checked exception void m2() throws Exception { System.out.println("From child m2"); }}Output:error: m2() in Child cannot override m2() in Parent
void m2() throws Exception{ System.out.println("From child m2");}
^
overridden method does not throw Exception
Rule#2 : If the super-class overridden method does throws an exception, subclass overriding method can only throw same, subclass exception. Throwing parent exception in Exception hierarchy will lead to compile time error.Also there is no issue if subclass overridden method is not throwing any exception.// Java program to demonstrate overriding when// superclass method does declare an exception class Parent { void m1() throws RuntimeException { System.out.println("From parent m1()"); }} class Child1 extends Parent { @Override // no issue while throwing same exception void m1() throws RuntimeException { System.out.println("From child1 m1()"); }}class Child2 extends Parent { @Override // no issue while throwing subclass exception void m1() throws ArithmeticException { System.out.println("From child2 m1()"); }}class Child3 extends Parent { @Override // no issue while not throwing any exception void m1() { System.out.println("From child3 m1()"); }}class Child4 extends Parent { @Override // compile-time error // issue while throwing parent exception void m1() throws Exception { System.out.println("From child4 m1()"); }}Output:error: m1() in Child4 cannot override m1() in Parent
void m1() throws Exception
^
overridden method does not throw Exception
Overriding and abstract method: Abstract methods in an interface or abstract class are meant to be overridden in derived concrete classes otherwise a compile-time error will be thrown. Overriding and synchronized/strictfp method : The presence of synchronized/strictfp modifier with method have no effect on the rules of overriding, i.e. itβs possible that a synchronized/strictfp method can override a non synchronized/strictfp one and vice-versa.
Overriding and Access-Modifiers : The access modifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the super-class can be made public, but not private, in the subclass. Doing so, will generate compile-time error.// A Simple Java program to demonstrate// Overriding and Access-Modifiers class Parent { // private methods are not overridden private void m1() { System.out.println("From parent m1()"); } protected void m2() { System.out.println("From parent m2()"); }} class Child extends Parent { // new m1() method // unique to Child class private void m1() { System.out.println("From child m1()"); } // overriding method // with more accessibility @Override public void m2() { System.out.println("From child m2()"); }} // Driver classclass Main { public static void main(String[] args) { Parent obj1 = new Parent(); obj1.m2(); Parent obj2 = new Child(); obj2.m2(); }}Output:From parent m2()
From child m2()
// A Simple Java program to demonstrate// Overriding and Access-Modifiers class Parent { // private methods are not overridden private void m1() { System.out.println("From parent m1()"); } protected void m2() { System.out.println("From parent m2()"); }} class Child extends Parent { // new m1() method // unique to Child class private void m1() { System.out.println("From child m1()"); } // overriding method // with more accessibility @Override public void m2() { System.out.println("From child m2()"); }} // Driver classclass Main { public static void main(String[] args) { Parent obj1 = new Parent(); obj1.m2(); Parent obj2 = new Child(); obj2.m2(); }}
From parent m2()
From child m2()
Final methods can not be overridden : If we donβt want a method to be overridden, we declare it as final. Please see Using final with Inheritance .// A Java program to demonstrate that// final methods cannot be overridden class Parent { // Can't be overridden final void show() {}} class Child extends Parent { // This would produce error void show() {}}Output:13: error: show() in Child cannot override show() in Parent
void show() { }
^
overridden method is final
// A Java program to demonstrate that// final methods cannot be overridden class Parent { // Can't be overridden final void show() {}} class Child extends Parent { // This would produce error void show() {}}
Output:
13: error: show() in Child cannot override show() in Parent
void show() { }
^
overridden method is final
Static methods can not be overridden(Method Overriding vs Method Hiding) : When you define a static method with same signature as a static method in base class, it is known as method hiding.The following table summarizes what happens when you define a method with the same signature as a method in a super-class. Superclass Instance MethodSuperclass Static MethodSubclass Instance MethodOverridesGenerates a compile-time errorSubclass Static MethodGenerates a compile-time errorHides// Java program to show that// if the static method is redefined by// a derived class, then it is not// overriding, it is hiding class Parent { // Static method in base class // which will be hidden in subclass static void m1() { System.out.println("From parent " + "static m1()"); } // Non-static method which will // be overridden in derived class void m2() { System.out.println("From parent " + "non-static(instance) m2()"); }} class Child extends Parent { // This method hides m1() in Parent static void m1() { System.out.println("From child static m1()"); } // This method overrides m2() in Parent @Override public void m2() { System.out.println("From child " + "non-static(instance) m2()"); }} // Driver classclass Main { public static void main(String[] args) { Parent obj1 = new Child(); // As per overriding rules this // should call to class Child static // overridden method. Since static // method can not be overridden, it // calls Parent's m1() obj1.m1(); // Here overriding works // and Child's m2() is called obj1.m2(); }}Output:From parent static m1()
From child non-static(instance) m2()
The following table summarizes what happens when you define a method with the same signature as a method in a super-class.
// Java program to show that// if the static method is redefined by// a derived class, then it is not// overriding, it is hiding class Parent { // Static method in base class // which will be hidden in subclass static void m1() { System.out.println("From parent " + "static m1()"); } // Non-static method which will // be overridden in derived class void m2() { System.out.println("From parent " + "non-static(instance) m2()"); }} class Child extends Parent { // This method hides m1() in Parent static void m1() { System.out.println("From child static m1()"); } // This method overrides m2() in Parent @Override public void m2() { System.out.println("From child " + "non-static(instance) m2()"); }} // Driver classclass Main { public static void main(String[] args) { Parent obj1 = new Child(); // As per overriding rules this // should call to class Child static // overridden method. Since static // method can not be overridden, it // calls Parent's m1() obj1.m1(); // Here overriding works // and Child's m2() is called obj1.m2(); }}
From parent static m1()
From child non-static(instance) m2()
Private methods can not be overridden : Private methods cannot be overridden as they are bonded during compile time. Therefore we canβt even override private methods in a subclass.(See this for details).
The overriding method must have same return type (or subtype) : From Java 5.0 onwards it is possible to have different return type for a overriding method in child class, but childβs return type should be sub-type of parentβs return type. This phenomena is known as covariant return type.
Invoking overridden method from sub-class : We can call parent class method in overriding method using super keyword.// A Java program to demonstrate that overridden// method can be called from sub-class // Base Classclass Parent { void show() { System.out.println("Parent's show()"); }} // Inherited classclass Child extends Parent { // This method overrides show() of Parent @Override void show() { super.show(); System.out.println("Child's show()"); }} // Driver classclass Main { public static void main(String[] args) { Parent obj = new Child(); obj.show(); }}Output:Parent's show()
Child's show()
// A Java program to demonstrate that overridden// method can be called from sub-class // Base Classclass Parent { void show() { System.out.println("Parent's show()"); }} // Inherited classclass Child extends Parent { // This method overrides show() of Parent @Override void show() { super.show(); System.out.println("Child's show()"); }} // Driver classclass Main { public static void main(String[] args) { Parent obj = new Child(); obj.show(); }}
Parent's show()
Child's show()
Overriding and constructor : We can not override constructor as parent and child class can never have constructor with same name(Constructor name must always be same as Class name).
Overriding and Exception-Handling : Below are two rules to note when overriding methods related to exception-handling.Rule#1 : If the super-class overridden method does not throw an exception, subclass overriding method can only throws the unchecked exception, throwing checked exception will lead to compile-time error./* Java program to demonstrate overriding when superclass method does not declare an exception*/ class Parent { void m1() { System.out.println("From parent m1()"); } void m2() { System.out.println("From parent m2()"); }} class Child extends Parent { @Override // no issue while throwing unchecked exception void m1() throws ArithmeticException { System.out.println("From child m1()"); } @Override // compile-time error // issue while throwing checked exception void m2() throws Exception { System.out.println("From child m2"); }}Output:error: m2() in Child cannot override m2() in Parent
void m2() throws Exception{ System.out.println("From child m2");}
^
overridden method does not throw Exception
Rule#2 : If the super-class overridden method does throws an exception, subclass overriding method can only throw same, subclass exception. Throwing parent exception in Exception hierarchy will lead to compile time error.Also there is no issue if subclass overridden method is not throwing any exception.// Java program to demonstrate overriding when// superclass method does declare an exception class Parent { void m1() throws RuntimeException { System.out.println("From parent m1()"); }} class Child1 extends Parent { @Override // no issue while throwing same exception void m1() throws RuntimeException { System.out.println("From child1 m1()"); }}class Child2 extends Parent { @Override // no issue while throwing subclass exception void m1() throws ArithmeticException { System.out.println("From child2 m1()"); }}class Child3 extends Parent { @Override // no issue while not throwing any exception void m1() { System.out.println("From child3 m1()"); }}class Child4 extends Parent { @Override // compile-time error // issue while throwing parent exception void m1() throws Exception { System.out.println("From child4 m1()"); }}Output:error: m1() in Child4 cannot override m1() in Parent
void m1() throws Exception
^
overridden method does not throw Exception
Rule#1 : If the super-class overridden method does not throw an exception, subclass overriding method can only throws the unchecked exception, throwing checked exception will lead to compile-time error./* Java program to demonstrate overriding when superclass method does not declare an exception*/ class Parent { void m1() { System.out.println("From parent m1()"); } void m2() { System.out.println("From parent m2()"); }} class Child extends Parent { @Override // no issue while throwing unchecked exception void m1() throws ArithmeticException { System.out.println("From child m1()"); } @Override // compile-time error // issue while throwing checked exception void m2() throws Exception { System.out.println("From child m2"); }}Output:error: m2() in Child cannot override m2() in Parent
void m2() throws Exception{ System.out.println("From child m2");}
^
overridden method does not throw Exception
/* Java program to demonstrate overriding when superclass method does not declare an exception*/ class Parent { void m1() { System.out.println("From parent m1()"); } void m2() { System.out.println("From parent m2()"); }} class Child extends Parent { @Override // no issue while throwing unchecked exception void m1() throws ArithmeticException { System.out.println("From child m1()"); } @Override // compile-time error // issue while throwing checked exception void m2() throws Exception { System.out.println("From child m2"); }}
Output:
error: m2() in Child cannot override m2() in Parent
void m2() throws Exception{ System.out.println("From child m2");}
^
overridden method does not throw Exception
Rule#2 : If the super-class overridden method does throws an exception, subclass overriding method can only throw same, subclass exception. Throwing parent exception in Exception hierarchy will lead to compile time error.Also there is no issue if subclass overridden method is not throwing any exception.// Java program to demonstrate overriding when// superclass method does declare an exception class Parent { void m1() throws RuntimeException { System.out.println("From parent m1()"); }} class Child1 extends Parent { @Override // no issue while throwing same exception void m1() throws RuntimeException { System.out.println("From child1 m1()"); }}class Child2 extends Parent { @Override // no issue while throwing subclass exception void m1() throws ArithmeticException { System.out.println("From child2 m1()"); }}class Child3 extends Parent { @Override // no issue while not throwing any exception void m1() { System.out.println("From child3 m1()"); }}class Child4 extends Parent { @Override // compile-time error // issue while throwing parent exception void m1() throws Exception { System.out.println("From child4 m1()"); }}Output:error: m1() in Child4 cannot override m1() in Parent
void m1() throws Exception
^
overridden method does not throw Exception
// Java program to demonstrate overriding when// superclass method does declare an exception class Parent { void m1() throws RuntimeException { System.out.println("From parent m1()"); }} class Child1 extends Parent { @Override // no issue while throwing same exception void m1() throws RuntimeException { System.out.println("From child1 m1()"); }}class Child2 extends Parent { @Override // no issue while throwing subclass exception void m1() throws ArithmeticException { System.out.println("From child2 m1()"); }}class Child3 extends Parent { @Override // no issue while not throwing any exception void m1() { System.out.println("From child3 m1()"); }}class Child4 extends Parent { @Override // compile-time error // issue while throwing parent exception void m1() throws Exception { System.out.println("From child4 m1()"); }}
Output:
error: m1() in Child4 cannot override m1() in Parent
void m1() throws Exception
^
overridden method does not throw Exception
Overriding and abstract method: Abstract methods in an interface or abstract class are meant to be overridden in derived concrete classes otherwise a compile-time error will be thrown.
Overriding and synchronized/strictfp method : The presence of synchronized/strictfp modifier with method have no effect on the rules of overriding, i.e. itβs possible that a synchronized/strictfp method can override a non synchronized/strictfp one and vice-versa.
Note :
In C++, we need virtual keyword to achieve overriding or Run Time Polymorphism. In Java, methods are virtual by default.We can have multilevel method-overriding.// A Java program to demonstrate// multi-level overriding // Base Classclass Parent { void show() { System.out.println("Parent's show()"); }} // Inherited classclass Child extends Parent { // This method overrides show() of Parent void show() { System.out.println("Child's show()"); }} // Inherited classclass GrandChild extends Child { // This method overrides show() of Parent void show() { System.out.println("GrandChild's show()"); }} // Driver classclass Main { public static void main(String[] args) { Parent obj1 = new GrandChild(); obj1.show(); }}Output:GrandChild's show()
Overriding vs Overloading :Overloading is about same method have different signatures. Overriding is about same method, same signature but different classes connected through inheritance.Overloading is an example of compiler-time polymorphism and overriding is an example of run time polymorphism.
In C++, we need virtual keyword to achieve overriding or Run Time Polymorphism. In Java, methods are virtual by default.
We can have multilevel method-overriding.// A Java program to demonstrate// multi-level overriding // Base Classclass Parent { void show() { System.out.println("Parent's show()"); }} // Inherited classclass Child extends Parent { // This method overrides show() of Parent void show() { System.out.println("Child's show()"); }} // Inherited classclass GrandChild extends Child { // This method overrides show() of Parent void show() { System.out.println("GrandChild's show()"); }} // Driver classclass Main { public static void main(String[] args) { Parent obj1 = new GrandChild(); obj1.show(); }}Output:GrandChild's show()
// A Java program to demonstrate// multi-level overriding // Base Classclass Parent { void show() { System.out.println("Parent's show()"); }} // Inherited classclass Child extends Parent { // This method overrides show() of Parent void show() { System.out.println("Child's show()"); }} // Inherited classclass GrandChild extends Child { // This method overrides show() of Parent void show() { System.out.println("GrandChild's show()"); }} // Driver classclass Main { public static void main(String[] args) { Parent obj1 = new GrandChild(); obj1.show(); }}
GrandChild's show()
Overriding vs Overloading :Overloading is about same method have different signatures. Overriding is about same method, same signature but different classes connected through inheritance.Overloading is an example of compiler-time polymorphism and overriding is an example of run time polymorphism.
Overloading is about same method have different signatures. Overriding is about same method, same signature but different classes connected through inheritance.Overloading is an example of compiler-time polymorphism and overriding is an example of run time polymorphism.
Overloading is about same method have different signatures. Overriding is about same method, same signature but different classes connected through inheritance.
Overloading is an example of compiler-time polymorphism and overriding is an example of run time polymorphism.
Why Method Overriding ?
As stated earlier, overridden methods allow Java to support run-time polymorphism. Polymorphism is essential to object-oriented programming for one reason: it allows a general class to specify methods that will be common to all of its derivatives while allowing subclasses to define the specific implementation of some or all of those methods. Overridden methods are another way that Java implements the βone interface, multiple methodsβ aspect of polymorphism.
Dynamic Method Dispatch is one of the most powerful mechanisms that object-oriented design brings to bear on code reuse and robustness. The ability to exist code libraries to call methods on instances of new classes without recompiling while maintaining a clean abstract interface is a profoundly powerful tool.
Overridden methods allow us to call methods of any of the derived classes without even knowing the type of derived class object.
When to apply Method Overriding ?(with example)
Overriding and Inheritance : Part of the key to successfully applying polymorphism is understanding that the superclasses and subclasses form a hierarchy which moves from lesser to greater specialization. Used correctly, the superclass provides all elements that a subclass can use directly. It also defines those methods that the derived class must implement on its own. This allows the subclass the flexibility to define its methods, yet still enforces a consistent interface. Thus, by combining inheritance with overridden methods, a superclass can define the general form of the methods that will be used by all of its subclasses.
Letβs look at a more practical example that uses method overriding. Consider an employee management software for an organization, let the code has a simple base class Employee, the class has methods like raiseSalary(), transfer(), promote(), .. etc. Different types of employees like Manager, Engineer, ..etc may have their implementations of the methods present in base class Employee. In our complete software, we just need to pass a list of employees everywhere and call appropriate methods without even knowing the type of employee. For example, we can easily raise the salary of all employees by iterating through the list of employees. Every type of employee may have its logic in its class, we donβt need to worry because if raiseSalary() is present for a specific employee type, only that method would be called.
// A Simple Java program to demonstrate application// of overriding in Java // Base Classclass Employee { public static int base = 10000; int salary() { return base; }} // Inherited classclass Manager extends Employee { // This method overrides salary() of Parent int salary() { return base + 20000; }} // Inherited classclass Clerk extends Employee { // This method overrides salary() of Parent int salary() { return base + 10000; }} // Driver classclass Main { // This method can be used to print the salary of // any type of employee using base class reference static void printSalary(Employee e) { System.out.println(e.salary()); } public static void main(String[] args) { Employee obj1 = new Manager(); // We could also get type of employee using // one more overridden method.loke getType() System.out.print("Manager's salary : "); printSalary(obj1); Employee obj2 = new Clerk(); System.out.print("Clerk's salary : "); printSalary(obj2); }}
Manager's salary : 30000
Clerk's salary : 20000
Method Overriding (Java Programming Language) | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersMethod Overriding (Java Programming Language) | GeeksforGeeksWatch laterShareCopy link13/17InfoShoppingTap 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 / 16:20β’Liveβ’<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=i6GzimCuFhM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Related Article:
Dynamic Method Dispatch or Runtime Polymorphism in Java
Overriding equals() method of Object class
Overriding toString() method of Object class
Overloading in java
Output of Java program | Set 18 (Overriding)
This article is contributed by Twinkle Tyagi and 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 review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ArpitGupta13
sushantdas
Redjohn77
akashpatra
simmytarika5
java-inheritance
java-overriding
Java
School Programming
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays.sort() in Java with examples
Split() String method in Java with examples
Reverse a string in Java
How to iterate any Map in Java
Stream In Java
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Inheritance in C++
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Mar, 2022"
},
{
"code": null,
"e": 508,
"s": 54,
"text": "In any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, same parameters or signature, and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class."
},
{
"code": null,
"e": 1098,
"s": 508,
"text": "Method overriding is one of the way by which java achieve Run Time Polymorphism.The version of a method that is executed will be determined by the object that is used to invoke it. If an object of a parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the subclass is used to invoke the method, then the version in the child class will be executed. In other words, it is the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed."
},
{
"code": "// A Simple Java program to demonstrate// method overriding in java // Base Classclass Parent { void show() { System.out.println(\"Parent's show()\"); }} // Inherited classclass Child extends Parent { // This method overrides show() of Parent @Override void show() { System.out.println(\"Child's show()\"); }} // Driver classclass Main { public static void main(String[] args) { // If a Parent type reference refers // to a Parent object, then Parent's // show is called Parent obj1 = new Parent(); obj1.show(); // If a Parent type reference refers // to a Child object Child's show() // is called. This is called RUN TIME // POLYMORPHISM. Parent obj2 = new Child(); obj2.show(); }}",
"e": 1906,
"s": 1098,
"text": null
},
{
"code": null,
"e": 1938,
"s": 1906,
"text": "Parent's show()\nChild's show()\n"
},
{
"code": null,
"e": 1969,
"s": 1940,
"text": "Rules for method overriding:"
},
{
"code": null,
"e": 9738,
"s": 1969,
"text": "Overriding and Access-Modifiers : The access modifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the super-class can be made public, but not private, in the subclass. Doing so, will generate compile-time error.// A Simple Java program to demonstrate// Overriding and Access-Modifiers class Parent { // private methods are not overridden private void m1() { System.out.println(\"From parent m1()\"); } protected void m2() { System.out.println(\"From parent m2()\"); }} class Child extends Parent { // new m1() method // unique to Child class private void m1() { System.out.println(\"From child m1()\"); } // overriding method // with more accessibility @Override public void m2() { System.out.println(\"From child m2()\"); }} // Driver classclass Main { public static void main(String[] args) { Parent obj1 = new Parent(); obj1.m2(); Parent obj2 = new Child(); obj2.m2(); }}Output:From parent m2()\nFrom child m2()\n Final methods can not be overridden : If we donβt want a method to be overridden, we declare it as final. Please see Using final with Inheritance .// A Java program to demonstrate that// final methods cannot be overridden class Parent { // Can't be overridden final void show() {}} class Child extends Parent { // This would produce error void show() {}}Output:13: error: show() in Child cannot override show() in Parent\n void show() { }\n ^\n overridden method is final\nStatic methods can not be overridden(Method Overriding vs Method Hiding) : When you define a static method with same signature as a static method in base class, it is known as method hiding.The following table summarizes what happens when you define a method with the same signature as a method in a super-class. Superclass Instance MethodSuperclass Static MethodSubclass Instance MethodOverridesGenerates a compile-time errorSubclass Static MethodGenerates a compile-time errorHides// Java program to show that// if the static method is redefined by// a derived class, then it is not// overriding, it is hiding class Parent { // Static method in base class // which will be hidden in subclass static void m1() { System.out.println(\"From parent \" + \"static m1()\"); } // Non-static method which will // be overridden in derived class void m2() { System.out.println(\"From parent \" + \"non-static(instance) m2()\"); }} class Child extends Parent { // This method hides m1() in Parent static void m1() { System.out.println(\"From child static m1()\"); } // This method overrides m2() in Parent @Override public void m2() { System.out.println(\"From child \" + \"non-static(instance) m2()\"); }} // Driver classclass Main { public static void main(String[] args) { Parent obj1 = new Child(); // As per overriding rules this // should call to class Child static // overridden method. Since static // method can not be overridden, it // calls Parent's m1() obj1.m1(); // Here overriding works // and Child's m2() is called obj1.m2(); }}Output:From parent static m1()\nFrom child non-static(instance) m2()\n Private methods can not be overridden : Private methods cannot be overridden as they are bonded during compile time. Therefore we canβt even override private methods in a subclass.(See this for details). The overriding method must have same return type (or subtype) : From Java 5.0 onwards it is possible to have different return type for a overriding method in child class, but childβs return type should be sub-type of parentβs return type. This phenomena is known as covariant return type. Invoking overridden method from sub-class : We can call parent class method in overriding method using super keyword.// A Java program to demonstrate that overridden// method can be called from sub-class // Base Classclass Parent { void show() { System.out.println(\"Parent's show()\"); }} // Inherited classclass Child extends Parent { // This method overrides show() of Parent @Override void show() { super.show(); System.out.println(\"Child's show()\"); }} // Driver classclass Main { public static void main(String[] args) { Parent obj = new Child(); obj.show(); }}Output:Parent's show()\nChild's show()\nOverriding and constructor : We can not override constructor as parent and child class can never have constructor with same name(Constructor name must always be same as Class name).Overriding and Exception-Handling : Below are two rules to note when overriding methods related to exception-handling.Rule#1 : If the super-class overridden method does not throw an exception, subclass overriding method can only throws the unchecked exception, throwing checked exception will lead to compile-time error./* Java program to demonstrate overriding when superclass method does not declare an exception*/ class Parent { void m1() { System.out.println(\"From parent m1()\"); } void m2() { System.out.println(\"From parent m2()\"); }} class Child extends Parent { @Override // no issue while throwing unchecked exception void m1() throws ArithmeticException { System.out.println(\"From child m1()\"); } @Override // compile-time error // issue while throwing checked exception void m2() throws Exception { System.out.println(\"From child m2\"); }}Output:error: m2() in Child cannot override m2() in Parent\n void m2() throws Exception{ System.out.println(\"From child m2\");}\n ^\n overridden method does not throw Exception\nRule#2 : If the super-class overridden method does throws an exception, subclass overriding method can only throw same, subclass exception. Throwing parent exception in Exception hierarchy will lead to compile time error.Also there is no issue if subclass overridden method is not throwing any exception.// Java program to demonstrate overriding when// superclass method does declare an exception class Parent { void m1() throws RuntimeException { System.out.println(\"From parent m1()\"); }} class Child1 extends Parent { @Override // no issue while throwing same exception void m1() throws RuntimeException { System.out.println(\"From child1 m1()\"); }}class Child2 extends Parent { @Override // no issue while throwing subclass exception void m1() throws ArithmeticException { System.out.println(\"From child2 m1()\"); }}class Child3 extends Parent { @Override // no issue while not throwing any exception void m1() { System.out.println(\"From child3 m1()\"); }}class Child4 extends Parent { @Override // compile-time error // issue while throwing parent exception void m1() throws Exception { System.out.println(\"From child4 m1()\"); }}Output:error: m1() in Child4 cannot override m1() in Parent\n void m1() throws Exception\n ^\n overridden method does not throw Exception\n Overriding and abstract method: Abstract methods in an interface or abstract class are meant to be overridden in derived concrete classes otherwise a compile-time error will be thrown. Overriding and synchronized/strictfp method : The presence of synchronized/strictfp modifier with method have no effect on the rules of overriding, i.e. itβs possible that a synchronized/strictfp method can override a non synchronized/strictfp one and vice-versa."
},
{
"code": null,
"e": 10861,
"s": 9738,
"text": "Overriding and Access-Modifiers : The access modifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the super-class can be made public, but not private, in the subclass. Doing so, will generate compile-time error.// A Simple Java program to demonstrate// Overriding and Access-Modifiers class Parent { // private methods are not overridden private void m1() { System.out.println(\"From parent m1()\"); } protected void m2() { System.out.println(\"From parent m2()\"); }} class Child extends Parent { // new m1() method // unique to Child class private void m1() { System.out.println(\"From child m1()\"); } // overriding method // with more accessibility @Override public void m2() { System.out.println(\"From child m2()\"); }} // Driver classclass Main { public static void main(String[] args) { Parent obj1 = new Parent(); obj1.m2(); Parent obj2 = new Child(); obj2.m2(); }}Output:From parent m2()\nFrom child m2()\n"
},
{
"code": "// A Simple Java program to demonstrate// Overriding and Access-Modifiers class Parent { // private methods are not overridden private void m1() { System.out.println(\"From parent m1()\"); } protected void m2() { System.out.println(\"From parent m2()\"); }} class Child extends Parent { // new m1() method // unique to Child class private void m1() { System.out.println(\"From child m1()\"); } // overriding method // with more accessibility @Override public void m2() { System.out.println(\"From child m2()\"); }} // Driver classclass Main { public static void main(String[] args) { Parent obj1 = new Parent(); obj1.m2(); Parent obj2 = new Child(); obj2.m2(); }}",
"e": 11643,
"s": 10861,
"text": null
},
{
"code": null,
"e": 11677,
"s": 11643,
"text": "From parent m2()\nFrom child m2()\n"
},
{
"code": null,
"e": 12176,
"s": 11679,
"text": "Final methods can not be overridden : If we donβt want a method to be overridden, we declare it as final. Please see Using final with Inheritance .// A Java program to demonstrate that// final methods cannot be overridden class Parent { // Can't be overridden final void show() {}} class Child extends Parent { // This would produce error void show() {}}Output:13: error: show() in Child cannot override show() in Parent\n void show() { }\n ^\n overridden method is final\n"
},
{
"code": "// A Java program to demonstrate that// final methods cannot be overridden class Parent { // Can't be overridden final void show() {}} class Child extends Parent { // This would produce error void show() {}}",
"e": 12398,
"s": 12176,
"text": null
},
{
"code": null,
"e": 12406,
"s": 12398,
"text": "Output:"
},
{
"code": null,
"e": 12528,
"s": 12406,
"text": "13: error: show() in Child cannot override show() in Parent\n void show() { }\n ^\n overridden method is final\n"
},
{
"code": null,
"e": 14371,
"s": 12528,
"text": "Static methods can not be overridden(Method Overriding vs Method Hiding) : When you define a static method with same signature as a static method in base class, it is known as method hiding.The following table summarizes what happens when you define a method with the same signature as a method in a super-class. Superclass Instance MethodSuperclass Static MethodSubclass Instance MethodOverridesGenerates a compile-time errorSubclass Static MethodGenerates a compile-time errorHides// Java program to show that// if the static method is redefined by// a derived class, then it is not// overriding, it is hiding class Parent { // Static method in base class // which will be hidden in subclass static void m1() { System.out.println(\"From parent \" + \"static m1()\"); } // Non-static method which will // be overridden in derived class void m2() { System.out.println(\"From parent \" + \"non-static(instance) m2()\"); }} class Child extends Parent { // This method hides m1() in Parent static void m1() { System.out.println(\"From child static m1()\"); } // This method overrides m2() in Parent @Override public void m2() { System.out.println(\"From child \" + \"non-static(instance) m2()\"); }} // Driver classclass Main { public static void main(String[] args) { Parent obj1 = new Child(); // As per overriding rules this // should call to class Child static // overridden method. Since static // method can not be overridden, it // calls Parent's m1() obj1.m1(); // Here overriding works // and Child's m2() is called obj1.m2(); }}Output:From parent static m1()\nFrom child non-static(instance) m2()\n"
},
{
"code": null,
"e": 14494,
"s": 14371,
"text": "The following table summarizes what happens when you define a method with the same signature as a method in a super-class."
},
{
"code": "// Java program to show that// if the static method is redefined by// a derived class, then it is not// overriding, it is hiding class Parent { // Static method in base class // which will be hidden in subclass static void m1() { System.out.println(\"From parent \" + \"static m1()\"); } // Non-static method which will // be overridden in derived class void m2() { System.out.println(\"From parent \" + \"non-static(instance) m2()\"); }} class Child extends Parent { // This method hides m1() in Parent static void m1() { System.out.println(\"From child static m1()\"); } // This method overrides m2() in Parent @Override public void m2() { System.out.println(\"From child \" + \"non-static(instance) m2()\"); }} // Driver classclass Main { public static void main(String[] args) { Parent obj1 = new Child(); // As per overriding rules this // should call to class Child static // overridden method. Since static // method can not be overridden, it // calls Parent's m1() obj1.m1(); // Here overriding works // and Child's m2() is called obj1.m2(); }}",
"e": 15786,
"s": 14494,
"text": null
},
{
"code": null,
"e": 15848,
"s": 15786,
"text": "From parent static m1()\nFrom child non-static(instance) m2()\n"
},
{
"code": null,
"e": 16054,
"s": 15850,
"text": "Private methods can not be overridden : Private methods cannot be overridden as they are bonded during compile time. Therefore we canβt even override private methods in a subclass.(See this for details)."
},
{
"code": null,
"e": 16345,
"s": 16056,
"text": "The overriding method must have same return type (or subtype) : From Java 5.0 onwards it is possible to have different return type for a overriding method in child class, but childβs return type should be sub-type of parentβs return type. This phenomena is known as covariant return type."
},
{
"code": null,
"e": 17022,
"s": 16347,
"text": "Invoking overridden method from sub-class : We can call parent class method in overriding method using super keyword.// A Java program to demonstrate that overridden// method can be called from sub-class // Base Classclass Parent { void show() { System.out.println(\"Parent's show()\"); }} // Inherited classclass Child extends Parent { // This method overrides show() of Parent @Override void show() { super.show(); System.out.println(\"Child's show()\"); }} // Driver classclass Main { public static void main(String[] args) { Parent obj = new Child(); obj.show(); }}Output:Parent's show()\nChild's show()\n"
},
{
"code": "// A Java program to demonstrate that overridden// method can be called from sub-class // Base Classclass Parent { void show() { System.out.println(\"Parent's show()\"); }} // Inherited classclass Child extends Parent { // This method overrides show() of Parent @Override void show() { super.show(); System.out.println(\"Child's show()\"); }} // Driver classclass Main { public static void main(String[] args) { Parent obj = new Child(); obj.show(); }}",
"e": 17542,
"s": 17022,
"text": null
},
{
"code": null,
"e": 17574,
"s": 17542,
"text": "Parent's show()\nChild's show()\n"
},
{
"code": null,
"e": 17756,
"s": 17574,
"text": "Overriding and constructor : We can not override constructor as parent and child class can never have constructor with same name(Constructor name must always be same as Class name)."
},
{
"code": null,
"e": 20266,
"s": 17756,
"text": "Overriding and Exception-Handling : Below are two rules to note when overriding methods related to exception-handling.Rule#1 : If the super-class overridden method does not throw an exception, subclass overriding method can only throws the unchecked exception, throwing checked exception will lead to compile-time error./* Java program to demonstrate overriding when superclass method does not declare an exception*/ class Parent { void m1() { System.out.println(\"From parent m1()\"); } void m2() { System.out.println(\"From parent m2()\"); }} class Child extends Parent { @Override // no issue while throwing unchecked exception void m1() throws ArithmeticException { System.out.println(\"From child m1()\"); } @Override // compile-time error // issue while throwing checked exception void m2() throws Exception { System.out.println(\"From child m2\"); }}Output:error: m2() in Child cannot override m2() in Parent\n void m2() throws Exception{ System.out.println(\"From child m2\");}\n ^\n overridden method does not throw Exception\nRule#2 : If the super-class overridden method does throws an exception, subclass overriding method can only throw same, subclass exception. Throwing parent exception in Exception hierarchy will lead to compile time error.Also there is no issue if subclass overridden method is not throwing any exception.// Java program to demonstrate overriding when// superclass method does declare an exception class Parent { void m1() throws RuntimeException { System.out.println(\"From parent m1()\"); }} class Child1 extends Parent { @Override // no issue while throwing same exception void m1() throws RuntimeException { System.out.println(\"From child1 m1()\"); }}class Child2 extends Parent { @Override // no issue while throwing subclass exception void m1() throws ArithmeticException { System.out.println(\"From child2 m1()\"); }}class Child3 extends Parent { @Override // no issue while not throwing any exception void m1() { System.out.println(\"From child3 m1()\"); }}class Child4 extends Parent { @Override // compile-time error // issue while throwing parent exception void m1() throws Exception { System.out.println(\"From child4 m1()\"); }}Output:error: m1() in Child4 cannot override m1() in Parent\n void m1() throws Exception\n ^\n overridden method does not throw Exception\n"
},
{
"code": null,
"e": 21271,
"s": 20266,
"text": "Rule#1 : If the super-class overridden method does not throw an exception, subclass overriding method can only throws the unchecked exception, throwing checked exception will lead to compile-time error./* Java program to demonstrate overriding when superclass method does not declare an exception*/ class Parent { void m1() { System.out.println(\"From parent m1()\"); } void m2() { System.out.println(\"From parent m2()\"); }} class Child extends Parent { @Override // no issue while throwing unchecked exception void m1() throws ArithmeticException { System.out.println(\"From child m1()\"); } @Override // compile-time error // issue while throwing checked exception void m2() throws Exception { System.out.println(\"From child m2\"); }}Output:error: m2() in Child cannot override m2() in Parent\n void m2() throws Exception{ System.out.println(\"From child m2\");}\n ^\n overridden method does not throw Exception\n"
},
{
"code": "/* Java program to demonstrate overriding when superclass method does not declare an exception*/ class Parent { void m1() { System.out.println(\"From parent m1()\"); } void m2() { System.out.println(\"From parent m2()\"); }} class Child extends Parent { @Override // no issue while throwing unchecked exception void m1() throws ArithmeticException { System.out.println(\"From child m1()\"); } @Override // compile-time error // issue while throwing checked exception void m2() throws Exception { System.out.println(\"From child m2\"); }}",
"e": 21889,
"s": 21271,
"text": null
},
{
"code": null,
"e": 21897,
"s": 21889,
"text": "Output:"
},
{
"code": null,
"e": 22076,
"s": 21897,
"text": "error: m2() in Child cannot override m2() in Parent\n void m2() throws Exception{ System.out.println(\"From child m2\");}\n ^\n overridden method does not throw Exception\n"
},
{
"code": null,
"e": 23464,
"s": 22076,
"text": "Rule#2 : If the super-class overridden method does throws an exception, subclass overriding method can only throw same, subclass exception. Throwing parent exception in Exception hierarchy will lead to compile time error.Also there is no issue if subclass overridden method is not throwing any exception.// Java program to demonstrate overriding when// superclass method does declare an exception class Parent { void m1() throws RuntimeException { System.out.println(\"From parent m1()\"); }} class Child1 extends Parent { @Override // no issue while throwing same exception void m1() throws RuntimeException { System.out.println(\"From child1 m1()\"); }}class Child2 extends Parent { @Override // no issue while throwing subclass exception void m1() throws ArithmeticException { System.out.println(\"From child2 m1()\"); }}class Child3 extends Parent { @Override // no issue while not throwing any exception void m1() { System.out.println(\"From child3 m1()\"); }}class Child4 extends Parent { @Override // compile-time error // issue while throwing parent exception void m1() throws Exception { System.out.println(\"From child4 m1()\"); }}Output:error: m1() in Child4 cannot override m1() in Parent\n void m1() throws Exception\n ^\n overridden method does not throw Exception\n"
},
{
"code": "// Java program to demonstrate overriding when// superclass method does declare an exception class Parent { void m1() throws RuntimeException { System.out.println(\"From parent m1()\"); }} class Child1 extends Parent { @Override // no issue while throwing same exception void m1() throws RuntimeException { System.out.println(\"From child1 m1()\"); }}class Child2 extends Parent { @Override // no issue while throwing subclass exception void m1() throws ArithmeticException { System.out.println(\"From child2 m1()\"); }}class Child3 extends Parent { @Override // no issue while not throwing any exception void m1() { System.out.println(\"From child3 m1()\"); }}class Child4 extends Parent { @Override // compile-time error // issue while throwing parent exception void m1() throws Exception { System.out.println(\"From child4 m1()\"); }}",
"e": 24401,
"s": 23464,
"text": null
},
{
"code": null,
"e": 24409,
"s": 24401,
"text": "Output:"
},
{
"code": null,
"e": 24550,
"s": 24409,
"text": "error: m1() in Child4 cannot override m1() in Parent\n void m1() throws Exception\n ^\n overridden method does not throw Exception\n"
},
{
"code": null,
"e": 24737,
"s": 24552,
"text": "Overriding and abstract method: Abstract methods in an interface or abstract class are meant to be overridden in derived concrete classes otherwise a compile-time error will be thrown."
},
{
"code": null,
"e": 25003,
"s": 24739,
"text": "Overriding and synchronized/strictfp method : The presence of synchronized/strictfp modifier with method have no effect on the rules of overriding, i.e. itβs possible that a synchronized/strictfp method can override a non synchronized/strictfp one and vice-versa."
},
{
"code": null,
"e": 25010,
"s": 25003,
"text": "Note :"
},
{
"code": null,
"e": 26119,
"s": 25010,
"text": "In C++, we need virtual keyword to achieve overriding or Run Time Polymorphism. In Java, methods are virtual by default.We can have multilevel method-overriding.// A Java program to demonstrate// multi-level overriding // Base Classclass Parent { void show() { System.out.println(\"Parent's show()\"); }} // Inherited classclass Child extends Parent { // This method overrides show() of Parent void show() { System.out.println(\"Child's show()\"); }} // Inherited classclass GrandChild extends Child { // This method overrides show() of Parent void show() { System.out.println(\"GrandChild's show()\"); }} // Driver classclass Main { public static void main(String[] args) { Parent obj1 = new GrandChild(); obj1.show(); }}Output:GrandChild's show()\nOverriding vs Overloading :Overloading is about same method have different signatures. Overriding is about same method, same signature but different classes connected through inheritance.Overloading is an example of compiler-time polymorphism and overriding is an example of run time polymorphism."
},
{
"code": null,
"e": 26240,
"s": 26119,
"text": "In C++, we need virtual keyword to achieve overriding or Run Time Polymorphism. In Java, methods are virtual by default."
},
{
"code": null,
"e": 26932,
"s": 26240,
"text": "We can have multilevel method-overriding.// A Java program to demonstrate// multi-level overriding // Base Classclass Parent { void show() { System.out.println(\"Parent's show()\"); }} // Inherited classclass Child extends Parent { // This method overrides show() of Parent void show() { System.out.println(\"Child's show()\"); }} // Inherited classclass GrandChild extends Child { // This method overrides show() of Parent void show() { System.out.println(\"GrandChild's show()\"); }} // Driver classclass Main { public static void main(String[] args) { Parent obj1 = new GrandChild(); obj1.show(); }}Output:GrandChild's show()\n"
},
{
"code": "// A Java program to demonstrate// multi-level overriding // Base Classclass Parent { void show() { System.out.println(\"Parent's show()\"); }} // Inherited classclass Child extends Parent { // This method overrides show() of Parent void show() { System.out.println(\"Child's show()\"); }} // Inherited classclass GrandChild extends Child { // This method overrides show() of Parent void show() { System.out.println(\"GrandChild's show()\"); }} // Driver classclass Main { public static void main(String[] args) { Parent obj1 = new GrandChild(); obj1.show(); }}",
"e": 27556,
"s": 26932,
"text": null
},
{
"code": null,
"e": 27577,
"s": 27556,
"text": "GrandChild's show()\n"
},
{
"code": null,
"e": 27875,
"s": 27577,
"text": "Overriding vs Overloading :Overloading is about same method have different signatures. Overriding is about same method, same signature but different classes connected through inheritance.Overloading is an example of compiler-time polymorphism and overriding is an example of run time polymorphism."
},
{
"code": null,
"e": 28146,
"s": 27875,
"text": "Overloading is about same method have different signatures. Overriding is about same method, same signature but different classes connected through inheritance.Overloading is an example of compiler-time polymorphism and overriding is an example of run time polymorphism."
},
{
"code": null,
"e": 28307,
"s": 28146,
"text": "Overloading is about same method have different signatures. Overriding is about same method, same signature but different classes connected through inheritance."
},
{
"code": null,
"e": 28418,
"s": 28307,
"text": "Overloading is an example of compiler-time polymorphism and overriding is an example of run time polymorphism."
},
{
"code": null,
"e": 28442,
"s": 28418,
"text": "Why Method Overriding ?"
},
{
"code": null,
"e": 28904,
"s": 28442,
"text": "As stated earlier, overridden methods allow Java to support run-time polymorphism. Polymorphism is essential to object-oriented programming for one reason: it allows a general class to specify methods that will be common to all of its derivatives while allowing subclasses to define the specific implementation of some or all of those methods. Overridden methods are another way that Java implements the βone interface, multiple methodsβ aspect of polymorphism."
},
{
"code": null,
"e": 29216,
"s": 28904,
"text": "Dynamic Method Dispatch is one of the most powerful mechanisms that object-oriented design brings to bear on code reuse and robustness. The ability to exist code libraries to call methods on instances of new classes without recompiling while maintaining a clean abstract interface is a profoundly powerful tool."
},
{
"code": null,
"e": 29345,
"s": 29216,
"text": "Overridden methods allow us to call methods of any of the derived classes without even knowing the type of derived class object."
},
{
"code": null,
"e": 29395,
"s": 29347,
"text": "When to apply Method Overriding ?(with example)"
},
{
"code": null,
"e": 30030,
"s": 29395,
"text": "Overriding and Inheritance : Part of the key to successfully applying polymorphism is understanding that the superclasses and subclasses form a hierarchy which moves from lesser to greater specialization. Used correctly, the superclass provides all elements that a subclass can use directly. It also defines those methods that the derived class must implement on its own. This allows the subclass the flexibility to define its methods, yet still enforces a consistent interface. Thus, by combining inheritance with overridden methods, a superclass can define the general form of the methods that will be used by all of its subclasses."
},
{
"code": null,
"e": 30851,
"s": 30030,
"text": "Letβs look at a more practical example that uses method overriding. Consider an employee management software for an organization, let the code has a simple base class Employee, the class has methods like raiseSalary(), transfer(), promote(), .. etc. Different types of employees like Manager, Engineer, ..etc may have their implementations of the methods present in base class Employee. In our complete software, we just need to pass a list of employees everywhere and call appropriate methods without even knowing the type of employee. For example, we can easily raise the salary of all employees by iterating through the list of employees. Every type of employee may have its logic in its class, we donβt need to worry because if raiseSalary() is present for a specific employee type, only that method would be called."
},
{
"code": "// A Simple Java program to demonstrate application// of overriding in Java // Base Classclass Employee { public static int base = 10000; int salary() { return base; }} // Inherited classclass Manager extends Employee { // This method overrides salary() of Parent int salary() { return base + 20000; }} // Inherited classclass Clerk extends Employee { // This method overrides salary() of Parent int salary() { return base + 10000; }} // Driver classclass Main { // This method can be used to print the salary of // any type of employee using base class reference static void printSalary(Employee e) { System.out.println(e.salary()); } public static void main(String[] args) { Employee obj1 = new Manager(); // We could also get type of employee using // one more overridden method.loke getType() System.out.print(\"Manager's salary : \"); printSalary(obj1); Employee obj2 = new Clerk(); System.out.print(\"Clerk's salary : \"); printSalary(obj2); }}",
"e": 31952,
"s": 30851,
"text": null
},
{
"code": null,
"e": 32001,
"s": 31952,
"text": "Manager's salary : 30000\nClerk's salary : 20000\n"
},
{
"code": null,
"e": 32915,
"s": 32001,
"text": "Method Overriding (Java Programming Language) | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersMethod Overriding (Java Programming Language) | GeeksforGeeksWatch laterShareCopy link13/17InfoShoppingTap 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 / 16:20β’Liveβ’<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=i6GzimCuFhM\" 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": 32932,
"s": 32915,
"text": "Related Article:"
},
{
"code": null,
"e": 32988,
"s": 32932,
"text": "Dynamic Method Dispatch or Runtime Polymorphism in Java"
},
{
"code": null,
"e": 33031,
"s": 32988,
"text": "Overriding equals() method of Object class"
},
{
"code": null,
"e": 33076,
"s": 33031,
"text": "Overriding toString() method of Object class"
},
{
"code": null,
"e": 33096,
"s": 33076,
"text": "Overloading in java"
},
{
"code": null,
"e": 33141,
"s": 33096,
"text": "Output of Java program | Set 18 (Overriding)"
},
{
"code": null,
"e": 33457,
"s": 33141,
"text": "This article is contributed by Twinkle Tyagi and 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 review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 33582,
"s": 33457,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 33595,
"s": 33582,
"text": "ArpitGupta13"
},
{
"code": null,
"e": 33606,
"s": 33595,
"text": "sushantdas"
},
{
"code": null,
"e": 33616,
"s": 33606,
"text": "Redjohn77"
},
{
"code": null,
"e": 33627,
"s": 33616,
"text": "akashpatra"
},
{
"code": null,
"e": 33640,
"s": 33627,
"text": "simmytarika5"
},
{
"code": null,
"e": 33657,
"s": 33640,
"text": "java-inheritance"
},
{
"code": null,
"e": 33673,
"s": 33657,
"text": "java-overriding"
},
{
"code": null,
"e": 33678,
"s": 33673,
"text": "Java"
},
{
"code": null,
"e": 33697,
"s": 33678,
"text": "School Programming"
},
{
"code": null,
"e": 33702,
"s": 33697,
"text": "Java"
},
{
"code": null,
"e": 33800,
"s": 33702,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33836,
"s": 33800,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 33880,
"s": 33836,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 33905,
"s": 33880,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 33936,
"s": 33905,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 33951,
"s": 33936,
"text": "Stream In Java"
},
{
"code": null,
"e": 33969,
"s": 33951,
"text": "Python Dictionary"
},
{
"code": null,
"e": 33994,
"s": 33969,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 34010,
"s": 33994,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 34033,
"s": 34010,
"text": "Introduction To PYTHON"
}
] |
Form a palindrome | Practice | GeeksforGeeks
|
Given a string, find the minimum number of characters to be inserted to convert it to palindrome.
For Example:
ab: Number of insertions required is 1. bab or aba
aa: Number of insertions required is 0. aa
abcd: Number of insertions required is 3. dcbabcd
Example 1:
Input: str = "abcd"
Output: 3
Explanation: Inserted character marked
with bold characters in dcbabcd
Example 2:
Input: str = "aa"
Output: 0
Explanation:"aa" is already a palindrome.
Your Task:
You don't need to read input or print anything. Your task is to complete the function countMin() which takes the string str as inputs and returns the answer.
Expected Time Complexity: O(N2), N = |str|
Expected Auxiliary Space: O(N2)
Constraints:
1 β€ |str| β€ 103
str contains only lower case alphabets.
0
chessnoobdjin 8 hours
C++
int findMinInsertions(string S){
int n = S.size(), dp[n+1][n+1];
memset(dp, 0, sizeof(dp));
string s = S;
reverse(s.begin(), s.end());
for(int i=1; i<=n; i++){
for(int j=1; j<=n; j++){
if(s[i-1] == S[j-1])
dp[i][j] += 1+dp[i-1][j-1];
else
dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
}
}
return n-dp[n][n];
}
+1
akkeshri140420011 day ago
int lps(vector<vector<int>>&dp,int n,string &str){
for(int g=0;g<n;g++){
for(int i=0,j=g;j<n;j++,i++){
if(g==0){
dp[i][j]=1;
}
else if(g==1){
if(str[i]==str[j]){
dp[i][j]=2;
}
else{
dp[i][j]=1;
}
}
else{
if(str[i]==str[j]){
dp[i][j]=2+dp[i+1][j-1];
}
else{
dp[i][j]=max(dp[i][j-1],dp[i+1][j]);
}
}
}
}
return dp[0][n-1];
}
int countMin(string str){
//complete the function here
int n=str.length();
vector<vector<int>>dp(n,vector<int>(n));
return n-lps(dp,n,str);
}
0
himanshukug19cs2 days ago
int[][] dp; int sol(String str,int i ,int j){ if(i>=j) return 0; if(dp[i][j]!=-1) return dp[i][j]; if(str.charAt(i)==str.charAt(j)) return dp[i][j]=sol(str,i+1,j-1); else return dp[i][j]=1+Math.min(sol(str,i+1,j),sol(str,i,j-1)); } int countMin(String str) { // code here dp= new int[str.length()][str.length()]; for(int i=0;i<str.length();i++){ Arrays.fill(dp[i],-1); } return sol(str,0,str.length()-1); }
0
2019sushilkumarkori5 days ago
int countMin(string str){
//complete the function here
int n = str.length();
string str2 = str;
reverse(str2.begin(),str2.end());
int t[n+1][n+1];
for(int i=0;i<=n;i++){
for(int j=0;j<=n;j++){
if(i==0 || j==0){
t[i][j] = 0;
}
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(str[i-1]==str2[j-1]){
t[i][j] = 1+t[i-1][j-1];
}
else{
t[i][j] = max(t[i][j-1],t[i-1][j]);
}
}
}
return n-t[n][n];
}
0
taakiyabhicu
This comment was deleted.
+1
1107khyati2 weeks ago
n-LPS(str) and to find LPS = LCS(str, reverse of str)
class Solution{
public:
int LCS(string str,string s)
{
int n=str.length();
int m=s.length();
int maxi=INT_MIN;
vector<vector<int>>dp(n+1,vector<int>(m+1,0));
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if(str[i-1]==s[j-1])
{
dp[i][j]=1+dp[i-1][j-1];
maxi=max(maxi,dp[i][j]);
}
else
dp[i][j]=max(dp[i][j-1],dp[i-1][j]);
}
}
if(maxi==INT_MIN)
return 0;
else
return maxi;
}
int countMin(string str)
{
int n=str.length();
string s=str;
reverse(s.begin(),s.end());
return n-LCS(str,s);
}
};
+1
mbi20210122 weeks ago
class Solution{ public: int cm(string &str, string &t, vector<vector<int>>&dp, int i, int j) { if(i<0 || j<0)return 0; if(dp[i][j]!=-1)return dp[i][j]; int ta=0,nt=0; if(str[i]==t[j]) { ta= 1+cm(str,t,dp,i-1,j-1); } nt= max( cm(str,t,dp,i-1,j), cm(str,t,dp,i,j-1) ); return dp[i][j]= max(ta,nt); } int countMin(string str){ int flag=0; int n=str.size(); vector<vector<int>>dp(n, vector<int>(n,-1)); string t=str; reverse(t.begin(), t.end()); int ans= cm(str, t, dp, n-1,n-1); ans=n-ans; return ans; }};
0
shivaraj52 weeks ago
//Simple LCS
int countMin(string s1){ //complete the function here string s2=s1; reverse(s2.begin(),s2.end()); int n=s1.length(); int m=s2.length(); int dp[n+1][m+1]; for(int i=0;i<=n;i++){ for(int j=0;j<=m;j++){ if(i==0 || j==0) dp[i][j]=0; else if(s1[i-1]==s2[j-1]) dp[i][j]=1+dp[i-1][j-1]; else dp[i][j]=max(dp[i-1][j],dp[i][j-1]); } } //m-dp[n][m] -> insertion return m-dp[n][m]; }
0
parasdhanwal2 weeks ago
Java | DP
class Solution{
static int countMin(String a)
{
String b="";
for (int i=0; i<a.length(); i++)
{
char ch=a.charAt(i);
b=ch+b;
}
int x=a.length();
return (x-lcs(x-1,x-1,a,b));
}
static int lcs(int x, int y, String a, String b)
{
if(a.equals(b)){
return a.length();
}
int dp[][]= new int [a.length()+1][b.length()+1];
for(int i=1;i<=a.length();i++){
for(int j=1;j<=b.length();j++){
if(a.charAt(i-1)==b.charAt(j-1)){
dp[i][j]=dp[i-1][j-1]+1;
}
else{
dp[i][j]=Math.max(dp[i-1][j],dp[i][j-1]);
}
}
}
return (dp[a.length()][b.length()]);
}
}
0
piyushpravanjan3332 weeks ago
DP Solution Using PYTHON (Using Concept of LCS AND LPS)
class Solution: def lcs(self,Str1,Str2): n = len(Str1) m=len(Str2) dp = [[-1]*(m+1) for _ in range(n+1)] for i in range(n+1): dp[i][0] = 0 for j in range(m+1): dp[0][j] =0 for i in range(1,n+1): for j in range(1,m+1): if(Str1[i-1]==Str2[j-1]): dp[i][j] = 1+dp[i-1][j-1] else: dp[i][j] = max(dp[i-1][j],dp[i][j-1]) return dp[n][m] def LongPalinSeq(self,Str): Str1= Str[::-1] return self.lcs(Str,Str1) def countMin(self, Str): # code here return len(Str) - self.LongPalinSeq(Str)
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.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems 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": 493,
"s": 238,
"text": "Given a string, find the minimum number of characters to be inserted to convert it to palindrome.\nFor Example:\nab: Number of insertions required is 1. bab or aba\naa: Number of insertions required is 0. aa\nabcd: Number of insertions required is 3. dcbabcd"
},
{
"code": null,
"e": 505,
"s": 493,
"text": "\nExample 1:"
},
{
"code": null,
"e": 607,
"s": 505,
"text": "Input: str = \"abcd\"\nOutput: 3\nExplanation: Inserted character marked\nwith bold characters in dcbabcd\n"
},
{
"code": null,
"e": 618,
"s": 607,
"text": "Example 2:"
},
{
"code": null,
"e": 688,
"s": 618,
"text": "Input: str = \"aa\"\nOutput: 0\nExplanation:\"aa\" is already a palindrome."
},
{
"code": null,
"e": 1006,
"s": 688,
"text": "\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function countMin() which takes the string str as inputs and returns the answer.\n\nExpected Time Complexity: O(N2), N = |str|\nExpected Auxiliary Space: O(N2)\n\nConstraints:\n1 β€ |str| β€ 103\nstr contains only lower case alphabets."
},
{
"code": null,
"e": 1008,
"s": 1006,
"text": "0"
},
{
"code": null,
"e": 1030,
"s": 1008,
"text": "chessnoobdjin 8 hours"
},
{
"code": null,
"e": 1034,
"s": 1030,
"text": "C++"
},
{
"code": null,
"e": 1438,
"s": 1034,
"text": "int findMinInsertions(string S){\n int n = S.size(), dp[n+1][n+1];\n memset(dp, 0, sizeof(dp));\n string s = S;\n reverse(s.begin(), s.end());\n for(int i=1; i<=n; i++){\n for(int j=1; j<=n; j++){\n if(s[i-1] == S[j-1])\n dp[i][j] += 1+dp[i-1][j-1];\n else\n dp[i][j] = max(dp[i-1][j], dp[i][j-1]);\n }\n }\n return n-dp[n][n];\n}"
},
{
"code": null,
"e": 1441,
"s": 1438,
"text": "+1"
},
{
"code": null,
"e": 1467,
"s": 1441,
"text": "akkeshri140420011 day ago"
},
{
"code": null,
"e": 2280,
"s": 1467,
"text": "int lps(vector<vector<int>>&dp,int n,string &str){\n for(int g=0;g<n;g++){\n for(int i=0,j=g;j<n;j++,i++){\n if(g==0){\n dp[i][j]=1;\n }\n else if(g==1){\n if(str[i]==str[j]){\n dp[i][j]=2;\n }\n else{\n dp[i][j]=1;\n }\n }\n else{\n if(str[i]==str[j]){\n dp[i][j]=2+dp[i+1][j-1];\n }\n else{\n dp[i][j]=max(dp[i][j-1],dp[i+1][j]);\n }\n }\n }\n }\n return dp[0][n-1];\n }\n int countMin(string str){\n //complete the function here\n int n=str.length();\n vector<vector<int>>dp(n,vector<int>(n));\n return n-lps(dp,n,str);\n }\n"
},
{
"code": null,
"e": 2282,
"s": 2280,
"text": "0"
},
{
"code": null,
"e": 2308,
"s": 2282,
"text": "himanshukug19cs2 days ago"
},
{
"code": null,
"e": 2839,
"s": 2308,
"text": " int[][] dp; int sol(String str,int i ,int j){ if(i>=j) return 0; if(dp[i][j]!=-1) return dp[i][j]; if(str.charAt(i)==str.charAt(j)) return dp[i][j]=sol(str,i+1,j-1); else return dp[i][j]=1+Math.min(sol(str,i+1,j),sol(str,i,j-1)); } int countMin(String str) { // code here dp= new int[str.length()][str.length()]; for(int i=0;i<str.length();i++){ Arrays.fill(dp[i],-1); } return sol(str,0,str.length()-1); }"
},
{
"code": null,
"e": 2841,
"s": 2839,
"text": "0"
},
{
"code": null,
"e": 2871,
"s": 2841,
"text": "2019sushilkumarkori5 days ago"
},
{
"code": null,
"e": 3551,
"s": 2871,
"text": "int countMin(string str){\n //complete the function here\n int n = str.length();\n string str2 = str;\n reverse(str2.begin(),str2.end());\n int t[n+1][n+1];\n for(int i=0;i<=n;i++){\n for(int j=0;j<=n;j++){\n if(i==0 || j==0){\n t[i][j] = 0;\n }\n }\n }\n for(int i=1;i<=n;i++){\n for(int j=1;j<=n;j++){\n if(str[i-1]==str2[j-1]){\n t[i][j] = 1+t[i-1][j-1];\n }\n else{\n t[i][j] = max(t[i][j-1],t[i-1][j]);\n }\n }\n }\n return n-t[n][n];\n }"
},
{
"code": null,
"e": 3553,
"s": 3551,
"text": "0"
},
{
"code": null,
"e": 3566,
"s": 3553,
"text": "taakiyabhicu"
},
{
"code": null,
"e": 3592,
"s": 3566,
"text": "This comment was deleted."
},
{
"code": null,
"e": 3595,
"s": 3592,
"text": "+1"
},
{
"code": null,
"e": 3617,
"s": 3595,
"text": "1107khyati2 weeks ago"
},
{
"code": null,
"e": 3671,
"s": 3617,
"text": "n-LPS(str) and to find LPS = LCS(str, reverse of str)"
},
{
"code": null,
"e": 4486,
"s": 3671,
"text": "class Solution{\n public:\n \n int LCS(string str,string s)\n {\n int n=str.length();\n int m=s.length();\n int maxi=INT_MIN;\n vector<vector<int>>dp(n+1,vector<int>(m+1,0));\n \n for(int i=1;i<=n;i++)\n {\n for(int j=1;j<=m;j++)\n {\n if(str[i-1]==s[j-1])\n {\n dp[i][j]=1+dp[i-1][j-1];\n maxi=max(maxi,dp[i][j]);\n }\n else\n dp[i][j]=max(dp[i][j-1],dp[i-1][j]);\n }\n }\n if(maxi==INT_MIN)\n return 0;\n else\n return maxi;\n }\n \n int countMin(string str)\n {\n int n=str.length();\n string s=str;\n reverse(s.begin(),s.end());\n return n-LCS(str,s);\n }\n};"
},
{
"code": null,
"e": 4489,
"s": 4486,
"text": "+1"
},
{
"code": null,
"e": 4511,
"s": 4489,
"text": "mbi20210122 weeks ago"
},
{
"code": null,
"e": 5112,
"s": 4511,
"text": "class Solution{ public: int cm(string &str, string &t, vector<vector<int>>&dp, int i, int j) { if(i<0 || j<0)return 0; if(dp[i][j]!=-1)return dp[i][j]; int ta=0,nt=0; if(str[i]==t[j]) { ta= 1+cm(str,t,dp,i-1,j-1); } nt= max( cm(str,t,dp,i-1,j), cm(str,t,dp,i,j-1) ); return dp[i][j]= max(ta,nt); } int countMin(string str){ int flag=0; int n=str.size(); vector<vector<int>>dp(n, vector<int>(n,-1)); string t=str; reverse(t.begin(), t.end()); int ans= cm(str, t, dp, n-1,n-1); ans=n-ans; return ans; }};"
},
{
"code": null,
"e": 5114,
"s": 5112,
"text": "0"
},
{
"code": null,
"e": 5135,
"s": 5114,
"text": "shivaraj52 weeks ago"
},
{
"code": null,
"e": 5148,
"s": 5135,
"text": "//Simple LCS"
},
{
"code": null,
"e": 5603,
"s": 5148,
"text": "int countMin(string s1){ //complete the function here string s2=s1; reverse(s2.begin(),s2.end()); int n=s1.length(); int m=s2.length(); int dp[n+1][m+1]; for(int i=0;i<=n;i++){ for(int j=0;j<=m;j++){ if(i==0 || j==0) dp[i][j]=0; else if(s1[i-1]==s2[j-1]) dp[i][j]=1+dp[i-1][j-1]; else dp[i][j]=max(dp[i-1][j],dp[i][j-1]); } } //m-dp[n][m] -> insertion return m-dp[n][m]; }"
},
{
"code": null,
"e": 5605,
"s": 5603,
"text": "0"
},
{
"code": null,
"e": 5629,
"s": 5605,
"text": "parasdhanwal2 weeks ago"
},
{
"code": null,
"e": 5639,
"s": 5629,
"text": "Java | DP"
},
{
"code": null,
"e": 6455,
"s": 5641,
"text": "class Solution{\n static int countMin(String a)\n {\n String b=\"\";\n for (int i=0; i<a.length(); i++)\n {\n char ch=a.charAt(i); \n b=ch+b; \n }\n int x=a.length(); \n return (x-lcs(x-1,x-1,a,b));\n \n }\n\n static int lcs(int x, int y, String a, String b)\n {\n if(a.equals(b)){\n return a.length();\n \n }\n int dp[][]= new int [a.length()+1][b.length()+1];\n for(int i=1;i<=a.length();i++){\n for(int j=1;j<=b.length();j++){\n if(a.charAt(i-1)==b.charAt(j-1)){\n dp[i][j]=dp[i-1][j-1]+1;\n }\n else{\n dp[i][j]=Math.max(dp[i-1][j],dp[i][j-1]);\n }\n }\n}\n \n return (dp[a.length()][b.length()]);\n }\n }"
},
{
"code": null,
"e": 6457,
"s": 6455,
"text": "0"
},
{
"code": null,
"e": 6487,
"s": 6457,
"text": "piyushpravanjan3332 weeks ago"
},
{
"code": null,
"e": 6543,
"s": 6487,
"text": "DP Solution Using PYTHON (Using Concept of LCS AND LPS)"
},
{
"code": null,
"e": 7165,
"s": 6545,
"text": "class Solution: def lcs(self,Str1,Str2): n = len(Str1) m=len(Str2) dp = [[-1]*(m+1) for _ in range(n+1)] for i in range(n+1): dp[i][0] = 0 for j in range(m+1): dp[0][j] =0 for i in range(1,n+1): for j in range(1,m+1): if(Str1[i-1]==Str2[j-1]): dp[i][j] = 1+dp[i-1][j-1] else: dp[i][j] = max(dp[i-1][j],dp[i][j-1]) return dp[n][m] def LongPalinSeq(self,Str): Str1= Str[::-1] return self.lcs(Str,Str1) def countMin(self, Str): # code here return len(Str) - self.LongPalinSeq(Str)"
},
{
"code": null,
"e": 7311,
"s": 7165,
"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": 7347,
"s": 7311,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7357,
"s": 7347,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7367,
"s": 7357,
"text": "\nContest\n"
},
{
"code": null,
"e": 7430,
"s": 7367,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7615,
"s": 7430,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 7899,
"s": 7615,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 8045,
"s": 7899,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 8122,
"s": 8045,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 8163,
"s": 8122,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 8191,
"s": 8163,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 8262,
"s": 8191,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 8449,
"s": 8262,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
Lodash _.isUndefined() Method
|
06 Sep, 2020
The _.isUndefined() method is used to find whether the given value is undefined or not. It returns True if the given value is undefined. Otherwise, it returns false.
Syntax:
_.isUndefined(value)
Parameters: This method accepts a single parameter as mentioned above and described below.
value: This parameter holds the value to check.
value: This parameter holds the value to check.
Return Value: This method returns true if the value is undefined, else false.
Example 1: In the following example, const _ = require(βlodashβ) is used to import the lodash library into the file.
Javascript
// The lodash library is included const _ = require("lodash"); // Use of _.isUndefined() method console.log(_.isUndefined(null)); console.log(_.isUndefined(void 0)); console.log(_.isUndefined('gfg'));
Output:
false
true
false
Example 2:
Javascript
// The lodash library is includedconst _ = require("lodash"); // Use of _.isUndefined() method console.log(_.isUndefined(window.missingVariable)); console.log(_.isUndefined(10)); console.log(_.isUndefined(undefined));
Output:
true
false
true
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Sep, 2020"
},
{
"code": null,
"e": 194,
"s": 28,
"text": "The _.isUndefined() method is used to find whether the given value is undefined or not. It returns True if the given value is undefined. Otherwise, it returns false."
},
{
"code": null,
"e": 202,
"s": 194,
"text": "Syntax:"
},
{
"code": null,
"e": 223,
"s": 202,
"text": "_.isUndefined(value)"
},
{
"code": null,
"e": 314,
"s": 223,
"text": "Parameters: This method accepts a single parameter as mentioned above and described below."
},
{
"code": null,
"e": 362,
"s": 314,
"text": "value: This parameter holds the value to check."
},
{
"code": null,
"e": 410,
"s": 362,
"text": "value: This parameter holds the value to check."
},
{
"code": null,
"e": 488,
"s": 410,
"text": "Return Value: This method returns true if the value is undefined, else false."
},
{
"code": null,
"e": 605,
"s": 488,
"text": "Example 1: In the following example, const _ = require(βlodashβ) is used to import the lodash library into the file."
},
{
"code": null,
"e": 616,
"s": 605,
"text": "Javascript"
},
{
"code": "// The lodash library is included const _ = require(\"lodash\"); // Use of _.isUndefined() method console.log(_.isUndefined(null)); console.log(_.isUndefined(void 0)); console.log(_.isUndefined('gfg')); ",
"e": 825,
"s": 616,
"text": null
},
{
"code": null,
"e": 833,
"s": 825,
"text": "Output:"
},
{
"code": null,
"e": 851,
"s": 833,
"text": "false\ntrue\nfalse\n"
},
{
"code": null,
"e": 862,
"s": 851,
"text": "Example 2:"
},
{
"code": null,
"e": 873,
"s": 862,
"text": "Javascript"
},
{
"code": "// The lodash library is includedconst _ = require(\"lodash\"); // Use of _.isUndefined() method console.log(_.isUndefined(window.missingVariable)); console.log(_.isUndefined(10)); console.log(_.isUndefined(undefined)); ",
"e": 1099,
"s": 873,
"text": null
},
{
"code": null,
"e": 1107,
"s": 1099,
"text": "Output:"
},
{
"code": null,
"e": 1124,
"s": 1107,
"text": "true\nfalse\ntrue\n"
},
{
"code": null,
"e": 1142,
"s": 1124,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 1153,
"s": 1142,
"text": "JavaScript"
},
{
"code": null,
"e": 1170,
"s": 1153,
"text": "Web Technologies"
},
{
"code": null,
"e": 1268,
"s": 1170,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1329,
"s": 1268,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1369,
"s": 1329,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1410,
"s": 1369,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 1452,
"s": 1410,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 1474,
"s": 1452,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 1536,
"s": 1474,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1569,
"s": 1536,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1630,
"s": 1569,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1680,
"s": 1630,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Position of robot after given movements
|
17 May, 2021
Given a robot which can only move in four directions, UP(U), DOWN(D), LEFT(L), RIGHT(R). Given a string consisting of instructions to move. Output the coordinates of a robot after executing the instructions. Initial position of robot is at origin(0, 0).
Examples:
Input : move = βUDDLRLβ Output : (-1, -1)Explanation:Move U : (0, 0)β(0, 1)Move D : (0, 1)β(0, 0)Move D : (0, 0)β(0, -1)Move L : (0, -1)β(-1, -1)Move R : (-1, -1)β(0, -1)Move L : (0, -1)β(-1, -1)Therefore final position after the completemovement is: (-1, -1)
Input : move = βUDDLLRUUUDUURUDDUULLDRRRRβOutput : (2, 3)
Source: Goldman Sachs Interview Experience | Set 36 .
Approach: Count number of up movements (U), down movements (D), left movements (L) and right movements (R) as countUp, countDown, countLeft and countRight respectively. Final x-coordinate will be (countRight β countLeft) and y-coordinate will be (countUp β countDown).
Below is the implementation of the above idea:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to find final position of// robot after the complete movement#include <bits/stdc++.h>using namespace std; // Function to find final position of// robot after the complete movementvoid finalPosition(string move){ int l = move.size(); int countUp = 0, countDown = 0; int countLeft = 0, countRight = 0; // Traverse the instruction string 'move' for (int i = 0; i < l; i++) { // For each movement increment its // respective counter if (move[i] == 'U') countUp++; else if (move[i] == 'D') countDown++; else if (move[i] == 'L') countLeft++; else if (move[i] == 'R') countRight++; } // Required final position of robot cout << "Final Position: (" << (countRight - countLeft) << ", " << (countUp - countDown) << ")" << endl;} // Driver codeint main(){ string move = "UDDLLRUUUDUURUDDUULLDRRRR"; finalPosition(move); return 0;}
// Java implementation to find final position// of robot after the complete movement import java.io.*; class GFG { // function to find final position of // robot after the complete movement static void finalPosition(String move) { int l = move.length(); int countUp = 0, countDown = 0; int countLeft = 0, countRight = 0; // traverse the instruction string // 'move' for (int i = 0; i < l; i++) { // for each movement increment // its respective counter if (move.charAt(i) == 'U') countUp++; else if (move.charAt(i) == 'D') countDown++; else if (move.charAt(i) == 'L') countLeft++; else if (move.charAt(i) == 'R') countRight++; } // required final position of robot System.out.println("Final Position: (" + (countRight - countLeft) + ", " + (countUp - countDown) + ")"); } // Driver code public static void main(String[] args) { String move = "UDDLLRUUUDUURUDDUULLDRRRR"; finalPosition(move); }} // This code is contributed by vt_m
# Python3 implementation to find final position# of robot after the complete movement # function to find final position of# robot after the complete movement def finalPosition(move): l = len(move) countUp, countDown = 0, 0 countLeft, countRight = 0, 0 # traverse the instruction string # 'move' for i in range(l): # for each movement increment # its respective counter if (move[i] == 'U'): countUp += 1 elif(move[i] == 'D'): countDown += 1 elif(move[i] == 'L'): countLeft += 1 elif(move[i] == 'R'): countRight += 1 # required final position of robot print("Final Position: (", (countRight - countLeft), ", ", (countUp - countDown), ")") # Driver codeif __name__ == '__main__': move = "UDDLLRUUUDUURUDDUULLDRRRR" finalPosition(move) # This code is contributed by 29AjayKumar
// C# implementation to find final position// of robot after the complete movementusing System; class GFG { // function to find final position of // robot after the complete movement static void finalPosition(String move) { int l = move.Length; int countUp = 0, countDown = 0; int countLeft = 0, countRight = 0; // traverse the instruction string // 'move' for (int i = 0; i < l; i++) { // for each movement increment // its respective counter if (move[i] == 'U') countUp++; else if (move[i] == 'D') countDown++; else if (move[i] == 'L') countLeft++; else if (move[i] == 'R') countRight++; } // required final position of robot Console.WriteLine("Final Position: (" + (countRight - countLeft) + ", " + (countUp - countDown) + ")"); } // Driver code public static void Main() { String move = "UDDLLRUUUDUURUDDUULLDRRRR"; finalPosition(move); }} // This code is contributed by Sam007
<?php// PHP implementation to find// final position of robot after// the complete movement // function to find final position of// robot after the complete movementfunction finalPosition($move){ $l = strlen($move); $countUp = 0; $countDown = 0; $countLeft = 0; $countRight = 0; // traverse the instruction // string 'move' for ($i = 0; $i < $l; $i++) { // for each movement increment its // respective counter if ($move[$i] == 'U') $countUp++; else if ($move[$i] == 'D') $countDown++; else if ($move[$i] == 'L') $countLeft++; else if ($move[$i] == 'R') $countRight++; } // required final position of robot echo "Final Position: (" . ($countRight - $countLeft) . ", " , ($countUp - $countDown) . ")" ."\n";} // Driver Code $move = "UDDLLRUUUDUURUDDUULLDRRRR"; finalPosition($move); // This code is contributed by Sam007?>
<script> // Javascript implementation to find final position // of robot after the complete movement // function to find final position of // robot after the complete movement function finalPosition(move) { let l = move.length; let countUp = 0, countDown = 0; let countLeft = 0, countRight = 0; // traverse the instruction string // 'move' for (let i = 0; i < l; i++) { // for each movement increment // its respective counter if (move[i] == 'U') countUp++; else if (move[i] == 'D') countDown++; else if (move[i] == 'L') countLeft++; else if (move[i] == 'R') countRight++; } // required final position of robot document.write("Final Position: (" + (countRight - countLeft) + ", " + (countUp - countDown) + ")"); } let move = "UDDLLRUUUDUURUDDUULLDRRRR"; finalPosition(move); </script>
Final Position: (2, 3)
Sam007
nidhi_biet
29AjayKumar
aishbetu
mukesh07
Goldman Sachs
Strings
Goldman Sachs
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n17 May, 2021"
},
{
"code": null,
"e": 307,
"s": 53,
"text": "Given a robot which can only move in four directions, UP(U), DOWN(D), LEFT(L), RIGHT(R). Given a string consisting of instructions to move. Output the coordinates of a robot after executing the instructions. Initial position of robot is at origin(0, 0)."
},
{
"code": null,
"e": 318,
"s": 307,
"text": "Examples: "
},
{
"code": null,
"e": 578,
"s": 318,
"text": "Input : move = βUDDLRLβ Output : (-1, -1)Explanation:Move U : (0, 0)β(0, 1)Move D : (0, 1)β(0, 0)Move D : (0, 0)β(0, -1)Move L : (0, -1)β(-1, -1)Move R : (-1, -1)β(0, -1)Move L : (0, -1)β(-1, -1)Therefore final position after the completemovement is: (-1, -1)"
},
{
"code": null,
"e": 636,
"s": 578,
"text": "Input : move = βUDDLLRUUUDUURUDDUULLDRRRRβOutput : (2, 3)"
},
{
"code": null,
"e": 690,
"s": 636,
"text": "Source: Goldman Sachs Interview Experience | Set 36 ."
},
{
"code": null,
"e": 959,
"s": 690,
"text": "Approach: Count number of up movements (U), down movements (D), left movements (L) and right movements (R) as countUp, countDown, countLeft and countRight respectively. Final x-coordinate will be (countRight β countLeft) and y-coordinate will be (countUp β countDown)."
},
{
"code": null,
"e": 1006,
"s": 959,
"text": "Below is the implementation of the above idea:"
},
{
"code": null,
"e": 1010,
"s": 1006,
"text": "C++"
},
{
"code": null,
"e": 1015,
"s": 1010,
"text": "Java"
},
{
"code": null,
"e": 1023,
"s": 1015,
"text": "Python3"
},
{
"code": null,
"e": 1026,
"s": 1023,
"text": "C#"
},
{
"code": null,
"e": 1030,
"s": 1026,
"text": "PHP"
},
{
"code": null,
"e": 1041,
"s": 1030,
"text": "Javascript"
},
{
"code": "// C++ implementation to find final position of// robot after the complete movement#include <bits/stdc++.h>using namespace std; // Function to find final position of// robot after the complete movementvoid finalPosition(string move){ int l = move.size(); int countUp = 0, countDown = 0; int countLeft = 0, countRight = 0; // Traverse the instruction string 'move' for (int i = 0; i < l; i++) { // For each movement increment its // respective counter if (move[i] == 'U') countUp++; else if (move[i] == 'D') countDown++; else if (move[i] == 'L') countLeft++; else if (move[i] == 'R') countRight++; } // Required final position of robot cout << \"Final Position: (\" << (countRight - countLeft) << \", \" << (countUp - countDown) << \")\" << endl;} // Driver codeint main(){ string move = \"UDDLLRUUUDUURUDDUULLDRRRR\"; finalPosition(move); return 0;}",
"e": 2033,
"s": 1041,
"text": null
},
{
"code": "// Java implementation to find final position// of robot after the complete movement import java.io.*; class GFG { // function to find final position of // robot after the complete movement static void finalPosition(String move) { int l = move.length(); int countUp = 0, countDown = 0; int countLeft = 0, countRight = 0; // traverse the instruction string // 'move' for (int i = 0; i < l; i++) { // for each movement increment // its respective counter if (move.charAt(i) == 'U') countUp++; else if (move.charAt(i) == 'D') countDown++; else if (move.charAt(i) == 'L') countLeft++; else if (move.charAt(i) == 'R') countRight++; } // required final position of robot System.out.println(\"Final Position: (\" + (countRight - countLeft) + \", \" + (countUp - countDown) + \")\"); } // Driver code public static void main(String[] args) { String move = \"UDDLLRUUUDUURUDDUULLDRRRR\"; finalPosition(move); }} // This code is contributed by vt_m",
"e": 3261,
"s": 2033,
"text": null
},
{
"code": "# Python3 implementation to find final position# of robot after the complete movement # function to find final position of# robot after the complete movement def finalPosition(move): l = len(move) countUp, countDown = 0, 0 countLeft, countRight = 0, 0 # traverse the instruction string # 'move' for i in range(l): # for each movement increment # its respective counter if (move[i] == 'U'): countUp += 1 elif(move[i] == 'D'): countDown += 1 elif(move[i] == 'L'): countLeft += 1 elif(move[i] == 'R'): countRight += 1 # required final position of robot print(\"Final Position: (\", (countRight - countLeft), \", \", (countUp - countDown), \")\") # Driver codeif __name__ == '__main__': move = \"UDDLLRUUUDUURUDDUULLDRRRR\" finalPosition(move) # This code is contributed by 29AjayKumar",
"e": 4169,
"s": 3261,
"text": null
},
{
"code": "// C# implementation to find final position// of robot after the complete movementusing System; class GFG { // function to find final position of // robot after the complete movement static void finalPosition(String move) { int l = move.Length; int countUp = 0, countDown = 0; int countLeft = 0, countRight = 0; // traverse the instruction string // 'move' for (int i = 0; i < l; i++) { // for each movement increment // its respective counter if (move[i] == 'U') countUp++; else if (move[i] == 'D') countDown++; else if (move[i] == 'L') countLeft++; else if (move[i] == 'R') countRight++; } // required final position of robot Console.WriteLine(\"Final Position: (\" + (countRight - countLeft) + \", \" + (countUp - countDown) + \")\"); } // Driver code public static void Main() { String move = \"UDDLLRUUUDUURUDDUULLDRRRR\"; finalPosition(move); }} // This code is contributed by Sam007",
"e": 5344,
"s": 4169,
"text": null
},
{
"code": "<?php// PHP implementation to find// final position of robot after// the complete movement // function to find final position of// robot after the complete movementfunction finalPosition($move){ $l = strlen($move); $countUp = 0; $countDown = 0; $countLeft = 0; $countRight = 0; // traverse the instruction // string 'move' for ($i = 0; $i < $l; $i++) { // for each movement increment its // respective counter if ($move[$i] == 'U') $countUp++; else if ($move[$i] == 'D') $countDown++; else if ($move[$i] == 'L') $countLeft++; else if ($move[$i] == 'R') $countRight++; } // required final position of robot echo \"Final Position: (\" . ($countRight - $countLeft) . \", \" , ($countUp - $countDown) . \")\" .\"\\n\";} // Driver Code $move = \"UDDLLRUUUDUURUDDUULLDRRRR\"; finalPosition($move); // This code is contributed by Sam007?>",
"e": 6322,
"s": 5344,
"text": null
},
{
"code": "<script> // Javascript implementation to find final position // of robot after the complete movement // function to find final position of // robot after the complete movement function finalPosition(move) { let l = move.length; let countUp = 0, countDown = 0; let countLeft = 0, countRight = 0; // traverse the instruction string // 'move' for (let i = 0; i < l; i++) { // for each movement increment // its respective counter if (move[i] == 'U') countUp++; else if (move[i] == 'D') countDown++; else if (move[i] == 'L') countLeft++; else if (move[i] == 'R') countRight++; } // required final position of robot document.write(\"Final Position: (\" + (countRight - countLeft) + \", \" + (countUp - countDown) + \")\"); } let move = \"UDDLLRUUUDUURUDDUULLDRRRR\"; finalPosition(move); </script>",
"e": 7405,
"s": 6322,
"text": null
},
{
"code": null,
"e": 7428,
"s": 7405,
"text": "Final Position: (2, 3)"
},
{
"code": null,
"e": 7435,
"s": 7428,
"text": "Sam007"
},
{
"code": null,
"e": 7446,
"s": 7435,
"text": "nidhi_biet"
},
{
"code": null,
"e": 7458,
"s": 7446,
"text": "29AjayKumar"
},
{
"code": null,
"e": 7467,
"s": 7458,
"text": "aishbetu"
},
{
"code": null,
"e": 7476,
"s": 7467,
"text": "mukesh07"
},
{
"code": null,
"e": 7490,
"s": 7476,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 7498,
"s": 7490,
"text": "Strings"
},
{
"code": null,
"e": 7512,
"s": 7498,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 7520,
"s": 7512,
"text": "Strings"
}
] |
Ways of iterating over a array in JavaScript.
|
22 Nov, 2021
Arrays in Javascripts, are single variables used to store different kind of elements.For example, a simple array accesses may something like this:
javascript
<script>array = [ 'geeks', '4', 'geeks' ]; // Accessing array elements one by oneconsole.log(array[0]);console.log(array[1]);console.log(array[2]);</script>
Output:
geeks
4
geeks
There are multiple ways one can iterate over an array in Javascript. The most useful ones are mentioned below.Using for loop. This is similar to for loops in other languages like C/C++, Java, etc
javascript
<script>array = [ 1, 2, 3, 4, 5, 6 ];for (index = 0; index < array.length; index++) { console.log(array[index]);}</script>
Output:
1
2
3
4
5
6
Using while loop. This is again similar to other languages.
javascript
<script>index = 0;array = [ 1, 2, 3, 4, 5, 6 ]; while (index < array.length) { console.log(array[index]); index++;}</script>
Output:
1
2
3
4
5
6
using forEach method. The forEach method calls the provided function once for every array element in the order.
javascript
<script>index = 0;array = [ 1, 2, 3, 4, 5, 6 ]; array.forEach(myFunction);function myFunction(item, index){ console.log(item);}</script>
Output:
1
2
3
4
5
6
Using every method. The every() method checks if all elements in an array pass a test (provided as a function).
javascript
<script>index = 0;array = [ 1, 2, 3, 4, 5, 6 ]; const under_five = x => x < 5; if (array.every(under_five)) { console.log('All are less than 5');}else { console.log('At least one element is not less than 5');}</script>
Output:
At least one element is not less than 5.
Using map. A map applies a function over every element and then returns the new array.
javascript
<script>index = 0;array = [ 1, 2, 3, 4, 5, 6 ]; square = x => Math.pow(x, 2);squares = array.map(square);console.log(array);console.log(squares);</script>
Output:
1 2 3 4 5 6
1 4 9 16 25 36
Using Filter
It is used to filter values from an array and return the new filtered array
Javascript
<script> array = [ 1, 2, 3, 4, 5, 6 ]; even = x => x%2 === 0;evens = array.filter(even);console.log(array);console.log(evens); </script>
Output:
[ 1, 2, 3, 4, 5, 6 ]
[ 2, 4, 6 ]
Using Reduce
It is used to reduce the array into one single value using some functional logic
Javascript
<script> array = [ 1, 2, 3, 4, 5, 6 ]; const helperSum = (acc,curr) => acc+currsum = array.reduce(helperSum, 0); console.log(array)console.log(sum); </script>
Output:
[ 1, 2, 3, 4, 5, 6 ]
21
Using Some
It is used to check whether some array values passes a test
Javascript
<script> array = [ 1, 2, 3, 4, 5, 6 ]; const lessthanFourCheck = (element) => element < 4 ;const lessthanFour = array.some(lessthanFourCheck) console.log(array);if(lessthanFour){ console.log("At least one element is less than 4" )}else{ console.log("All elements are greater than 4 ")} </script>
Output :
[ 1, 2, 3, 4, 5, 6 ]
At least one element is less than 4
Pallavi Yadav
prasanna1995
javascript-array
JavaScript-Misc
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 177,
"s": 28,
"text": "Arrays in Javascripts, are single variables used to store different kind of elements.For example, a simple array accesses may something like this: "
},
{
"code": null,
"e": 188,
"s": 177,
"text": "javascript"
},
{
"code": "<script>array = [ 'geeks', '4', 'geeks' ]; // Accessing array elements one by oneconsole.log(array[0]);console.log(array[1]);console.log(array[2]);</script>",
"e": 345,
"s": 188,
"text": null
},
{
"code": null,
"e": 355,
"s": 345,
"text": "Output: "
},
{
"code": null,
"e": 369,
"s": 355,
"text": "geeks\n4\ngeeks"
},
{
"code": null,
"e": 567,
"s": 369,
"text": "There are multiple ways one can iterate over an array in Javascript. The most useful ones are mentioned below.Using for loop. This is similar to for loops in other languages like C/C++, Java, etc "
},
{
"code": null,
"e": 578,
"s": 567,
"text": "javascript"
},
{
"code": "<script>array = [ 1, 2, 3, 4, 5, 6 ];for (index = 0; index < array.length; index++) { console.log(array[index]);}</script>",
"e": 704,
"s": 578,
"text": null
},
{
"code": null,
"e": 714,
"s": 704,
"text": "Output: "
},
{
"code": null,
"e": 726,
"s": 714,
"text": "1\n2\n3\n4\n5\n6"
},
{
"code": null,
"e": 788,
"s": 726,
"text": "Using while loop. This is again similar to other languages. "
},
{
"code": null,
"e": 799,
"s": 788,
"text": "javascript"
},
{
"code": "<script>index = 0;array = [ 1, 2, 3, 4, 5, 6 ]; while (index < array.length) { console.log(array[index]); index++;}</script>",
"e": 930,
"s": 799,
"text": null
},
{
"code": null,
"e": 940,
"s": 930,
"text": "Output: "
},
{
"code": null,
"e": 952,
"s": 940,
"text": "1\n2\n3\n4\n5\n6"
},
{
"code": null,
"e": 1066,
"s": 952,
"text": "using forEach method. The forEach method calls the provided function once for every array element in the order. "
},
{
"code": null,
"e": 1077,
"s": 1066,
"text": "javascript"
},
{
"code": "<script>index = 0;array = [ 1, 2, 3, 4, 5, 6 ]; array.forEach(myFunction);function myFunction(item, index){ console.log(item);}</script>",
"e": 1217,
"s": 1077,
"text": null
},
{
"code": null,
"e": 1227,
"s": 1217,
"text": "Output: "
},
{
"code": null,
"e": 1239,
"s": 1227,
"text": "1\n2\n3\n4\n5\n6"
},
{
"code": null,
"e": 1353,
"s": 1239,
"text": "Using every method. The every() method checks if all elements in an array pass a test (provided as a function). "
},
{
"code": null,
"e": 1364,
"s": 1353,
"text": "javascript"
},
{
"code": "<script>index = 0;array = [ 1, 2, 3, 4, 5, 6 ]; const under_five = x => x < 5; if (array.every(under_five)) { console.log('All are less than 5');}else { console.log('At least one element is not less than 5');}</script>",
"e": 1589,
"s": 1364,
"text": null
},
{
"code": null,
"e": 1599,
"s": 1589,
"text": "Output: "
},
{
"code": null,
"e": 1640,
"s": 1599,
"text": "At least one element is not less than 5."
},
{
"code": null,
"e": 1729,
"s": 1640,
"text": "Using map. A map applies a function over every element and then returns the new array. "
},
{
"code": null,
"e": 1740,
"s": 1729,
"text": "javascript"
},
{
"code": "<script>index = 0;array = [ 1, 2, 3, 4, 5, 6 ]; square = x => Math.pow(x, 2);squares = array.map(square);console.log(array);console.log(squares);</script>",
"e": 1895,
"s": 1740,
"text": null
},
{
"code": null,
"e": 1905,
"s": 1895,
"text": "Output: "
},
{
"code": null,
"e": 1933,
"s": 1905,
"text": "1 2 3 4 5 6 \n1 4 9 16 25 36"
},
{
"code": null,
"e": 1946,
"s": 1933,
"text": "Using Filter"
},
{
"code": null,
"e": 2022,
"s": 1946,
"text": "It is used to filter values from an array and return the new filtered array"
},
{
"code": null,
"e": 2033,
"s": 2022,
"text": "Javascript"
},
{
"code": "<script> array = [ 1, 2, 3, 4, 5, 6 ]; even = x => x%2 === 0;evens = array.filter(even);console.log(array);console.log(evens); </script>",
"e": 2170,
"s": 2033,
"text": null
},
{
"code": null,
"e": 2178,
"s": 2170,
"text": "Output:"
},
{
"code": null,
"e": 2211,
"s": 2178,
"text": "[ 1, 2, 3, 4, 5, 6 ]\n[ 2, 4, 6 ]"
},
{
"code": null,
"e": 2224,
"s": 2211,
"text": "Using Reduce"
},
{
"code": null,
"e": 2305,
"s": 2224,
"text": "It is used to reduce the array into one single value using some functional logic"
},
{
"code": null,
"e": 2316,
"s": 2305,
"text": "Javascript"
},
{
"code": "<script> array = [ 1, 2, 3, 4, 5, 6 ]; const helperSum = (acc,curr) => acc+currsum = array.reduce(helperSum, 0); console.log(array)console.log(sum); </script>",
"e": 2475,
"s": 2316,
"text": null
},
{
"code": null,
"e": 2483,
"s": 2475,
"text": "Output:"
},
{
"code": null,
"e": 2507,
"s": 2483,
"text": "[ 1, 2, 3, 4, 5, 6 ]\n21"
},
{
"code": null,
"e": 2518,
"s": 2507,
"text": "Using Some"
},
{
"code": null,
"e": 2578,
"s": 2518,
"text": "It is used to check whether some array values passes a test"
},
{
"code": null,
"e": 2589,
"s": 2578,
"text": "Javascript"
},
{
"code": "<script> array = [ 1, 2, 3, 4, 5, 6 ]; const lessthanFourCheck = (element) => element < 4 ;const lessthanFour = array.some(lessthanFourCheck) console.log(array);if(lessthanFour){ console.log(\"At least one element is less than 4\" )}else{ console.log(\"All elements are greater than 4 \")} </script>",
"e": 2893,
"s": 2589,
"text": null
},
{
"code": null,
"e": 2903,
"s": 2893,
"text": "Output : "
},
{
"code": null,
"e": 2960,
"s": 2903,
"text": "[ 1, 2, 3, 4, 5, 6 ]\nAt least one element is less than 4"
},
{
"code": null,
"e": 2974,
"s": 2960,
"text": "Pallavi Yadav"
},
{
"code": null,
"e": 2987,
"s": 2974,
"text": "prasanna1995"
},
{
"code": null,
"e": 3004,
"s": 2987,
"text": "javascript-array"
},
{
"code": null,
"e": 3020,
"s": 3004,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3031,
"s": 3020,
"text": "JavaScript"
}
] |
Program to find sum of elements in a given array
|
21 Jun, 2022
Given an array of integers, find sum of its elements.Examples :
Input : arr[] = {1, 2, 3}
Output : 6
1 + 2 + 3 = 6
Input : arr[] = {15, 12, 13, 10}
Output : 50
C++
C
Java
Python3
C#
PHP
Javascript
/* C++ Program to find sum of elements in a given array */#include <bits/stdc++.h>using namespace std; // function to return sum of elements // in an array of size n int sum(int arr[], int n) { int sum = 0; // initialize sum // Iterate through all elements // and add them to sum for (int i = 0; i < n; i++) sum += arr[i]; return sum; } // Driver codeint main() { int arr[] = {12, 3, 4, 15}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Sum of given array is " << sum(arr, n); return 0; } // This code is contributed by rathbhupendra
/* C Program to find sum of elements in a given array */#include <bits/stdc++.h> // function to return sum of elements// in an array of size nint sum(int arr[], int n){ int sum = 0; // initialize sum // Iterate through all elements // and add them to sum for (int i = 0; i < n; i++) sum += arr[i]; return sum;} int main(){ int arr[] = {12, 3, 4, 15}; int n = sizeof(arr) / sizeof(arr[0]); printf("Sum of given array is %d", sum(arr, n)); return 0;}
/* Java Program to find sum of elements in a given array */class Test{ static int arr[] = {12,3,4,15}; // method for sum of elements in an array static int sum() { int sum = 0; // initialize sum int i; // Iterate through all elements and add them to sum for (i = 0; i < arr.length; i++) sum += arr[i]; return sum; } // Driver method public static void main(String[] args) { System.out.println("Sum of given array is " + sum()); } }
# Python 3 code to find sum # of elements in given arraydef _sum(arr,n): # return sum using sum # inbuilt sum() function return(sum(arr)) # driver functionarr=[]# input values to listarr = [12, 3, 4, 15] # calculating length of arrayn = len(arr) ans = _sum(arr,n) # display sumprint ('Sum of the array is ',ans) # This code is contributed by Himanshu Ranjan
// C# Program to find sum of elements in a// given array using System; class GFG { // method for sum of elements in an array static int sum(int []arr, int n) { int sum = 0; // initialize sum // Iterate through all elements and // add them to sum for (int i = 0; i < n; i++) sum += arr[i]; return sum; } // Driver method public static void Main() { int []arr = {12,3,4,15}; int n = arr.Length; Console.Write("Sum of given array is " + sum(arr, n)); } } // This code is contributed by Sam007.
<?php// PHP Program to find sum of // elements in a given array // function to return sum // of elements in an array// of size nfunction sum( $arr, $n){ // initialize sum $sum = 0; // Iterate through all elements // and add them to sum for ($i = 0; $i < $n; $i++) $sum += $arr[$i]; return $sum;} // Driver Code$arr =array(12, 3, 4, 15);$n = sizeof($arr);echo "Sum of given array is ", sum($arr, $n); // This code is contributed by aj_36?>
<script>//JavaScript Program to find //sum of elements in a given array // function to return sum of elements // in an array of size n function sum(arr) { let sum = 0; // initialize sum // Iterate through all elements // and add them to sum for (let i = 0; i < arr.length; i++) sum += arr[i]; return sum; } // Driver code let arr = [12, 3, 4, 15]; document.write("Sum of given array is " + sum(arr)); // This code is contributed by Surbhi Tyagi </script>
Sum of given array is 34
Time Complexity: O(n)
Auxiliary Space: O(1)
Another Method: Using STLCalling inbuilt function for sum of elements of an array in STL.accumulate(first, last, sum);first, last : first and last elements of range whose elements are to be addedsum : initial value of the sum
This function returns the array sum.
C++
Java
Python3
C#
Javascript
/* C++ Program to find sum of elements in a given array */#include <bits/stdc++.h>using namespace std; // Driver codeint main() { int arr[] = {12, 3, 4, 15}; int n = sizeof(arr) / sizeof(arr[0]); // calling accumulate function, passing first, last element and // initial sum, which is 0 in this case. cout << "Sum of given array is " << accumulate(arr, arr + n, 0); return 0; } // This code is contributed by pranoy_coder
/* Java Program to find sum of elements in a given array */import java.util.*; class GFG{ static int accumulate(int []arr) { int sum = 0; for(int i = 0; i < arr.length; i++) { sum = sum + arr[i]; } return sum; } // Driver codepublic static void main(String[] args) { int arr[] = {12, 3, 4, 15}; int n = arr.length; // calling accumulate function, passing first, last element and // initial sum, which is 0 in this case. System.out.print("Sum of given array is " + accumulate(arr)); } } // This code is contributed by umadevi9616
# Python3 program to find sum of elements # in a given array # Driver codeif __name__ == "__main__": arr = [ 12, 3, 4, 15 ] n = len(arr) # Calling accumulate function, passing # first, last element and initial sum, # which is 0 in this case. print("Sum of given array is ", sum(arr)); # This code is contributed by ukasp
/* C# Program to find sum of elements in a given array */using System;public class GFG { static int accumulate(int[] arr) { int sum = 0; for (int i = 0; i < arr.Length; i++) { sum = sum + arr[i]; } return sum; } // Driver code public static void Main(String[] args) { int []arr = { 12, 3, 4, 15 }; int n = arr.Length; // calling accumulate function, passing first, last element and // initial sum, which is 0 in this case. Console.Write("Sum of given array is " + accumulate(arr)); }} // This code is contributed by gauravrajput1
<script> /* javascript Program to find sum of elements in a given array */ function accumulate(arr) { let sum = 0; for(let i = 0; i < arr.length; i++) { sum = sum + arr[i]; } return sum; } // Driver code let arr = [12, 3, 4, 15]; let n = arr.length; // calling accumulate function, passing first, last element and // initial sum, which is 0 in this case document.write("Sum of given array is " + accumulate(arr)); // This code is contributed by vaibhavrabadiya3.</script>
Sum of given array is 34
Time Complexity: O(n)
Auxiliary Space: O(1)
Find sum of elements in a given array | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersFind sum of elements in a given array | 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 / 1:40β’Liveβ’<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=sKHKHrEfHbI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Another Method#2: Using Recursion
C++
/* C++ Program to find sum of elementsin a given array using recursion */#include<iostream>using namespace std; // function to return sum of elements// in an array of size nint sum(int arr[],int n){ //base case if(n==0){ return 0; } else{ //recursively calling the function return arr[0]+sum(arr+1,n-1); }}int main(){ int arr[] = {12, 3, 4, 15}; int n=sizeof(arr)/sizeof(arr[0]); cout<<sum(arr,n); return 0; // This code is contributed by Shivesh Kumar Dwivedi}
34
jit_t
rathbhupendra
surbhityagi15
rishavmahato348
pranoy_coder
ukasp
vaibhavrabadiya3
umadevi9616
GauravRajput1
anandkumarshivam2266
cpdwivedi916
Arrays
Mathematical
School Programming
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 117,
"s": 52,
"text": "Given an array of integers, find sum of its elements.Examples : "
},
{
"code": null,
"e": 214,
"s": 117,
"text": "Input : arr[] = {1, 2, 3}\nOutput : 6\n1 + 2 + 3 = 6\n\nInput : arr[] = {15, 12, 13, 10}\nOutput : 50"
},
{
"code": null,
"e": 218,
"s": 214,
"text": "C++"
},
{
"code": null,
"e": 220,
"s": 218,
"text": "C"
},
{
"code": null,
"e": 225,
"s": 220,
"text": "Java"
},
{
"code": null,
"e": 233,
"s": 225,
"text": "Python3"
},
{
"code": null,
"e": 236,
"s": 233,
"text": "C#"
},
{
"code": null,
"e": 240,
"s": 236,
"text": "PHP"
},
{
"code": null,
"e": 251,
"s": 240,
"text": "Javascript"
},
{
"code": "/* C++ Program to find sum of elements in a given array */#include <bits/stdc++.h>using namespace std; // function to return sum of elements // in an array of size n int sum(int arr[], int n) { int sum = 0; // initialize sum // Iterate through all elements // and add them to sum for (int i = 0; i < n; i++) sum += arr[i]; return sum; } // Driver codeint main() { int arr[] = {12, 3, 4, 15}; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Sum of given array is \" << sum(arr, n); return 0; } // This code is contributed by rathbhupendra",
"e": 836,
"s": 251,
"text": null
},
{
"code": "/* C Program to find sum of elements in a given array */#include <bits/stdc++.h> // function to return sum of elements// in an array of size nint sum(int arr[], int n){ int sum = 0; // initialize sum // Iterate through all elements // and add them to sum for (int i = 0; i < n; i++) sum += arr[i]; return sum;} int main(){ int arr[] = {12, 3, 4, 15}; int n = sizeof(arr) / sizeof(arr[0]); printf(\"Sum of given array is %d\", sum(arr, n)); return 0;}",
"e": 1322,
"s": 836,
"text": null
},
{
"code": "/* Java Program to find sum of elements in a given array */class Test{ static int arr[] = {12,3,4,15}; // method for sum of elements in an array static int sum() { int sum = 0; // initialize sum int i; // Iterate through all elements and add them to sum for (i = 0; i < arr.length; i++) sum += arr[i]; return sum; } // Driver method public static void main(String[] args) { System.out.println(\"Sum of given array is \" + sum()); } }",
"e": 1886,
"s": 1322,
"text": null
},
{
"code": "# Python 3 code to find sum # of elements in given arraydef _sum(arr,n): # return sum using sum # inbuilt sum() function return(sum(arr)) # driver functionarr=[]# input values to listarr = [12, 3, 4, 15] # calculating length of arrayn = len(arr) ans = _sum(arr,n) # display sumprint ('Sum of the array is ',ans) # This code is contributed by Himanshu Ranjan",
"e": 2265,
"s": 1886,
"text": null
},
{
"code": "// C# Program to find sum of elements in a// given array using System; class GFG { // method for sum of elements in an array static int sum(int []arr, int n) { int sum = 0; // initialize sum // Iterate through all elements and // add them to sum for (int i = 0; i < n; i++) sum += arr[i]; return sum; } // Driver method public static void Main() { int []arr = {12,3,4,15}; int n = arr.Length; Console.Write(\"Sum of given array is \" + sum(arr, n)); } } // This code is contributed by Sam007.",
"e": 2946,
"s": 2265,
"text": null
},
{
"code": "<?php// PHP Program to find sum of // elements in a given array // function to return sum // of elements in an array// of size nfunction sum( $arr, $n){ // initialize sum $sum = 0; // Iterate through all elements // and add them to sum for ($i = 0; $i < $n; $i++) $sum += $arr[$i]; return $sum;} // Driver Code$arr =array(12, 3, 4, 15);$n = sizeof($arr);echo \"Sum of given array is \", sum($arr, $n); // This code is contributed by aj_36?>",
"e": 3432,
"s": 2946,
"text": null
},
{
"code": "<script>//JavaScript Program to find //sum of elements in a given array // function to return sum of elements // in an array of size n function sum(arr) { let sum = 0; // initialize sum // Iterate through all elements // and add them to sum for (let i = 0; i < arr.length; i++) sum += arr[i]; return sum; } // Driver code let arr = [12, 3, 4, 15]; document.write(\"Sum of given array is \" + sum(arr)); // This code is contributed by Surbhi Tyagi </script>",
"e": 3999,
"s": 3432,
"text": null
},
{
"code": null,
"e": 4024,
"s": 3999,
"text": "Sum of given array is 34"
},
{
"code": null,
"e": 4046,
"s": 4024,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 4068,
"s": 4046,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 4312,
"s": 4068,
"text": "Another Method: Using STLCalling inbuilt function for sum of elements of an array in STL.accumulate(first, last, sum);first, last : first and last elements of range whose elements are to be addedsum : initial value of the sum"
},
{
"code": null,
"e": 4349,
"s": 4312,
"text": "This function returns the array sum."
},
{
"code": null,
"e": 4353,
"s": 4349,
"text": "C++"
},
{
"code": null,
"e": 4358,
"s": 4353,
"text": "Java"
},
{
"code": null,
"e": 4366,
"s": 4358,
"text": "Python3"
},
{
"code": null,
"e": 4369,
"s": 4366,
"text": "C#"
},
{
"code": null,
"e": 4380,
"s": 4369,
"text": "Javascript"
},
{
"code": "/* C++ Program to find sum of elements in a given array */#include <bits/stdc++.h>using namespace std; // Driver codeint main() { int arr[] = {12, 3, 4, 15}; int n = sizeof(arr) / sizeof(arr[0]); // calling accumulate function, passing first, last element and // initial sum, which is 0 in this case. cout << \"Sum of given array is \" << accumulate(arr, arr + n, 0); return 0; } // This code is contributed by pranoy_coder",
"e": 4829,
"s": 4380,
"text": null
},
{
"code": "/* Java Program to find sum of elements in a given array */import java.util.*; class GFG{ static int accumulate(int []arr) { int sum = 0; for(int i = 0; i < arr.length; i++) { sum = sum + arr[i]; } return sum; } // Driver codepublic static void main(String[] args) { int arr[] = {12, 3, 4, 15}; int n = arr.length; // calling accumulate function, passing first, last element and // initial sum, which is 0 in this case. System.out.print(\"Sum of given array is \" + accumulate(arr)); } } // This code is contributed by umadevi9616",
"e": 5481,
"s": 4829,
"text": null
},
{
"code": "# Python3 program to find sum of elements # in a given array # Driver codeif __name__ == \"__main__\": arr = [ 12, 3, 4, 15 ] n = len(arr) # Calling accumulate function, passing # first, last element and initial sum, # which is 0 in this case. print(\"Sum of given array is \", sum(arr)); # This code is contributed by ukasp",
"e": 5835,
"s": 5481,
"text": null
},
{
"code": "/* C# Program to find sum of elements in a given array */using System;public class GFG { static int accumulate(int[] arr) { int sum = 0; for (int i = 0; i < arr.Length; i++) { sum = sum + arr[i]; } return sum; } // Driver code public static void Main(String[] args) { int []arr = { 12, 3, 4, 15 }; int n = arr.Length; // calling accumulate function, passing first, last element and // initial sum, which is 0 in this case. Console.Write(\"Sum of given array is \" + accumulate(arr)); }} // This code is contributed by gauravrajput1 ",
"e": 6466,
"s": 5835,
"text": null
},
{
"code": "<script> /* javascript Program to find sum of elements in a given array */ function accumulate(arr) { let sum = 0; for(let i = 0; i < arr.length; i++) { sum = sum + arr[i]; } return sum; } // Driver code let arr = [12, 3, 4, 15]; let n = arr.length; // calling accumulate function, passing first, last element and // initial sum, which is 0 in this case document.write(\"Sum of given array is \" + accumulate(arr)); // This code is contributed by vaibhavrabadiya3.</script>",
"e": 7043,
"s": 6466,
"text": null
},
{
"code": null,
"e": 7068,
"s": 7043,
"text": "Sum of given array is 34"
},
{
"code": null,
"e": 7090,
"s": 7068,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 7112,
"s": 7090,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 8004,
"s": 7112,
"text": "Find sum of elements in a given array | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersFind sum of elements in a given array | 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 / 1:40β’Liveβ’<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=sKHKHrEfHbI\" 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": 8038,
"s": 8004,
"text": "Another Method#2: Using Recursion"
},
{
"code": null,
"e": 8042,
"s": 8038,
"text": "C++"
},
{
"code": "/* C++ Program to find sum of elementsin a given array using recursion */#include<iostream>using namespace std; // function to return sum of elements// in an array of size nint sum(int arr[],int n){ //base case if(n==0){ return 0; } else{ //recursively calling the function return arr[0]+sum(arr+1,n-1); }}int main(){ int arr[] = {12, 3, 4, 15}; int n=sizeof(arr)/sizeof(arr[0]); cout<<sum(arr,n); return 0; // This code is contributed by Shivesh Kumar Dwivedi}",
"e": 8556,
"s": 8042,
"text": null
},
{
"code": null,
"e": 8559,
"s": 8556,
"text": "34"
},
{
"code": null,
"e": 8565,
"s": 8559,
"text": "jit_t"
},
{
"code": null,
"e": 8579,
"s": 8565,
"text": "rathbhupendra"
},
{
"code": null,
"e": 8593,
"s": 8579,
"text": "surbhityagi15"
},
{
"code": null,
"e": 8609,
"s": 8593,
"text": "rishavmahato348"
},
{
"code": null,
"e": 8622,
"s": 8609,
"text": "pranoy_coder"
},
{
"code": null,
"e": 8628,
"s": 8622,
"text": "ukasp"
},
{
"code": null,
"e": 8645,
"s": 8628,
"text": "vaibhavrabadiya3"
},
{
"code": null,
"e": 8657,
"s": 8645,
"text": "umadevi9616"
},
{
"code": null,
"e": 8671,
"s": 8657,
"text": "GauravRajput1"
},
{
"code": null,
"e": 8692,
"s": 8671,
"text": "anandkumarshivam2266"
},
{
"code": null,
"e": 8705,
"s": 8692,
"text": "cpdwivedi916"
},
{
"code": null,
"e": 8712,
"s": 8705,
"text": "Arrays"
},
{
"code": null,
"e": 8725,
"s": 8712,
"text": "Mathematical"
},
{
"code": null,
"e": 8744,
"s": 8725,
"text": "School Programming"
},
{
"code": null,
"e": 8751,
"s": 8744,
"text": "Arrays"
},
{
"code": null,
"e": 8764,
"s": 8751,
"text": "Mathematical"
}
] |
How to use complete horizontal line space in HTML ?
|
13 Jan, 2022
In this article, we will create a complete horizontal line space using HTML. To create the horizontal line space, we will use the <hr> tag.
The <hr> tag stands for horizontal rule and is used to insert a horizontal rule or a thematic break in an HTML page to divide or separate document sections. The <hr> tag is an empty tag, and it does not require an end tag.
Syntax:
<hr>
Attributes:
align: It specifies the alignment of the horizontal rule.
noshade: It specifies the bar without shading effect.
size: It specifies the height of the horizontal rule.
width: It specifies the width of the horizontal rule.
Approach: In the below example, we will create two paragraph elements containing some content and add a <hr> tag between these two paragraph elements to create a horizontal line space.
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <title> How to use complete horizontal line space in HTML? </title></head> <body> <center> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> How to use complete horizontal line space in HTML? </h3> <p>Welcome to GeeksforGeeks</p> <hr> <p>Learning portal</p> </center></body></html>
Output:
HTML-Questions
HTML-Tags
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Make a div horizontally scrollable using CSS
DOM (Document Object Model)
How to get values from html input array using JavaScript ?
Installation of Node.js on Linux
How to create footer to stay at the bottom of a Web page?
How do you run JavaScript script through the Terminal?
Node.js fs.readFileSync() Method
How to set space between the flexbox ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Jan, 2022"
},
{
"code": null,
"e": 168,
"s": 28,
"text": "In this article, we will create a complete horizontal line space using HTML. To create the horizontal line space, we will use the <hr> tag."
},
{
"code": null,
"e": 391,
"s": 168,
"text": "The <hr> tag stands for horizontal rule and is used to insert a horizontal rule or a thematic break in an HTML page to divide or separate document sections. The <hr> tag is an empty tag, and it does not require an end tag."
},
{
"code": null,
"e": 399,
"s": 391,
"text": "Syntax:"
},
{
"code": null,
"e": 404,
"s": 399,
"text": "<hr>"
},
{
"code": null,
"e": 416,
"s": 404,
"text": "Attributes:"
},
{
"code": null,
"e": 474,
"s": 416,
"text": "align: It specifies the alignment of the horizontal rule."
},
{
"code": null,
"e": 528,
"s": 474,
"text": "noshade: It specifies the bar without shading effect."
},
{
"code": null,
"e": 582,
"s": 528,
"text": "size: It specifies the height of the horizontal rule."
},
{
"code": null,
"e": 636,
"s": 582,
"text": "width: It specifies the width of the horizontal rule."
},
{
"code": null,
"e": 821,
"s": 636,
"text": "Approach: In the below example, we will create two paragraph elements containing some content and add a <hr> tag between these two paragraph elements to create a horizontal line space."
},
{
"code": null,
"e": 830,
"s": 821,
"text": "Example:"
},
{
"code": null,
"e": 835,
"s": 830,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> How to use complete horizontal line space in HTML? </title></head> <body> <center> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3> How to use complete horizontal line space in HTML? </h3> <p>Welcome to GeeksforGeeks</p> <hr> <p>Learning portal</p> </center></body></html>",
"e": 1271,
"s": 835,
"text": null
},
{
"code": null,
"e": 1279,
"s": 1271,
"text": "Output:"
},
{
"code": null,
"e": 1294,
"s": 1279,
"text": "HTML-Questions"
},
{
"code": null,
"e": 1304,
"s": 1294,
"text": "HTML-Tags"
},
{
"code": null,
"e": 1311,
"s": 1304,
"text": "Picked"
},
{
"code": null,
"e": 1316,
"s": 1311,
"text": "HTML"
},
{
"code": null,
"e": 1333,
"s": 1316,
"text": "Web Technologies"
},
{
"code": null,
"e": 1338,
"s": 1333,
"text": "HTML"
},
{
"code": null,
"e": 1436,
"s": 1338,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1460,
"s": 1436,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1499,
"s": 1460,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 1544,
"s": 1499,
"text": "Make a div horizontally scrollable using CSS"
},
{
"code": null,
"e": 1572,
"s": 1544,
"text": "DOM (Document Object Model)"
},
{
"code": null,
"e": 1631,
"s": 1572,
"text": "How to get values from html input array using JavaScript ?"
},
{
"code": null,
"e": 1664,
"s": 1631,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1722,
"s": 1664,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 1777,
"s": 1722,
"text": "How do you run JavaScript script through the Terminal?"
},
{
"code": null,
"e": 1810,
"s": 1777,
"text": "Node.js fs.readFileSync() Method"
}
] |
How to convert a DOM nodelist to an array using JavaScript ?
|
04 Oct, 2021
NodeList objects are the collection of nodes, usually returned by properties such as Node.childNodes and methods such as document.querySelectorAll(). Although NodeList is not an actual Array but it is possible to iterate over it with the help of forEach() method. NodeList can also be converted into actual array by following methods.
Method 1: By using Array.prototype.slice.call() method.
Syntax:
const array = Array.prototype.slice.call(nodeList);
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <title>Document</title></head> <body> <p>Hello geeks 1</p> <p>Hello geeks 2</p> <p>Hello geeks 3</p> <p>Hello geeks 4</p> <script> // This is nodeList const nodeList = document.querySelectorAll('p'); console.log(nodeList); // Converting using Array.prototype.slice.call const array1 = Array.prototype.slice.call(nodeList); console.log(array1); </script></body> </html>
Output:
Method 2: With the help of Array.from() method.
Syntax:
const array = Array.from(nodeList);
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <title>Document</title></head> <body> <p>Hello geeks 1</p> <p>Hello geeks 2</p> <p>Hello geeks 3</p> <p>Hello geeks 4</p> <script> // This is nodeList const nodeList = document.querySelectorAll('p'); console.log(nodeList); // Converting to array using Array.from() method const array = Array.from(nodeList); console.log(array); </script></body> </html>
Output:
Method 3: Using ES6 spread syntax, it allows an iterable such as an array expression or string to be expanded in places where zero or more arguments or elements are expected.
Syntax:
const array = [ ...nodeList ]
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <title>Document</title></head> <body> <p>Hello geeks 1</p> <p>Hello geeks 2</p> <p>Hello geeks 3</p> <p>Hello geeks 4</p> <script> // This is nodeList const nodeList = document.querySelectorAll('p'); console.log(nodeList); // Converting using Spread syntax const array1 = [...nodeList]; console.log(array1); </script></body> </html>
Output:
Note: Method 2 and Method 3 may not work in older browsers properly but will work fine in all modern browsers.
akshaysingh98088
HTML-Misc
JavaScript-Misc
Picked
HTML
JavaScript
Web Technologies
Web technologies Questions
Write From Home
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Oct, 2021"
},
{
"code": null,
"e": 363,
"s": 28,
"text": "NodeList objects are the collection of nodes, usually returned by properties such as Node.childNodes and methods such as document.querySelectorAll(). Although NodeList is not an actual Array but it is possible to iterate over it with the help of forEach() method. NodeList can also be converted into actual array by following methods."
},
{
"code": null,
"e": 419,
"s": 363,
"text": "Method 1: By using Array.prototype.slice.call() method."
},
{
"code": null,
"e": 428,
"s": 419,
"text": "Syntax: "
},
{
"code": null,
"e": 480,
"s": 428,
"text": "const array = Array.prototype.slice.call(nodeList);"
},
{
"code": null,
"e": 490,
"s": 480,
"text": "Example: "
},
{
"code": null,
"e": 495,
"s": 490,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <title>Document</title></head> <body> <p>Hello geeks 1</p> <p>Hello geeks 2</p> <p>Hello geeks 3</p> <p>Hello geeks 4</p> <script> // This is nodeList const nodeList = document.querySelectorAll('p'); console.log(nodeList); // Converting using Array.prototype.slice.call const array1 = Array.prototype.slice.call(nodeList); console.log(array1); </script></body> </html>",
"e": 1089,
"s": 495,
"text": null
},
{
"code": null,
"e": 1097,
"s": 1089,
"text": "Output:"
},
{
"code": null,
"e": 1145,
"s": 1097,
"text": "Method 2: With the help of Array.from() method."
},
{
"code": null,
"e": 1154,
"s": 1145,
"text": "Syntax: "
},
{
"code": null,
"e": 1190,
"s": 1154,
"text": "const array = Array.from(nodeList);"
},
{
"code": null,
"e": 1200,
"s": 1190,
"text": "Example: "
},
{
"code": null,
"e": 1205,
"s": 1200,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <title>Document</title></head> <body> <p>Hello geeks 1</p> <p>Hello geeks 2</p> <p>Hello geeks 3</p> <p>Hello geeks 4</p> <script> // This is nodeList const nodeList = document.querySelectorAll('p'); console.log(nodeList); // Converting to array using Array.from() method const array = Array.from(nodeList); console.log(array); </script></body> </html>",
"e": 1783,
"s": 1205,
"text": null
},
{
"code": null,
"e": 1791,
"s": 1783,
"text": "Output:"
},
{
"code": null,
"e": 1967,
"s": 1791,
"text": "Method 3: Using ES6 spread syntax, it allows an iterable such as an array expression or string to be expanded in places where zero or more arguments or elements are expected. "
},
{
"code": null,
"e": 1976,
"s": 1967,
"text": "Syntax: "
},
{
"code": null,
"e": 2006,
"s": 1976,
"text": "const array = [ ...nodeList ]"
},
{
"code": null,
"e": 2016,
"s": 2006,
"text": "Example: "
},
{
"code": null,
"e": 2021,
"s": 2016,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <title>Document</title></head> <body> <p>Hello geeks 1</p> <p>Hello geeks 2</p> <p>Hello geeks 3</p> <p>Hello geeks 4</p> <script> // This is nodeList const nodeList = document.querySelectorAll('p'); console.log(nodeList); // Converting using Spread syntax const array1 = [...nodeList]; console.log(array1); </script></body> </html>",
"e": 2579,
"s": 2021,
"text": null
},
{
"code": null,
"e": 2587,
"s": 2579,
"text": "Output:"
},
{
"code": null,
"e": 2699,
"s": 2587,
"text": "Note: Method 2 and Method 3 may not work in older browsers properly but will work fine in all modern browsers. "
},
{
"code": null,
"e": 2716,
"s": 2699,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 2726,
"s": 2716,
"text": "HTML-Misc"
},
{
"code": null,
"e": 2742,
"s": 2726,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 2749,
"s": 2742,
"text": "Picked"
},
{
"code": null,
"e": 2754,
"s": 2749,
"text": "HTML"
},
{
"code": null,
"e": 2765,
"s": 2754,
"text": "JavaScript"
},
{
"code": null,
"e": 2782,
"s": 2765,
"text": "Web Technologies"
},
{
"code": null,
"e": 2809,
"s": 2782,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2825,
"s": 2809,
"text": "Write From Home"
},
{
"code": null,
"e": 2830,
"s": 2825,
"text": "HTML"
}
] |
StackOverflowError in Java with examples
|
07 Apr, 2020
StackOverflowError is an error which Java doesnβt allow to catch, for instance, stack running out of space, as itβs one of the most common runtime errors one can encounter.
The main cause of the StackOverflowError is that we havenβt provided the proper terminating condition to our recursive function or template, which means it will turn into an infinite loop.
When does StackOverflowError encountered?
When we invoke a method, a new stack frame is created on the call stack or on the thread stack size. This stack frame holds parameters of the invoked method, mostly the local variables and the return address of the method. The creation of these stack frames will be iterative and will be stopped only when the end of the method invokes is found in the nested methods. In amidst of this process, if JVM runs out of space for the new stack frames which are required to be created, it will throw a StackOverflowError.
For example: Lack of proper or no termination condition. This is mostly the cause of this situation termed as unterminated or infinite recursion.
Given below is the implementation of infinite recursion:
// Java program to demonstrate// infinite recursion error public class StackOverflowErrorClass { static int i = 0; // Method to print numbers public static int printNumber(int x) { i = i + 2; System.out.println(i); return i + printNumber(i + 2); } public static void main(String[] args) { // Recursive call without any // terminating condition StackOverflowErrorClass.printNumber(i); }}
Runtime Error:
RunTime Error in java code :- Exception in thread βmainβ java.lang.StackOverflowErrorat java.io.PrintStream.write(PrintStream.java:526)at java.io.PrintStream.print(PrintStream.java:597)at java.io.PrintStream.println(PrintStream.java:736)at StackOverflowErrorClass.printNumber(StackOverflowErrorClass.java:13)at StackOverflowErrorClass.printNumber(StackOverflowErrorClass.java:14)at StackOverflowErrorClass.printNumber(StackOverflowErrorClass.java:14)...
Note: Please run this on your system to see an error thrown, due to the stack size, this may not show error on online IDE.
How to fix StackOverflowError?
Avoiding repetitive calls: Try to introduce a proper terminating condition or some condition for the recursive calls to ensure that it terminates.Given below is the implementation with proper terminating condition:// Java Program to demonstrate proper// use of terminating condition // Printing natural numberspublic class stackOverflow { static int i = 0; public static int printNumber(int x) { i = i + 2; System.out.println(i); // Terminating condition if (i == 10) return i; return i + printNumber(i + 2); } public static void main(String[] args) { stackOverflow.printNumber(i); }}Output:2
4
6
8
10
Increasing the Stack Size: The second method could be, if you notice that itβs implemented correctly still we see an error, then we can avoid that only by increasing the Stack Size in order to store the required number of recursive calls. This is achieved by changing the settings of the compiler.Cyclic Relationships between classes is the relationship caused when two different classes instantiate each other inside their constructors.StackOverflowError is encountered because the constructor of Class A1 is instantiating Class A2, and the constructor of Class A2 is again instantiating Class A1, and it occurs repeatedly until we see StackOverflow. This error is mainly due to the bad calling of constructors, that is, calling each other, which is not even required, and also it doesnβt hold any significance, so we can just avoid introducing them in the codes.Given below is the implementation of Cyclic Relationships Between Classes:// Java Program to demonstrate// cyclic relationship between class public class A1 { public A2 type2; public A1() { // Constructor of A2 is called // hence object of A2 is created type2 = new A2(); } public static void main(String[] args) { // Cycle is started by // invoking constructor of class A1 A1 type1 = new A1(); }} class A2 { public A1 type1; public A2() { // Constructor of A1 is called // hence object of A1 is created type1 = new A1(); }}Runtime Error:RunTime Error in java code :- Exception in thread βmainβ java.lang.StackOverflowErrorat A2.(A1.java:32)at A1.(A1.java:13)at A2.(A1.java:32)...Note: This will keep repeating, Infinite Recursion is seen by these infinite cyclic calls.
Avoiding repetitive calls: Try to introduce a proper terminating condition or some condition for the recursive calls to ensure that it terminates.Given below is the implementation with proper terminating condition:// Java Program to demonstrate proper// use of terminating condition // Printing natural numberspublic class stackOverflow { static int i = 0; public static int printNumber(int x) { i = i + 2; System.out.println(i); // Terminating condition if (i == 10) return i; return i + printNumber(i + 2); } public static void main(String[] args) { stackOverflow.printNumber(i); }}Output:2
4
6
8
10
Given below is the implementation with proper terminating condition:
// Java Program to demonstrate proper// use of terminating condition // Printing natural numberspublic class stackOverflow { static int i = 0; public static int printNumber(int x) { i = i + 2; System.out.println(i); // Terminating condition if (i == 10) return i; return i + printNumber(i + 2); } public static void main(String[] args) { stackOverflow.printNumber(i); }}
2
4
6
8
10
Increasing the Stack Size: The second method could be, if you notice that itβs implemented correctly still we see an error, then we can avoid that only by increasing the Stack Size in order to store the required number of recursive calls. This is achieved by changing the settings of the compiler.Cyclic Relationships between classes is the relationship caused when two different classes instantiate each other inside their constructors.StackOverflowError is encountered because the constructor of Class A1 is instantiating Class A2, and the constructor of Class A2 is again instantiating Class A1, and it occurs repeatedly until we see StackOverflow. This error is mainly due to the bad calling of constructors, that is, calling each other, which is not even required, and also it doesnβt hold any significance, so we can just avoid introducing them in the codes.Given below is the implementation of Cyclic Relationships Between Classes:// Java Program to demonstrate// cyclic relationship between class public class A1 { public A2 type2; public A1() { // Constructor of A2 is called // hence object of A2 is created type2 = new A2(); } public static void main(String[] args) { // Cycle is started by // invoking constructor of class A1 A1 type1 = new A1(); }} class A2 { public A1 type1; public A2() { // Constructor of A1 is called // hence object of A1 is created type1 = new A1(); }}Runtime Error:RunTime Error in java code :- Exception in thread βmainβ java.lang.StackOverflowErrorat A2.(A1.java:32)at A1.(A1.java:13)at A2.(A1.java:32)...Note: This will keep repeating, Infinite Recursion is seen by these infinite cyclic calls.
Cyclic Relationships between classes is the relationship caused when two different classes instantiate each other inside their constructors.
StackOverflowError is encountered because the constructor of Class A1 is instantiating Class A2, and the constructor of Class A2 is again instantiating Class A1, and it occurs repeatedly until we see StackOverflow. This error is mainly due to the bad calling of constructors, that is, calling each other, which is not even required, and also it doesnβt hold any significance, so we can just avoid introducing them in the codes.
Given below is the implementation of Cyclic Relationships Between Classes:
// Java Program to demonstrate// cyclic relationship between class public class A1 { public A2 type2; public A1() { // Constructor of A2 is called // hence object of A2 is created type2 = new A2(); } public static void main(String[] args) { // Cycle is started by // invoking constructor of class A1 A1 type1 = new A1(); }} class A2 { public A1 type1; public A2() { // Constructor of A1 is called // hence object of A1 is created type1 = new A1(); }}
Runtime Error:
RunTime Error in java code :- Exception in thread βmainβ java.lang.StackOverflowErrorat A2.(A1.java:32)at A1.(A1.java:13)at A2.(A1.java:32)...
Note: This will keep repeating, Infinite Recursion is seen by these infinite cyclic calls.
Java-Exception Handling
Java-Exceptions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Apr, 2020"
},
{
"code": null,
"e": 201,
"s": 28,
"text": "StackOverflowError is an error which Java doesnβt allow to catch, for instance, stack running out of space, as itβs one of the most common runtime errors one can encounter."
},
{
"code": null,
"e": 390,
"s": 201,
"text": "The main cause of the StackOverflowError is that we havenβt provided the proper terminating condition to our recursive function or template, which means it will turn into an infinite loop."
},
{
"code": null,
"e": 432,
"s": 390,
"text": "When does StackOverflowError encountered?"
},
{
"code": null,
"e": 947,
"s": 432,
"text": "When we invoke a method, a new stack frame is created on the call stack or on the thread stack size. This stack frame holds parameters of the invoked method, mostly the local variables and the return address of the method. The creation of these stack frames will be iterative and will be stopped only when the end of the method invokes is found in the nested methods. In amidst of this process, if JVM runs out of space for the new stack frames which are required to be created, it will throw a StackOverflowError."
},
{
"code": null,
"e": 1093,
"s": 947,
"text": "For example: Lack of proper or no termination condition. This is mostly the cause of this situation termed as unterminated or infinite recursion."
},
{
"code": null,
"e": 1150,
"s": 1093,
"text": "Given below is the implementation of infinite recursion:"
},
{
"code": "// Java program to demonstrate// infinite recursion error public class StackOverflowErrorClass { static int i = 0; // Method to print numbers public static int printNumber(int x) { i = i + 2; System.out.println(i); return i + printNumber(i + 2); } public static void main(String[] args) { // Recursive call without any // terminating condition StackOverflowErrorClass.printNumber(i); }}",
"e": 1610,
"s": 1150,
"text": null
},
{
"code": null,
"e": 1625,
"s": 1610,
"text": "Runtime Error:"
},
{
"code": null,
"e": 2079,
"s": 1625,
"text": "RunTime Error in java code :- Exception in thread βmainβ java.lang.StackOverflowErrorat java.io.PrintStream.write(PrintStream.java:526)at java.io.PrintStream.print(PrintStream.java:597)at java.io.PrintStream.println(PrintStream.java:736)at StackOverflowErrorClass.printNumber(StackOverflowErrorClass.java:13)at StackOverflowErrorClass.printNumber(StackOverflowErrorClass.java:14)at StackOverflowErrorClass.printNumber(StackOverflowErrorClass.java:14)..."
},
{
"code": null,
"e": 2202,
"s": 2079,
"text": "Note: Please run this on your system to see an error thrown, due to the stack size, this may not show error on online IDE."
},
{
"code": null,
"e": 2233,
"s": 2202,
"text": "How to fix StackOverflowError?"
},
{
"code": null,
"e": 4659,
"s": 2233,
"text": "Avoiding repetitive calls: Try to introduce a proper terminating condition or some condition for the recursive calls to ensure that it terminates.Given below is the implementation with proper terminating condition:// Java Program to demonstrate proper// use of terminating condition // Printing natural numberspublic class stackOverflow { static int i = 0; public static int printNumber(int x) { i = i + 2; System.out.println(i); // Terminating condition if (i == 10) return i; return i + printNumber(i + 2); } public static void main(String[] args) { stackOverflow.printNumber(i); }}Output:2\n4\n6\n8\n10\nIncreasing the Stack Size: The second method could be, if you notice that itβs implemented correctly still we see an error, then we can avoid that only by increasing the Stack Size in order to store the required number of recursive calls. This is achieved by changing the settings of the compiler.Cyclic Relationships between classes is the relationship caused when two different classes instantiate each other inside their constructors.StackOverflowError is encountered because the constructor of Class A1 is instantiating Class A2, and the constructor of Class A2 is again instantiating Class A1, and it occurs repeatedly until we see StackOverflow. This error is mainly due to the bad calling of constructors, that is, calling each other, which is not even required, and also it doesnβt hold any significance, so we can just avoid introducing them in the codes.Given below is the implementation of Cyclic Relationships Between Classes:// Java Program to demonstrate// cyclic relationship between class public class A1 { public A2 type2; public A1() { // Constructor of A2 is called // hence object of A2 is created type2 = new A2(); } public static void main(String[] args) { // Cycle is started by // invoking constructor of class A1 A1 type1 = new A1(); }} class A2 { public A1 type1; public A2() { // Constructor of A1 is called // hence object of A1 is created type1 = new A1(); }}Runtime Error:RunTime Error in java code :- Exception in thread βmainβ java.lang.StackOverflowErrorat A2.(A1.java:32)at A1.(A1.java:13)at A2.(A1.java:32)...Note: This will keep repeating, Infinite Recursion is seen by these infinite cyclic calls."
},
{
"code": null,
"e": 5345,
"s": 4659,
"text": "Avoiding repetitive calls: Try to introduce a proper terminating condition or some condition for the recursive calls to ensure that it terminates.Given below is the implementation with proper terminating condition:// Java Program to demonstrate proper// use of terminating condition // Printing natural numberspublic class stackOverflow { static int i = 0; public static int printNumber(int x) { i = i + 2; System.out.println(i); // Terminating condition if (i == 10) return i; return i + printNumber(i + 2); } public static void main(String[] args) { stackOverflow.printNumber(i); }}Output:2\n4\n6\n8\n10\n"
},
{
"code": null,
"e": 5414,
"s": 5345,
"text": "Given below is the implementation with proper terminating condition:"
},
{
"code": "// Java Program to demonstrate proper// use of terminating condition // Printing natural numberspublic class stackOverflow { static int i = 0; public static int printNumber(int x) { i = i + 2; System.out.println(i); // Terminating condition if (i == 10) return i; return i + printNumber(i + 2); } public static void main(String[] args) { stackOverflow.printNumber(i); }}",
"e": 5868,
"s": 5414,
"text": null
},
{
"code": null,
"e": 5880,
"s": 5868,
"text": "2\n4\n6\n8\n10\n"
},
{
"code": null,
"e": 7621,
"s": 5880,
"text": "Increasing the Stack Size: The second method could be, if you notice that itβs implemented correctly still we see an error, then we can avoid that only by increasing the Stack Size in order to store the required number of recursive calls. This is achieved by changing the settings of the compiler.Cyclic Relationships between classes is the relationship caused when two different classes instantiate each other inside their constructors.StackOverflowError is encountered because the constructor of Class A1 is instantiating Class A2, and the constructor of Class A2 is again instantiating Class A1, and it occurs repeatedly until we see StackOverflow. This error is mainly due to the bad calling of constructors, that is, calling each other, which is not even required, and also it doesnβt hold any significance, so we can just avoid introducing them in the codes.Given below is the implementation of Cyclic Relationships Between Classes:// Java Program to demonstrate// cyclic relationship between class public class A1 { public A2 type2; public A1() { // Constructor of A2 is called // hence object of A2 is created type2 = new A2(); } public static void main(String[] args) { // Cycle is started by // invoking constructor of class A1 A1 type1 = new A1(); }} class A2 { public A1 type1; public A2() { // Constructor of A1 is called // hence object of A1 is created type1 = new A1(); }}Runtime Error:RunTime Error in java code :- Exception in thread βmainβ java.lang.StackOverflowErrorat A2.(A1.java:32)at A1.(A1.java:13)at A2.(A1.java:32)...Note: This will keep repeating, Infinite Recursion is seen by these infinite cyclic calls."
},
{
"code": null,
"e": 7762,
"s": 7621,
"text": "Cyclic Relationships between classes is the relationship caused when two different classes instantiate each other inside their constructors."
},
{
"code": null,
"e": 8190,
"s": 7762,
"text": "StackOverflowError is encountered because the constructor of Class A1 is instantiating Class A2, and the constructor of Class A2 is again instantiating Class A1, and it occurs repeatedly until we see StackOverflow. This error is mainly due to the bad calling of constructors, that is, calling each other, which is not even required, and also it doesnβt hold any significance, so we can just avoid introducing them in the codes."
},
{
"code": null,
"e": 8265,
"s": 8190,
"text": "Given below is the implementation of Cyclic Relationships Between Classes:"
},
{
"code": "// Java Program to demonstrate// cyclic relationship between class public class A1 { public A2 type2; public A1() { // Constructor of A2 is called // hence object of A2 is created type2 = new A2(); } public static void main(String[] args) { // Cycle is started by // invoking constructor of class A1 A1 type1 = new A1(); }} class A2 { public A1 type1; public A2() { // Constructor of A1 is called // hence object of A1 is created type1 = new A1(); }}",
"e": 8822,
"s": 8265,
"text": null
},
{
"code": null,
"e": 8837,
"s": 8822,
"text": "Runtime Error:"
},
{
"code": null,
"e": 8980,
"s": 8837,
"text": "RunTime Error in java code :- Exception in thread βmainβ java.lang.StackOverflowErrorat A2.(A1.java:32)at A1.(A1.java:13)at A2.(A1.java:32)..."
},
{
"code": null,
"e": 9071,
"s": 8980,
"text": "Note: This will keep repeating, Infinite Recursion is seen by these infinite cyclic calls."
},
{
"code": null,
"e": 9095,
"s": 9071,
"text": "Java-Exception Handling"
},
{
"code": null,
"e": 9111,
"s": 9095,
"text": "Java-Exceptions"
},
{
"code": null,
"e": 9116,
"s": 9111,
"text": "Java"
},
{
"code": null,
"e": 9121,
"s": 9116,
"text": "Java"
}
] |
How to use GROUP BY to concatenate strings in MySQL and how to set a separator for the concatenation?
|
To concatenate strings in MySQL with GROUP BY, you need to use GROUP_CONCAT() with a SEPARATOR parameter which may be comma(β) or space (β β) etc.
The syntax is as follows:
SELECT yourColumnName1,GROUP_CONCAT(yourColumnName2 SEPARATOR βyourValueβ) as anyVariableName FROM yourTableName GROUP BY yourColumnName1;
To understand the above syntax, let us create a table. The query to create a table is as follows:
mysql> create table GroupConcatenateDemo
-> (
-> Id int,
-> Name varchar(20)
-> );
Query OK, 0 rows affected (0.99 sec)
Insert some records in the table using insert command. The query to insert record is as follows:
mysql> insert into GroupConcatenateDemo values(10,'Larry');
Query OK, 1 row affected (0.41 sec)
mysql> insert into GroupConcatenateDemo values(11,'Mike');
Query OK, 1 row affected (0.18 sec)
mysql> insert into GroupConcatenateDemo values(12,'John');
Query OK, 1 row affected (0.14 sec)
mysql> insert into GroupConcatenateDemo values(10,'Elon');
Query OK, 1 row affected (0.63 sec)
mysql> insert into GroupConcatenateDemo values(10,'Bob');
Query OK, 1 row affected (0.12 sec)
mysql> insert into GroupConcatenateDemo values(11,'Sam');
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement. The query is as follows:
mysql> select *from GroupConcatenateDemo;
The following is the output:
+------+-------+
| Id | Name |
+------+-------+
| 10 | Larry |
| 11 | Mike |
| 12 | John |
| 10 | Elon |
| 10 | Bob |
| 11 | Sam |
+------+-------+
6 rows in set (0.00 sec)
Here is the query that use GROUP BY to concatenate the strings in MySQL. Perform GROUP BY on the basis of Id and concatenate the strings using GROUP_CONCAT() function in MySQL.
The query is as follows:
mysql> select Id,group_concat(Name SEPARATOR ',') as GroupConcatDemo from GroupConcatenateDemo
-> group by Id;
The following is the output:
+------+-----------------+
| Id | GroupConcatDemo |
+------+-----------------+
| 10 | Larry,Elon,Bob |
| 11 | Mike,Sam |
| 12 | John |
+------+-----------------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1209,
"s": 1062,
"text": "To concatenate strings in MySQL with GROUP BY, you need to use GROUP_CONCAT() with a SEPARATOR parameter which may be comma(β) or space (β β) etc."
},
{
"code": null,
"e": 1235,
"s": 1209,
"text": "The syntax is as follows:"
},
{
"code": null,
"e": 1374,
"s": 1235,
"text": "SELECT yourColumnName1,GROUP_CONCAT(yourColumnName2 SEPARATOR βyourValueβ) as anyVariableName FROM yourTableName GROUP BY yourColumnName1;"
},
{
"code": null,
"e": 1472,
"s": 1374,
"text": "To understand the above syntax, let us create a table. The query to create a table is as follows:"
},
{
"code": null,
"e": 1604,
"s": 1472,
"text": "mysql> create table GroupConcatenateDemo\n -> (\n -> Id int,\n -> Name varchar(20)\n -> );\nQuery OK, 0 rows affected (0.99 sec)"
},
{
"code": null,
"e": 1701,
"s": 1604,
"text": "Insert some records in the table using insert command. The query to insert record is as follows:"
},
{
"code": null,
"e": 2270,
"s": 1701,
"text": "mysql> insert into GroupConcatenateDemo values(10,'Larry');\nQuery OK, 1 row affected (0.41 sec)\nmysql> insert into GroupConcatenateDemo values(11,'Mike');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into GroupConcatenateDemo values(12,'John');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into GroupConcatenateDemo values(10,'Elon');\nQuery OK, 1 row affected (0.63 sec)\nmysql> insert into GroupConcatenateDemo values(10,'Bob');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into GroupConcatenateDemo values(11,'Sam');\nQuery OK, 1 row affected (0.14 sec)"
},
{
"code": null,
"e": 2354,
"s": 2270,
"text": "Display all records from the table using select statement. The query is as follows:"
},
{
"code": null,
"e": 2396,
"s": 2354,
"text": "mysql> select *from GroupConcatenateDemo;"
},
{
"code": null,
"e": 2425,
"s": 2396,
"text": "The following is the output:"
},
{
"code": null,
"e": 2620,
"s": 2425,
"text": "+------+-------+\n| Id | Name |\n+------+-------+\n| 10 | Larry |\n| 11 | Mike |\n| 12 | John |\n| 10 | Elon |\n| 10 | Bob |\n| 11 | Sam |\n+------+-------+\n6 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2797,
"s": 2620,
"text": "Here is the query that use GROUP BY to concatenate the strings in MySQL. Perform GROUP BY on the basis of Id and concatenate the strings using GROUP_CONCAT() function in MySQL."
},
{
"code": null,
"e": 2822,
"s": 2797,
"text": "The query is as follows:"
},
{
"code": null,
"e": 2936,
"s": 2822,
"text": "mysql> select Id,group_concat(Name SEPARATOR ',') as GroupConcatDemo from GroupConcatenateDemo\n -> group by Id;"
},
{
"code": null,
"e": 2965,
"s": 2936,
"text": "The following is the output:"
},
{
"code": null,
"e": 3179,
"s": 2965,
"text": "+------+-----------------+\n| Id | GroupConcatDemo |\n+------+-----------------+\n| 10 | Larry,Elon,Bob |\n| 11 | Mike,Sam |\n| 12 | John |\n+------+-----------------+\n3 rows in set (0.00 sec)"
}
] |
How to set Adapter to Auto Complete Text view?
|
Before getting into an example, we should know what is autocomplete textview in android. Autocomplete textview is just like an edit text and it is a subclass of editext, but it is going to show suggestion from a list as a dropdown list. We have to set up Threshold value to auto-complete text view. for example, we have set it up Threshold as 1 so if user enters one letter is going to give suggestion according to Threshold letter.
This example demonstrates about how to set up an adapter to auto-complete Textview.
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"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<AutoCompleteTextView
android:id="@+id/autoComplete"
android:layout_width="fill_parent"
android:hint="Enter programming language"
android:layout_height="wrap_content" />
</LinearLayout>
In the above we have declared autocomplete textview, when user enters a letter, it going to show list as suggestions in a drop-down menu.
Step 3 β Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
RadioButton radioButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final AutoCompleteTextView autoCompleteTextView=findViewById(R.id.autoComplete);
ArrayList arrayList=new ArrayList<>();
arrayList.add("Android");
arrayList.add("JAVA");
arrayList.add("CPP");
arrayList.add("C Programming");
arrayList.add("Kotlin");
arrayList.add("CSS");
arrayList.add("HTML");
arrayList.add("PHP");
arrayList.add("Swift");
ArrayAdapter arrayAdapter=new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, arrayList);
autoCompleteTextView.setAdapter(arrayAdapter);
autoCompleteTextView.setThreshold(1);
autoCompleteTextView.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
Log.d("beforeTextChanged", String.valueOf(s));
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.d("onTextChanged", String.valueOf(s));
}
@Override
public void afterTextChanged(Editable s) {
Log.d("afterTextChanged", String.valueOf(s));
}
});
}
}
In the above code, we have stored some values in ArrayList and appended ArrayList to array adapter. We have set the adapter to auto-complete textview and added threshold as 1. 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 an 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 β
Initially, it going to show screen as above and enter ja in that textview it going to show result from adapter as shown below-
In the above result we have only one suggestion, Remove J and type c in that text view, it going to show multiple suggestions as shown below -
|
[
{
"code": null,
"e": 1496,
"s": 1062,
"text": " Before getting into an example, we should know what is autocomplete textview in android. Autocomplete textview is just like an edit text and it is a subclass of editext, but it is going to show suggestion from a list as a dropdown list. We have to set up Threshold value to auto-complete text view. for example, we have set it up Threshold as 1 so if user enters one letter is going to give suggestion according to Threshold letter."
},
{
"code": null,
"e": 1580,
"s": 1496,
"text": "This example demonstrates about how to set up an adapter to auto-complete Textview."
},
{
"code": null,
"e": 1709,
"s": 1580,
"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": 1774,
"s": 1709,
"text": "Step 2 β Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2379,
"s": 1774,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center\"\n android:orientation=\"vertical\"\n tools:context=\".MainActivity\">\n <AutoCompleteTextView\n android:id=\"@+id/autoComplete\"\n android:layout_width=\"fill_parent\"\n android:hint=\"Enter programming language\"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2517,
"s": 2379,
"text": "In the above we have declared autocomplete textview, when user enters a letter, it going to show list as suggestions in a drop-down menu."
},
{
"code": null,
"e": 2574,
"s": 2517,
"text": "Step 3 β Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 4613,
"s": 2574,
"text": "package com.example.andy.myapplication;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.text.Editable;\nimport android.text.TextWatcher;\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.AdapterView;\nimport android.widget.ArrayAdapter;\nimport android.widget.AutoCompleteTextView;\nimport android.widget.Button;\nimport android.widget.RadioButton;\nimport android.widget.Toast;\nimport java.util.ArrayList;\npublic class MainActivity extends AppCompatActivity {\n RadioButton radioButton;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final AutoCompleteTextView autoCompleteTextView=findViewById(R.id.autoComplete);\n ArrayList arrayList=new ArrayList<>();\n arrayList.add(\"Android\");\n arrayList.add(\"JAVA\");\n arrayList.add(\"CPP\");\n arrayList.add(\"C Programming\");\n arrayList.add(\"Kotlin\");\n arrayList.add(\"CSS\");\n arrayList.add(\"HTML\");\n arrayList.add(\"PHP\");\n arrayList.add(\"Swift\");\n ArrayAdapter arrayAdapter=new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, arrayList);\n autoCompleteTextView.setAdapter(arrayAdapter);\n autoCompleteTextView.setThreshold(1);\n autoCompleteTextView.addTextChangedListener(new TextWatcher() {\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) {\n Log.d(\"beforeTextChanged\", String.valueOf(s));\n }\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) {\n Log.d(\"onTextChanged\", String.valueOf(s));\n }\n @Override\n public void afterTextChanged(Editable s) {\n Log.d(\"afterTextChanged\", String.valueOf(s));\n }\n });\n }\n}"
},
{
"code": null,
"e": 5139,
"s": 4613,
"text": "In the above code, we have stored some values in ArrayList and appended ArrayList to array adapter. We have set the adapter to auto-complete textview and added threshold as 1. 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 an 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": 5266,
"s": 5139,
"text": "Initially, it going to show screen as above and enter ja in that textview it going to show result from adapter as shown below-"
},
{
"code": null,
"e": 5409,
"s": 5266,
"text": "In the above result we have only one suggestion, Remove J and type c in that text view, it going to show multiple suggestions as shown below -"
}
] |
Bisect Algorithm Functions in Python - GeeksforGeeks
|
19 Feb, 2021
The purpose of Bisect algorithm is to find a position in list where an element needs to be inserted to keep the list sorted.
Python in its definition provides the bisect algorithms using the module βbisectβ which allows to keep the list in sorted order after insertion of each element. This is essential as this reduces overhead time required to sort the list again and again after insertion of each element.
Important Bisection Functions
1. bisect(list, num, beg, end) :- This function returns the position in the sorted list, where the number passed in argument can be placed so as to maintain the resultant list in sorted order. If the element is already present in the list, the right most position where element has to be inserted is returned. This function takes 4 arguments, list which has to be worked with, number to insert, starting position in list to consider, ending position which has to be considered.
2. bisect_left(list, num, beg, end) :- This function returns the position in the sorted list, where the number passed in argument can be placed so as to maintain the resultant list in sorted order. If the element is already present in the list, the left most position where element has to be inserted is returned. This function takes 4 arguments, list which has to be worked with, number to insert, starting position in list to consider, ending position which has to be considered.
3. bisect_right(list, num, beg, end) :- This function works similar to the βbisect()β and mentioned above.
# Python code to demonstrate the working of# bisect(), bisect_left() and bisect_right() # importing "bisect" for bisection operationsimport bisect # initializing listli = [1, 3, 4, 4, 4, 6, 7] # using bisect() to find index to insert new element# returns 5 ( right most possible index )print ("The rightmost index to insert, so list remains sorted is : ", end="")print (bisect.bisect(li, 4)) # using bisect_left() to find index to insert new element# returns 2 ( left most possible index )print ("The leftmost index to insert, so list remains sorted is : ", end="")print (bisect.bisect_left(li, 4)) # using bisect_right() to find index to insert new element# returns 4 ( right most possible index )print ("The rightmost index to insert, so list remains sorted is : ", end="")print (bisect.bisect_right(li, 4, 0, 4))
Output:
The rightmost index to insert, so list remains sorted is : 5
The leftmost index to insert, so list remains sorted is : 2
The rightmost index to insert, so list remains sorted is : 4
Time Complexity:
O(log(n)) -> Bisect method works on the concept of binary search
4. insort(list, num, beg, end) :- This function returns the sorted list after inserting number in appropriate position, if the element is already present in the list, the element is inserted at the rightmost possible position. This function takes 4 arguments, list which has to be worked with, number to insert, starting position in list to consider, ending position which has to be considered.
5. insort_left(list, num, beg, end) :- This function returns the sorted list after inserting number in appropriate position, if the element is already present in the list, the element is inserted at the leftmost possible position. This function takes 4 arguments, list which has to be worked with, number to insert, starting position in list to consider, ending position which has to be considered.
6. insort_right(list, num, beg, end) :- This function works similar to the βinsort()β as mentioned above.
# Python code to demonstrate the working of# insort(), insort_left() and insort_right() # importing "bisect" for bisection operationsimport bisect # initializing listli1 = [1, 3, 4, 4, 4, 6, 7] # initializing listli2 = [1, 3, 4, 4, 4, 6, 7] # initializing listli3 = [1, 3, 4, 4, 4, 6, 7] # using insort() to insert 5 at appropriate position# inserts at 6th positionbisect.insort(li1, 5) print ("The list after inserting new element using insort() is : ")for i in range(0, 7): print(li1[i], end=" ") # using insort_left() to insert 5 at appropriate position# inserts at 6th positionbisect.insort_left(li2, 5) print("\r") print ("The list after inserting new element using insort_left() is : ")for i in range(0, 7): print(li2[i], end=" ") print("\r") # using insort_right() to insert 5 at appropriate position# inserts at 5th positionbisect.insort_right(li3, 5, 0, 4) print ("The list after inserting new element using insort_right() is : ")for i in range(0, 7): print(li3[i], end=" ")
Output:
The list after inserting new element using insort() is :
1 3 4 4 4 5 6
The list after inserting new element using insort_left() is :
1 3 4 4 4 5 6
The list after inserting new element using insort_right() is :
1 3 4 4 5 4 6
Time Complexity:
O(n) -> Inserting an element in sorted array requires traversal
YouTubeGeeksforGeeks502K subscribersPython Programming Tutorial | Bisect Algorithm Functions 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 / 3:32β’Liveβ’<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=7eiXnQY2xmg" 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 contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
rajatg98
python sorting-exercises
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
sum() function in Python
Print lists in Python (4 Different Ways)
|
[
{
"code": null,
"e": 24694,
"s": 24666,
"text": "\n19 Feb, 2021"
},
{
"code": null,
"e": 24819,
"s": 24694,
"text": "The purpose of Bisect algorithm is to find a position in list where an element needs to be inserted to keep the list sorted."
},
{
"code": null,
"e": 25103,
"s": 24819,
"text": "Python in its definition provides the bisect algorithms using the module βbisectβ which allows to keep the list in sorted order after insertion of each element. This is essential as this reduces overhead time required to sort the list again and again after insertion of each element."
},
{
"code": null,
"e": 25133,
"s": 25103,
"text": "Important Bisection Functions"
},
{
"code": null,
"e": 25611,
"s": 25133,
"text": "1. bisect(list, num, beg, end) :- This function returns the position in the sorted list, where the number passed in argument can be placed so as to maintain the resultant list in sorted order. If the element is already present in the list, the right most position where element has to be inserted is returned. This function takes 4 arguments, list which has to be worked with, number to insert, starting position in list to consider, ending position which has to be considered."
},
{
"code": null,
"e": 26093,
"s": 25611,
"text": "2. bisect_left(list, num, beg, end) :- This function returns the position in the sorted list, where the number passed in argument can be placed so as to maintain the resultant list in sorted order. If the element is already present in the list, the left most position where element has to be inserted is returned. This function takes 4 arguments, list which has to be worked with, number to insert, starting position in list to consider, ending position which has to be considered."
},
{
"code": null,
"e": 26200,
"s": 26093,
"text": "3. bisect_right(list, num, beg, end) :- This function works similar to the βbisect()β and mentioned above."
},
{
"code": "# Python code to demonstrate the working of# bisect(), bisect_left() and bisect_right() # importing \"bisect\" for bisection operationsimport bisect # initializing listli = [1, 3, 4, 4, 4, 6, 7] # using bisect() to find index to insert new element# returns 5 ( right most possible index )print (\"The rightmost index to insert, so list remains sorted is : \", end=\"\")print (bisect.bisect(li, 4)) # using bisect_left() to find index to insert new element# returns 2 ( left most possible index )print (\"The leftmost index to insert, so list remains sorted is : \", end=\"\")print (bisect.bisect_left(li, 4)) # using bisect_right() to find index to insert new element# returns 4 ( right most possible index )print (\"The rightmost index to insert, so list remains sorted is : \", end=\"\")print (bisect.bisect_right(li, 4, 0, 4))",
"e": 27024,
"s": 26200,
"text": null
},
{
"code": null,
"e": 27032,
"s": 27024,
"text": "Output:"
},
{
"code": null,
"e": 27218,
"s": 27032,
"text": "The rightmost index to insert, so list remains sorted is : 5\nThe leftmost index to insert, so list remains sorted is : 2\nThe rightmost index to insert, so list remains sorted is : 4\n"
},
{
"code": null,
"e": 27235,
"s": 27218,
"text": "Time Complexity:"
},
{
"code": null,
"e": 27300,
"s": 27235,
"text": "O(log(n)) -> Bisect method works on the concept of binary search"
},
{
"code": null,
"e": 27695,
"s": 27300,
"text": "4. insort(list, num, beg, end) :- This function returns the sorted list after inserting number in appropriate position, if the element is already present in the list, the element is inserted at the rightmost possible position. This function takes 4 arguments, list which has to be worked with, number to insert, starting position in list to consider, ending position which has to be considered."
},
{
"code": null,
"e": 28094,
"s": 27695,
"text": "5. insort_left(list, num, beg, end) :- This function returns the sorted list after inserting number in appropriate position, if the element is already present in the list, the element is inserted at the leftmost possible position. This function takes 4 arguments, list which has to be worked with, number to insert, starting position in list to consider, ending position which has to be considered."
},
{
"code": null,
"e": 28200,
"s": 28094,
"text": "6. insort_right(list, num, beg, end) :- This function works similar to the βinsort()β as mentioned above."
},
{
"code": "# Python code to demonstrate the working of# insort(), insort_left() and insort_right() # importing \"bisect\" for bisection operationsimport bisect # initializing listli1 = [1, 3, 4, 4, 4, 6, 7] # initializing listli2 = [1, 3, 4, 4, 4, 6, 7] # initializing listli3 = [1, 3, 4, 4, 4, 6, 7] # using insort() to insert 5 at appropriate position# inserts at 6th positionbisect.insort(li1, 5) print (\"The list after inserting new element using insort() is : \")for i in range(0, 7): print(li1[i], end=\" \") # using insort_left() to insert 5 at appropriate position# inserts at 6th positionbisect.insort_left(li2, 5) print(\"\\r\") print (\"The list after inserting new element using insort_left() is : \")for i in range(0, 7): print(li2[i], end=\" \") print(\"\\r\") # using insort_right() to insert 5 at appropriate position# inserts at 5th positionbisect.insort_right(li3, 5, 0, 4) print (\"The list after inserting new element using insort_right() is : \")for i in range(0, 7): print(li3[i], end=\" \")",
"e": 29205,
"s": 28200,
"text": null
},
{
"code": null,
"e": 29213,
"s": 29205,
"text": "Output:"
},
{
"code": null,
"e": 29444,
"s": 29213,
"text": "The list after inserting new element using insort() is : \n1 3 4 4 4 5 6 \nThe list after inserting new element using insort_left() is : \n1 3 4 4 4 5 6 \nThe list after inserting new element using insort_right() is : \n1 3 4 4 5 4 6 \n"
},
{
"code": null,
"e": 29461,
"s": 29444,
"text": "Time Complexity:"
},
{
"code": null,
"e": 29525,
"s": 29461,
"text": "O(n) -> Inserting an element in sorted array requires traversal"
},
{
"code": null,
"e": 30390,
"s": 29525,
"text": "YouTubeGeeksforGeeks502K subscribersPython Programming Tutorial | Bisect Algorithm Functions 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 / 3:32β’Liveβ’<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=7eiXnQY2xmg\" 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": 30691,
"s": 30390,
"text": "This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 30816,
"s": 30691,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 30825,
"s": 30816,
"text": "rajatg98"
},
{
"code": null,
"e": 30850,
"s": 30825,
"text": "python sorting-exercises"
},
{
"code": null,
"e": 30857,
"s": 30850,
"text": "Python"
},
{
"code": null,
"e": 30955,
"s": 30857,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30977,
"s": 30955,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 31009,
"s": 30977,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 31051,
"s": 31009,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 31077,
"s": 31051,
"text": "Python String | replace()"
},
{
"code": null,
"e": 31114,
"s": 31077,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 31143,
"s": 31114,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 31185,
"s": 31143,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 31241,
"s": 31185,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 31266,
"s": 31241,
"text": "sum() function in Python"
}
] |
Reverse First K elements of Queue | Practice | GeeksforGeeks
|
Given an integer K and a queue of integers, we need to reverse the order of the first K elements of the queue, leaving the other elements in the same relative order.
Only following standard operations are allowed on queue.
enqueue(x) : Add an item x to rear of queue
dequeue() : Remove an item from front of queue
size() : Returns number of elements in queue.
front() : Finds front item.
Note: The above operations represent the general processings. In-built functions of the respective languages can be used to solve the problem.
Example 1:
Input:
5 3
1 2 3 4 5
Output:
3 2 1 4 5
Explanation:
After reversing the given
input from the 3rd position the resultant
output will be 3 2 1 4 5.
Example 2:
Input:
4 4
4 3 2 1
Output:
1 2 3 4
Explanation:
After reversing the given
input from the 4th position the resultant
output will be 1 2 3 4.
Your Task:
Complete the provided function modifyQueue that takes queue and k as parameters and returns a modified queue. The printing is done automatically by the driver code.
Expected Time Complexity : O(n)
Expected Auxiliary Space : O(n)
Constraints:
1 <= N <= 1000
1 <= K <= N
Note: The Input/Output format and the Example given are used for the system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code.
0
hrithikjain98893 days ago
Total Time Taken :-0.02/1.62
// just removing first k element from queue and push it to a stack
then pop those element from stack (as element from stack are poped out from backside ,so they are already in reverse order) and push these element into a new queue and then push the other remaining element from queue.
queue<int> modifyQueue(queue<int> q, int k) { // add code here. stack<int> s; queue<int> q1; int p=k; while(p--){ s.push(q.front()); q.pop();}while(k--){ q1.push(s.top()); s.pop();}while(q.size()!=0){ q1.push(q.front()); q.pop();}return q1;
}
0
tanvib20141 week ago
queue<int> modifyQueue(queue<int> q, int k) {
stack<int> st;
queue<int> res;
while(k--){
int x = q.front(); q.pop();
st.push(x);
}
while(!st.empty()){
int x = st.top();
st.pop();
res.push(x);
}
while(!q.empty()){
int x = q.front();
q.pop();
res.push(x);
}
return res;
}
0
lovedeep79051 week ago
//Only using stack java code
Stack<Integer> stack=new Stack<>(); int m=q.size()-k; for(int i=0;i<k;i++){ stack.push(q.remove()); } for(int i=0;i<k;i++){ q.add(stack.pop()); } for(int i=0;i<m;i++){ int removed=q.remove(); q.add(removed); } return q;
0
shilsoumyadip1 week ago
queue<int> modifyQueue(queue<int> q, int k) {
stack<int>s; int x = q.size(); while(!q.empty() and q.size() != x - k ) { s.push(q.front()); q.pop(); } queue<int>q1; while(!q.empty()) { q1.push(q.front()); q.pop(); } while(!s.empty()) { q.push(s.top()); s.pop(); } while(!q1.empty()) { q.push(q1.front()); q1.pop(); } return q;}
0
harshscode1 week ago
stack<int> s; for(int i=0;i<k;i++) { s.push(q.front()); q.pop(); } while(!s.empty()) { q.push(s.top()); s.pop(); } int size=q.size()-k; while(size--) { int x=q.front(); q.pop(); q.push(x); } return q;
0
ankitap99322 weeks ago
queue<int> modifyQueue(queue<int> q, int k) { //adding element till k to stack stack<int> s; for(int i=0;i<k;i++){ int x=q.front(); q.pop(); s.push(x); } //push back stack element to queue...why? --> these are those reversed k elements while(!s.empty()){ q.push(s.top()); s.pop(); } //since element in pushed from back in queue so our queue at this stage will be 4 5 3 2 1 //so ratate from n-k (n=q.size()) int n=q.size(); for(int i=0;i<n-k;i++){ int x=q.front(); q.pop(); q.push(x); } return q;}
0
sharmadikshant57053 weeks ago
queue<int> modifyQueue(queue<int> q, int k) { // add code here. stack <int> s; //pop first k from queue and push into stack for(int i=0;i<k ; i++){ int val = q.front(); q.pop(); s.push(val); } // s till not empty while(!s.empty()){ int val = s.top(); s.pop(); q.push(val); } int t = q.size() - k; while(t--){ int val = q.front(); q.pop(); q.push(val); } return q;
0
amarrajsmart1974 weeks ago
Easy C++ Solution.Time Taken=0.0/1.6 Sec.
queue<int> modifyQueue(queue<int> q, int k) { // add code here. stack <int> st; int n=q.size(); queue<int> q1; for(int i=0;i<k;i++) { st.push(q.front()); q.pop(); } for(int i=0;i<k;i++) { q.push(st.top()); st.pop(); } for(int i=0;i<n-k;i++) { q1.push(q.front()); q.pop(); } for(int i=0;i<n-k;i++) { q.push(q1.front()); q1.pop(); } return q;}
0
akbhobhiya4 weeks ago
queue<int> modifyQueue(queue<int> q, int k) {
// add code here.
int n = q.size();
vector<int>ak,an;
for(int i=0;i<k;i++){
ak.push_back(q.front());
q.pop();
}
for(int i=k;i<n;i++){
an.push_back(q.front());
q.pop();
}
reverse(ak.begin(),ak.end());
for(int i=0;i<k;i++)q.push(ak[i]);
for(int i=k;i<n;i++)q.push(an[i-k]);
return q;
}
0
abhishekyadav952014 weeks ago
SIMPLE C++ SOL.
//
queue<int> modifyQueue(queue<int> q, int k) {stack<int>s;int n=q.size();for(int i=0;i<k;i++){ int a=q.front(); q.pop(); s.push(a);}while(!s.empty()){ q.push(s.top()); s.pop();}for(int i=0;i<n-k;i++){ int a =q.front(); q.pop(); q.push(a);}return q;}
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": 404,
"s": 238,
"text": "Given an integer K and a queue of integers, we need to reverse the order of the first K elements of the queue, leaving the other elements in the same relative order."
},
{
"code": null,
"e": 461,
"s": 404,
"text": "Only following standard operations are allowed on queue."
},
{
"code": null,
"e": 505,
"s": 461,
"text": "enqueue(x) : Add an item x to rear of queue"
},
{
"code": null,
"e": 552,
"s": 505,
"text": "dequeue() : Remove an item from front of queue"
},
{
"code": null,
"e": 598,
"s": 552,
"text": "size() : Returns number of elements in queue."
},
{
"code": null,
"e": 769,
"s": 598,
"text": "front() : Finds front item.\nNote: The above operations represent the general processings. In-built functions of the respective languages can be used to solve the problem."
},
{
"code": null,
"e": 780,
"s": 769,
"text": "Example 1:"
},
{
"code": null,
"e": 932,
"s": 780,
"text": "Input:\n5 3\n1 2 3 4 5\n\nOutput: \n3 2 1 4 5\n\nExplanation: \nAfter reversing the given\ninput from the 3rd position the resultant\noutput will be 3 2 1 4 5.\n\n"
},
{
"code": null,
"e": 943,
"s": 932,
"text": "Example 2:"
},
{
"code": null,
"e": 1087,
"s": 943,
"text": "Input:\n4 4\n4 3 2 1\n\nOutput: \n1 2 3 4\n\nExplanation: \nAfter reversing the given\ninput from the 4th position the resultant\noutput will be 1 2 3 4."
},
{
"code": null,
"e": 1263,
"s": 1087,
"text": "Your Task:\nComplete the provided function modifyQueue that takes queue and k as parameters and returns a modified queue. The printing is done automatically by the driver code."
},
{
"code": null,
"e": 1327,
"s": 1263,
"text": "Expected Time Complexity : O(n)\nExpected Auxiliary Space : O(n)"
},
{
"code": null,
"e": 1367,
"s": 1327,
"text": "Constraints:\n1 <= N <= 1000\n1 <= K <= N"
},
{
"code": null,
"e": 1686,
"s": 1367,
"text": "Note: The Input/Output format and the Example given are used for the system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code."
},
{
"code": null,
"e": 1688,
"s": 1686,
"text": "0"
},
{
"code": null,
"e": 1714,
"s": 1688,
"text": "hrithikjain98893 days ago"
},
{
"code": null,
"e": 1745,
"s": 1714,
"text": " Total Time Taken :-0.02/1.62 "
},
{
"code": null,
"e": 1813,
"s": 1745,
"text": "// just removing first k element from queue and push it to a stack "
},
{
"code": null,
"e": 2031,
"s": 1813,
"text": "then pop those element from stack (as element from stack are poped out from backside ,so they are already in reverse order) and push these element into a new queue and then push the other remaining element from queue."
},
{
"code": null,
"e": 2300,
"s": 2033,
"text": "queue<int> modifyQueue(queue<int> q, int k) { // add code here. stack<int> s; queue<int> q1; int p=k; while(p--){ s.push(q.front()); q.pop();}while(k--){ q1.push(s.top()); s.pop();}while(q.size()!=0){ q1.push(q.front()); q.pop();}return q1;"
},
{
"code": null,
"e": 2302,
"s": 2300,
"text": "}"
},
{
"code": null,
"e": 2304,
"s": 2302,
"text": "0"
},
{
"code": null,
"e": 2325,
"s": 2304,
"text": "tanvib20141 week ago"
},
{
"code": null,
"e": 2695,
"s": 2325,
"text": "queue<int> modifyQueue(queue<int> q, int k) {\n stack<int> st;\n queue<int> res;\n while(k--){\n int x = q.front(); q.pop();\n st.push(x);\n }\n while(!st.empty()){\n int x = st.top();\n st.pop();\n res.push(x);\n }\n while(!q.empty()){\n int x = q.front();\n q.pop();\n res.push(x);\n }\n return res;\n}"
},
{
"code": null,
"e": 2697,
"s": 2695,
"text": "0"
},
{
"code": null,
"e": 2720,
"s": 2697,
"text": "lovedeep79051 week ago"
},
{
"code": null,
"e": 2749,
"s": 2720,
"text": "//Only using stack java code"
},
{
"code": null,
"e": 3079,
"s": 2751,
"text": " Stack<Integer> stack=new Stack<>(); int m=q.size()-k; for(int i=0;i<k;i++){ stack.push(q.remove()); } for(int i=0;i<k;i++){ q.add(stack.pop()); } for(int i=0;i<m;i++){ int removed=q.remove(); q.add(removed); } return q; "
},
{
"code": null,
"e": 3081,
"s": 3079,
"text": "0"
},
{
"code": null,
"e": 3105,
"s": 3081,
"text": "shilsoumyadip1 week ago"
},
{
"code": null,
"e": 3151,
"s": 3105,
"text": "queue<int> modifyQueue(queue<int> q, int k) {"
},
{
"code": null,
"e": 3521,
"s": 3151,
"text": "stack<int>s; int x = q.size(); while(!q.empty() and q.size() != x - k ) { s.push(q.front()); q.pop(); } queue<int>q1; while(!q.empty()) { q1.push(q.front()); q.pop(); } while(!s.empty()) { q.push(s.top()); s.pop(); } while(!q1.empty()) { q.push(q1.front()); q1.pop(); } return q;}"
},
{
"code": null,
"e": 3523,
"s": 3521,
"text": "0"
},
{
"code": null,
"e": 3544,
"s": 3523,
"text": "harshscode1 week ago"
},
{
"code": null,
"e": 3863,
"s": 3544,
"text": " stack<int> s; for(int i=0;i<k;i++) { s.push(q.front()); q.pop(); } while(!s.empty()) { q.push(s.top()); s.pop(); } int size=q.size()-k; while(size--) { int x=q.front(); q.pop(); q.push(x); } return q; "
},
{
"code": null,
"e": 3865,
"s": 3863,
"text": "0"
},
{
"code": null,
"e": 3888,
"s": 3865,
"text": "ankitap99322 weeks ago"
},
{
"code": null,
"e": 4469,
"s": 3888,
"text": "queue<int> modifyQueue(queue<int> q, int k) { //adding element till k to stack stack<int> s; for(int i=0;i<k;i++){ int x=q.front(); q.pop(); s.push(x); } //push back stack element to queue...why? --> these are those reversed k elements while(!s.empty()){ q.push(s.top()); s.pop(); } //since element in pushed from back in queue so our queue at this stage will be 4 5 3 2 1 //so ratate from n-k (n=q.size()) int n=q.size(); for(int i=0;i<n-k;i++){ int x=q.front(); q.pop(); q.push(x); } return q;}"
},
{
"code": null,
"e": 4471,
"s": 4469,
"text": "0"
},
{
"code": null,
"e": 4501,
"s": 4471,
"text": "sharmadikshant57053 weeks ago"
},
{
"code": null,
"e": 4953,
"s": 4501,
"text": "queue<int> modifyQueue(queue<int> q, int k) { // add code here. stack <int> s; //pop first k from queue and push into stack for(int i=0;i<k ; i++){ int val = q.front(); q.pop(); s.push(val); } // s till not empty while(!s.empty()){ int val = s.top(); s.pop(); q.push(val); } int t = q.size() - k; while(t--){ int val = q.front(); q.pop(); q.push(val); } return q;"
},
{
"code": null,
"e": 4955,
"s": 4953,
"text": "0"
},
{
"code": null,
"e": 4982,
"s": 4955,
"text": "amarrajsmart1974 weeks ago"
},
{
"code": null,
"e": 5024,
"s": 4982,
"text": "Easy C++ Solution.Time Taken=0.0/1.6 Sec."
},
{
"code": null,
"e": 5487,
"s": 5026,
"text": "queue<int> modifyQueue(queue<int> q, int k) { // add code here. stack <int> st; int n=q.size(); queue<int> q1; for(int i=0;i<k;i++) { st.push(q.front()); q.pop(); } for(int i=0;i<k;i++) { q.push(st.top()); st.pop(); } for(int i=0;i<n-k;i++) { q1.push(q.front()); q.pop(); } for(int i=0;i<n-k;i++) { q.push(q1.front()); q1.pop(); } return q;}"
},
{
"code": null,
"e": 5489,
"s": 5487,
"text": "0"
},
{
"code": null,
"e": 5511,
"s": 5489,
"text": "akbhobhiya4 weeks ago"
},
{
"code": null,
"e": 5917,
"s": 5511,
"text": "queue<int> modifyQueue(queue<int> q, int k) {\n // add code here.\n int n = q.size();\n vector<int>ak,an;\n for(int i=0;i<k;i++){\n ak.push_back(q.front());\n q.pop();\n }\n for(int i=k;i<n;i++){\n an.push_back(q.front());\n q.pop();\n }\n reverse(ak.begin(),ak.end());\n for(int i=0;i<k;i++)q.push(ak[i]);\n for(int i=k;i<n;i++)q.push(an[i-k]);\n return q;\n}"
},
{
"code": null,
"e": 5919,
"s": 5917,
"text": "0"
},
{
"code": null,
"e": 5949,
"s": 5919,
"text": "abhishekyadav952014 weeks ago"
},
{
"code": null,
"e": 5965,
"s": 5949,
"text": "SIMPLE C++ SOL."
},
{
"code": null,
"e": 5968,
"s": 5965,
"text": "//"
},
{
"code": null,
"e": 6236,
"s": 5968,
"text": "queue<int> modifyQueue(queue<int> q, int k) {stack<int>s;int n=q.size();for(int i=0;i<k;i++){ int a=q.front(); q.pop(); s.push(a);}while(!s.empty()){ q.push(s.top()); s.pop();}for(int i=0;i<n-k;i++){ int a =q.front(); q.pop(); q.push(a);}return q;}"
},
{
"code": null,
"e": 6382,
"s": 6236,
"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": 6418,
"s": 6382,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6428,
"s": 6418,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6438,
"s": 6428,
"text": "\nContest\n"
},
{
"code": null,
"e": 6501,
"s": 6438,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6649,
"s": 6501,
"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": 6857,
"s": 6649,
"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": 6963,
"s": 6857,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Groovy - Variables
|
Variables in Groovy can be defined in two ways β using the native syntax for the data type or the next is by using the def keyword. For variable definitions it is mandatory to either provide a type name explicitly or to use "def" in replacement. This is required by the Groovy parser.
There are following basic types of variable in Groovy as explained in the previous chapter β
byte β This is used to represent a byte value. An example is 2.
byte β This is used to represent a byte value. An example is 2.
short β This is used to represent a short number. An example is 10.
short β This is used to represent a short number. An example is 10.
int β This is used to represent whole numbers. An example is 1234.
int β This is used to represent whole numbers. An example is 1234.
long β This is used to represent a long number. An example is 10000090.
long β This is used to represent a long number. An example is 10000090.
float β This is used to represent 32-bit floating point numbers. An example is 12.34.
float β This is used to represent 32-bit floating point numbers. An example is 12.34.
double β This is used to represent 64-bit floating point numbers which are longer decimal number representations which may be required at times. An example is 12.3456565.
double β This is used to represent 64-bit floating point numbers which are longer decimal number representations which may be required at times. An example is 12.3456565.
char β This defines a single character literal. An example is βaβ.
char β This defines a single character literal. An example is βaβ.
Boolean β This represents a Boolean value which can either be true or false.
Boolean β This represents a Boolean value which can either be true or false.
String β These are text literals which are represented in the form of chain of characters. For example βHello Worldβ.
String β These are text literals which are represented in the form of chain of characters. For example βHello Worldβ.
Groovy also allows for additional types of variables such as arrays, structures and classes which we will see in the subsequent chapters.
A variable declaration tells the compiler where and how much to create the storage for the variable.
Following is an example of variable declaration β
class Example {
static void main(String[] args) {
// x is defined as a variable
String x = "Hello";
// The value of the variable is printed to the console
println(x);
}
}
When we run the above program, we will get the following result β
Hello
The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Groovy, just like Java is a case-sensitive programming language.
class Example {
static void main(String[] args) {
// Defining a variable in lowercase
int x = 5;
// Defining a variable in uppercase
int X = 6;
// Defining a variable with the underscore in it's name
def _Name = "Joe";
println(x);
println(X);
println(_Name);
}
}
When we run the above program, we will get the following result β
5
6
Joe
We can see that x and X are two different variables because of case sensitivity and in the third case, we can see that _Name begins with an underscore.
You can print the current value of a variable with the println function. The following example shows how this can be achieved.
class Example {
static void main(String[] args) {
//Initializing 2 variables
int x = 5;
int X = 6;
//Printing the value of the variables to the console
println("The value of x is " + x + "The value of X is " + X);
}
}
When we run the above program, we will get the following result β
The value of x is 5 The value of X is 6
52 Lectures
8 hours
Krishna Sakinala
49 Lectures
2.5 hours
Packt Publishing
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2523,
"s": 2238,
"text": "Variables in Groovy can be defined in two ways β using the native syntax for the data type or the next is by using the def keyword. For variable definitions it is mandatory to either provide a type name explicitly or to use \"def\" in replacement. This is required by the Groovy parser."
},
{
"code": null,
"e": 2616,
"s": 2523,
"text": "There are following basic types of variable in Groovy as explained in the previous chapter β"
},
{
"code": null,
"e": 2680,
"s": 2616,
"text": "byte β This is used to represent a byte value. An example is 2."
},
{
"code": null,
"e": 2744,
"s": 2680,
"text": "byte β This is used to represent a byte value. An example is 2."
},
{
"code": null,
"e": 2812,
"s": 2744,
"text": "short β This is used to represent a short number. An example is 10."
},
{
"code": null,
"e": 2880,
"s": 2812,
"text": "short β This is used to represent a short number. An example is 10."
},
{
"code": null,
"e": 2947,
"s": 2880,
"text": "int β This is used to represent whole numbers. An example is 1234."
},
{
"code": null,
"e": 3014,
"s": 2947,
"text": "int β This is used to represent whole numbers. An example is 1234."
},
{
"code": null,
"e": 3086,
"s": 3014,
"text": "long β This is used to represent a long number. An example is 10000090."
},
{
"code": null,
"e": 3158,
"s": 3086,
"text": "long β This is used to represent a long number. An example is 10000090."
},
{
"code": null,
"e": 3244,
"s": 3158,
"text": "float β This is used to represent 32-bit floating point numbers. An example is 12.34."
},
{
"code": null,
"e": 3330,
"s": 3244,
"text": "float β This is used to represent 32-bit floating point numbers. An example is 12.34."
},
{
"code": null,
"e": 3501,
"s": 3330,
"text": "double β This is used to represent 64-bit floating point numbers which are longer decimal number representations which may be required at times. An example is 12.3456565."
},
{
"code": null,
"e": 3672,
"s": 3501,
"text": "double β This is used to represent 64-bit floating point numbers which are longer decimal number representations which may be required at times. An example is 12.3456565."
},
{
"code": null,
"e": 3739,
"s": 3672,
"text": "char β This defines a single character literal. An example is βaβ."
},
{
"code": null,
"e": 3806,
"s": 3739,
"text": "char β This defines a single character literal. An example is βaβ."
},
{
"code": null,
"e": 3883,
"s": 3806,
"text": "Boolean β This represents a Boolean value which can either be true or false."
},
{
"code": null,
"e": 3960,
"s": 3883,
"text": "Boolean β This represents a Boolean value which can either be true or false."
},
{
"code": null,
"e": 4079,
"s": 3960,
"text": "String β These are text literals which are represented in the form of chain of characters. For example βHello Worldβ. "
},
{
"code": null,
"e": 4198,
"s": 4079,
"text": "String β These are text literals which are represented in the form of chain of characters. For example βHello Worldβ. "
},
{
"code": null,
"e": 4336,
"s": 4198,
"text": "Groovy also allows for additional types of variables such as arrays, structures and classes which we will see in the subsequent chapters."
},
{
"code": null,
"e": 4437,
"s": 4336,
"text": "A variable declaration tells the compiler where and how much to create the storage for the variable."
},
{
"code": null,
"e": 4487,
"s": 4437,
"text": "Following is an example of variable declaration β"
},
{
"code": null,
"e": 4695,
"s": 4487,
"text": "class Example { \n static void main(String[] args) { \n // x is defined as a variable \n String x = \"Hello\";\n\t\t\n // The value of the variable is printed to the console \n println(x);\n }\n}"
},
{
"code": null,
"e": 4761,
"s": 4695,
"text": "When we run the above program, we will get the following result β"
},
{
"code": null,
"e": 4768,
"s": 4761,
"text": "Hello\n"
},
{
"code": null,
"e": 5024,
"s": 4768,
"text": "The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Groovy, just like Java is a case-sensitive programming language."
},
{
"code": null,
"e": 5371,
"s": 5024,
"text": "class Example { \n static void main(String[] args) { \n // Defining a variable in lowercase \n int x = 5;\n\t \n // Defining a variable in uppercase \n int X = 6; \n\t \n // Defining a variable with the underscore in it's name \n def _Name = \"Joe\"; \n\t\t\n println(x); \n println(X); \n println(_Name); \n } \n}"
},
{
"code": null,
"e": 5437,
"s": 5371,
"text": "When we run the above program, we will get the following result β"
},
{
"code": null,
"e": 5449,
"s": 5437,
"text": "5 \n6 \nJoe \n"
},
{
"code": null,
"e": 5601,
"s": 5449,
"text": "We can see that x and X are two different variables because of case sensitivity and in the third case, we can see that _Name begins with an underscore."
},
{
"code": null,
"e": 5728,
"s": 5601,
"text": "You can print the current value of a variable with the println function. The following example shows how this can be achieved."
},
{
"code": null,
"e": 5994,
"s": 5728,
"text": "class Example { \n static void main(String[] args) { \n //Initializing 2 variables \n int x = 5; \n int X = 6; \n\t \n //Printing the value of the variables to the console \n println(\"The value of x is \" + x + \"The value of X is \" + X); \n }\n}"
},
{
"code": null,
"e": 6060,
"s": 5994,
"text": "When we run the above program, we will get the following result β"
},
{
"code": null,
"e": 6102,
"s": 6060,
"text": "The value of x is 5 The value of X is 6 \n"
},
{
"code": null,
"e": 6135,
"s": 6102,
"text": "\n 52 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 6153,
"s": 6135,
"text": " Krishna Sakinala"
},
{
"code": null,
"e": 6188,
"s": 6153,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6206,
"s": 6188,
"text": " Packt Publishing"
},
{
"code": null,
"e": 6213,
"s": 6206,
"text": " Print"
},
{
"code": null,
"e": 6224,
"s": 6213,
"text": " Add Notes"
}
] |
What are Partial functions in JavaScript?
|
Partial functions allow takes a function as an argument and along with it takes arguments of other types too. It then uses some of the arguments passed and returns a function that will take the remaining arguments. The function returned when invoked will call the parent function with the original and its own set of arguments.
Following is the code for partial functions in JavaScript β
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 18px;
font-weight: 500;
color: rebeccapurple;
}
</style>
</head>
<body>
<h1>Partial function in JavaScript</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to see partial function invocation
</h3>
<script>
let resultEle = document.querySelector(".result");
function partialFunction(f) {
return function (a) {
return function (b) {
return f(a, b);
};
};
}
function multiply(a, b) {
return a * b;
}
document.querySelector(".Btn").addEventListener("click", () => {
resultEle.innerHTML = "partialFunction(multiply) = " + partialFunction(multiply) + "<br>";
resultEle.innerHTML += "partialFunction(multiply)(22) = " + partialFunction(multiply)(22) +
"<br>";
resultEle.innerHTML += "partialFunction(multiply)(22)(33) = " + partialFunction(multiply)(22)(33) + "<br>";
});
</script>
</body>
</html>
The above code will produce the following output β
On clicking the βCLICK HEREβ button β
|
[
{
"code": null,
"e": 1390,
"s": 1062,
"text": "Partial functions allow takes a function as an argument and along with it takes arguments of other types too. It then uses some of the arguments passed and returns a function that will take the remaining arguments. The function returned when invoked will call the parent function with the original and its own set of arguments."
},
{
"code": null,
"e": 1450,
"s": 1390,
"text": "Following is the code for partial functions in JavaScript β"
},
{
"code": null,
"e": 1461,
"s": 1450,
"text": " Live Demo"
},
{
"code": null,
"e": 2691,
"s": 1461,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 18px;\n font-weight: 500;\n color: rebeccapurple;\n }\n</style>\n</head>\n<body>\n<h1>Partial function in JavaScript</h1>\n<div class=\"result\"></div>\n<button class=\"Btn\">CLICK HERE</button>\n<h3>\nClick on the above button to see partial function invocation\n</h3>\n<script>\n let resultEle = document.querySelector(\".result\");\n function partialFunction(f) {\n return function (a) {\n return function (b) {\n return f(a, b);\n };\n };\n }\n function multiply(a, b) {\n return a * b;\n }\n document.querySelector(\".Btn\").addEventListener(\"click\", () => {\n resultEle.innerHTML = \"partialFunction(multiply) = \" + partialFunction(multiply) + \"<br>\";\n resultEle.innerHTML += \"partialFunction(multiply)(22) = \" + partialFunction(multiply)(22) +\n\"<br>\";\n resultEle.innerHTML += \"partialFunction(multiply)(22)(33) = \" + partialFunction(multiply)(22)(33) + \"<br>\";\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2742,
"s": 2691,
"text": "The above code will produce the following output β"
},
{
"code": null,
"e": 2780,
"s": 2742,
"text": "On clicking the βCLICK HEREβ button β"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.